text
stringlengths
180
608k
[Question] [ Write two programs such that when the bytes of their source code are XOR-d together it produces a third, valid program, all in the same language. The length of each of the three programs in bytes must be identical. The first program should output `A`. The second program should output `B`. The third program should output `C`. A newline is optional, but if one outputs a newline, both of the others must too. If you use any command line flags you must you the same ones for each program, i.e. all three programs must be executed the same way. If you're using a language like PHP that traditionally starts with the same combination of characters, e.g. `<?` but there is a command line option that drops those characters you may use that instead, i.e. PHP must only be run from the command line. No input is allowed. Each program must be self-contained. If your program is written entirely in ASCII the following tables might help: ``` Codes 0x20 - 0x3F !"#$%&'()*+,-./ 0123456789:;<=>? Codes 0x40 - 0x5F @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\]^_ Codes 0x60 - 0x7E `abcdefghijklmno pqrstuvwxyz{|}~ ``` ### EDIT Using non-printing characters **is allowed** as I didn't expressly forbid it originally. However, if you want to post a version that uses only printable characters as well that would be great! (Score whichever is the shortest.) The "clever factor" of using control codes has somewhat worn off now... ### END EDIT XOR-ing any two codes from the same block will produce a code less than 0x20 which is therefore not a valid printable ASCII code, e.g. 0x41 (`A`) XOR 0x5A (`Z`) = 0x1B. XOR-ing any two codes from different blocks will produce a code from the third block, e.g. 0x61 (`a`) XOR 0x54 (`T`) = 0x35 (`5`). ``` | @` !Aa "Bb #Cc $Dd %Ee &Ff 'Gg (Hh )Ii *Jj +Kk ,Ll -Mm .Nn /Oo 0Pp 1Qq 2Rr 3Ss 4Tt 5Uu 6Vv 7Ww 8Xx 9Yy :Zz ;[{ <\| =]} >^~ ?_ --- + --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @` | @` !Aa "Bb #Cc $Dd %Ee &Ff 'Gg (Hh )Ii *Jj +Kk ,Ll -Mm .Nn /Oo 0Pp 1Qq 2Rr 3Ss 4Tt 5Uu 6Vv 7Ww 8Xx 9Yy :Zz ;[{ <\| =]} >^~ ?_ !Aa | !Aa @` #Cc "Bb %Ee $Dd 'Gg &Ff )Ii (Hh +Kk *Jj -Mm ,Ll /Oo .Nn 1Qq 0Pp 3Ss 2Rr 5Uu 4Tt 7Ww 6Vv 9Yy 8Xx ;[{ :Zz =]} <\| ?_ >^~ "Bb | "Bb #Cc @` !Aa &Ff 'Gg $Dd %Ee *Jj +Kk (Hh )Ii .Nn /Oo ,Ll -Mm 2Rr 3Ss 0Pp 1Qq 6Vv 7Ww 4Tt 5Uu :Zz ;[{ 8Xx 9Yy >^~ ?_ <\| =]} #Cc | #Cc "Bb !Aa @` 'Gg &Ff %Ee $Dd +Kk *Jj )Ii (Hh /Oo .Nn -Mm ,Ll 3Ss 2Rr 1Qq 0Pp 7Ww 6Vv 5Uu 4Tt ;[{ :Zz 9Yy 8Xx ?_ >^~ =]} <\| $Dd | $Dd %Ee &Ff 'Gg @` !Aa "Bb #Cc ,Ll -Mm .Nn /Oo (Hh )Ii *Jj +Kk 4Tt 5Uu 6Vv 7Ww 0Pp 1Qq 2Rr 3Ss <\| =]} >^~ ?_ 8Xx 9Yy :Zz ;[{ %Ee | %Ee $Dd 'Gg &Ff !Aa @` #Cc "Bb -Mm ,Ll /Oo .Nn )Ii (Hh +Kk *Jj 5Uu 4Tt 7Ww 6Vv 1Qq 0Pp 3Ss 2Rr =]} <\| ?_ >^~ 9Yy 8Xx ;[{ :Zz &Ff | &Ff 'Gg $Dd %Ee "Bb #Cc @` !Aa .Nn /Oo ,Ll -Mm *Jj +Kk (Hh )Ii 6Vv 7Ww 4Tt 5Uu 2Rr 3Ss 0Pp 1Qq >^~ ?_ <\| =]} :Zz ;[{ 8Xx 9Yy 'Gg | 'Gg &Ff %Ee $Dd #Cc "Bb !Aa @` /Oo .Nn -Mm ,Ll +Kk *Jj )Ii (Hh 7Ww 6Vv 5Uu 4Tt 3Ss 2Rr 1Qq 0Pp ?_ >^~ =]} <\| ;[{ :Zz 9Yy 8Xx (Hh | (Hh )Ii *Jj +Kk ,Ll -Mm .Nn /Oo @` !Aa "Bb #Cc $Dd %Ee &Ff 'Gg 8Xx 9Yy :Zz ;[{ <\| =]} >^~ ?_ 0Pp 1Qq 2Rr 3Ss 4Tt 5Uu 6Vv 7Ww )Ii | )Ii (Hh +Kk *Jj -Mm ,Ll /Oo .Nn !Aa @` #Cc "Bb %Ee $Dd 'Gg &Ff 9Yy 8Xx ;[{ :Zz =]} <\| ?_ >^~ 1Qq 0Pp 3Ss 2Rr 5Uu 4Tt 7Ww 6Vv *Jj | *Jj +Kk (Hh )Ii .Nn /Oo ,Ll -Mm "Bb #Cc @` !Aa &Ff 'Gg $Dd %Ee :Zz ;[{ 8Xx 9Yy >^~ ?_ <\| =]} 2Rr 3Ss 0Pp 1Qq 6Vv 7Ww 4Tt 5Uu +Kk | +Kk *Jj )Ii (Hh /Oo .Nn -Mm ,Ll #Cc "Bb !Aa @` 'Gg &Ff %Ee $Dd ;[{ :Zz 9Yy 8Xx ?_ >^~ =]} <\| 3Ss 2Rr 1Qq 0Pp 7Ww 6Vv 5Uu 4Tt ,Ll | ,Ll -Mm .Nn /Oo (Hh )Ii *Jj +Kk $Dd %Ee &Ff 'Gg @` !Aa "Bb #Cc <\| =]} >^~ ?_ 8Xx 9Yy :Zz ;[{ 4Tt 5Uu 6Vv 7Ww 0Pp 1Qq 2Rr 3Ss -Mm | -Mm ,Ll /Oo .Nn )Ii (Hh +Kk *Jj %Ee $Dd 'Gg &Ff !Aa @` #Cc "Bb =]} <\| ?_ >^~ 9Yy 8Xx ;[{ :Zz 5Uu 4Tt 7Ww 6Vv 1Qq 0Pp 3Ss 2Rr .Nn | .Nn /Oo ,Ll -Mm *Jj +Kk (Hh )Ii &Ff 'Gg $Dd %Ee "Bb #Cc @` !Aa >^~ ?_ <\| =]} :Zz ;[{ 8Xx 9Yy 6Vv 7Ww 4Tt 5Uu 2Rr 3Ss 0Pp 1Qq /Oo | /Oo .Nn -Mm ,Ll +Kk *Jj )Ii (Hh 'Gg &Ff %Ee $Dd #Cc "Bb !Aa @` ?_ >^~ =]} <\| ;[{ :Zz 9Yy 8Xx 7Ww 6Vv 5Uu 4Tt 3Ss 2Rr 1Qq 0Pp 0Pp | 0Pp 1Qq 2Rr 3Ss 4Tt 5Uu 6Vv 7Ww 8Xx 9Yy :Zz ;[{ <\| =]} >^~ ?_ @` !Aa "Bb #Cc $Dd %Ee &Ff 'Gg (Hh )Ii *Jj +Kk ,Ll -Mm .Nn /Oo 1Qq | 1Qq 0Pp 3Ss 2Rr 5Uu 4Tt 7Ww 6Vv 9Yy 8Xx ;[{ :Zz =]} <\| ?_ >^~ !Aa @` #Cc "Bb %Ee $Dd 'Gg &Ff )Ii (Hh +Kk *Jj -Mm ,Ll /Oo .Nn 2Rr | 2Rr 3Ss 0Pp 1Qq 6Vv 7Ww 4Tt 5Uu :Zz ;[{ 8Xx 9Yy >^~ ?_ <\| =]} "Bb #Cc @` !Aa &Ff 'Gg $Dd %Ee *Jj +Kk (Hh )Ii .Nn /Oo ,Ll -Mm 3Ss | 3Ss 2Rr 1Qq 0Pp 7Ww 6Vv 5Uu 4Tt ;[{ :Zz 9Yy 8Xx ?_ >^~ =]} <\| #Cc "Bb !Aa @` 'Gg &Ff %Ee $Dd +Kk *Jj )Ii (Hh /Oo .Nn -Mm ,Ll 4Tt | 4Tt 5Uu 6Vv 7Ww 0Pp 1Qq 2Rr 3Ss <\| =]} >^~ ?_ 8Xx 9Yy :Zz ;[{ $Dd %Ee &Ff 'Gg @` !Aa "Bb #Cc ,Ll -Mm .Nn /Oo (Hh )Ii *Jj +Kk 5Uu | 5Uu 4Tt 7Ww 6Vv 1Qq 0Pp 3Ss 2Rr =]} <\| ?_ >^~ 9Yy 8Xx ;[{ :Zz %Ee $Dd 'Gg &Ff !Aa @` #Cc "Bb -Mm ,Ll /Oo .Nn )Ii (Hh +Kk *Jj 6Vv | 6Vv 7Ww 4Tt 5Uu 2Rr 3Ss 0Pp 1Qq >^~ ?_ <\| =]} :Zz ;[{ 8Xx 9Yy &Ff 'Gg $Dd %Ee "Bb #Cc @` !Aa .Nn /Oo ,Ll -Mm *Jj +Kk (Hh )Ii 7Ww | 7Ww 6Vv 5Uu 4Tt 3Ss 2Rr 1Qq 0Pp ?_ >^~ =]} <\| ;[{ :Zz 9Yy 8Xx 'Gg &Ff %Ee $Dd #Cc "Bb !Aa @` /Oo .Nn -Mm ,Ll +Kk *Jj )Ii (Hh 8Xx | 8Xx 9Yy :Zz ;[{ <\| =]} >^~ ?_ 0Pp 1Qq 2Rr 3Ss 4Tt 5Uu 6Vv 7Ww (Hh )Ii *Jj +Kk ,Ll -Mm .Nn /Oo @` !Aa "Bb #Cc $Dd %Ee &Ff 'Gg 9Yy | 9Yy 8Xx ;[{ :Zz =]} <\| ?_ >^~ 1Qq 0Pp 3Ss 2Rr 5Uu 4Tt 7Ww 6Vv )Ii (Hh +Kk *Jj -Mm ,Ll /Oo .Nn !Aa @` #Cc "Bb %Ee $Dd 'Gg &Ff :Zz | :Zz ;[{ 8Xx 9Yy >^~ ?_ <\| =]} 2Rr 3Ss 0Pp 1Qq 6Vv 7Ww 4Tt 5Uu *Jj +Kk (Hh )Ii .Nn /Oo ,Ll -Mm "Bb #Cc @` !Aa &Ff 'Gg $Dd %Ee ;[{ | ;[{ :Zz 9Yy 8Xx ?_ >^~ =]} <\| 3Ss 2Rr 1Qq 0Pp 7Ww 6Vv 5Uu 4Tt +Kk *Jj )Ii (Hh /Oo .Nn -Mm ,Ll #Cc "Bb !Aa @` 'Gg &Ff %Ee $Dd <\| | <\| =]} >^~ ?_ 8Xx 9Yy :Zz ;[{ 4Tt 5Uu 6Vv 7Ww 0Pp 1Qq 2Rr 3Ss ,Ll -Mm .Nn /Oo (Hh )Ii *Jj +Kk $Dd %Ee &Ff 'Gg @` !Aa "Bb #Cc =]} | =]} <\| ?_ >^~ 9Yy 8Xx ;[{ :Zz 5Uu 4Tt 7Ww 6Vv 1Qq 0Pp 3Ss 2Rr -Mm ,Ll /Oo .Nn )Ii (Hh +Kk *Jj %Ee $Dd 'Gg &Ff !Aa @` #Cc "Bb >^~ | >^~ ?_ <\| =]} :Zz ;[{ 8Xx 9Yy 6Vv 7Ww 4Tt 5Uu 2Rr 3Ss 0Pp 1Qq .Nn /Oo ,Ll -Mm *Jj +Kk (Hh )Ii &Ff 'Gg $Dd %Ee "Bb #Cc @` !Aa ?_ | ?_ >^~ =]} <\| ;[{ :Zz 9Yy 8Xx 7Ww 6Vv 5Uu 4Tt 3Ss 2Rr 1Qq 0Pp /Oo .Nn -Mm ,Ll +Kk *Jj )Ii (Hh 'Gg &Ff %Ee $Dd #Cc "Bb !Aa @` ``` Look up two characters from different columns and pick the character from their intersection that's in the other column, e.g. `B` and `e`: `"Bb` XOR `%Ee` is `'Gg`. `B` is second column and `e` is third column so pick the character from the first column in `'Gg`: `'`. Example source: ``` Ld+|?dpHs'-,pUe (Program 1) ~bWn=n5Xe!t_G($3 (Program 2) ^.3EAQQ(-RSrkXqV (Program 3) ``` Note that in each column there can only be one digit, one uppercase letter and one lowercase letter. For each column you may use any character you like in the first program, then your choice of 64 characters in the second program but only one possible character in the third program. 0x7F is not valid anywhere. If you use Unicode it's up to you to validate the XOR-ing and you must say how it's encoded, e.g. UTF-8, UTF-16, etc. Each file must use the same encoding. Score: Length of one program. Fewest bytes win! [Answer] # GolfScript, 6 bytes A ``` A'AA'| ``` B ``` cdc"B" ``` C ``` "C"ce^ ``` `|` and `^` are setwise or and xor with the empty input string, which would do nothing but remove duplicates in the string. ### Original version (with non-printable characters) A ``` Xz'A'v ``` B ``` z9\x05"B" ``` C ``` "C"ceT ``` GolfScript ignores the undefined things, and the three programs are just `'A'` `"B"` `"C"`. [Answer] # Javascript, 23 bytes Program A: ``` alert(' A '[~-~~2],'B') ``` Program B: ``` alert(FL$RSsYnYW1f='B') ``` Program C: ``` \0\0\0\0\0\0alert('C')\0;\0\0\03\0\0 ``` You can test the conversion with the following function: ``` function xorString(a, b) { b = b || ''; var length = Math.max(a.length, b.length); var chars = a.split('').map(function(charA, i) { var charB = b[i] || ' '; return String.fromCharCode(charA.charCodeAt(0) ^ charB.charCodeAt(0)); }); return chars.join(''); } ``` [Answer] # PHP, 15+1 bytes This one was ~~easy~~ **REALLY** harder than expected, but fun! Sadly, this is the 3rd rewrite due to invalid answers. This time, it is meant to run in the console (using the parameter `-r`). **Program A:** ``` echo A;E925Z9A; ``` **Program B:** ``` echo B; zzzzzz; ``` **Result of XORing:** ``` \0\0\0\0\0\3\0eCHO C;\0 //base 64: AAAAAAADAGVDSE8gQzsA ``` Hex dump: ``` |00|01|02|03|04|05|06|07|08|09|0A|0B|0C|0D|0E|0F| TEXT -------------------------------------------------------------------- 00 |00|00|00|00|00|03|00|65|43|48|4F|20|43|3B|00| |.......eCHO C;. ==================================================================== ``` PHP will throw warnings about having the `\0` and `\3` chars before the echo, but that is ignorable. It's just warnings! It still runs and outputs the right answer! --- Try running this, in your console: ``` php -r "@eval('echo B; zzzzzz;' ^ 'echo A;E925Z9A;');" ``` If you can't, try one of these: * <http://sandbox.onlinephpfunctions.com/code/cd88c68d3195b1b4d5551603dbc3792552e5c058> * <http://ideone.com/abzCFM> If you still cant, run the code yourself: ``` <?php error_reporting( 0 ); $program_a = 'echo A;E925Z9A;'; $program_b = 'echo B; zzzzzz;'; eval( $program_a ); eval( $program_b ); eval( $program_c = $program_a ^ $program_b ); echo PHP_EOL, 'a ^ b = '; var_dump( $program_c ); ``` --- ## Old code, invalid: **Program A:** ``` <?=A;zzzzz; ``` **Program B:** ``` <?=B;FEG9A; ``` **Result of XORing:** ``` \0\0\0\0<?=C;\0 //base64: AAAAAwA8Pz1DOwA= ``` [Answer] # Pip, 4 bytes Since user23013 is using non-printing ASCII in GolfScript, I figured I could do the same in [Pip](http://github.com/dloscutoff/pip). It does require redirecting `stderr`, but [that's okay](http://meta.codegolf.stackexchange.com/a/4781/16766), right? **A** ``` ??'A ``` where the two `?`s represent ASCII character 0. **B** ``` 'C'B ``` **C** ``` 'C?? ``` where the two `?`s represent ASCII characters 0 and 3, respectively. Place each program in a file (`A.pip` for example). On Linux, do: ``` ./pip.py A.pip 2>/dev/null ``` On Windows: ``` pip.py A.pip 2>nul ``` If error output is verboten, here's a 5-byte solution in printable ASCII: ``` pAa'A f"B" P'Cec ``` [Answer] # [Microscript](http://esolangs.org/wiki/Microscript), 8 bytes each A: `'APhgap)` B: `'BPh@" A` C: `<0><3><0><0>'CPh` [Answer] # Python, ~~19~~ ~~15~~ 14 bytes a.py ``` 00000000 70 72 69 6e 00 28 32 50 69 0a 74 22 41 22 |prin.(2Pi.t"A"| ``` b.py ``` 00000000 70 72 69 6e 74 22 42 22 00 64 00 00 02 00 |print"B".d....| ``` c.py ``` 00000000 00 00 00 00 74 0a 70 72 69 6e 74 22 43 22 |....t.print"C"| ``` I came up with this solution when I noticed that python (2.7.6 on Ubuntu 14.04) after seeing a NUL character will ignore the rest of that line. Shortened by 1 bytes once I realized that the space after print wasn't needed. And shortened by 4 more bytes once I realized that the NUL character also cause the newline to be ignored so I can use it to break lines in the middle of a keyword. [Answer] # [Chip](https://github.com/Phlarx/chip), 8 bytes All require the flag `-w`. ### Program A ``` a*gt*... ``` (`.` is the null character `\x00`) ### Program B ``` ...*gb*t ``` (`.` is the null character `\x00`) ### Program C ``` a*g^Mb*t ``` Both A and B produce three warnings each (e.g.: `1:6 WARN: '' (0) is not a valid character`), but they can be safely ignored since they go to stderr. The elements `^` and `M` are valid, but do nothing here. I'm fairly sure that this is the best that can be done with non-printables allowed. I'm not sure this proof is complete, but here goes: A requires `a`, `g`, `t`, and some way to activate those elements (a minimum of two symbols are needed for this, and `*` is the simplest option here). Similarly, B requires `b`, `g`, `t`, and two `*`s, and C requires `a`, `b`, `g`, `t`, and two `*`s. If C borrows its symbols directly from A and B, there will be two letters and two `*`s that remain unclaimed. (In my implementation, A's `t` and B's `g`). Those four elements can be overlapped so that they are mangled in C (producing `^` and `M` in this case). We now have those two mangled elements, plus the six required elements from above (C requires 6, the others only 5, but we need max() here), for a total of 8 elements. --- ## [Chip](https://github.com/Phlarx/chip) (warning-free), 10 bytes All require the flags `-wo`. ### Program A ``` a*HH^t*Gg ``` (there is a trailing space) ### Program B ``` KKb*t*^g G ``` ### Program C ``` *a*b*^t Gg ``` This is provably the best we can do within printable ASCII, as follows: The three programs, combined, need a total of 2 `a`s, 2 `b`s, 3 `g`s, and 3 `t`s. Since none of these characters can transition to another, we need `2+2+3+3 = 10` separate positions. ]
[Question] [ [JSFuck](http://www.jsfuck.com/) is an esoteric language in which any Javascript statement can be accurately reproduced into another valid Javascript program that uses only the 6 characters `[]()!+`. The JSFuck converter, when given an input of `alert("Hello World!")`, produces a block of code that is 22,948 characters long. Because the program used a lot of automatic conversions to create that block, I believe that the code can be made a lot shorter using manual optimizations. Your task is to build a Javascript program that performs the task `alert("Hello World!")`, using only the characters `[]()!+`. The shortest code to do so wins. [Answer] # Manually, 2874 bytes yeah... ## Firefox, 2874 bytes ``` [][(![]+[])[+!![]]+(!![]+[])[+[]]][([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+[]+(+[])]+([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]+[]+(!![]+!![])]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[+[]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+(!![]+[])[!![]+!![]]+([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+([]+[]))[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(![]+[][(![]+[])[+!![]]+(!![]+[])[+![]]]+[])[+!![]+[]+(!![]+!![]+!![])]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+(![]+[]+[][[]])[+!![]+[]+(+[])]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(![]+[])[+!![]])()(+[])[!![]+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[+[]])()[(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]](([][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]][([][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]]+[])[!![]+!![]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+(![]+[])[+!![]]])(!![])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]]+([][[]]+[])[!![]+!![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]][(![]+[])[+!![]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+([][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]]+[])[!![]+!![]]]((+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))+[])[+[]]+(![]+[])[+[]])) ``` ## Chrome, 2884 bytes ``` [][(![]+[])[+!![]]+(!![]+[])[+[]]][([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+[]+(+[])]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]+[]+(!![]+!![])]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[+[]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+(!![]+[])[!![]+!![]]+([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+([]+[]))[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(![]+[][(![]+[])[+!![]]+(!![]+[])[+![]]]+[])[+!![]+[]+(!![]+!![]+!![])]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+(![]+[]+[][[]])[+!![]+[]+(+[])]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(![]+[])[+!![]])()(+[])[!![]+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[+[]])()[(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]](([][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]][([][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]]+[])[!![]+!![]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+(![]+[])[+!![]]])(!![])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]]+([][[]]+[])[!![]+!![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]][(![]+[])[+!![]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+([][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]]+[])[!![]+!![]]]((+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))+[])[+[]]+(![]+[])[+[]])) ``` ## Hybrid (Firefox and Chrome), 3116 bytes ``` [][(![]+[])[+!![]]+(!![]+[])[+[]]][([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+(![]+[]+[][[]])[+!![]+[]+(+[])]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[+[]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+(![]+[]+[][[]])[+!![]+[]+(+[])]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]+[]+(!![]+!![])]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[+[]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+(!![]+[])[!![]+!![]]+([][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+([]+[]))[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[!![]+!![]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(![]+[][(![]+[])[+!![]]+(!![]+[])[+![]]]+[])[+!![]+[]+(!![]+!![]+!![])]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+(![]+[]+[][[]])[+!![]+[]+(+[])]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(![]+[])[+!![]])()(+[])[!![]+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[+[]])()[(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]](([][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]][([][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]]+[])[!![]+!![]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+(![]+[])[+!![]]])(!![])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+[])]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]]+([][[]]+[])[!![]+!![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]][(![]+[])[+!![]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]]+[])[+!![]+[]+(+!![])]+([][(![]+[])[+!![]]+(!![]+[])[+[]]][(![]+[])[+[]]]+[])[!![]+!![]]]((+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))+[])[+[]]+(![]+[])[+[]])) ``` --- ## Explanation Here's the basic structure: ``` []["at"]["constructor"]("return [].at.f=self")()["alert"]("Hello World!") ``` As you can see, we set `Array.prototype.at.f` as `self`, being the root object. This will be an helpful shortcut for later as we can run any function like this: ``` // Without the shortcut: []["at"]["constructor"]("return functionName")()(/* ARGS */) // With the shortcut: []["at"]["f"]["functionName"](/* ARGS */) ``` Then it's only a matter of optimizing each characters. I used [JSFuck's script](https://github.com/aemkei/jsfuck/blob/master/jsfuck.js) (on GitHub) as a base for my script and found the missing characters and optimized some of the existing ones. #### General optimizations * The relatively new `Array.prototype.at` is replacing `Array.prototype.flat` * `+[]` replace `+![]` for `0` * When a digit is bigger than 1, you can omit the first `+` (`(+!![]+!![])` => `(!![]+!![])`) * Appending `false`,`NaN`, `undefined`, etc..., in front of something helps it having smaller digits (`(NaN+[]["at"])[11]` is shorter than `([]+[]["at"])[13]`) * `([]+[])` is a standalone string, but appending an array `[]` is enough to "stringify" something #### Interesting characters These are the characters that aren't in the JSFuck's script, or where I took a different approach. `=` ``` []["at"]["constructor"]("return btoa")()(0)[2] ``` `=` is by far the longest character in the whole script. Since we're currently defining `[].at.f` we can't use it. `btoa` does some sort of `padEnd()` but with `=`. `H` ``` []["at"]["f"]["btoa"](true)[1] ``` Conveniently, `btoa(true)` returns `'dHJ1ZQ=='`, containing `H` `W` ``` ([]["at"]["f"]+[])[11] ``` `[].at.f` being the root object `Window`, returns `[object Window]`. `!` ``` []["at"]["f"]["atob"]("If") ``` After some testings, I figured out that `atob("If")` returns `!`. `[` and `]` ``` // Firefox ([]["at"]+[])[20] // [ ([]["at"]+[])[32] // ] // Chrome (true+[]["at"]+[])[20] // [ (true+[]["at"]+[])[32] // ] ``` I kept it for last because it's the sole reason why it only works in Firefox. For the hybrid version it's the same as in the JSFuck's script. But why ? ``` []["at"]+[] // In Chrome: 'function at() { [native code] }' // In Firefox: 'function at() {\n [native code]\n}' ``` Yeah, it doesn't align... #### Conclusion `atob()` and `btoa()` are amazing! [Answer] # JScrewIt (different solutions: 16117, 14747, and 5903 characters) Javascript engines are not identical; slight implementation differences may cause code that works in a browser not to work in another one. In case of lipogrammatic code like JSFuck - which largely relies on hacks to encode things as short as possible - incompatibilities are even larger. For example, the code generated by JSFuck for `alert("Hello World!")` does not run on Internet Explorer. If this is an acceptable limitation, we can still drop the size down to **16117 ~~22174~~ characters** (I cannot include the whole code directly because answer size is limited to 30000 characters): <http://jsfiddle.net/ep2jqsj4/1/> A code that works on Internet Explorer too, but not so on some older browsers, takes **14747 characters** to encode: <http://jsfiddle.net/bbxfqboq/> Finally, if it's ok to have code that runs on current Firefox *[update]* and Safari *[end update]* only, we could do it with **5903 ~~5911~~ characters**: <http://jsfiddle.net/pkyLy0j8/1/> I encoded all of those with [JScrewIt](http://jscrew.it). You can find other encoders similar to JSFuck listed on Esolang: <http://esolangs.org/wiki/JSFuck>. I tried all of them and I have to say JScrewIt seems to be the best one (and also the only one that works in all browsers), though I havent't analysed how it works in detail. Another interesting encoder is [6chars.js](http://syllab.fr/projets/experiments/sixcharsjs/), which generates larger output for short input like `alert("Hello World!")`, but when the input gets longer it performs better than the other encoders because it encodes characters as numbers. Numbers are shorter to write in JSFuck but require extra overhead to decode. Unfortunately, 6chars.js only works in Chrome and I can't say if it's being still actively developed. It would be interesting to know if there are more of such encoders. If one could join methods used by different encoders in one tool it would be possible to produce even shorter solutions. [Answer] # JSFuck (15,863 characters) Not really optimized (just 7,085 characters), but it's not that optimizations are really possible, as JSFuck is just a simple language hack. ``` [][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([][[]]+[])[!+[]+!+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]]+[+!+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])() ``` [Answer] # 2305 bytes, Firefox ``` [[][(![]+[])[+!![]]+(!![]+[])[+[]]][([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]+[!![]+!![]]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+![]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[+!![]]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[+[]])()][(![]+[])[+!![]]+(!![]+[])[+[]]][![]][(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]]([][(![]+[])[+!![]]+(!![]+[])[+[]]][![]][([]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(![]+[])[+!![]]](!![])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(+[]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][![]])[+!![]+[+!![]]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]]+([][[]]+[])[!![]+!![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][![]][(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[!![]+!![]]]((+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))+[])[+[]]+![])[+[]]) ``` 2307 for chrome: ``` [[][(![]+[])[+!![]]+(!![]+[])[+[]]][([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]+[+!![]]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+![]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[+!![]]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[+[]])()][(![]+[])[+!![]]+(!![]+[])[+[]]][![]][(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]]([][(![]+[])[+!![]]+(!![]+[])[+[]]][![]][([]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(![]+[])[+!![]]](!![])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][![]])[+!![]+[+!![]]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]]+([][[]]+[])[!![]+!![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][![]][(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[!![]+!![]]]((+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))+[])[+[]]+![])[+[]]) ``` 2446 for both: ``` [[][(![]+[])[+!![]]+(!![]+[])[+[]]][([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]](([[!![]][+!!++(+[]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]+([[!![]][+!!++(+[]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]+[!![]+!![]]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+![]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[+!![]]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[+[]])()][(![]+[])[+!![]]+(!![]+[])[+[]]][![]][(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]]([][(![]+[])[+!![]]+(!![]+[])[+[]]][![]][([]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(![]+[])[+!![]]](!![])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+!![]]]+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][![]])[+!![]+[+!![]]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]]+([][[]]+[])[!![]+!![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][![]][(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[!![]+!![]]]((+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))+[])[+[]]+![])[+[]]) ``` Strongly based on [CreaZyp154's solution](https://codegolf.stackexchange.com/a/245382/) with the following changes: * Use `[].at.false` instead of `[].at.f` since `false` is shorter than `f` * [JScrewIt](https://jscrew.it/) as generator * `atob("If")` => `atob("Ifalse")[0]` Because of the work of JScrewIt on shortening result, we just need to rewrite the optimized part because of the short way `[].at.false`. Copy this code to JScrewIt: ``` [[]["at"]["constructor"]("[].at.false=self")()]["at"][false]["alert"]([]["at"][false]["btoa"](true)[1]+'e'+'l'+'l'+'o'+' '+(NaN+[]["at"][false])[11]+'o'+'r'+'l'+'d'+[]["at"][false]["atob"]("Ifalse")[0]) ``` [Answer] [jsfuck.com](https://jsfuck.com) encodes it to 6592 characters (Eval Source on, Run In Parent Scope off). The output runs in Chrome: ``` [][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[+!+[]]+[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([][[]]+[])[!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[+!+[]])[(![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]]((!![]+[])[+[]])[([][(!![]+[])[!+[]+!+[]+!+[]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]](([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+![]+(![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]])()[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]])+[])[+!+[]])+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]])())() ``` [Answer] # JScrewIt, 3522 bytes ``` [][(![]+[])[+!![]]+(!![]+[])[+[]]][([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]])()([][(![]+[])[+!![]]+(!![]+[])[+[]]][([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]+([]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(!![])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]][([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]((!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(+[]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]])+(+[![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[+[]])())[+!![]+[+!![]]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]]+([][[]]+[])[!![]+!![]]+[][(![]+[])[+!![]]+(!![]+[])[+[]]][([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(+[]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+[+[]]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[!![]+!![]])()((+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))+[])[+[]]+![])[+[]]) ``` Compiled with `JScrewIt.encode('alert("Hello, World!")', {features: ['FF','AT']})`. Relies upon the very new [`Array.prototype.at()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at) which significantly decreases code size (4537 bytes without `at()`, 3522 bytes with `at()`). i believe this method is currently only implemented in Firefox nightly, but you can run the code in current Firefox with this polyfill first: ``` const at = new Function(); at.toString = () => `function at() { [native code] }`; Array.prototype.at = at; ``` [Answer] ## JSFuck, 18827 ``` [][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[+[]]+(!![]+[])[+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+((+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[!+[]+!+[]]+(+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+[+!+[]])[+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+!+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[+!+[]]+[+[]]+[+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[+!+[]]+[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[+!+[]]+[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[+!+[]]+[+!+[]]+[+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[+!+[]]+[+!+[]]+[+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[+!+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[+!+[]]+[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[+!+[]]+[+[]]+[+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+[!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])() ``` Couldn't get it down much further. Autogenerated code, I optimized the readable JS code for the generator. Only did very few optimizations in the JSFuck code. ]
[Question] [ **Write the shortest program that generates guitar tabs for the chords given as input.** So that the guitarists among you don't have an advantage, and to make it deterministic (and probably easier to code), here are the **only** forms of the chords authorized: ``` Major chords: E F F# G G# A A# B C C# D D# e 0---1---2---3---4---0---1---2---3---4---5---6--- B 0---1---2---3---4---2---3---4---5---6---7---8--- G 1---2---3---4---5---2---3---4---5---6---7---8--- D 2---3---4---5---6---2---3---4---5---6---7---8--- A 2---3---4---5---6---0---1---2---3---4---5---6--- E 0---1---2---3---4---0---1---2---3---4---5---6--- Minor chords: Em Fm F#m Gm G#m Am A#m Bm Cm C#m Dm D#m e 0---1---2---3---4---0---1---2---3---4---5---6--- B 0---1---2---3---4---1---2---3---4---5---6---7--- G 0---1---2---3---4---2---3---4---5---6---7---8--- D 2---3---4---5---6---2---3---4---5---6---7---8--- A 2---3---4---5---6---0---1---2---3---4---5---6--- E 0---1---2---3---4---0---1---2---3---4---5---6--- ``` Note that the 5 first chords and the 7 last chords of each series have different forms. All the chords are simple major or minor chords (no 7th or other variations). You should take care of flats too. Reminder: ``` A# = Bb C# = Db D# = Eb F# = Gb G# = Ab B#, Cb, E# and Fb are not used ``` Output **must** include the first column with the cord names, as shown above. It does **not** have to include the chord name on top. Chords must be separated by 3 `-` as shown above. The final 3 `-` are optional. Input is a string consisting of chord names, separated by spaces. An example input is: ``` Bm Gb A E G D Em F# ``` and the corresponding output is: ``` e 2---2---0---0---3---5---0---2--- B 3---2---2---0---3---7---0---2--- G 4---3---2---1---4---7---0---3--- D 4---4---2---2---5---7---2---4--- A 2---4---0---2---5---5---2---4--- E 2---2---0---0---3---5---0---2--- ``` [Answer] ## JavaScript, 297 277 262 235 223 chars No carriage returns in the golfed version are significant; they are there only to make the answer readable. Semicolons are significant. *Edit:* Replaced the outer `map` with a while loop and other edits. Finally inside of 2ร— the size of the Golfscript version (for now)! *Edit:* Replaced the `indexOf` with math, broke down the lookup table, other small improvements. *Edit:* Another `map` to `for` and put in a final `\n` I had been unnecessarily eating. Finally inside of Jules's Python version. ``` i=prompt(o='').split(' ');for(r=6;o+=' EADGBe'[r]+' ',r--;o+='\n') for(j=0;n=i[j++];o+=(([84,13,52,5][2*/m/.test(n)+x]*8>>2*r&3)+y-7*x)+'---') y=n.charCodeAt(0),y=(2*y-(y>66)-(y>69)+(n[1]<'$')-(n[1]=='b')+2)%12,x=y>6;alert(o) ``` Output no longer takes advantage of the trailing `---` being optional as: ``` e 2---2---0---0---3---5---0---2--- B 3---2---2---0---3---7---0---2--- G 4---3---2---1---4---7---0---3--- D 4---4---2---2---5---7---2---4--- A 2---4---0---2---5---5---2---4--- E 2---2---0---0---3---5---0---2--- ``` [Answer] ## Golfscript, 136 chars ``` [["eBGDAE"{[]+" "+}/]]\" "/{.-2\{"bm#A B C D E F G"?.)!!*(+}/14%.3>-.8>-.7/@109?0>2*+[963 780 882 753]{3base(;}%=\7%{+'---'+}+%}%+zip n* ``` Fully 23 chars (17.5%) deal with those two characters at the start of each output row. Sample output, testing the edge cases: ``` $ golfscript.rb tabs.gs <<<"E G# Ab A Db D# Em G#m Abm Am D#m" e 0---4---4---0---4---6---0---4---4---0---5--- B 0---4---4---2---6---8---0---4---4---1---6--- G 1---5---5---2---6---8---0---4---4---2---7--- D 2---6---6---2---6---8---2---6---6---2---7--- A 2---6---6---0---4---6---2---6---6---0---5--- E 0---4---4---0---4---6---0---4---4---0---5--- ``` I've only spent about an hour on this, so it can probably be reduced by 5 to 10 chars at least. Conceptually it turns out to be quite similar to DocMax's solution: lookup table for four cases, then increment by an offset and join the strings in the right order. [Answer] After coding this up, I realized I could have done this a lot smarter...maybe I'll make another entry. Hopefully I'll just get points for being the quickest! Anyway, there is 962 characters of Perl. ``` %c =(B=>{E=>0,F=>1,Gb=>2,G=>3,Ab=>4,A=>2,Bb=>3,B=>4,C=>5,Db=>6,D=>7,Eb=>8,Em=>0,Fm=>1,Gbm=>2,Gm=>3,Abm=>0,Am=>1,Bbm=>2,Bm=>3,Cm=>4,Dbm=>5,Dm=>6,Ebm=>7},G=>{E=>1,F=>2,Gb=>3,G=>4,Ab=>5,A=>2,Bb=>3,B=>4,C=>5,Db=>6,D=>7,Eb=>8,Em=>0,Fm=>1,Gbm=>2,Gm=>3,Abm=>4,Am=>2,Bbm=>3,Bm=>4,Cm=>5,Dbm=>6,Dm=>7,Ebm=>8},D=>{E=>2,F=>3,Gb=>4,G=>5,Ab=>6,A=>2,Bb=>3,B=>4,C=>5,Db=>6,D=>7,Eb=>8,Em=>2,Fm=>3,Gbm=>4,Gm=>5,Abm=>6,Am=>2,Bbm=>3,Bm=>4,Cm=>5,Dbm=>6,Dm=>7,Ebm=>8},A=>{E=>2,F=>3,Gb=>4,G=>5,Ab=>6,A=>0,Bb=>1,B=>2,C=>3,Db=>4,D=>5,Eb=>6,Em=>2,Fm=>3,Gbm=>4,Gm=>5,Abm=>6,Am=>0,Bbm=>1,Bm=>2,Cm=>3,Dbm=>4,Dm=>5,Ebm=>6},E=>{E=>0,F=>1,Gb=>2,G=>3,Ab=>4,A=>0,Bb=>1,B=>2,C=>3,Db=>4,D=>5,Eb=>6,Em=>0,Fm=>1,Gbm=>2,Gm=>3,Abm=>4,Am=>0,Bbm=>1,Bm=>2,Cm=>3,Dbm=>4,Dm=>5,Ebm=>6}); %b=('A#'=>'Bb','C#'=>'Db','D#'=>'Eb','F#'=>'Gb','G#'=>'Ab'); foreach(qw(e B G D A E)){p($_,@ARGV)} sub p{$s = shift;print "$s ";$s = uc($s);foreach(@_){while(($h,$f)=each(%b)){s/$h/$f/}print "$c{$s}->{$_}---"}print "\n"} ``` Here is the corresponding output. ``` dhrasmus:Desktop standage$ perl guitar Bm Gb A E G D Em F# e 2---2---0---0---3---5---0---2--- B 3---2---2---0---3---7---0---2--- G 4---3---2---1---4---7---0---3--- D 4---4---2---2---5---7---2---4--- A 2---4---0---2---5---5---2---4--- E 2---2---0---0---3---5---0---2--- ``` [Answer] Since shorter solutions have been given already (damn you GolfScript!), here is mine: ## Python, 229 chars ``` s=[("E EmF FmF#GbG GmG#AbA AmA#BbB BmC CmC#DbD DmD#Eb".find("%-02s"%s[:2])/4,s[-1]!='m')for s in raw_input().split()] for c in range(6): l='eBGDAE'[c]+' ' for(i,M)in s:x=i>4;l+=`i-5*x+2*(2<c+x<5)+(M+x)*(c==2-x)`+"---" print l ``` Output: ``` > echo "Bm Gb A E G D Em F#" | python guitar.py e 2---2---0---0---3---5---0---2--- B 3---2---2---0---3---7---0---2--- G 4---3---2---1---4---7---0---3--- D 4---4---2---2---5---7---2---4--- A 2---4---0---2---5---5---2---4--- E 2---2---0---0---3---5---0---2--- ``` [Answer] **Python, 449 chars** ``` z=int f=str r=range j=''.join n='E F F# G G# A A# B C C# D D#'.split() n+=[x+'m'for x in n] c=[j([f(z(x)+i)for x in'001220'])for i in r(5)]+[j([f(z(x)+i)for x in'022200'])for i in r(7)] c+=[x[:2]+f(z(x[2])-1)+x[3:]for x in c[:5]]+[x[0]+f(z(x[1])-1)+x[2:]for x in c[5:]] a=[c[n.index((chr(ord(i[0])-1)+'#'+i[2:]).replace('@','G')if len(i)-1 and i[1]=='b'else i)]for i in raw_input().split()] for i in r(6):print'eBGDAE'[i],j([x[i]+'-'*3 for x in a]) ``` [Answer] # C99 - 231 characters The chords are given on the command line, one argument per chord, and of course there is no input validation of any kind. ``` #include<stdio.h> int main(int c,char**v){for(char*o="e0)B2)G2*D2+A0+E0)",i,m;*o;o+=3,v-=c,puts(""))for(printf("%c ",*o);*++v;printf("%c---",i-(i>2)-i/9+o[1+i/8]-(*o-66-i/8*5?0:m?m+2[*v]>99:0)))m=1[*v],i=(**v*2-4+m/35-m/98*3)%14;} ``` Sample run: ``` $ ./a.out Bm Gb A E G D Em F# e 2---2---0---0---3---5---0---2--- B 3---2---2---0---3---7---0---2--- G 4---3---2---1---4---7---0---3--- D 4---4---2---2---5---7---2---4--- A 2---4---0---2---5---5---2---4--- E 2---2---0---0---3---5---0---2--- ``` ## Un-golfed ``` #include<stdio.h> int main(int c,char**v){ // o points to three characters per output line: // string name, number for A, adjusted number for E (ASCII code minus 7) char* o="e0)B2)G2*D2+A0+E0)", i, // chord: A=0, A#=1, ..., G#=13, allowing also 3="E#" and 9="B#" m; // second character in chord name for (; *o; o+=3) { printf("%c ", *o); for (; *++v; ) { m = 1[*v], i = (**v*2-4+m/35-m/98*3)%14; // parse & adjust for sharp, flat printf("%c---", i-(i>2)-i/9 // eliminate "E#", "B#" +o[1+i/8] // get the number for a major chord // adjust for minor... -(*o-66-i/8*5 ? 0 : m ? m+2[*v]>99 : 0)); } v -= c; // rewind argument pointer puts(""); } } ``` ## Nonstandard C - 206 characters If we don't care about language specifications, GCC can compile the following one-liner into a functional binary, even though it mixes C99 variable declarations with a K&R style argument declaration (and an implicit declaration of printf). ``` main(c,v)char**v;{for(char*o="e0)B2)G2*D2+A0+E0)",i,m;*o;o+=3,v-=c,puts(""))for(printf("%c ",*o);*++v;printf("%c---",i-(i>2)-i/9+o[1+i/8]-(*o-66-i/8*5?0:m?m+2[*v]>99:0)))m=1[*v],i=(**v*2-4+m/35-m/98*3)%14;} ``` [Answer] **C++, 432** ``` #include <cmath> #include <iostream> F(int c){c-=65;return c*1.6+sin(c/5.+.3);} T(int a,int s){if(s)return(a=(T(a,s-1)+2)%3)-=(a==1&s>2);return(a<7)*2;} #define c(a,b) while(*(++j)==a)b;--j; #define O std::cout<< main(int a,char*p[]){ int P=2;for(int i=-1;++i<6;P=2){O p[1][i];O" ";while(P<a){char*j=p[P++]; int f=F(*j);c('#',++f)c('b',--f) int t=T(f,i)*3.5;if(*(++j)!='m'){--j;t+=(t==3);} O(f-F(p[1][i])+t+24)%12;O"---"; }O'\n';}} ``` Note that this needs the guitar tuning as the first parameter. (Most non-standard-tunings will give you ridiculous fingerbreaking results, but I guess you're content with standard tuning.) For Hotel California, you can do `$./a.out EBGDAE Cbm Gb Bbb Fb G D Em F# Bm F# G## D## F## C## D##m E##`. Result: ``` E 2---2---0---0---3---5---0---2---2---2---5---0---3---5---0---2--- B 3---2---2---0---3---7---0---2---3---2---5---0---3---7---0---2--- G 4---3---2---1---4---7---0---3---4---3---6---1---4---7---0---3--- D 4---4---2---2---5---7---2---4---4---4---7---2---5---7---2---4--- A 2---4---0---2---5---5---2---4---2---4---7---2---5---5---2---4--- E 2---2---0---0---3---5---0---2---2---2---5---0---3---5---0---2--- ``` [Answer] **390 345 340 Postscript** Simplified to a guitar-pragmatic approach (the E shape is just a variation of the A shape, shifted down a string, with one finger change). Borrowed the encoded-string idea from the other answers. ``` [/p{print}/x{exch}/e{cvx exec}/d{dup 0 get}/f{forall}(A0#1B2C3D5E7F8G:b;){}forall/m{dup 4 2 copy get 1 sub put}109{m 48}/+{[3 1 roll x{1 index add x}f]}/*{[0 0 2 2 2 0 0]x{load e 48 sub +}f d 12 gt{-12 +}if d 6 gt{m -7 + 1}{0}ifelse 6 getinterval}>>begin[ARGUMENTS{*}f][(E)(A)(D)(G)(B)(e)]6{[x e p( )p]x[x{[x e( )cvs p(---)p]}f]x()=}repeat ``` *Previously:* **450 442 418 Postscript** I fixed the output format with this one, too. (Previous versions began "E---" rather than "e ".) ``` <</i{index}/a{add}/p{pop}/x{exch}/g{getinterval}/r{print}/f{forall}/e{exec}>>begin<<65[0 2 3 5 -5 -4 -2]{1 i 1 a}f p 35{1 a}98{1 sub}109{x dup 4 20 put x}>>begin[ARGUMENTS{[x[0 5 12 17 21 24 29 0]x{load e}f x{1 i a x}f]dup 0 get 0 ge{0}{1}ifelse 7 g[0 -5 -10 -15 -19 -24 -29]0 1 6{2 copy get 3 i 2 i get a 3 copy put p p}for x p 0 6 g}f][(E)(A)(D)(G)(B)(e)]6{[x cvx e r( )r]x[x{[x cvx e( )cvs r(---)r]}f]x(\n)r}repeat ``` How to run it: `gsnd -q -- tab.ps Bm Gb A E G D Em F\#` (hide the sharp from the shell). The *un-golfed* version was almost more difficult than the golfed one. But I tried to be thorough. *Edit: a few more comments on the tricksy-bits.* ``` %!PS << %axioms and operations /t{2 2 1} %major tetrachord /m{t t 2} %mixolydian mode /u{2 1 2} %minor tetrachord /a{u u} %aolian mode /s{m m t} %2.5-octave mixolydian intervals /r{3 1 roll} /${[exch 0 exch{1 index add}forall]} %running sum: convert (relative)intervals to (abstract)fretstops /+{[r exch{1 index add exch}forall pop]} %scale array by scalar /@{[r{2 copy get r pop}forall pop]} %select array elements from array of indices /&{0 1 3 index length 1 sub{ %array2 += array1 2 copy get 3 index 2 index get add 3 copy put pop pop}for exch pop} >>begin<< %map ascii values to scaling functions 65[a]$ %generate fretstops of the A aolian scale to assign scalars to note names [0 0 0 0 -12 -12 -12]& %drop E F and G down an octave {[exch/+ cvx]cvx 1 index 1 add}forall pop %generate the pairs 'A'->{0 +}, 'B'->{2 +} 35{1 +} %'#'-> scale up by one 98{-1 +} %'b'-> scale down by one 109{dup 4 2 copy get 1 sub put} %'m'-> tweak the 'third' down by one %generate chord pattern from (string) /*{[s]$ %generate fretstops of the E mixolydian scale [1 4 8 11 13 15 18] %A-shape figured bass: IV chord of E mixolydian -1 + %convert scale degrees to array indices @ %generate chord template by selecting indices from mixolydian scale exch{load exec}forall %execute ascii values, scaling the pattern dup 0 get 0 ge{0}{1}ifelse 6 getinterval %discard first note if it has fallen off the bottom [0 -5 -10 -15 -19 -24]&} %subtract the string offsets >>begin %activate definitions %(A)* pstack()= clear %[0 0 2 2 2 0] %(B)* pstack()= clear %[2 2 4 4 4 2] %(F#)* pstack()= clear %[2 4 4 3 2 2] %(Abm)* pstack()= %[4 6 6 4 4 4] [ARGUMENTS{*}forall] %convert array of strings to array of patterns [(E)(A)(D)(G)(B)(e)] %array of string names 6{ %for each "string" [exch cvx exec print( )print] %pop string name and print with space exch %put names behind numbers [exch{ %for each "chord" [exch cvx exec( )cvs print(---)print] %pop number, convert, print with trailing hyphens }forall] %zip up chord array for next iteration ()= %print a newline exch %put numbers behind names }repeat ``` And how about *House of the Rising Sun* as a test? ``` 04:51 PM:~ 0> gsnd -q -- tabb.ps Em G A C Em G B B Em G A C Em B Em B|sed 's/^/ /' e 0---3---0---3---0---3---2---2---0---3---0---3---0---2---0---2--- B 0---3---2---5---0---3---4---4---0---3---2---5---0---4---0---4--- G 0---4---2---5---0---4---4---4---0---4---2---5---0---4---0---4--- D 2---5---2---5---2---5---4---4---2---5---2---5---2---4---2---4--- A 2---5---0---3---2---5---2---2---2---5---0---3---2---2---2---2--- E 0---3---0---3---0---3---2---2---0---3---0---3---0---2---0---2--- ``` ]
[Question] [ *(Randomly inspired by <https://mathoverflow.net/q/339890>)* *(Related: [1](https://codegolf.stackexchange.com/q/12879/42963), [2](https://codegolf.stackexchange.com/q/89852/42963))* Given an input list of distinct prime numbers (e.g., `[2, 5, 7]`), and a integer `n`, output all positive integers strictly smaller than `n` that contain only those primes as divisors. For input `[2, 5, 7]` and `n=15` this means an output of `[2, 4, 5, 7, 8, 10, 14]`. **Further Examples** ``` [list] n | output [2, 5, 7] 15 | [2, 4, 5, 7, 8, 10, 14] [2, 5, 7] 14 | [2, 4, 5, 7, 8, 10] [2] 3 | [2] [2] 9 | [2, 4, 8] [103, 101, 97] 10000 | [97, 101, 103, 9409, 9797, 9991] [97, 101, 103] 104 | [97, 101, 103] ``` **Rules and Clarifications** * The input list is guaranteed non-empty, but may be only a single element * You can assume the input list is pre-sorted in whatever way is most convenient * `n` will always be larger than the largest element in the input list * Since, e.g., `2**0 = 1`, you can optionally include `1` in your output list * Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963) * You can print the result to STDOUT or return it as a function result * Either a full program or a function are acceptable * If applicable, you can assume the input/output integers fit in your language's native `int` range * [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] # [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ร‡โ”€โ˜ผ?โ–ฌยต ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=80c40f3f16e6&i=[2+5+7]+15%0A[2+5+7]+14%0A[2]+3%0A[2]+9%0A[103+101+97]+10000%0A[97+101+103]+104&a=1&m=2) ### Unpacked (7 bytes) and explanation: ``` vf:Fn-! vf Filter range [1..n-1]: :F Distinct prime factors n- Remove all in provided list ! Is empty? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Pmร‘ส’โ€บ ``` -1 byte thanks to *@ovs* (and *@Grimmy*, who provided [`sะธPร‘ส’โ€บ`](https://tio.run/##yy9OTMpM/f@/@MKOgMMTT0161LDr//9oIx3TWC5DAwA) as 6 bytes alternative initially). Takes the list as first input, and integer as second. Includes the optional `1` in the output. Extremely slow approach (the `[2,5,7], 15` test case already times out). [Try it online.](https://tio.run/##yy9OTMpM/f8/IPfwxFOTHjXs@v8/2kjHNJbL0AAA) (No test suite, because it's too slow for most.) **Explanation:** ``` P # Take the product of the (implicit) input-list # i.e. [2,5] โ†’ 10 m # Take the (implicit) input-integer to the power this product # i.e. 10 โ†’ 10000000000 ร‘ # Get all divisors of this integer # (the bottleneck for larger integers in this approach) # โ†’ [1,2,4,5,8,10,16,20,25,32,40,50,64,80,100,125,128,160,200,250,256,320,400,500,512,625,640,800,1000,1024,1250,1280,1600,2000,2500,2560,3125,3200,4000,5000,5120,6250,6400,8000,10000,12500,12800,15625,16000,20000,25000,25600,31250,32000,40000,50000,62500,64000,78125,80000,100000,125000,128000,156250,160000,200000,250000,312500,320000,390625,400000,500000,625000,640000,781250,800000,1000000,1250000,1562500,1600000,1953125,2000000,2500000,3125000,3200000,3906250,4000000,5000000,6250000,7812500,8000000,9765625,10000000,12500000,15625000,16000000,19531250,20000000,25000000,31250000,39062500,40000000,50000000,62500000,78125000,80000000,100000000,125000000,156250000,200000000,250000000,312500000,400000000,500000000,625000000,1000000000,1250000000,2000000000,2500000000,5000000000,10000000000] ส’ # Filter this list of divisors: โ€บ # Only keep those where the (implicit) input-integer is larger than the divisor # โ†’ [1,2,4,5,8] # (after the filter, the result is output implicitly) ``` --- **Two faster 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternatives:** ``` <Lส’fรฅP ``` Takes the integer as first input, list as second. Includes the optional `1` in the output. [Try it online](https://tio.run/##yy9OTMpM/f/fxufUpLTDSwP@/zc05Yo20jHVMY8FAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6H8bn1OTIorTDi8N@F@r8z862tBUJ9pIx1THPDZWRyHa0ASZZwzkgBmWMIahARDoACljHUMDQx1LqC4DoDZLc7AQUCo2NhYA). **Explanation:** ``` < # Decrease the (implicit) input by 1 L # Create a list in the range [1,input-1] ส’ # Filter it by: f # Get all prime factors of the current number (without duplicates) รฅ # Check for each if its in the (implicit) input-list P # And check if this is truthy for all # (after the filter, the result is output implicitly) ``` --- Thanks to *@Grimmy*: ``` GNfรฅPโ€“ ``` [Try it online](https://tio.run/##yy9OTMpM/f/f3S/t8NKARw2T//83NOWKNtIx1TGPBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VQmhP53j/BLO7w04FHD5P@1h7bZ/4@ONjTViTbSMdUxj43VUYg2NEHmGQM5YIYljGFoAAQ6QMpYx9DAUMcSqssAqM3SHCwElIqNjQUA). ``` G # Loop `N` in the range [1, (implicit) input): Nf # Get all prime factors of `N` (without duplicates) รฅ # Check for each if its in the (implicit) input-list P # And check if this is truthy for all โ€“ # If it is, output the current `N` with trailing newline ``` [Answer] # JavaScript (ES6), ~~64 ... 52~~ 50 bytes Takes input as `(n)(primes)` where *primes* is a set. Outputs by modifying the set. ``` n=>g=(s,q=1)=>{for(p of s)(p*=q)<n&&g(s.add(p),p)} ``` [Try it online!](https://tio.run/##lc/BDoIwDADQu1@xE2nNJEwkhGj5CY/GA4GNSMg2GNGD8dvnguGowZ6atq9pu@peuXq82WmnTSO9Iq@pbAkcH0gglU9lRrDMKOYQ7JYGPOkoasHFVdOARW7x5Z2cGDEtH@wsJ7jsecbzKx6ZApEhhG7Ia6Od6WXcm3aubH6gw2r0Aemf88XaeZGkXCSCF8tlSYi1uMhnG3Ys@Otf/g0 "JavaScript (Node.js) โ€“ Try It Online") ### Commented ``` n => // n = maximum value g = ( // g is a recursive function taking: s, // s = set of primes q = 1 // q = current product, initialized to 1 ) => { // for(p of s) // for each value p in s: (p *= q) // multiply p by q < n && // if the result is less than n: g( // do a recursive call: s.add(p), // with p added to the set p // with q = p ) // end of recursive call } // ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~68~~ 65 bytes ``` f=lambda s,n,c=1:n//c*s and f(s,n,s[0]*c)+f(s[1:],n,c)or[c][:c<n] ``` [Try it online!](https://tio.run/##dZBBasMwEEX3PsXglZUOxE4cUpl6UUoXXfUAiiiuIlNDIhtJpimmZ3dHtqEpoQNa6P33ZzHdl/9ozXYc6/JUnd@PFTg0qMqsMOu1WjmozBHqJEAnUrlS7I5@Iitk0FhrhZKiUA9Gjl47/6Yqpx2UIKJEbCTCFkFkCBvJcCF8IQg5wv3CEXYIe0qz3XUcIEmEU3r5jZz/I89ilm7DhwQ@2SnNXOD7JZgUnqc8sEA559ncvnamdn7blSySUVS3FjrbnLVDODXnxiPoSweNgd@TFBHQtL2n29TJH5tNUeWcth5ca70@JiQyKMuwB6GOD@bFdL0vgjjM5e@Dee39AgfyCTxfOq2oXsBARQLxtJoKxifxU2stxfBo3Ke2MRt/AA "Python 3 โ€“ Try It Online") *-3 bytes thanks to @xnor* The function takes a prime sequence and an integer n as inputs. The output is a list that includes 1. # Ungolfed: ``` def f(s, n, c=1): if not c < n: return [] elif not s: return [c] else: return f(s,n,s[0]*c) + f(s[1:],n,c) ``` [Try it online!](https://tio.run/##dZFBa4MwGIbv/ooXT2bLQauli8zDGDvstB9gwyhpZEIbJYmso@y3uy/qWLeyDzzkeZ83wpf@w791Jh/HvW7QJI7DcKgqY2UEmraB6TwU7mFmQmO1H6xBLSegD4vkrgT1bTj9Nwu/MtzVqbxRDLfhXGelJKbY6LXzr2rntEOFOkrqleTIOeqMYyUZX4hYCEfBcbdwjjXHhtJsfRkHSBLhlL7iSi7@kWcxS/NwIEFMdkozF8RmCSZFFKkILFAhRDa3L52pXVx3JYtkFDWdRW/bo6Z3OLTH1nPoU4/W4Gcl8ya7wdNumuSXzaZo55y29Byd9XqfkMhQVeEejibemmfTD74M4nkuf27Ny@AXeCafwNOp14rqJc5UJBBPV1PB@CR@7KylGA/GvWsbs/EL "Python 3 โ€“ Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 51 bytes For each prime `x` in the list of primes `p` the expression `mapM((<$>[0..n]).(^))p` computes all powers \$1,x,x^2,\ldots,x^n\$ (where \$n\$ is the second input just used as an upper bound) and then the cartesian product of all these sequences. After that we compute the `product` of all entries of this cartesian product and filter out all that are too large. This means that it is incredibly slow or might even crash if `n` is large or the list of primes `p` is large, as this cartesian product contains \$(\#p)^n\$ entries. ``` p#n=[k|k<-product<$>mapM((<$>[0..n]).(^))p,k<n,k>1] ``` [Try it online!](https://tio.run/##FcyxCsIwEADQXzlohgRisEJxSTt11C8IEYIKhmuuR3Ju/nvU7U3vlRo@t63nwnsVWJMkd8lNOg80B/ygP3DdH@@7eLWUxFetfwhH5ygap2/GsEVPFpcx9pIywQxcMwkoaP9RgR4MhJOFycI5wjj1Lw "Haskell โ€“ Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 39 bytes ``` l%n=[k|k<-[2..n-1],mod(product l^k)k<1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0c1zzY6uybbRjfaSE8vT9cwVic3P0WjoCg/pTS5RCEnLlsz28Yw9n9uYmaegq1CQVFmXomCioJCtJGOgqmOgnmsgqqCoel/AA "Haskell โ€“ Try It Online") Checks if `k` is divisible only by primes in `l` by seeing if the product of `l` taken to a high power is divisible by `k`. [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` lambda l,n:[k for k in range(2,n)if reduce(int.__mul__,l)**n%k<1] ``` [Try it online!](https://tio.run/##TYrLCoMwFAX3fsXdFBIJYnwgSvslqQRbkxoSrxIMpV@fRrrp5gxzmP1zLBtWUd/u0U3rY57AMRyEBb15sGAQ/IQvRSqG1Gjwag5PRQwehZRrcFIyR/McL/bKx/hejFPAh92nADTJDe7hIJRGUTFoGXQjA95m/9YkS6x/6DPRd@kt@Tn1GZTNFw "Python 2 โ€“ Try It Online") Checks if `k` is divisible only by primes in `l` by seeing if the product of `l` taken to a high power is divisible by `k`. If `l` can be taken as a list of strings `eval("*".join(l))` [saves 3 bytes](https://tio.run/##TYxNCoMwFIT3nuIhFBIJxfiDaOtJrIuUmhoTnyFNW3r6NNJNN/Mxw8zYj583LILsL8GI9XoTYBh2gwa5OdCgEJzA@0QKhlRJmF7CkDRLj8umkBhKswwP@szH8J6VmYB3cd4rtE9P6Mk6hR4kWYUlD@@YofElDAWDmkEzMuB18u@q6CLLH9pkaJuY5nyXci/k1Rc) over `reduce(int.__mul__,l)` and can be used in Python 3 which lacks `reduce`. **[Python 3](https://docs.python.org/3/), 64 bytes** ``` def f(l,n,P=1): for x in l:P*=x n-=1;P**n%n or print(n);f(l,n) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI0cnTyfA1lDTikshLb9IoUIhM08hxypAy7aCSyFP19bQOkBLK081TwEoV1CUmVeikadpDdal@T9NI9pIR8FUR8E8VkfB0ETzPwA "Python 3 โ€“ Try It Online") A function the prints in reverse order and terminates with error. The recursive solution below would be shorter if `n` itself were included in the list. I tried recursively computing the product of `l` as well, but that was longer. **62 bytes (non-working)** ``` f=lambda l,n:n*[f]and[n][reduce(int.__mul__,l)**n%n:]+f(l,n-1) ``` [Try it online!](https://tio.run/##TYpNCsMgGAX3OYWbglpbYn4IEXoSEbFVScB8kaCUnt4auunmDfOY@EnLDl0p/hHM9rQGBQYCqPTKgJWg5OFsfjm8QrprveWgNQuEUriAUFePa37jpLyXNTjERTxqiDymK8ScMCFFdgyNDE2KIT42/zZUq@x/mBs5T/Vt@Tn9GbTDFw "Python 2 โ€“ Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 25 bytes [SBCS](https://wikipedia.org/wiki/SBCS) ``` {โบ{v/โจโบ>vโ†โˆช,โˆ˜.ร—โจโต}โฃโบโŠข1,โต} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR767qMv1HvSuADLuyR20THnWs0nnUMUPv8HSw4NbaR72LgXKPuhYZ6oC4/9MUgKoU0kBKe/sedTU/6l3zqHfLofXGj9omPuqbGhzkDCRDPDyD/xsaKKQpGCkYK5gCAA "APL (Dyalog Unicode) โ€“ Try It Online") **How it works**: The main idea of this solution is that we take the input primes `โต`, we prepend 1 to them with `1,โต` and we multiply these numbers all together a bunch of times, where "a bunch of times" is the `n` input (refered to by `โบ`). This repetition is controlled by `โฃโบ`. What we actually repeat is the inner dfn `{v/โจโบ>vโ†โˆช,โˆ˜.ร—โจโต}` This dfn takes as `โบ` the input `n` and as `โต` the multiplications we have so far. Then, `โˆ˜.ร—โจโต` multiplies all those accumulated multiplications so far with themselves, into a matrix that looks like a "times table" of `โต` with itself. Then `โˆช,` flattens and removes duplicates and assigns that to `v` with `vโ†`. Finally, `v/โจโบ>v` filters out elements greater than or equal to `โบ`, which is the `n` input. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 10 bytes ``` โ€ฆ@eโŸชแธโ€กโป!โŸซโ‡ ``` [Try it online!](https://tio.run/##ASoA1f9nYWlh///igKZAZeKfquG4jeKAoeKBuyHin6vigYf//zE0ClsyIDUgN10 "Gaia โ€“ Try It Online") I've never used `โ€ก` with a monad before, it's quite helpful for stack manipulation. ``` โ€ฆ | push [0..n-1] @e | push list of primes โŸช โŸซโ‡ | filter [0..n-1] for where the following predicate is true: แธโ€ก | the list of prime factors โป | minus the list of primes ! | is empty ``` [Answer] # [J](http://jsoftware.com/), 24 bytes ``` (]#~0=1#.(-."1~q:))2}.i. ``` [Try it online!](https://tio.run/##bYwxCsJAEEX7nOKTFEnAHXaSDcksbCVYWdlbiYvaiAcwV19nDWJAB34x77@ZWyqpjggeNTaw8BpD2B72u9Qcq9kGrqgxVPL88G3bPelKqS2K8@lyRweHASMmsAU7GK8ogwge/ijr3n36oInov/q0eBGyMBn1ljU9xFnRXYmIcPYyza28n1od/Fypttqy5tIL "J โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` แน–ร†ffฦ‘ยฅฦ‡ ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//4bmWw4ZmZsaRwqXGh////zE1/zIsNSw3 "Jelly โ€“ Try It Online") A dyadic link taking the exclusive upper bound as its left argument and the list of primes as its right. Returns a list that includes 1 as well as the numbers only composed of the supplied primes. An alternative 7 would be `แน–ร†fแธŸยฅรแธŸ` [Answer] # [Python 2](https://docs.python.org/2/), 98 bytes ``` lambda a,n:[i for i in R(2,n)if{p for p in R(2,i+1)if(i%p<1)*all(j%p for j in R(2,p))}<=a] R=range ``` [Try it online!](https://tio.run/##PcqxCsIwEIDhvU9xSyGnGUxUQqV5ia7qcKLRKzENoYuUPHu0Sl3@4eOPr/ExBF2cPRVPz8uVgGQ4HBnckICBA3RCy4Dspvi1uBiv1UcF17FVuCLvRV//ln5ZImJuLZ2rziYK91uJicMITkxa7qXJ0mD1p8ZIUBs1Z5vn7rC8AQ "Python 2 โ€“ Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), ~~11~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` k รจ@e!รธV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=awroQGUh%2bFY&input=MTUKWzIsNSw3XQ) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ยฉk e!รธV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=qWsgZSH4Vg&input=MTUKWzIsNSw3XQ) [Answer] # [Ruby](https://www.ruby-lang.org/) `-rprime`, 61 bytes ``` ->n,l{(2..n).select{|i|i.prime_division.all?{|b,|[b]-l==[]}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ6daw0hPL09Trzg1JzW5pLomsyZTr6AoMzc1PiWzLLM4Mz9PLzEnx766JkmnJjopVjfH1jY6tra29n@BQlq0oamOQrSRjgKQMo@N/f8vv6AEqKH4v24R2AgA "Ruby โ€“ Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 64 bytes ``` \d+ $* \G1 $.`,$`; +`,(1+)(\1)*(?=;.* \1\b) ,1$#2$* !`\d+(?=,1;) ``` [Try it online!](https://tio.run/##RYu7CsJAEEX7@YoRV9jHEHITQwiLWOYnphhFCxsL8f83kyrN4XAfv/f/8320S1yt6atQyKQrKHQmwSoVk4iSoiLleL/VLrNCn4kE4Tz4@GT@8kZQU2uYKg/Ck/BMuB4@utKyA73HyyyMHjvGDQ "Retina 0.8.2 โ€“ Try It Online") List includes smaller test cases (`10000` times out because of all the long strings). Takes input in the order `n f1 f2 f3...` (factors do not need to be prime but they do need to be coprime). Output includes `1`. Explanation: ``` \d+ $* ``` Convert to unary. ``` \G1 $.`,$`; ``` Generate a list from 0 to `n-1`, in both decimal and unary. ``` +`,(1+)(\1)*(?=;.* \1\b) ,1$#2$* ``` Repeatedly divide the unary by any available factors. ``` !`\d+(?=,1;) ``` Output the decimal numbers where the unary number has been reduced to `1`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` f!-PThQtUe ``` [Try it online!](https://tio.run/##K6gsyfj/P01RNyAkI7AkNPX//@hoIx1THfNYHUPTWAA "Pyth โ€“ Try It Online") Takes input as `[[primes...], n]` ``` Ue # range(0, Q[-1]) (Q is the input, implicit) t # [1:] -> range(1, Q[-1]), tUe == PSe f # filter that on the condition: lambda T: PT # prime_divisors(T) - hQ # - Q[0] ! # logical negation (![] == True) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 27 bytes ``` {grep [*](@^a)**$^b%%*,^$b} ``` [Try it online!](https://tio.run/##bYxNC4JAFEXX@ivuQmNmHFJTS5OgFu1at3FGUNIIskRXof5282NRQYv3ePe8wy2z6r7uixcWOXZ9c62yEhGTZB8nlDEtTnWd8VhLuz5/ViD32yOrKRpVKba1SUS0ZEJSEHExKERrhqpSJy/kRLOWx/PhxGFoNg3Vro9WHB7HRsL20GKM7kw4fA7bGsaV6pfm/tVGRcKZfvMdfDx/IMFm1OxxOUOLNdX8wDc "Perl 6 โ€“ Try It Online") Port of xnor's Haskell solution. Also outputs 1. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~22~~ 20 bytes ``` ๏ผฉฮฆโ€ฆยฒฮทโฌคโ€ฆยทยฒฮนโˆจ๏นชฮนฮปโŠ™ฮธยฌ๏นชฮปฮฝ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zpyS1SCMoMS89VcNIRyFDU0fBMSdHwzMvOae0OLMsFS6TCZTxL9LwzU8pzcnXyNRRyAEpzavUKNRR8MsvgUnk6CjkaUKB9f//0dFAraY6CuaxOgqGprH/dctyEgE "Charcoal โ€“ Try It Online") Link is to verbose version of code. Too slow for the larger test case. Explanation: ``` ฮฆ Filter on โ€ฆ Range from ยฒ Literal `2` to ฮท Input limit โฌค Where all values โ€ฆยท Inclusive range from ยฒ Literal `2` to ฮน Filter value โˆจ Either ฮป Inner value ๏นช Is not a divisor of ฮน Filter value โŠ™ Or any of ฮธ Input primes ฮฝ Current prime ยฌ๏นช Is a divisor of ฮป Inner value ๏ผฉ Cast to string for implicit print ``` Previous faster 22-byte answer: ``` โŠžฯ…ยน๏ผฆฯ…๏ผฆร—ฮนฮธ๏ผฆโ€บโ€นฮบฮทโ„–ฯ…ฮบโŠžฯ…ฮบ๏ผฉฯ… ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gtDhDo1RHwVDTmistv0hBo1RTAUyHZOamFmtk6igUakJF3ItSE0tSizR8UouLNbJ1FDI0dRSc80vzSkD6szWBymCGZQMNCyjKBMo4JxYDpTU1rf//j442NDAGWmRgqKNgaR4LYgFB7H/dshwA "Charcoal โ€“ Try It Online") Link is to verbose version of code. Output includes `1`. Explanation: ``` โŠžฯ…ยน ``` Push `1` to the predefined empty list. ``` ๏ผฆฯ… ``` Loop over the list, including any items pushed to it during the loop. ``` ๏ผฆร—ฮนฮธ ``` Multiply the current item by each prime and loop over the products. ``` ๏ผฆโ€บโ€นฮบฮทโ„–ฯ…ฮบ ``` Check whether the product is a new value. ``` โŠžฯ…ฮบ ``` If so then push it to the list. ``` ๏ผฉฯ… ``` Print the list. [Answer] # [C (clang)](http://clang.llvm.org/), 115 bytes ``` #define f(n,l,z){int j,i,k,x[n]={};for(i=x[1]=1;i<n;printf(x[i]+"\0%d ",i++))for(j=z;j--;k<n?x[k]=x[i]:0)k=i*l[j];} ``` [Try it online!](https://tio.run/##dZHRaoMwFIbvfYrgGCTzSBOjFJeGPUgqo1QdUZsVa0EqPrszOodl7cnl9/055M/RP1YH8zVo06BzrU/Z5ZOpRHYBRLDtxWbDIgc9npGFzioXTDmb4c5DPV7b3NqMckCMMkDxvIxSupZCK8XbX2e0ZykcXtIs1yZDOTZQwY10NlSAhhJaZcZQL/LvGmvZKpZIJvTOiPFO0@S4VTrx3D19TZEL2vMIsWYhb6LwfVHuzEerykRa7Z2SUuq3ShWJ6KeKTgdtMEGdk2MWwVIYcOKcr80Fuy4RFoVPEV9IAOyexE@JbYUulP9bRv@2hfdsnPnNCLt7g5A/ncykFtovqbPmWhtEhdMPPw "C (clang) โ€“ Try It Online") A Sieve of Eratosthenes based solution. (Includes 1 in the output) Thanks to @ceilingcat suggestion : printf(x[i]+"\0%d ",i++) instead of x[i]&&printf("%d ",i),i++ I suppose it shifts the pointer of the literal but didn't found any documentation, if anyone can give me some insights it would be welcome. [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` fศฏยฆโฐupล€ยฒ ``` [Try it online!](https://tio.run/##ASEA3v9odXNr//9myK/CpuKBsHVwxYDCsv///zE1/1syLDUsN10 "Husk โ€“ Try It Online") ]
[Question] [ **This question already has answers here**: ["Hello, World!"](/questions/55422/hello-world) (974 answers) Closed 7 years ago. Is it possible to write (pack) a shorter than 145 bytes version of a program with "Hello world" (plus new line) output if the length of the program is measured as a number of bytes in program's ELF (x86) representation? Reduction technique in mind is described here: 1. <http://timelessname.com/elfbin/> 2. <http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html> Please reply with providing a code example. Note, [1](http://en.wikipedia.org/wiki/Executable_and_Linkable_Format#Specifications) says "Hi world" and [2] returns 42 instead of an output, hence I assume current solution to be *142 + (len("Hello") - len("Hi"))* which is **145**. **[EDIT]** **Limits of ELF**: syntactically a program translated into ELF is determined by its interpreter (libc), which is a combination of: * Target architecture (Generic, AMD64, ARM, IA-32, MIPS, [etc.](http://en.wikipedia.org/wiki/Executable_and_Linkable_Format#Specifications)) * OS kernel (which communicates with implementation of ELF interpreter and often is itself packed into an ELF binary) From TIS spec. 1.2 > > There is one valid program interpreter for programs conforming to the > ELF specification for the Intel architecture: /usr/lib/libc.so.1 > > > In theory - all clear - multiple combinations times version differences (Arch, OS) are possible. In practice - because standard is less strict than any BNF for CFG or other finer (smaller) formal language - there can be implementation differences (options) including shorter length of the program. On one hand, because ELF is not that precise (one naturally expects) it is much more difficult to do code-golf with it. Hence a "Hello world\n" program is expected to be by default in **TIS ELF 1.2, x86 (Generic Intel), Linux 2.6.(20+)**. On the other hand having a shorter ELF that runs e.g. on \*BSD seems like an extremely valuable knowledge to me! For example ELF64 (latest draft) is much more interesting incl. the differences with ELF(x86). So, *please* share a solution that can be accepted with correction to specific configuration. *Motivation*: It is the practical part that is interesting for me and code-golf is a very nice way to show how tricky it is to come up with any machine- (or even byte) code in general and why ELF does apparently such a good job (in my understanding). Thus a golf solution is not only cool per say but also can provide a practical knowledge of unexpected interpretation differences of ELF (if an alternative combination is given). [Answer] Even if you require full adherence to the ELF specification, you can squeeze it into 98 bytes: ``` org 0x04B34000 db 0x7F, "ELF", 1, 1, 1, 0 ; e_ident dd 0, 0 dw 2 ; e_type dw 3 ; e_machine dd 1 ; e_version dd _start ; e_entry dd phdr - $$ ; e_phoff dd 0 ; e_shoff dd 0 ; e_flags dw 0x34 ; e_ehsize dw 0x20 ; e_phentsize phdr: dd 1 ; e_phnum ; p_type ; e_shentsize dd 0 ; e_shnum ; p_offset ; e_shstrndx db 0 ; p_vaddr _start: inc eax mov bl, 4 mov dl, 12 ; p_paddr jmp short part2 dd filesize ; p_filesz dd filesize ; p_memsz dd 5 ; p_flags dd 0x1000 ; p_align str: db 'Hello world', 10 part2: mov ecx, str again: xchg eax, ebx int 0x80 jmp short again filesize equ $ - $$ ``` Or if you prefer hex bytes: `7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 35 40 B3 04 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 40 B3 04 B2 0C EB 1C 62 00 00 00 62 00 00 00 05 00 00 00 00 10 00 00 48 65 6C 6C 6F 20 77 6F 72 6C 64 0A B9 4C 40 B3 04 93 CD 80 EB FB` The ELF specification explicitly permits different sections to overlap, so it is perfectly legal to let the program segment header table share bytes with the ELF header. Furthermore, the x86 version of the ELF standard states that the p\_paddr field is *ignored*, as opposed to merely being *unused* (which typically comes with the requirement that it be set to zero. Thus it is safe to contain arbitrary bytes. Finally, three more bytes are saved by overlapping the code with the load address. [Answer] Looking at link [2] [A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux](http://www.muppetlabs.com/%7Ebreadbox/software/tiny/teensy.html), by appending the literal string 'Hello, world!' to the end (instead of letting the last 7 bytes auto fill with zeros), you should be able to squeeze it to 59 bytes, assuming your print logic isn't longer than 8 bytes. In fact, the user 'breadbox', who I assume to be the writer of the post, has posted a 57 byte version on [anarchy golf](http://golf.shinh.org/l.rb?out). It might be useful to look at some of his other post mortems: they seem to be all ELF format. ### EDIT: 61 bytes Using breadbox's nested header approach, I was able to produce this 61 byte solution: ``` BITS 32 org 0x05000000 db 0x7F, "ELF" dd 1 dd 0 dd $$ dw 2 dw 3 dd 0x0500001B dd 0x0500001B dd 4 mov dl, 12 mov ecx, msg int 0x80 db 0x25 dw 0x20 dw 0x01 inc eax int 0x80 msg db 'Hello world', 10 ``` Assemble as: ``` nasm -fbin hello.asm chmod +x hello ./hello ``` Producing: ``` 00000000 7f 45 4c 46 01 00 00 00 00 00 00 00 00 00 00 05 |.ELF............| 00000010 02 00 03 00 1b 00 00 05 1b 00 00 05 04 00 00 00 |................| 00000020 b2 0c b9 31 00 00 05 cd 80 25 20 00 01 00 40 cd |...1.....% ...@.| 00000030 80 48 65 6c 6c 6f 20 77 6f 72 6c 64 0a |.Hello world.| ``` The code begins at 0x001B: ``` 0540000000 add eax, 0x00000004 ;sys_write B20C mov dl, 12 ;message length B92E000005 mov ecx, msg ;message pointer CD80 int 0x80 ;syscall 2520000100 and eax, 0x00010020 ;clears eax 40 inc eax ;sys_exit CD80 int 0x80 ;syscall ``` The 32-bit `add` is necessary (instead of `mov al, 4` for example), because it's also used as the program header offset, and needs to be exactly 4 (where the program header starts in the above code). The `and` later on is used to clear eax, because 0x20 and 0x01 are unavoidable header values. ### EDIT: 111 bytes (with proper headers) If, on the other hand, you'd rather your headers adhere to the ELF specifications (even if your kernel ignores them), you could use this instead: ``` BITS 32 org 0x08048000 ehdr: ; Elf32_Ehdr db 0x7F, "ELF", 1, 1, 1, 0 ; e_ident times 8 db 0 dw 2 ; e_type dw 3 ; e_machine dd 1 ; e_version dd _start ; e_entry dd phdr - $$ ; e_phoff dd 0 ; e_shoff dd 0 ; e_flags dw ehdrsize ; e_ehsize dw phdrsize ; e_phentsize dw 1 ; e_phnum dw 0 ; e_shentsize dw 0 ; e_shnum dw 0 ; e_shstrndx ehdrsize equ $ - ehdr phdr: ; Elf32_Phdr dd 1 ; p_type dd 0 ; p_offset dd $$ ; p\_vaddr dd $$ ; p_paddr dd filesize ; p_filesz dd filesize ; p_memsz dd 5 ; p_flags dd 0x1000 ; p_align phdrsize equ $ - phdr _start: mov al, 4 mov dl, msg_len mov ecx, msg int 0x80 mov al, 1 int 0x80 msg db 'Hello world', 10 msg_len equ $ - msg filesize equ $ - $$ ``` It's tempting to overlap the last 8 bytes of the ehdr with the first 8 bytes of the phdr, since they are identical (and therefore, all headers would be correct), but in the spirit of being proper, I decided not to. This assembles to a 111 byte solution: ``` 00000000 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 |.ELF............| 00000010 02 00 03 00 01 00 00 00 54 80 04 08 34 00 00 00 |........T...4...| 00000020 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 |........4. .....| 00000030 00 00 00 00 01 00 00 00 00 00 00 00 00 80 04 08 |................| 00000040 00 80 04 08 6f 00 00 00 6f 00 00 00 05 00 00 00 |....o...o.......| 00000050 00 10 00 00 b0 04 b2 0c b9 63 80 04 08 cd 80 b0 |.........c......| 00000060 01 cd 80 48 65 6c 6c 6f 20 77 6f 72 6c 64 0a |...Hello world.| ``` ]
[Question] [ Given two nonempty arrays of natural numbers \$a\$ and \$b\$, return the shortest nonempty array of pairs of natural numbers \$q\$ such that the sequence of first elements of \$q\$ consists of a whole number of repeated copies of \$a\$, and the sequence of second elements of \$q\$ consists of a whole number of repeated copies of \$b\$. When \$a\$ and \$b\$ have the same length, this acts like a zip, but when the lengths of \$a\$ and \$b\$ are coprime, this acts like a Cartesian product. You can use any reasonable input and output format for arrays (pointers, lists, space-separated strings, strings of char codes, etc.) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer (measured in bytes) wins. ## Test Cases ``` [1], [2] -> [(1, 2)] [1, 2], [3] -> [(1, 3), (2, 3)] [1, 2], [3, 4] -> [(1, 3), (2, 4)] [1, 2, 3, 4], [5, 6] -> [(1, 5), (2, 6), (3, 5), (4, 6)] [5, 5, 5], [5, 5, 5] -> [(5, 5), (5, 5), (5, 5)] [5, 5], [5, 5, 5] -> [(5, 5), (5, 5), (5, 5), (5, 5), (5, 5), (5, 5)] [1, 2, 3, 4], [1, 2, 3, 4, 5, 6] -> [(1, 1), (2, 2), (3, 3), (4, 4), (1, 5), (2, 6), (3, 1), (4, 2), (1, 3), (2, 4), (3, 5), (4, 6)] ``` [Answer] # [J](http://jsoftware.com/), ~~14~~ 13 bytes ``` ,./@($&>~*./) ``` [Try it online!](https://tio.run/##dY9NCsIwEIX3PcVDim2lTc3kZ9GiCIIrV15BLOLGG3j1OFOTakUJGV6G703e3MJCFQM2HQrUWKPj2yjsT8dDqFW7K/Pl9rFSbRWqLLucr3eUGoQcXCs0nTx7kQN3dCQoEgYsTMKIQSMg/QbtDJSnoBRRG1EnqAcDrCz828QWNjppDSyT0YxG9@Ic5PRjdcIZPhH03@AHxtPT9imzliCEcQJ/ZzELp6VHmHb7HzipKbgPTw "J โ€“ Try It Online") *-1 byte thanks to Bubbler* This answer takes the two lists as its left arg, and the two list lengths as its right arg. * `($&>~*./)` is a dyadic hook which applies gcd between the two right arg lengths `*./` and the reshapes the two left arg lists `$` to that length after opening them `&>`. At this point they'll be the same length so boxing is no longer needed. * `[:,./` so now we can just zip them `,.` --- ## original answer taking the lists directly ## [J](http://jsoftware.com/), ~~17~~ 16 bytes ``` (*.&#$[),.*.&#$] ``` [Try it online!](https://tio.run/##dY49C8IwEIb3/ooXLbaRNpjLxxBwEpycXMVJLMXF/z/FS7wWK0pI7sjzHPc@0ko3A/YRDTrsEPn2Gofz6Zjard6s64vqdGmuSVXV/TY@0RoQavCr0EeuA0gICbHgxgomFuwvwX0KcKI4UXxWAphw5xBmmVUe8AgyYMuAL9yXM7yr8PDFl9RMkUzeR3mfzfscFhlM/iPM0f/mmjrOl14 "J โ€“ Try It Online") * `*.&#` is the gcd `*.` after taking length `#` of both args It turns out to be shorter to repeat this phrase than to remain DRY. * `,.` is zip and and `$` is shape. So we shape the left arg `[` by the gcd of the list lengths, do the same to the right arg `]`, and zip them. [Answer] # [C (clang)](http://clang.llvm.org/), ~~70~~ 68 bytes ``` i;f(*a,*b,x,y){for(i=0;printf("(%d,%d)",a[i%x],b[i%y]),++i%x+i%y;);} ``` [Try it online!](https://tio.run/##hZDdboMwDIXveQqrVaVk9X5ICL1g2@VeguWCFLpF6mjVUmldxbN3TgiMdpMmBNjHn53jLG@X66J@O59ttmI3Bd4Y/MQjP602O2afHrLtztbNik3YrMRZySdY5Hb2qdHQ76g5zueU0nvMeNaep7Zerg9lBY/7prSbu/fnKJqW1crWFbywAg2HfmAOE05HkoZ7@1VtKOT3ISKC96q5UHm2PTR7NgH9WlN/FJEIH4WtGYdTBC4r4lzDE5ziFsGEWLRZ5AzEaGIeBU4EDoUjQyYDKdCIgZQXZMgkJoGVaOTAJgOLjiA@KArTwCdokoFXfZUeR1/kHa/QqIFPh7qj0990iiYd6EXvBgSCRPCGfokICqF3t0CzcP27qjnsanjIovacxxpyoeH2GRhtRuXcdZMoNTg1JxkkZ24g16MyTddXQDIA3emEueNHg5TnUs6kjxMXux7ljaquoYt8i/LY6NvD/5N/947MIeTXF/WzUOyNCm9UeqMJ7xZA6FZAV4p9SfDxHVzs9g0 "C (clang) โ€“ Try It Online") Takes input as pointer to `a` and `b` and the lengths, prints `q` to std out. We use the modulo of an iterator by the data lengths e.g. `i % x` and `i % y` to access data, when both modules are equal to 0 , `i` is LCM and the function terminates. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แนโ‚ฌรฆl/}Z ``` A dyadic Link accepting a list of the two lists on the left and a list of their respective lengths on the right which yields a lists of lists. (A monadic Link accepting only the left argument costs 8 bytes, `แนโ‚ฌแบˆรฆl/$Z`) **[Try it online!](https://tio.run/##y0rNyan8///hzsZHTWsOL8vRr436//9/dLShjoKRjoKxjoJJrI4CEk9HwVRHwSw29n@0CYgGAA "Jelly โ€“ Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hzsZHTWsOL8vRr436f3j5w10dRyc93DlDM/L//@joaMNYHQU4iDaKjeXSAQrqKBjBxaONsQrqKJggxHUUwHwdhWhTHQUziDiQBUIQLXAeXAphFIoUqmkIHlgNyORYAA "Jelly โ€“ Try It Online"). ### How? ``` แนโ‚ฌรฆl/}Z - Link: list of lists [a, b], list [length(a), length(b)] } - use the right argument as the left argument of: / - reduce by: รฆl - least common multiple (i.e. LCM(length(a), length(b)) โ‚ฌ - for each list in the left argument (i.e. for x in [a,b]): แน - mould like (i.e. repeat x cyclically until its length is the calculated LCM) Z - transpose ``` [Answer] # [R](https://www.r-project.org/), ~~69~~ ~~60~~ ~~54~~ 51 bytes ``` function(a,b,x,y)cbind(rep(a,y/sum(!(1:x*y)%%x)),b) ``` [Try it online!](https://tio.run/##JYpBCoAgFAX3ncIWgj9ehGUtpMtkJbTIohL09Ca1GYZhrmTZWLNkvZuf7XBigkFApNlsbhHXeuYSm9vvohRShyoS54EIhpLNYYDUCgMUFfa7e3SEX1pCl5Fe "R โ€“ Try It Online") Loosely based on [my answer to this question](https://codegolf.stackexchange.com/a/143726/67312). Takes `a`,`b`, and the lengths as `x` and `y`, respectively. Returns a two-column matrix. Thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder) for [saving 4 bytes](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jUSdJp0KnUqfQ1tCqQqtSMzkpMy9Foyi1ACiTm5mnURitWKiqWhGrqV@hqZOk@T9Nw9DKTMfQykTHTMdEkysNrNRUx1hTB8Iw0tQxBhL/AQ), and then another 3. Relies on the identity \$xy=GCD(x,y)\cdot LCM(x,y)\$; repeats `a` by \$y/GCD(x,y)\$ times to get it to the LCM length, and `cbind` automatically recycles `b` accordingly. [Answer] # [J](http://jsoftware.com/), 8 bytes ``` *.&#$&>; ``` [Try it online!](https://tio.run/##hY@9DoIwGEV3nuJGCYKBxv7AUKODJk7GwZW4qKBxcXLz3evXAg0iiWna3rbnJLcPM2GzGiuNGVIsoGlmDNvjfmfmLJqG0XppcNgwBLE7l0nKXDgFSXCtzq@blcvqcn8GdkH81hwCIWhNkGk0UJzyBDVS4SnRUhIUZA@1OpFynFQ/pITyqGrR3KIF6I2SQjGQSCExR@FF6cS8x@Vu1M3uuWKUG1K8q8xtD2F7SNtD4asbt3cC/mt/@naJepsP "J โ€“ Try It Online") Takes two vectors as left/right args and gives a two-row matrix where each column represents a pair. If you insist a two-column matrix, prepend `[:|:` to the code, which is still shorter than [previous J answer](https://codegolf.stackexchange.com/a/197934/78410). ### How it works ``` *.&#$&>; NB. Tacit function; left=vector 1, right=vector 2 ; NB. Nested 2-item vector of two vectors $&> NB. Disclose each and recycle to the length of... *.&# NB. LCM of the lengths NB. Two disclosed vectors automatically form a 2-row matrix ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` โ‚ฌg.ยฟฮดโˆรธ ``` Takes the input as a pair of lists of integers. [Try it online](https://tio.run/##yy9OTMpM/f//UdOadL1D@89tedTRe3jH///R0YY6CkY6CsY6CiaxOgpIPB0FUx0Fs9hYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLjufx/1LQmXe/Q/nNbHnX0Ht7xX@fQNvv/0dHRhrE60UaxsToKQKaOEZBjjMLRMYFzdUAcnWhTHTOIkKkOEIIFQDRMCFUAoQ3K0gFrjwUA). **Explanation:** ``` โ‚ฌg # Get the length of each inner list in the (implicit) input-pair of lists .ยฟ # Take the Least Common Multiple for the two values in this pair of lengths ฮดโˆ # Extend both inner list in the (implicit) input-pair of lists to this length รธ # Then zip/transpose the (now equal-length) list of lists, swapping rows/columns # (after which the result is output implicitly) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~39~~ ~~36~~ 25 bytes *-3 bytes thanks to Jo King* ``` {zip $_>>[^[lcm]($_)X%*]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/uiqzQEEl3s4uOi46Jzk3VkMlXjNCVSu29n9xYqVCGlBKIS2/iEtDw1BHU0dBw0hHU1MHzFMwAvGNMfgKJggRHQUwHyhuqqNgBhEHskAIKghmwsUxBFENQfDAaoAG/gcA "Perl 6 โ€“ Try It Online") ### Explanation ``` { } # Anonymous block $_>>[ ] # Index into both input arrays ^[lcm]($_) # Range [0,lcm) X%* # modulo array size zip # Zip ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~85~~ 76 bytes ``` n;z(a,i,j)int*a;{for(n=0;a[n*2+i+j]=a[n%i],a[n+++n+i+j]=a[n%j+i],n%i+n%j;);} ``` [Try it online!](https://tio.run/##bZHdcoIwEIXveYpIx5nErBVsbevE9EWUC0DUMHQtFKczMjw73YD4V2824ezhy@YkHm/juHkyGGeHdbL4Kddm/7z7dK6VzER3UmFwayXHYMmO3NYRMLt0Vaiu9RUa5MKpHNbKBlJgqD11@g6XvucFuvJhCi/wCjN4g3f4gDl4tWJGz3tj9M9oDameWcNkYrQdQTAaLEuQh8L2bqRI9KjcolpYbaXNvmDcjoQLo1BKQQYMdEjlrp2e29IEOjoZjjwHulaL/6ZYyg13Q82HaxfCpRe0OmrfLr87kyWMW/RAe@Jsh85M9OAGI1YYdaToMSl6SIoeknLtnghGpleMvGeQxFjV/0HHEkwwF6zBFukTE6WeqtbJzIbxAec4NuNUDH1PXMZYYXcWYzXVIikPBTJ69LpBdeRhmxc5R6GqKN82Xrr@aCpptDb6oQm6QCRetJRiB2pJ2iqh6qb5Aw "C (gcc) โ€“ Try It Online") Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for reduction 85->76 bytes. The code above is golfed so that all the information is stored in a single integer array, which saves 2 bytes; the logic though is the same as previously with three arrays. [Try code with three arrays online](https://tio.run/##bZHdcoIwEIXv8xQrHWcSiRXs/6TpiyAXCaLGoVEQxxkZXr10E6q11psNe86ZbzchGy@zrMtWqgKVxFGUyibmU/7AH/kTf@Yv/JW/8agVxEf0v8jZKp3lTVSMrcHwNQcrI9EdKWvmm6ZM7GiaSpXYoUkFdmEY2lRq7NepaA8rU@QUvRB7Jtruztis2M/z9109N5v71Qe5VAqjr6TK2KWTyGTi5h/NlvrNRhyuT@f3lQnit/1UxlJGGgJednu7T0mxY4DwIrdUMQHrv5JmLoc3RA7AFneoFzRQkg7nAVdJlHrfytgd/opA8QXSgYzYOc77MD5IHz/pbGZ1T9K3SfomSd8klTL4IUQXhPJEQAmgOeVxKKIYBNwFXAljJNpQToVPglkAHeDviiP2O35m@xkALdYqr/eVBRzXEtJ9ZYtCLXfd@PAN) this code has less bytes, but the arrays are global so that information is not directly passed in or out of function. # How description of algorithm with ungolfed code or at least less golfed code. setup (see online code) * `a[],b[]` input data - `q[]` output data * `i,j` length of `a,b` * `n` loop counter ``` do{ }while(n%i+n%j);} // open loop that ends when counter mod i and j =0 q[n*2]=a[n%i]; // q[0,2,4...]=a[0,1,2...] q[n+++n]=b[n%j]; // q[1,3,5...]=b[0,1,2...] and increase loop counter ``` In the golfing process all the data input and output was put into a single `int` array. The first `i` members are the contents of `a`, the next `j` members are the contents of `b` and the remainder of the array is filled with zeroes so that when `q` is calculated it can be placed directly after the `b` items in the same array the first zero in the array indicates `q` end. This use of a single integer array for data input and output saves 2 bytes. OP has indicated that this approach is acceptable for this challenge. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 35 bytes ``` {$^a <<,<<flat $^b xx($a lcm$b)/$b} ``` [Try it online!](https://tio.run/##ZYxBCoMwFET3nmIWH0ngQ9FWV@lVlKQ0q4iiLgy2Z48xLZUizGLeY5jhObo6dB65xT2s1GgoxUpZp2dQY7AsgjTcoyMjL2TeYdIeFi9qYfsxE6JgyRAlS8mJUO58PTFuh2Ekjr5i1B8f256vTPXnT/L/5KC0iYdhAw "Perl 6 โ€“ Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` โ‰”ยนฮท๏ผทโŠ™ฮธ๏นชฮท๏ผฌฮบโ‰ฆโŠ•ฮท๏ผฉ๏ผฅฮท๏ผฅฮธยงฮปฮบ ``` [Try it online!](https://tio.run/##TY07D8IwEIN3fsWNV@kYeC6dIqZKVGKPMkRN1ESEa0nD69eHFBjwYlnyZ3dOx27QIWcxTb5nXBG4ql48nA8WUPALrwTtYG5hQEdwtNwnh@eqCFo9/qiGu2gvlpM1X/4UPSc86Clhac3kbGVKpIaNfWIg@IxUdc5SynK7JtgQbBXBXyLYEeyVUnl5D28 "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes input as an array of arrays and outputs as a double-spaced list of pairs. Explanation: ``` โ‰”ยนฮท๏ผทโŠ™ฮธ๏นชฮท๏ผฌฮบโ‰ฆโŠ•ฮท ``` Count up from 1 until the LCM of the lengths of the arrays has been reached. (This O(nยฒ) but even O(n) would cost 3 bytes.) ``` ๏ผฉ๏ผฅฮท๏ผฅฮธยงฮปฮบ ``` Map over the implicit range and cyclically index both arrays. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes ``` Thread@PadRight[#,{2,LCM@@(Length/@#)},#]& ``` [Try it online!](https://tio.run/##bYw9C4MwGIR3f8VBQFp4i2g/NkugqwUp3SRDqNE46CDZQn57GkNLLS3ccPfccaM0Wo3SDA/pO5T@rmclW17L9jb02jSMbEHV5cr5plJTb3TG2dYRE6mv52EKA@zO6BomBFJkPIG1NncEWzhHCULMCcUC9j@AcFgzQiShORJO7yb4RS8c7ar5g7@vPimuwq3zTw "Wolfram Language (Mathematica) โ€“ Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~78~~ 76 bytes -2 bytes thanks to Noodle9 ``` lambda a,b:zip((x:=len(b))//(g:=math.gcd(y:=len(a),x))*a,y//g*b) import math ``` [Try it online!](https://tio.run/##jY5BCsIwEEX3PcUsZyQ0aFWk0JOoi4m17UCahjRC6@Vjih5A@PAW//H5fo3D5KqLD6mDBm7J8mhaBlamfotHXOrGPh0aIq2xr5uR41D2jxbXb8GkFqIdq1XrfmeokNFPIcLmJc6TV3ERhaCbAgiIy/GviFTO3krmvTB/WYUPm2NljtghK8iXKO3hABUcix/hBOcP "Python 3.8 (pre-release) โ€“ Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes ``` ,ยจ/โˆงโฅโ‰ขโดยจโฎ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@fQCv1HHcsf9S591LnoUe@WQyse9a77n/aobcKj3r5HfVM9/R91NR9ab/yobSKQFxzkDCRDPDyD/6snqiukKagnqXOpJyaBmclgZjKYnZKaBuGlgLmpaekZmVnqXAA "APL (Dyalog Extended) โ€“ Try It Online") Takes two input strings as left and right arguments respectively. Being able to take lengths as separate arguments doesn't really help. ### How it works ``` ,ยจ/โˆงโฅโ‰ขโดยจโฎ โ left: string a, right: string b โฎ โ 2-item nested array of [a, b] โดยจ โ Reshape (by cycling elements) each of [a, b] to the length of... โˆงโฅโ‰ข โ LCM of lengths of a and b ,ยจ/ โ Reduce by "pair up element-wise" ``` [Answer] # JavaScript (ES6), ~~77 68 64~~ 58 bytes *Saved 6 bytes thanks to @AZTECCO* Takes input as `(a, b, a_length, b_length)`. ``` (a,b,n,N)=>(g=i=>[[a[i%n],b[i%N]],...++i%n+i%N?g(i):[]])`` ``` [Try it online!](https://tio.run/##hZFbDoIwEEX/XUV/TNo4QvqADxN0B2xg0kR8EYwBI8btYysTkYdhQnO5LZx2bq/ZK6uPj@L@XJfV6dxckoZncIASUpFseZ4UyRYxw2JZWjg4Sa2FIAhWKzfjRrrLeSE2aK3Y75tjVdbV7RzcqpxfOEoL7Fuofl1bEpgUgoUhQ@7elbCLIcLNfv9DPUaoPkILYFx5nUMBMwOa8icYo8w0yn3QIjACFg9Qpo@KCBV71eSN9yO0g/mn5fVdW9qfjNARoXo6iewan0CqOeQ/nQmmc589fUifprtgJAWjKBhNwRivE8FJWle03t3RKNjmDQ "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` {lร—โ†™X}แต›แธƒโ‚g,?zbแต ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wvzrn8PRHbTMjgJzZD3c0P2pqTNexr0oCSf2Pjo42jNVRiDaKBZHRhjoKRiCGMRpXR8EEIaKjAOYDuaY6CmYQcSALhKCCYCZcHEMQ1RAED6wGaGAsAA "Brachylog โ€“ Try It Online") Initially, I thought "it's funny, Brachylog has a cycling zip builtin but I don't think I'll need it", but my various attempts at `j` and `zโ‚‚`-based solutions have simply refused to terminate on test cases where the second list is longer than the first. ``` { }แต› For each element of the input, l the length ร— multiplied by โ†™X something { }แต› comes out to the same value. แธƒโ‚ Convert that value to unary, g wrap it in a list, ,? append the elements of the input, z cycling zip, bแต and remove the first element from each element of the result. ``` Note that [`{ร—โ†™Xโ„•โ‚}แต›` calculates LCM](https://codegolf.stackexchange.com/a/185353/85334), but the `โ„•โ‚` constraint isn't necessary in this case because `z` fails if any element of its input is empty (since it can't be cycled). [Answer] # [Perl 5](https://www.perl.org/), 104 bytes ``` sub f{($A,$B,%s)=@_;map[$$A[$$_[0]],$$B[$$_[1]]],grep!$s{$$\_[0],$$_[1]}++,map[$_%@$A,$_%@$B],0..@$A*@$B} ``` [Try it online!](https://tio.run/##fZBRb5swEMff/Sm81hXQHCGQkKphqUi01731LUUWpYbSBsywozWK8tkzH2RJW221ZPjf3e/Of7sR7To8HNTmkeY7my2ALeFKOfOYR1XarBhbmM1XoyQBxpad9hMTFK1ovjG164vQ5/eDAXRd/CrGUfhbJjAaDk14bfT@cPmsdaNmnpfJJ1HIdT5UOs1exVv2nNaFGGay8n5thNKlrJXn397cjm68LG21UGVau@uscmXu6t/STds23SqyUYLeG342@ylbEZFqS2MDazqnaAW3atal9sBLoFcr944mg1P4UHvwIsvasuD7j8X94i4iuWztboqzI9SsamuzFNgjxOKtMY/DeHTMx4XU87yvOn2yVDaOsy8ovcDnoF1kgQWmzwHscKAjzfqSxMM@khal1v9Ic/yePMlacHRe1kVEOMcLcU784xAa0PMyz@BDQMzu4/HnmkkEMH4HwOQfwAQB6GohTD8CIQJT7DRqAlMSQogS0aPo0S74@yGn0lfUp8/ZxVEAuulc@OgiQBdjdNEhZ2c@5gJ6us7Z7eEP "Perl 5 โ€“ Try It Online") Slightly ungolfed: ``` sub f { ($A,$B,%s) = @_; #input A and B, %s is the "seen" dictionary map [$$A[$$_[0]], $$B[$$_[1]]], #convert indexes to values from input A and B, return that. grep !$s{$$\_[0],$$_[1]}++, #filter out index pairs seen before map [$_%@$A,$_%@$B], #make array of pairs where 1st elem is #...index of A and 2nd is index of B, #...but modulo their size respectively 0..@$A*@$B #loop from 0 to size_of_A * size_of_B } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 52 bytes ``` ->x,y{a=x.size;a/=g=a.gcd b=y.size;(x*b/=g).zip y*a} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9euQqeyOtG2Qq84syrVOlHfNt02US89OUUhybYSIqZRoZUEFNbUq8osUKjUSqz9X6CQFh1tqKNgFKujAAHRxjoKJrGxXHAZHQWwiI5CtKmOghl2GQRPRwGi6j8A "Ruby โ€“ Try It Online") ]
[Question] [ ## The Idea We've done matrix spirals before, and full rotations, and even [diagonal rotations](https://codegolf.stackexchange.com/questions/63755/rotate-the-anti-diagonals), but not, as far as I can find, *snake rotations*! What is a snake rotation? Imagine the rows of a matrix snaking back and forth, with dividers between them like the dividers of long queue: ``` +--------------+ 1 2 3 4 5| +------------ | |10 9 8 7 6| | +-----------+ |11 12 13 14 15| +------------ | 20 19 18 17 16| +--------------+ ``` Now imagine rotating these items by 2. Each item advances, like people moving in a line, and the items at the end spill out and return to the beginning: ``` +--------------+ --> 19 20 1 2 3| +------------ | | 8 7 6 5 4| | +-----------+ | 9 10 11 12 13| +------------ | <-- 18 17 16 15 14| +--------------+ ``` If there are an odd number of rows it will exit from the right, but still wrap to the beginning. For example, here's a 3 rotation: ``` +--------------+ 1 2 3 4 5| +------------ | |10 9 8 7 6| | +-----------+ |11 12 13 14 15 +--------------+ +--------------+ --> 13 14 15 1 2| +------------ | | 7 6 5 4 3| | +-----------+ | 8 9 10 11 12 --> +--------------+ ``` A negative rotation will take you backwards. Here's a -2 rotation: ``` +--------------+ <-- 3 4 5 6 7| +------------ | |12 11 10 9 8| | +-----------+ |13 14 15 1 2 <-- +--------------+ ``` ## The Challenge Your function or program will take 2 inputs, in any convenient format: * A matrix * A integer (positive or negative) indicating how many places to rotate it. It will return: * The rotated matrix Notes: * Code golf. Fewest bytes wins. * Matrixes need not be square, but will contain at least 2 rows and 2 columns * Positive integers will rotate row 1 toward the right * Negative integers will rotate row 1 toward the left * You may reverse the meaning of positive / negative rotation numbers, if convenient * The rotation number can be larger than the number of items. In that case, it will wrap. That is, it will be equivalent to the number modulo the number of items. * The matrix will contain only integers, but it may contain any integers, including repeats ## Test Cases Format: * Matrix * Rotation number * Expected return value --- ``` 4 5 6 7 1 6 4 7 5 ``` --- ``` 2 3 4 5 6 7 8 9 10 11 12 13 -3 5 9 8 7 12 11 10 6 13 2 3 4 ``` --- ``` 8 8 7 7 5 5 6 6 10 5 5 8 8 6 6 7 7 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` UรeแบŽแน™แนโธUรe ``` A dyadic Link accepting the marix on the left and the rotation integer on the right (uses the reverse meaning of positive / negative) **[Try it online!](https://tio.run/##y0rNyan8/z/08ITUh7v6Hu6c@XBn46PGHSD@////o6ONdBSMdRRMdBRMY3UUos10FMx1FCx0FCxBPEMDHQVDQyAGKjI0jo39bwwA "Jelly โ€“ Try It Online")** ### How? ``` UรeแบŽแน™แนโธUรe - Link: matrix of integers, M; integer, R รe - apply to even indices of M: U - reverse each แบŽ - tighten แน™ - rotate left by R แน - mould like: โธ - chain's left argument, M รe - apply to even indices: U - reverse each ``` [Answer] # [R](https://www.r-project.org/), ~~121~~ ~~110~~ 101 bytes ``` function(m,n,o=t(m)){o[,j]=o[i<-nrow(o):1,j<-c(F,T)];o[(seq(o)+n-1)%%sum(1|o)+1]=o;o[,j]=o[i,j];t(o)} ``` [Try it online!](https://tio.run/##TYxNCoMwEIX3PUU3hQmdgBONStRtT9CduCihgkISqpEW2p7dDhRE3mKY7/1Ma3@s5dov3sYheHDoMTQRnBDv0OLYNaEdaumn8IQgDOFYSwsXvIquCi3M9wfjs5ckTqd5cUAffolb1dbmU0VOfdce3C1OwwsskNFIicmRyJBGlRjKBWaoeRmVOGzRzBSoWIxph5WhFFMuMJfpzrBQYokFS7Ny5FX1j1Ei1h8 "R โ€“ Try It Online") ### Walkthrough ``` function(m,n) { # Input: m - matrix, n - shift o <- t(m) # Transpose the matrix, since R works in column-major order # while our snake goes in row-major order i <- nrow(o):1 # Take row indices in reverse j <- c(F,T) # Take even column indices (FALSE, TRUE, FALSE, TRUE, ...) o[,j] <- o[i,j] # "Normalize" the matrix by reversing every second column o[(seq(o)+n-1) %% # Perform the shift: add n-1 to indices, length(o)+1] <- o # Modulo sequence length, and +1 again o[,j] <- o[i,j] # Reverse even columns again to return to snake form t(o) # Transpose the matrix back to orginal shape and return } ``` [Answer] # [Python 3.8 (pre-releasSSSse)](https://docs.python.org/3.8/), 119 bytes ``` lambda m,r,n=-1:[[m[(k:=(j+(s:=r+i)//w)%h)][::n**k][s%w]for i in range(w:=len(m[0]))][::n**j]for j in range(h:=len(m))] ``` An unnamed function accepting `matrix, rotation` which yields the new matrix. Uses the opposite rotation sign. **[Try it online!](https://tio.run/##Rc7bToQwEAbga/sUk5gN7W730F0P2KQ@hLe1FxhBykJLSl00xmfHAdxw8SedyTedab9j6d0pbcNQqNehzpq39wwaHrhTWyG1bjQ9S0WrDe2kChvL9vuerUpmtJRuvT4b3a16U/gAFqyDkLmPnPZS1bmjjT4YdpXVhKoFlf8IxdBkMdgvUKAJaBAc4Ig5Ye4w94ZjWxzw@YRJMY@Yh7mNWqAWqAVqMWpDgo9ZtN7hn9uUkJB3n3XEoqDzLg5XwcgttMG6SGe01IyMJ8/dF99Pp0@FJDezSDgku8pbR5Mf@Xz8TXY4gQvohcE4e1lm8APGhj8 "Python 3.8 (pre-release) โ€“ Try It Online")** ### How? We set `n=-1` upfront to save on parentheses later and take the matrix as `m` and the rotation as `r`. A new matrix is constructed with the same dimensions as `m` - with a width of `w` (`w:=len(m[0])`) and a height of `h` (`h:=len(m)`). Every other row of this matrix is reversed (`[::n**j]`). The values are looked up by calculating their row and column in the original, `m` using the current elements row, `i`, and column, `j`... We set `s` to `r+i` and `k` to `(j+s//w)%h`. `k` is the row of the original to access for our current element. In order to easily access odd indexed rows from the right we reverse such rows before accessing their elements (with `[:n**k]`), this means the element of interest is at `s%w`. [Answer] # [J](http://jsoftware.com/), ~~41~~ ~~30~~ 21 bytes -11 bytes thanks to Jonah! -9 bytes thanks to FrownyFrog & ngn ! ``` $@]t@$(|.,@t=.|.@]/\) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/VRxiSxxUNGr0dBxKbPVq9Bxi9WM0/2tyKXClJmfkKyjEGyqkKZgoaCtk6hkpGEEE1dWhkgrGQEkj7Uw9YwUTVKl4QwOQlIKJioWChYI5EJoCoZmC2X8A "J โ€“ Try It Online") Reversed `+/-` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 102 bytes Takes input as `(matrix)(integer)`. The meaning of the sign of the integer is inverted. ``` m=>n=>(g=m=>m.map(r=>r.sort(_=>~m,m=~m)))(m.map(r=>r.map(_=>a[(l+n++%l)%l]),l=(a=g(m).flat()).length)) ``` [Try it online!](https://tio.run/##rZDLboNADEX3fIU3kWzhjDIQSLIwP4JQNUqBtppHBCjL/DoBkrRVJXaVvLD8OPfaX@Zq@nP3eRm2PrzXYyOjk8JLga1MiVPOXLCTolN96AZ8k@Lm2MnNERH@6s7J1DQl2tjH8cbSxlbEVtBIi45UY82ARMrWvh0@iMZz8H2wtbKhxQbLCKAEzZAwpAx7hqziuaZ3DCeGI8OBIX/WNOuEdcp6zzqroopwmxJF/4tMVog/IMgnxENerwz/1V5WFu3Tt5mX9kJau@P4Mnx4gjKeI58veDjYTU@9Aw "JavaScript (Node.js) โ€“ Try It Online") ### Helper function The helper function \$g\$ is used to 'snakify' or 'unsnakify' a matrix by reversing rows at odd indices. ``` g = m => // m[] = input matrix m.map(r => // for each row r[] in m[]: r.sort(_ => // sort r[]: ~m, // using either 0 (don't reverse) or -1 (reverse) m = ~m // and toggling m before each iteration // (on the 1st iteration: m[] is coerced to 0, so it yields -1) ) // end of sort() ) // end of map() ``` ### Main function ``` m => n => // m[] = matrix, n = integer g( // invoke g on the final result m.map(r => // for each row r[] in m[]: r.map(_ => // for each entry in r[]: a[(l + n++ % l) % l] // get the rotated value from a[]; increment n ), // end of inner map() l = ( // l is the length of a[]: a = g(m).flat() // a[] is the flatten result of g(m) ).length // (e.g. [[1,2],[3,4]] -> [[1,2],[4,3]] -> [1,2,4,3]) ) // end of outer map() ) // end of call to g ``` [Answer] # Pyth, 20 bytes ``` L.e_W%k2bbyclQ.>syQE ``` Try it online [here](https://pyth.herokuapp.com/?code=L.e_W%25k2bbyclQ.%3EsyQE&input=%5B%5B2%2C%20%203%2C%20%204%2C%20%205%5D%2C%5B6%2C%20%207%2C%20%208%2C%20%209%5D%2C%5B10%2C%2011%2C%2012%2C%2013%5D%5D%0A-3&debug=0). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` ฮตNFR]หœยฒ._ยนgรคฮตNFR ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3FY/t6DY03MObdKLP7Qz/fASsMD//9HRRjoKxjoKJjoKprE6CtFmOgrmOgoWOgqWIJ6hgY6CoSEQAxUZGsfGchkDAA "05AB1E โ€“ Try It Online") Thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) for -5. Unfortunately, I can't see how to golf the redundant part out. :( [Answer] # [Python 3](https://docs.python.org/3/), 94 bytes ``` lambda m,n:g(roll(g(m),n)) g=lambda b:[b[i][::(-1)**i]for i in r_[:len(b)]] from numpy import* ``` [Try it online!](https://tio.run/##LY7NasMwEITP0VPsrZKZQBTHPxX4SVRR7LR2BJZkhEIIfXjXinPb@WZnmOWZbsGX69h9rXPvhp@eHLyaeAzzzCfuBLwQbOre5qD0oK3RSvGjFEVhzRgiWbKe4rdW86/ngzCGjTE48ne3PMm6JcRUrOnaaca1vqAyYES6RmPyJQUypzOoBF1Ab59qUANqQZ87kCdICXmGLF/BY7knW7RotrLXU4UKNeq9@SQMY3mh6xN8Xpmuih0yieGR9WYoWqL1iRfjx99GBTvsWqz/ "Python 3 โ€“ Try It Online") Used the odd-row-reversal from [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/183181/81203). ``` lambda m,n:g(roll(g(m),n)) #reverse odd rows, shift elements, then reverse odd rows again. g=lambda b:[b[i][::(-1)**i] #reverse odd rows for i in r_[:len(b)]] #r_[:x] = range(x) from numpy import* #roll() and r_[] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` ๏ผฆ๏ผฅฮธโއ๏นชฮบยฒโฎŒฮนฮน๏ผฆฮนโŠžฯ…ฮบ๏ผฉ๏ผฅโชช๏ผฅฯ…ยงฯ…โปฮบฮท๏ผฌยงฮธโฐโއ๏นชฮบยฒโฎŒฮนฮน ``` [Try it online!](https://tio.run/##jY7NCoMwEITvPsUeE4jQaH/xVHoqVJC2t@AhaFqDEm2i0j59uiq99/DBMDs7TFFJW7Sy8f7RWiCp7MiLwV1ZI@2HpG05NC2pGUSUwVWNyjpFNGpNKYX5RVPIBleRgUFNkyCz2vTkJF0/l926Ri8K78f@bEr1nmSqzeCm4gqLGFyUefYV@QVwwmr2/xtCE@@FEBEDiJE1sslZACC2KHfIHjksFl8x4BzBOI/zyQzj3Idj8wU "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผฅฮธโއ๏นชฮบยฒโฎŒฮนฮน ``` Reverse alternate rows of the input. ``` ๏ผฆ...๏ผฆฮนโŠžฯ…ฮบ ``` Flatten the array. ``` ๏ผฅฯ…ยงฯ…โปฮบฮท ``` Rotate the flattened array. ``` โชช...๏ผฌยงฮธโฐ ``` Split the array back into rows. ``` ๏ผฅ...โއ๏นชฮบยฒโฎŒฮนฮน ``` Reverse alternate rows. ``` ๏ผฉ... ``` Convert each entry to string and output in the default output format which is one number per line with rows double-spaced. (Formatting with a separator would cost the length of the separator.) [Answer] # [Japt](https://github.com/ETHproductions/japt), 28 bytes ``` mร%2ยฉXร”ยชX c รฉV รฒUรŽl WยฉUยชรŸV1V ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=bc8lMqlY1KpYCmMg6VYg8lXObApXqVWq31YxVg&input=W1s0LCA1XSwKIFs2LCA3XV0KMQ) Port of [Arnauld's answer](https://codegolf.stackexchange.com/a/183166/8340). The biggest challenge was creating a reusable function. In particular, there is a helper function to reverse every other row. The approach that I am taking is to make a recursive call and depending on whether a variable is set. Transpiled JS: ``` // U: first input argument (matrix) // m: map it through a function U = U.m(function(X, Y, Z) { // if the row index is even, don't alter it // if the row index is odd, reverse it (w) return Y % 2 && X.w() || X }); V = U // flatten the matrix .c() // shift by the amount specified in second argument .รฉ(V) // partition back to matrix .รฒ( // the number of columns should be the same as input U.g().l() ); // if W is specified, return the result from the first line W && U || // otherwise, make a recursive call with the shifted matrix rp(V, 1, V) ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 20 bytes ``` โ†‘โˆ˜tโŠขโˆ˜โดโดโŒฝโˆ˜โˆŠโˆ˜(tโ†โŠขโˆ˜โŒฝ\โ†“) ``` [Try it online!](https://tio.run/##NY09CsJAEIV7TzFddgoxm7ib6DksbYISCQYixkbESgn@RRQRbPUCNtoINh5lLhJnV4RldvZ97@2LRmm9P43SbFDvpVGeJ72K9ucko@LgVjFPKo60ukxoc@OLyoc5u7fZVxueYmI8P7h7d6k4YVV1WJtR@aT1dWzxIm5Q@Wo72dCh7dKJoyR1WGDLeF773KXgFtEEhUJDgAgd89bQRBGwWPMt98CHvwdCaKGQLkgJ0gPpI9qMghajgJFnkQuadx9sFk2Va/8Kjcv4FCjQbPrHFYPQVGjLvw "APL (Dyalog Classic) โ€“ Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 141 bytes ``` a=>n=>{for(dynamic l=a.Length,w=a.GetLength(1),i=l,j,b=a.Clone();i-->0;)a[(j=(i+n%l+l)%l)/w,j/w%2<1?j%w:w-j%w-1]=b[i/w,i/w%2<1?i%w:w-i%w-1];} ``` [Try it online!](https://tio.run/##bVFNa4NAEL37K5aAsItj4ybNR6NrKYX2knsPksPGmmYWu4FoK0X87XbUtEkgl@XNvDdvPjYt/LTA9uXLphHaMoENPKUlHmwXxfFOtVrFVsX17nDk7z9Wf2LKcqXv1pn9KPdQEXzNyiHiUgCqHAxsKf2cH2zGRYi@Hweh0Ak3iqNn3dzLhZuLcQVmXLmTSD4at1pVPr2@3KhtgkThicKewp4KmzZ0vvWRlVlRFkwxm1XJhtUO1yuCbFigdhir72HWQAfmsCDQgF3RcDeEE5jCpRiW8DAEMgApQU5ATk8O/vSmxZJqFn0bCmYwgznM/3oGVNGEDl0v0@med8NzDVZQ/bCFYJ3HjmvBrQg7SIcmc4YqCDG6vG5At/S8oeCsM6Qz0fUvhOasY@ztiGXGdYJgNt6Ijfo2jDXOP7nG/qecIXmVatpf "C# (Visual C# Interactive Compiler) โ€“ Try It Online") -5 bytes total thanks to @someone! Anonymous function that performs an in-place modification to the input matrix. An single loop iterates over the cells. You can scan from top to bottom and left to right using the following formulas: * `row=i/w` * `col=i%w` Where `i` is a loop counter and `w` is the number of columns. This is varies slightly when scanning in a snake pattern. * `row=i/w` * `col=i%w` (0th, 2nd, 4th, etc. row) * `col=w-i%w-1` (1st, 3nd, 5th, etc. row) Another thing to note is that the `%` in C# does not convert to a positive value like it does in some other languages. A couple extra bytes are needed to account for this. ``` // a: input matrix // n: number of cells to rotate a=>n=>{ for( // l: total number of cells // w: number of columns // i: loop index // j: offset index // b: copy of input matrix dynamic l=a.Length, w=a.GetLength(1), i=l,j, b=a.Clone(); // iterate from i down to 0 i-->0; ) // calculate the offset `j` and use // the above formulas to index // into `a` for setting a value a[ (j=(i+n%l+l)%l)/w, j/w%2<1?j%w:w-j%w-1 ]= // use the un-offset index `i` and // the above formulas to read a // value from the input matrix b[ i/w, i/w%2<1?i%w:w-i%w-1 ]; } ``` ]
[Question] [ Some of your employees have broken capslock keys and you're too cheap to replace them. Help them out by creating the shortest program possible to correct their work! Simply convert each character in a given string from uppercase to lowercase and vice-versa... but there's a twist! You're also very excited for Christmas! So you're going to leave in a tiny "bug" that doesn't correct letters which are within sequences of `Christmas` (case-insensitive). ## Input For input you will use one single string (or array of bytes) that may contain newlines and ascii between [0x20 and 0x7e](http://www.asciitable.com/) ( - `~`). You don't need to worry about carriage returns or any other characters being in the string. ## Output The output should contain **only** the provided string with the upper and lowercase characters swapped (and the Christmas bug of course!). It can contain up to one extra trailing whitespace. ## Christmas Bug Let's explain this with an example: ``` Input: i CAN HARDLY WORK LIKE THIS please GET ME A NEW KEYBOARD FOR cHRISTMAS Output: I Can HaRdly work lIke thiS PLEASE geT Me A new keyboard for ChriStmas ``` `can` contains "c" which is the first letter of Christmas, so that isn't changed. The next letter in `Christmas` is "h", which is in `hardly` (which also contains the "r"), so that isn't changed, etc. `Christmas` itself only has one letter unchanged because by the time the code reaches there, it's actually looking for "s", not "c". Once the sequence is found, it should start all over again at "c", and begin iterating through `Christmas` once more. So `ChristmasChristmas` would be left unchanged. ## Test Cases ``` Input: Hello World! Output: hELLO wORLD! Input: I like pie :) Output: i LIKE PIE :) Input: hELP my KeYboarD iS BROKEN Output: Help MY kEyBOARd Is broken Input: cHRISTMAS IS COMING REALLY SOON! Output: cHRISTMAS is Coming really soon! Input: C is the first letter in cHRISTMAS Output: C IS ThE FIrST LETTER iN ChriSTMAS ``` ## Winner This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer wins! [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 16 bytes Thanks to *Emigna* for saving a byte and fixing a bug! ``` vyรl'ล’รŽยพรจQiยผรซลก}? ``` Explanation: ``` vy # For each character in the string... ร # Triplicate that character l # Convert to lowercase 'ล’รŽ # Compressed version of "christmas" ยพ # Push the counting variable (let's call this N) รจ # Get the nth character of "christmas", with modular indexing Qi } # If equal... ยผ # N += 1 รซ # Else... ลก # Swapcase ? # Print that character ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=dnnDkGwnxZLDjsK-w6hRacK8w6vFoX0_&input=IiIiaSBDQU4gSEFSRExZIFdPUksgTElLRSBUSElTIApwbGVhc2UgR0VUIE1FIEEgTkVXIEtFWUJPQVJEIEZPUiBjSFJJU1RNQVMiIiI) [Answer] # [V](https://github.com/DJMcMayhem/V), ~~38~~, 36 bytes ``` ร„VumaOchristmasรฒร‰f2x`a@"maj~HรฒHdjV~ ``` [Try it online!](https://tio.run/nexus/v#Pc49DoIwAIbh3Su4fPEInkDEahv@kkIgbFYo8o8pGGRhcvE6XIGDIS7ub568y/z2n5VwolRlbVeJdjtP8yfZv67isKtEPtJ5onHuj8uSQddsUI2fzBCBww2YzCDwKHPxKKVoJS7Eg0WgwSYBDBIenbXG2eGIKGeuZ2nuhkEXNajgcTmgb1SBkhUSXZr9mbtcGbkytexRyOHWCBUjaRT0ddP9bX4B "V โ€“ TIO Nexus") (contains input and expected output for comparison) When I first saw this, I thought it would be extremely easy. In fact, if it were not for the "christmas" bug, this would just be 2 bytes: `V~`. The christmas bug makes it significantly harder, for a very hacky answer. As usual, here is a hexdump: ``` 00000000: c456 756d 614f 6368 7269 7374 6d61 731b .VumaOchristmas. 00000010: f2c9 6632 7860 6140 226d 616a 7e48 f248 ..f2x`a@"maj~H.H 00000020: 646a 567e djV~ ``` [Answer] # PHP, ~~113~~ ~~110~~ 102 bytes ``` while($o=ord($c=$argv[1][$i++]))echo chr(32|$o==ord(christmas[$k%9])?$o|0&$k++:ctype_alpha($c)*32^$o); ``` takes input from first command line argument. Run with `-r`. **breakdown** ``` while($o=ord($c=$argv[1][$i++]))// loop through string characters echo chr( 32|$o==ord(christmas[$k%9]) // if $c equals next character in "christmas" ?$o|0&$k++ // no change, increase "christmas" index :ctype_alpha($c) // else if $c is a letter *32^$o // toggle bit 5 of the ascii code ); ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~36~~ 30 bytes ``` "@tk'schristma'H)=?HQXHx}Yo]&h ``` Strings with newlines need to be defined by concatenating with the ASCII code `10` (see example in the link with the test cases). [Try it online!](https://tio.run/nexus/matl#@6/kUJKtXpycUZRZXJKbqO6haWvvERjhUVEbmR@rlvH/v3qmgrOjn4KHY5CLT6RCuH@Qt4KPp7erQoiHZ7BCQU5qYnGqgrtriIKvq4Kjgp9ruIK3a6STP1C1gpt/kEKyR5BncIivY7A6AA "MATL โ€“ TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#Pc29CsIwGEbh2V7Fq4MfbroK4m8wobXVRtAiBWuNNDS1kmbQwWuvujg@w@Gc297MldTkhdWNqzLig8mU7478@U7qtF@06WrfElfG1DjU1ly75JGA0aXCQyuMB19rBMJn2Ar2c8c7UcGCLaoXfJVc6syuCKMhSEss4shnIaUe5TwWcr@ZSwiJZbQR4RoxmwdBAhlF4e@zhG7gCoWbto2DUc4pC33Hv6UP). ### Explanation ``` " % Implicit input of a string. For each character in that string @ % Push current character tk % Duplicate and convert to lowercase 'schristma' % Push string. This is 'Christmas' in lowercase and circularly % shifted such that the 'c' is in the second position H % Push contents of clipboard H, which is initiallized to 2. % This value will be gradually increased when a new character % from the the sequence is found ) % Get character from 'schristma' at that (modular) position = % Are they equal? ? % If so HQ % Push contents of clipboard H and add 1 XHx % Copy into clipboard K and delete } % Else Yo % Change case ] % End &h % Concatenate stack contents horizontally. This gives a string % with all characters processed up to now % Implicit end. Implicit display ``` [Answer] ## Pyke, ~~31~~ 25 bytes ``` FD.dา‘~o@Dl3+{DIoK)R!Il3 ``` [Try it here!](http://pyke.catbus.co.uk/?code=FD.d%01%D2%91%7Eo%40Dl3%2B%7BDIoK%29R%21Il3&input=cHRISTMAS+IS+COMING+REALLY+SOON) [Answer] # [Perl 6](http://perl6.org/), 84 bytes ``` {my $i=0;[~] (.lc~~"christmas".comb[$i%9]??(++$i&&$_)!!.ord>90??.uc!!.lc for .comb)} ``` [Answer] # C# 197 bytes Not going to win with this, but hopefully the smallest C# implementation that works... ``` string C(string s){int i=0,j=0;var r="";for(;i<s.Length;){char c=s[i++],o=(char)32;if(c=="christmas"[j]|c=="CHRISTMAS"[j])j=j>7?0:j+1;else if(c>64&c<91)c+=o;else if(c>96&c<123)c-=o;r+=c;}return r;} ``` Explanation: ``` string C(string s) { // define our two index ints // i for indexing across the input string // j for indexing across christmas int i = 0, j = 0; // r is our return string var r = ""; // declare our loop // skip the initialisation and afterthought for (; i < s.Length;) { // get our current character c, and increment index i // initial our offset char o (difference between upper and lower case) char c = s[i++], o = (char)32; // check if c is the current character in our christmas bug if (c == "christmas"[j] | c == "CHRISTMAS"[j]) // increment j (or reset to 0) j = j > 7 ? 0 : j + 1; // else if c is an upper case char else if (c > 64 & c < 91) // add our offset to make it lower case c += o; // else if c is lower case else if (c > 96 & c < 123) // subtract our offset to make it upper case c -= o; // append c to our return string r r += c; } return r; } ``` [Answer] # JavaScript, ~~122~~ ~~118~~ ~~114~~ ~~107~~ ~~104~~ 93 bytes ``` f= s=>s.replace(/./g,c=>(k=c.toLowerCase())=='christmas'[i%9]?++i&&c:k!=c?k:c.toUpperCase(),i=0) F=s=>console.log(f(s)) F(`Hello World!`) F(`I like pie :)`) F(`hELP my KeYboarD iS BROKEN`) F(`cHRISTMAS IS COMING REALLY SOON!`) F(`C is the first letter in cHRISTMAS`) ``` * 11 bytes off thanks @Neil. [Answer] # [Perl 6](https://perl6.org), 80 bytes ``` {my$i=0;S:g{.?<!{'christmas'.comb[$i%9]eq$/.lc&&++$i}>}=$/eq$/.lc??$/.uc!!$/.lc} ``` [Try it](https://tio.run/nexus/perl6#RY9RTsJAFEX/ZxW3pFIJpvhlIoikwEiblo5pSQhRP8owyMQpxU5rQgh7cBGuzI3ghBj9enkvN@eeV2uBjxuX9wjJ92jyYiXQPx3yvS371720@3pwB3fWweGbUuoqz7Tj8iJfPtny4vZFvNsdV/Fms9225fH@2Lc7v6fBwIyaW9Z5O550tseZ7ep6qatL5/vzy7lqPG8bLayLEkpuhT5JjLwYvpeMowXmLAkRBSHFzA9S7JTIjOuEzjCl8BDTOUK6GDKTxgNLwP0kSGdTLyW@UKrAvCjVyiKBYb8J7KRAt0U2NHqEeTQUi2WRlWOjIVMMExbSmPwRYPpGbBrEEyTUi4xMylhskRGkRrURWMtSV1CiqkQJuf3v/gE "Perl 6 โ€“ TIO Nexus") ``` { # bare block lambda with implicit parameter ๏ฝข$_๏ฝฃ my $i = 0; # counter S # substitute and return ( implicitly against ๏ฝข$_๏ฝฃ ) :global { . # any char ? # work around a bug where ๏ฝข$/๏ฝฃ doesn't get set <!{ # fail this match if this block returns True 'christmas'.comb\ # a list of the characters of ๏ฝขchristmas๏ฝฃ [ $i % 9 ] # grab a char from the list eq # is it equal to $/.lc # the lowercase version of the char && # if so ++$i # increment ๏ฝข$i๏ฝฃ ( result is True ) }> } = # for each matched char $/ eq $/.lc # is it lowercase? ?? $/.uc # the uppercase it !! $/.lc # otherwise lowercase it } ``` [Answer] # Java 7, 200 bytes ``` String c(char[]a){String r="";int i=0,s;Character l='a';for(char c:a)if((s="christma".indexOf(l=l.toLowerCase(c)))==i|i>7&s==4){r+=c;i=i>7?0:i+1;}else r+=l.isUpperCase(c)?l:l.toUpperCase(c);return r;} ``` Ugly, but it works.. Can definitely without any doubt be golfed more.. I'm rusty.. **Ungolfed:** ``` String c(char[] a){ String r = ""; int i = 0, s; Character l = 'a'; for(char c : a){ if((s = "christma".indexOf(l = l.toLowerCase(c))) == i) | i > 7 & s == 4){ r += c; i = i > 7 ? 0 : i+1; } else{ r += l.isUpperCase(c) ? l : l.toUpperCase(c); } } return r; } ``` **Test code:** [Try it here.](https://ideone.com/KzZqVL) ``` class M{ static String c(char[]a){String r="";int i=0,s;Character l='a';for(char c:a)if((s="christma".indexOf(l=l.toLowerCase(c)))==i|i>7&s==4){r+=c;i=i>7?0:i+1;}else r+=l.isUpperCase(c)?l:l.toUpperCase(c);return r;} public static void main(String[] a){ System.out.println(c("i CAN HARDLY WORK LIKE THIS please GET ME A NEW KEYBOARD FOR cHRISTMAS".toCharArray())); System.out.println(c("Hello World!".toCharArray())); System.out.println(c("I like pie :)".toCharArray())); System.out.println(c("hELP my KeYboarD\niS BROKEN".toCharArray())); System.out.println(c("cHRISTMAS IS COMING REALLY SOON!".toCharArray())); System.out.println(c("C is the first letter in cHRISTMAS".toCharArray())); } } ``` **Output:** ``` I Can HaRdly work lIke thiS PLEASE geT Me A new keyboard for ChriStmas hELLO wORLD! i LIKE PIE :) Help MY kEyBOARd Is broken cHRISTMAS is Coming really soon! C IS ThE FIrST LETTER iN ChriSTMAS ``` [Answer] # Python 100 bytes ``` def a(s,i=0,g=''): for c in s:a=c.lower()=='christmas'[i%9];i+=a;g+=[c.swapcase(),c][a] return g ``` [Answer] # Ruby, 63+1 = 64 bytes Uses the `-p` flag. ``` i=0;gsub(/./){|c|c=~/#{"christmas"[i%9]}/i?(i+=1;c):c.swapcase} ``` [Answer] ## C# 239 chars ``` var s=Console.ReadLine().ToCharArray();int j=0,i=0;var c="christmas";for(;j<s.Length;j++)if(s[j]==c[i%9]|s[j]==(c[i%9]-32))i++;else if(s[j]>64&s[j]<91)s[j]=(char)(s[j]+32);else if(s[j]>96&s[j]<123)s[j]=(char)(s[j]-32);Console.WriteLine(s); ``` more explicit version: ``` var s = Console.ReadLine().ToCharArray(); int j = 0,i = 0; var c = "christmas"; for (var j = 0; j < s.Length; j++) if (s[j] == c[i%9]|s[j] == (c[i%9] - 32))// non case sensitive compare with c i++;//next char in christmas else if (s[j] > 64 & s[j] < 91)//if between A and Z s[j] = (char)(s[j] + 32);//convert to a-z else if (s[j] > 96 & s[j] < 123)//if between a and z s[j] = (char)(s[j] - 32);//convert to A-Z Console.WriteLine(s); ``` this is a pretty naรฏve solution, and probably can be improved (maybe we can allow implicit conversion to char?). it assumes to be inside a function, reads from the console (stdin), and writes to it (stdout). edit: Char.IsUpper(s[j]) is 2 bytes longer than s[j]>64&&s[j]<91, Char.ToUpper is longer than my version too. [Answer] # Haskell, ~~222~~ 207 Bytes ``` import Data.Char s=(+(-65)).ord f=(`divMod`32).s l=[['a'..'z'],['A'..'Z']] c=cycle$map s"CHRISTMAS" k _[]=[] k(a:b)(x:y)|isAlpha x=let(d,m)=f x in if(m==a)then(x:k b y)else(l!!d!!m:k(a:b)y)|1>0=x:k(a:b)y main=interact$k c ``` --- updated: ``` import Data.Char s=(+(-65)).ord k _[]=[] k(a:b)(x:y)|isAlpha x=let(d,m)=s x`divMod`32 in if(m==a)then(x:k b y)else([['a'..'z'],['A'..'Z']]!!d!!m:k(a:b)y)|1>0=x:k(a:b)y main=interact$k$cycle$map s"CHRISTMAS" ``` ## How it works: > > > ``` > s=(+(-65)).ord > > ``` > > s x = ASCII value of x - ASCII value of 'A' > > > > ``` > f=(`divMod`32).s > > ``` > > f (s x) = (0,s x) for uppercase, (1, (s x-32)) for lowercase > > > > ``` > l=[['a'..'z'],['A'..'Z']] > > ``` > > parallel list of letters, indexable by f (lowercase->1->uppercase, uppercase->0->lowercase) > > > > ``` > c = cycle $ map s "CHRISTMAS" > > ``` > > infinite list of the ascii values of uppercase christmas repeated > > > > ``` > k _ []=[] > > ``` > > base case > > > > ``` > k (a:b) (x:y) | isAlpha x = let (d,m) =f x > in if m == a > then x : k b y > else (l!!d)!!m : k (a:b) y > | 1 > 0 = x : k (a:b) y > > ``` > > return non-alphanumeric characters, and either keep the letter if its s-value is the same as the current letter of christmas (going to the next letter), otherwise convert it to the other case and proceed > > > > ``` > main=interact$k c > > ``` > > IO > > > ]
[Question] [ It has been proven that the following 13 square [Wang tiles](http://en.wikipedia.org/wiki/Wang_tile) always tile the plane [aperiodically](http://en.wikipedia.org/wiki/Aperiodic_tiling). This means that when the squares are arranged in a grid with all neighboring sides the same color, a translation of the pattern will never match up with itself. ![Wang tiles](https://i.stack.imgur.com/F249x.png) We'll represent each tile textually by a 3ร—3 grid filled with spaces at the center and corners, and the numbers 1 through 5 instead of the colors red, green, blue, yellow, grey, at the edges: ``` 2 2 2 1 1 1 4 3 2 2 4 3 2 1 2 1 3 2 3 2 1 3 1 3 2 4 4 4 4 4 5 4 5 5 5 5 5 5 4 3 2 3 2 3 2 1 2 1 4 1 2 2 ``` # Goal Your task is to write a program that takes in a width and height and outputs a valid Wang tile grid with those dimensions. A valid tiling is one in which all the adjacent tile edges have the same color (or number). The smallest program in bytes wins. Your input should come from stdin or command line arguments and output should go to stdout. The exact input format can be anything reasonably obvious, like `>>> wangtiler 3 2`. The width and height are always positive integers. ### Example (width = 3, height = 2) Notice that when we layout the textual tiles the neighboring edges form necessary redundant pairs of digits: ``` 1 2 1 2 11 22 1 2 3 2 2 3 2 4 55 55 4 1 2 2 ``` (This is NOT the proper output format.) We can compress these horizontally and vertically to get: ``` 1 2 1 2 1 2 1 2 3 2 4 5 5 4 1 2 2 ``` This compressed format is the proper output format you must use. The odd numbered lines must include their trailing space. # Graphical Bonus Instead of having any textual output, your program may output an image of the tiled grid. The graphical tiles must be made up of four 45-45-90 triangles arranged in a square and use five easily distinguishable colors like the tiles above. The black borders are not required. The graphical tiles must be at least 32ร—32 pixels in size. No "compression" is applied to them. **Example bonus image:** (same grid as example above) ![bonus example](https://i.stack.imgur.com/rLcIT.png) The bonus is worth minus 150 bytes. # Notes * You must use this set of 13 tiles. * Tiles may not be rotated. * Tiles may appear any number of times (including none at all). * You may assume a valid tiling with any dimensions is possible. [Answer] ## Python (565 - 150 = 415) Btw... it seems that we can't naively just decide the next tile by the its left and top tile. There's some combination of tiles that will fit each other. This solution fills in left->right, top->down brute forces through all possible combinations and backtracks if a tile cannot fit in. For more info about the 13 tile proof: [An aperiodic set of 13 Wang tiles](http://www.sciencedirect.com/science/article/pii/S0012365X96001185) Width and Height are specified by `W` and `H` Red, Green, Blue, Yellow and Noir specified by `R`, `G`, `B`, `Y` and `N` ``` import Image,sys W,H=map(int,sys.argv[1:]) R=99 G=R<<8 B=G<<8 Y=G+R N=0 s="RGB";u=32;g=[[0,0]]*W*H;k=f=0 def t(c):i=Image.new(s,(2,2));k=i.load();q=16;k[1,0],k[1,1],k[0,1],k[0,0]=c;return i.resize([64]*2).rotate(45).crop((q,q,q+u,q+u)) while k<H*W: z=g[k][1];v=-1;j=k/W;i=k%W while z<13: l=map(eval,"GGGRRRYBGGYBGGBBRRGYYNNNNYBGBGBGRGRYRGGRRGGBBYYYYNNN"[z::13]) if(j<1or g[(j-1)*W+i][0][2]==l[0])and(i<1or g[j*W+i-1][0][1]==l[3]):g[k]=[l,z+1];v=1;z=99 z+=1 g[k][1]*=(v>0);k+=v m=Image.new(s,(W*u,H*u)) for e in g:m.paste(t(e[0]),(f%W*u,(f/W)*u));f+=1 m.show() ``` Output. Not the actual color scheme... cuz too glaring. This might make some interesting interior decor patterns...: ![enter image description here](https://i.stack.imgur.com/IVakV.png) [Answer] ### GolfScript, 200 characters ``` ~\:W*):R;1,{)\:C"=QCy_~{MTKAis]?OyJE?~WvM"[64 2400]{base}/@{>}+,{:T;[C,W<!{C W~)=T 64/^8/8%}*C,W%0>{C-1=64/T^8%}*]0-!},1<.!!{1,+}*+.,R<}do);W/.0={' '\512/8%`}%n@{.[.0=8%\{' '\64/8%}/n]\{' '\8/8%`}%n}/ ``` ASCII version with no graphic output. Give the input on STDIN - try [here](http://golfscript.apphb.com/?c=OyIzIDIiCgp%2BXDpXKik6UjsxLHspXDpDIj1RQ3lffntNVEtBaXNdP095SkU%2Ffld2TSJbNjQgMjQwMF17YmFzZX0vQHs%2BfSssezpUO1tDLFc8IXtDIFd%2BKT1UIDY0L144LzglfSpDLFclMD57Qy0xPTY0L1ReOCV9Kl0wLSF9LDE8LiEhezEsK30qKy4sUjx9ZG8pO1cvLjA9eycgJ1w1MTIvOCVgfSVuQHsuWy4wPTglXHsnICdcNjQvOCV9L25dXHsnICdcOC84JWB9JW59Lw%3D%3D&run=true). The code uses a plain backtracking approach and fills the space line by line. Examples: ``` > 3 2 1 2 1 2 1 2 1 2 3 2 5 4 4 5 2 2 1 > 8 5 1 2 1 2 1 2 1 2 2 1 2 1 2 1 2 1 2 2 3 2 3 2 3 2 3 5 4 4 5 5 4 4 5 5 2 2 4 2 2 2 4 2 5 4 5 5 4 5 4 4 5 2 1 1 2 1 2 1 1 1 3 2 1 2 1 3 2 1 2 2 2 3 2 2 2 2 5 4 5 4 4 5 4 5 4 2 1 2 2 1 2 1 2 ``` ### Graphical Bonus, score 122, 272 characters - 150 bonus ``` ~\:W*):R;1,{)\:C"=QCy_~{MTKAis]?OyJE?~WvM"[64 2400]{base}/@{>}+,{:T;[C,W<!{C W~)=T 64/^8/8%}*C,W%0>{C-1=64/T^8%}*]0-!},1<.!!{1,+}*+.,R<}do);W["P3\n"32W*" "3$,32*n 1n]\{{:^;512:X;16,{[^8%]1$*[^X/8%]31*@.+>[^64/8%]31*++32<}:F%8:X;16,-1%{F}%+}%zip{{+}*{8+2base(;~}%' '*n}/}/ ``` Same basic code with a different output formatter. The output is an image in PPM format (i.e. simply redirect the output to a file `image.ppm`). The colors are slightly different than the tiles in the question, but clearly distinguishable (1->blue, 2->green, 3->cyan, 4->red, 5->magenta). 16x12 example: ![16x12 wang example](https://i.stack.imgur.com/fxudq.png) [Answer] # Haskell, 208 bytes ``` p x|x<2/3=(3!x)3"3212"3 p x=(0.5!x)1"45423"2 f=floor (k!x)l s m=do{i<-[0,x..];[' ',s!!(2+f(i+x)-f i)]}:do{i<-[0,l*x..];s!!mod(f i)m:" "}:p(k*x) t n=take$2*n+1 main=do(w,h)<-readLn;putStr.unlines.t h$t w<$>p 1 ``` No searching, just math. Example run: given `(8,5)` on stdin, outputs ``` 2 2 2 2 2 2 2 2 4 5 4 5 4 5 4 5 4 1 2 1 2 1 2 1 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 4 5 5 4 4 5 5 4 4 4 2 2 2 4 2 2 2 4 4 5 4 5 5 4 5 4 1 1 2 1 1 2 1 2 3 2 1 3 2 1 3 2 3 2 2 2 2 2 2 2 3 ``` [Run online at Ideone](http://ideone.com/ZHZxNf) ]
[Question] [ **This question already has answers here**: [Compute the Kolakoski sequence](/questions/157403/compute-the-kolakoski-sequence) (47 answers) Closed 5 years ago. ## Definition1 > > A Kolakoski sequence is a *self-describing* infinite sequence {kn} of alternating blocks of 1's and 2's, given by the following rules: > > > * k0 = 1 > * kn = the length of the (n+1)'th block > > > ## The Task Given a positive integer `n`, generate the first `n` elements of the Kolakoski sequence. ## Details Input will be provided as a single command line argument `n`. Please write a full program that will print the first `n` elements of the Kolakoski sequence (in order) to STDOUT, with each element separated by your favorite whitespace. ## Scoring Lets count source code bytes this time with all whitespace included. Fewest number of bytes wins. In the event of a tie, the solution with the earliest submission time wins. ## The Sequence2 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, ... --- References 1. [John Smith](http://planetmath.org/?op=getuser&id=13766), [Ariel Scolnicov](http://planetmath.org/?op=getuser&id=338), [yark](http://planetmath.org/?op=getuser&id=2760). "Kolakoski sequence" (version 3). PlanetMath.org. Freely available at <http://planetmath.org/KolakoskiSequence.html>. 2. The Online Encyclopedia of Integer Sequences <http://oeis.org/A000002> Other resources * Kolakoski Sequence at Wikipedia <http://en.wikipedia.org/wiki/Kolakoski_sequence> * Kolakoski Sequence at Wolfram MathWorld <http://mathworld.wolfram.com/KolakoskiSequence.html> [Answer] # J - 23 char A little late to the party, but I'd like to bust out a neat little J trick here. ``` 1($1+2|I.)^:_~".>2{ARGV ``` Given input `N`, this verb operates by executing `N&($1+2|I.)` on a starting argument of 1 until it reaches a fixed point. If the item at index `i` in `y` is `n`, there will be `n` copies of `i` in `I.y`, so for instance `I. 0 1 1 0 0 3 1` is `1 2 5 5 5 6`. We mod the result of that by 2 and add one. Then, `x $ y` forces `y` into a list of length `x`, truncating it or extending it cyclically as necessary. So here's what happens when the input is, say, 10. ``` 10 ($1+2|I.)^:a: 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 2 1 2 1 2 1 2 1 2 1 2 2 1 2 2 1 2 2 1 1 2 2 1 1 2 1 1 2 2 1 2 2 1 1 2 1 2 2 1 ``` We start with a row of all 1s and then "settle down" into the Kolakoski sequence. First, it turns into `1 2 1 2 1 2...` as each contiguous block of ones or twos is described by length 1. Then we apply it again and it turns into `1 2 2 1 2 2 1 2 2...` since the ones are described by 1 and the twos are described by 2. The we continue again and again until we see there is no change, at which point we stop and give the result. Other "self-describing" sequences can be similarly derived in J using `I.` and `^:_`. --- ## Edit Over a year ago, @ardnew asked: > > what is the relationship between `n` and the number of those intermediate iterations required to generate the sequence of length `n`? > > > To make sure we're on the same page, I consider the calculation for `n` = 10 above to have taken 5 iterations. If there are *s* terms settled at the *i*-th iteration for `n`, then at the (*i*+1)-th iteration, there will be (at least) *k*0 + *k*1 + ... + *k**s* + 1 terms settled. The '+ 1' appears because the next term will also be correct, since it must be and is different from the term before it. So if K(*s*) is the sequence of partial sums of *k*n, then we can lower bound the number of iterations for `n` by the least *a* such that (1+K)*a*(1) โ‰ฅ `n`. I don't how to prove we don't accidentally do a bit better (by picking up more correct terms than we expected in some iteration), but according to the numbers, we don't: ``` k =: ($ 1 + 2 | I.)^:_&1 NB. Kolakoski seq pk =: +/\ @: k NB. partial sums ("K") ((1 + pk 2000) {~ <:) ::_:^:(i.20) 1 NB. iterating 1+K, say, 20 times 1 2 4 7 11 18 28 43 65 99 150 226 340 511 768 1153 1728 2590 _ _ NB. compare with observed number of settled terms up to 2000: +/"1 }. (k <./\ . ="1 ($1+2|I.)^:a:&1) 2000 1 2 4 7 11 18 28 43 65 99 150 226 340 511 768 1153 1728 2000 ``` The underscores are index errors (`:: _:`), telling us 20 iterations is too much for the first 2000 terms of *k*n to handle. [Answer] ## Ruby (73 characters) ``` s=[1,2,2];n=2;ARGV[0].to_i.times{puts s[n-2];s[n].times{s+=[1+n%2]};n+=1} ``` [Answer] ## GolfScript (48 chars) You can't test this online because the online GS shell doesn't take command-line arguments, but: ``` ;"#{ARGV[-1]}"~[1 2.]2{.2$=[1$2%)]*@\+\)}3$*;<n* ``` This takes input from stdin instead and [works](http://golfscript.apphb.com/?c=OyIxMiIKCn5bMSAyLl0yey4yJD1bMSQyJSldKkBcK1wpfTMkKjs8bio%3D) ``` ~[1 2.]2{.2$=[1$2%)]*@\+\)}3$*;<n* ``` [Answer] # Python 93 Adapted from my solution to [Calculate the nth term of Golomb's self-describing sequence](https://codegolf.stackexchange.com/questions/8374/calculate-the-nth-term-of-golombs-self-describing-sequence): ``` import sys;n=int(sys.argv[1]);a=[1,2,2]; for i in range(3,n):a+=[~i%2+1]*a[i-1] print a[:n] ``` Still trying to figure out how to do this with list comprehension which I just learned about today, but I'm running into problems with self-reference. EDIT: Instead of breaking if list was too long, just printed the appropriate slice. EDIT: Now pulling arg from command line [Answer] # Python (87 chars) My code turned out to be basically the same as [scleaver's solution](https://codegolf.stackexchange.com/a/8394/20260) even though I wrote it independently. It saves a few characters by not shifting the index i by 1. ``` import sys n=int(sys.argv[1]) l=[1,2,2] for i in range(2,n):l+=[1+i%2]*l[i] print l[:n] ``` [Answer] # Perl, ~~41~~ 39 bytes A trivial modification of the classic TPR(0,3) solution: ``` perl -E 'say$_=($.+=!--$.[$.])%2+1for@.=(0)x pop' 20 ``` [Answer] # Haskell 157 144 Haskell is kind of verbose so I expect this will be significantly longer than the shortest answer, but here it is. ``` import System a=1:2:drop 2(concat.zipWith replicate a.cycle$[1,2]) main=do args<-getArgs;putStr$concatMap((' ':).show)$take(read$args!!0::Int)a ``` ### Edit: Implemented FUZxxl's suggestions and also a few other small fixes. [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 128 bytes ``` (({}<((())<>)>)<{({}[()]<{{({}[()])<>(({}))<>}{}<>(()()()[{}])<>}<>{({}<>)<>}(())<>>)}>){({}[()]<({}<>)<>>)}{}{{}}<>{({}<>)<>}<> ``` [Try it online!](https://tio.run/##VYw7CoBADESvkym1DrnIYrHaKIKFbcjZ4wRZQdLM503Wux/X3rczU8RDRQRQg0GdvgkW9aFYFFRAkKVBXfOoikGBHFO/bwxh@P6MkqmHe/wGapk5zQ8 "Brain-Flak (BrainHack) โ€“ Try It Online") [Answer] # Python (118 characters) Takes n as a command line argument. Could trim four more characters if the printing of first n requirement is relaxed to first n or n + 1. I can't think of any more fat to trim...will be interested to see what a more experienced Python golfer could do ``` import sys k,b=[1,2,2],1 n=int(sys.argv[1]) while len(k)<n:k.extend([2,1][b%2]for z in range(k[b+1]));b+=1 print k[:n] ``` [Answer] ## Perl, 59 chars ``` say"@{[map{push@a,(2-$_%2)x($b=$a[$_-1]||$_);$b}1..shift]}" ``` As usual, run with Perl 5.10+ and the `-M5.010` switch to enable the `say` feature. [Answer] ### Javascript (414 Characters) ``` function range(n,e,t){if("undefined"==typeof e&&(e=n,n=0),"undefined"==typeof t&&(t=1),t>0&&n>=e||0>t&&e>=n)return[];for(var i=[],r=n;t>0?e>r:r>e;r+=t)i.push(r);return i}function kolakoskiGen(n){var e=[1,2,2],t=parseInt(n),r=range(2,t);for(i in r)if(-1!=r.indexOf(parseInt(i))){var f=[1+i%2];f.length=f.length*e[i],f[f.length-1]=f[0],2==f.length?(e[e.length]=f[0],e[e.length]=f[1]):e[e.length]=f[0]}console.log(e)} ``` Could probably be more Efficient ]
[Question] [ [Hamming numbers](http://en.wikipedia.org/wiki/Hamming_numbers) are numbers which evenly divide a power of 60. Equivalently, their prime factors are all \$ \le 5 \$. Given a positive integer, print that many Hamming numbers, in order. Rules: * Input will be a positive integer \$n \le 1,000,000 \$ * Output should be the first \$n\$ terms of <https://oeis.org/A051037> * Execution time must be \$<1\$ minute * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code wins [Answer] ## Haskell, ~~101~~ ~~97~~ 92+|n| characters ``` h=1:m 2h&m 3h&m 5h m=map.(*) c@(a:b)&o@(m:n)|a<m=a:b&o|a>m=m:c&n|0<1=a:b&n main=print$take 1000000h ``` Computes the full million in 3.7s on the machine I tested on (variably more if you actually want the output stored) Ungolfed: ``` -- print out the first million Hamming numbers main = print $ take 1000000 h -- h is the entire Hamming sequence. -- It starts with 1; for each number in the -- sequence, 2n, 3n and 5n are also in. h = 1 : (m 2 h) & (m 3 h) & (m 5 h) -- helper: m scales a list by a constant factor m f xs = map (f*) xs -- helper: (&) merges two ordered sequences a@(ha:ta) & b@(hb:tb) | ha < hb = ha : ta & b | ha > hb = hb : a & tb | otherwise = ha : ta & tb ``` All Haskell is notoriously good at: defining a list as a lazy function of itself, in a way that actually works. [Answer] **Python 181 Characters** ``` h=[] h.append(1) n=input() i=j=k=0 while n: print h[-1] while h[i]*2<=h[-1]: i+=1 while h[j]*3<=h[-1]: j+=1 while h[k]*5<=h[-1]: k+=1 h.append(min(h[i]*2,h[j]*3,h[k]*5)) n-=1 ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~34~~ 23 bytes ``` {โบโด{โต[โ‹โต]}โˆช,โตโˆ˜.ร—โณ5}โฃโ‰กโˆ˜1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHvbse9W4BUlujH/V2A6nY2kcdq3SAjEcdM/QOT3/Uu9m09lHv4kedC4EChkBdCkZcaQqGBgZcj3o69BXSFEwNQAAA "APL (Dyalog Classic) โ€“ Try It Online") TIO throws a WS FULL error for \$n = 1000000\$, but Dyalog on my laptop runs in about 45 seconds, not counting the scrolling to display numbers. ``` {โบโด{โต[โ‹โต]}โˆช,โตโˆ˜.ร—โณ5}โฃโ‰กโˆ˜1 Monadic function: {โบโด{โต[โ‹โต]}โˆช,โตโˆ˜.ร—โณ5} Define the following helper function g(โบ,โต): โตโˆ˜.ร—โณ5 Make a multiplication table between โต and (1 2 3 4 5). (Including 4 is unnecessary but saves bytes.) , Flatten the table into an array. โˆช Keep unique elements. {โต[โ‹โต]} Grade up the array and access it at those indices. (This is the APL idiom to sort an array.) โบโด Keep the first โบ elements; pad by repeating the array. {โบโด{โต[โ‹โต]}โˆช,โตโˆ˜.ร—โณ5}โฃโ‰ก Repeatedly apply g with some fixed left argument until a fixed point is reached. At this point we have a dyadic function that takes n on the left and the starting value on the right, and returns multiples of the n Hamming numbers. โˆ˜1 Fix 1 as the right argument. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 8 bytes ``` ฮปdวG7<;ศฏ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%CE%BBd%C7%8FG7%3C%3B%C8%AF&inputs=200&header=&footer=) ``` ฮป ;ศฏ # First n numbers where dวG # Maximum of prime factors 7< # Less than 7 ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~29~~ 26 bytes, times out when n>=200,000 on online interpreter. My first ever Vyxal post. 29->26, adviced by @lyxal. ``` 6ษฝ{:L?<|:2*$:3*$:5*โˆชโˆชโˆช}s?แบŽ ``` ## How it works ``` # let first hamming numbers are 1 to 6 6ษฝ # while items of they are less than n; do {:L?<| # for each item, multiply with those numbers # and then unify them; done :2*$:3*$:5*โˆชโˆชโˆช} # sort s # take first n items ?แบŽ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=6%C9%BD%7B%3AL%3F%3C%7C%3A2*%24%3A3*%24%3A5*%E2%88%AA%E2%88%AA%E2%88%AA%7Ds%3F%E1%BA%8E&inputs=200&header=&footer=) [Answer] ## Ruby - 154 231 characters ``` def k i,n;(l=Math).log(i,2)*l.log(i,3)*l.log(i,5)/6>n end def l i,n;k(i,n)?[i]:[i]+l(5*i,n)end def j i,n;k(i,n)?[i]:[i]+j(3*i,n)+l(5*i,n)end def h i,n;k(i,n)?[i]:[i]+h(2*i,n)+j(3*i,n)+l(5*i,n)end puts h(1,n=gets.to_i).sort.first n ``` And now it's fast enough, there is definitely a lot of golfing that can still happen though. ``` โ†’ time echo 1000000 | ruby golf-hamming.rb | wc 1000000 1000000 64103205 echo 1000000 0.00s user 0.00s system 0% cpu 0.003 total ruby golf-hamming.rb 40.39s user 0.81s system 99% cpu 41.229 total wc 1.58s user 0.05s system 3% cpu 41.228 total ``` [Answer] # MMIX, 92 bytes (23 instrs) I'm cheating a bit; instead of printing (which would take a lot of work, this being machine language), I instead pass the numbers to a function passed in! ``` 00000000: fe020004 34000100 e3030000 c1040300 โ€œยฃยกยฅ4ยกยขยกแบ‰ยคยกยกแธŠยฅยคยก 00000010: e7030001 da040403 3c040304 1d050403 แธƒยคยกยขแธทยฅยฅยค<ยฅยคยฅรธยฆยฅยค 00000020: feff0006 6204ff05 43fffffd 1d050405 โ€œโ€ยกยฉbยฅโ€ยฆCโ€โ€โ€™รธยฆยฅยฆ 00000030: feff0006 6204ff05 43fffffd 31ff0401 โ€œโ€ยกยฉbยฅโ€ยฆCโ€โ€โ€™1โ€ยฅยข 00000040: 5bfffff3 e7000001 c1050300 bf040100 [โ€โ€แน™แธƒยกยกยขแธŠยฆยคยกแธ‚ยฅยขยก 00000050: 5b00ffef f6040002 f8000000 [ยกโ€แนแบ‡ยฅยกยฃแบยกยกยก ``` ``` smooth5 GET $2,rJ NEG $0,1,$0 // n = 1 - n SETL $3,0 // i = 0 0H SET $4,$3 INCL $3,1 // loop: j = i++ SADD $4,$4,$3 // j = popcnt(j & ~i) SR $4,$3,$4 // j = i >> j (cheap way of getting out factors of 2) 1H DIV $5,$4,3 // lp3: k = j / 3 GET $255,rR // tmp = j % 3 CSZ $4,$255,$5 // if(!tmp) j = k BZ $255,1B // if(!tmp) goto lp3 1H DIV $5,$4,5 // lp5: k = j / 5 GET $255,rR // tmp = j % 5 CSZ $4,$255,$5 // if(!tmp) j = k BZ $255,1B // if(!tmp) goto lp3 CMP $255,$4,1 // tmp = j <=> 1 PBNZ $255,0B // iflikely(tmp) goto loop INCL $0,1 // n++ SET $5,$3 PUSHGO $4,$1,0 // f(i) PBNZ $0,0B // iflikely(n) goto loop PUT rJ,$2 POP 0,0 // return ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Rแธคร†fแน€โ‚ฌ<7T ``` [Try it online!](https://tio.run/##y0rNyan8/z/o4Y4lh9vSHu5seNS0xsY85P///4YGAA "Jelly โ€“ Try It Online") Returns all hamming numbers under n. **How?** ``` Rแธคร†fแน€โ‚ฌ<7T Main Link. Takes n on the left T Filter by R Inclusive range แธค Double each ร†f Prime factors โ‚ฌ For each แน€ Maximum <7 Less than 7 ``` My first serious jelly answer [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 97 bytes Inefficient but golfy. Lot's of keywords and whitespace, so potential for more golfing. ``` def f(n): h=[1] while(n:=n-1):h+=[min(j*k for j in(2,3,5)for k in h if j*k not in h)] return h ``` [Try it online!](https://tio.run/##JZDNboMwEITvPMWKE25dCf8AJhKHXipVrdQHQNwKgiR1IkJU9enpjHOwPbM79n7y9W@bL9GF67rv3@MkUxHVIZO5682Qye@8nMciHrr4YtRhfu76nyUWx6eTTJdVjgJjtdOVoj3ByizLJAzEy5a8wjPruN1X6H0bb5t00hstVovT4rVUWmotQUurxZRY6BgUDaoGZYuaRc6iZhvcgne8jb6H9qh75CroCrkaZ42zQaZBL8AHDGxxtnyz5JAycFIax1mW1lF5z/Fs1GkjDZ8wrSULYUhmE45PbI5wVBUbDVUIBE2kafPkpSKRC57oZC@rIcvW8XY/81@m4jzGgp@kVJZd1yVuRZ@/vb5/5jr/@siH/hHtOmYG/XBq/wc "Python 3.8 (pre-release) โ€“ Try It Online") # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 165 bytes Slightly golfed version of the [original Python entry](/a/466/86751). Reposted, because of its age. ``` def f(n): h=[1];i=j=k=0 while(n:=n-1): m=h[-1] while(h[i]*2<=m):i+=1 while(h[j]*3<=m):j+=1 while(h[k]*5<=m):k+=1 h+=[min(h[i]*2,h[j]*3,h[k]*5)] return h ``` [Try it online!](https://tio.run/##VVBLboMwFNxziidWkDgS/gAmrRfdVKpaqQdA3pXI5ONGhKjq6ekb00W7sD1vZuwZ@fo9h8@o7XValo/hQIcilvuMguulfxjd0Z1cldFXGM9DEfcu7iRkurjQ76RntEqhH/1GPbpLuR@3Tv7hj36jE3/8z5/8pk78aeXD1vWXMf6@JNaLYvWVHDQN832KFJZ5uM3kqJeClCAtyAiqBTWCrKBOkKx4sSKZlMxKphVzin2KOdXyLZ41brNuGBvmDftqxjX7Gj4bPlv2tKxZni0Hdnx2eLNCSGWRlOKQpTBqIGMQD6FJG9rgCdkpdEEZNFOpjkndNMoB1RBaIGtRNDVNm0FfIDTS1qA6ule1z7JpuN3P@JdDcR5igU8qyyy7TmOciz5/fnp5y0X@/pr7frU6B48X61QuPw "Python 3.8 (pre-release) โ€“ Try It Online") [Answer] # JavaScript (ES6), 110 bytes ``` f=h=>eval("g=n=>n-1n?n%2n?n%3n?n%5n?0:g(n/5n):g(n/3n):g(n/2n):1;r=[i=1n];while(!r[h-1])if(g(++i))r.push(i);r") ``` Theoretically works for arbitrarily large inputs, but prohibitively slow. [Answer] # [GAWK](https://www.gnu.org/software/gawk/manual/gawk.html) `-M`, ~~138~~ 120 bytes. It was originally [a post on rosetta code](http://rosettacode.org/wiki/Hamming_numbers#AWK). Without `-M` it overflows when huge value is input. ``` {a=2 b=3 c=5 for(s=h[0]=1;--$0;c-z||c=5*h[++k]){z=a<b?a:b s=s" "(z=h[++n]=z<c?z:c) a-z||a=2*h[++i] b-z||b=3*h[++j]}}$0=s ``` [Try it online!](https://tio.run/##HY1BCoMwEEX3c4oiLrQSiC3dqIMn6AlkFkmgaAVTOoVC1Kt3mrh8PN7/5juLrAYvYPEKDm/w8O@CcRw0Yd0qlevWqbBtUZ3HoapmKteAprO9aSwwcnbKioBJLYShc31oXAkmNXH2aCYCmzheHPykfc81skitf/71mfzCou5/ "AWK โ€“ Try It Online") ## Usage Given from stdin, as a line consists of a string of decimal natural number. ## Execution time Tested in my Termux. CPU is: ``` Architecture:ย ย ย ย ย ย ย  aarch64 CPU op-mode(s):ย ย ย ย ย  32-bit, 64-bit Byte Order:ย ย ย ย ย ย ย ย ย  Little Endian CPU(s):ย ย ย ย ย ย ย ย ย ย ย ย ย  8 On-line CPU(s) list: 0-7 Thread(s) per core:ย  1 Core(s) per socket:ย  4 Socket(s):ย ย ย ย ย ย ย ย ย ย  2 Vendor ID:ย ย ย ย ย ย ย ย ย ย  ARM Model:ย ย ย ย ย ย ย ย ย ย ย ย ย ย  4 Model name:ย ย ย ย ย ย ย ย ย  Cortex-A53 Stepping:ย ย ย ย ย ย ย ย ย ย ย  r0p4 CPU max MHz:ย ย ย ย ย ย ย ย  1768.0000 CPU min MHz:ย ย ย ย ย ย ย ย  449.0000 BogoMIPS:ย ย ย ย ย ย ย ย ย ย ย  52.00 Flags:ย ย ย ย ย ย ย ย ย ย ย ย ย ย  fp asimd evtstrm aes pmull sha1 sha2 crc32 ``` ### With original code 10^6th Hamming number is `519312780448388736089589843750000000000000000000000000000000000000000000000000000000`. ``` $ time echo 1000000 | awk -Mf Textfile/ham.awk # lots of output realย ย ย  2m36.842s userย ย ย  0m25.224s sysย ย ย ย  0m5.356s ``` ### If `$0=s` is removed ``` $ time echo 1000000 | awk -Mf Textfile/ham.awk realย ย ย  0m25.404s userย ย ย  0m24.676s sysย ย ย ย  0m0.716s ``` ## Note * Original 138 bytes of post outputs incorrectly: it outputs n+1 numbers, not n. [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 7 bytes ``` ะงdแธŸG7<แบ† ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLQp2ThuJ9HNzzhuoYiLCIiLCI0MCIsIjMuNC4xIl0=) Port of Emanrasu's Vyxal answer [Answer] ## Ursala, 103 ``` #import std #import nat smooth"p" "n" = ~&z take/"n" nleq-< (rep(length "n") ^Ts/~& product*K0/"p") <1> ``` **Output** for `main = smooth<2,3,5>* nrange(1,20)` ``` <1,2,3,4,5,6,8,9,10,12,15,16,18,20,24,25,27,30,32,36> ``` [Answer] ## Haskell, 71 ``` h n = drop n $ iterate (\(_,(a:t))-> (a,union t [2*a,3*a,5*a])) (0,[1]) ``` **Output** ``` *Main> map fst $ take 20 $ h 1 [1,2,3,4,5,6,8,9,10,12,15,16,18,20,24,25,27,30,32,36] ``` ]
[Question] [ *The goal of this challenge is to fill a niche that is mostly lacking on this site. In my observations there most parsing verification challenges fall into two categories:* 1. Super easy parsing. This parsing can usually be done with a regex, and regex based answers usually do well. 2. Super complex parsing. These are challenges with a lot of small parsing components that would on their own be type 1, but together make for long code with a lot of edge cases. Neither of these categories are really bad, each can have fun challenges, but I want to shoot for something different. A challenge which is hard, hard enough that a regex will be unable to do the brunt of the work but with an easy to understand spec. --- The goal of this challenge is to parse a *lisp-like* lambda function. Your code should accept a string as input and output of two possible consistent values. One which corresponds to an affirmative response (i.e. the input is a properly formatted lambda) and the other corresponds to a negative response (i.e. the input is *not* a properly formatted lambda). The string will only contain lowercase letters, spaces and parentheses (`(` or `)`). I've put together 3 specifications of what constitutes a validly formatted lambda for this challenge. The first is a quick intuition base explanation. It explains the process and what things mean even if it is not perfectly rigorous. The second a formal grammar which expresses the idea succinctly and with no ambiguity. And the third is raw code, which is the hardest to read for humans but allows you to play around with the idea by trying different inputs. I recommend you read one of the first two and play around with the third. ## Formatting The challenge uses a lisp like format. This consists of "lists" which are just parentheses enclosing lowercase words, and other lists separated each by exactly one space. So ``` (foo (bar baz) foobar) ``` Would be a lisp-like "list". For our challenge each list will be identified by it's first element (which should by highlighted by the syntax highlighter), which must be either `app`, `abs`, or `var`, representing applications, abstractions and variables, respectively. An application is the application of one lambda function to another. It is represented by a three element list starting with of course `app` followed by two other valid lambda expressions. So if `S` and `K` were valid lambdas then: ``` (app S K) ``` would be a valid lambda too. The other two abstractions and variables work together, an abstraction introduces new names for variables and variables use those names. An abstraction encloses some lambda which must be valid with the introduced variable name, and a variable can only use names which are given by abstractions that surround it. So ``` (abs x (abs y (var x))) ``` Is valid because the `x` name was introduced and used in a nested context. But ``` (app (abs x (var x)) (var x)) ``` Is not because even though there is an abstraction for `x` the second `(var x)` is not surrounded by any abstraction at all, let alone one that introduces `x`. Additionally abstractions can only introduce *new* variables, so ``` (abs x (abs x (var x))) ``` is not valid because the name `x` is ambiguous, it could refer to either abstraction. Variable names must be a string of lowercase ascii letters (`a`-`z`). ## Grammar Now for the golfy definition. This parse cannot be defined in terms of a context free grammar, so this grammar uses context. The context is a set of strings of lowercase ascii letters (these are the valid variable names) and is represented here with \$C\$. To start \$C\$ is empty. \$ S\left(C\right) := \left\{ \begin{array}[rr] \ \color{green}{\texttt{(var }}x\color{green}{\texttt{)}} & \textrm{ where } x\in C \\ \color{green}{\texttt{(abs }} x\texttt{ }S(C\cup\{x\})\color{green}{\texttt{)}} & \textrm{ where } x\notin C\\ \color{green}{\texttt{(app }} S(C)\texttt{ }S(C)\color{green}{\texttt{)}} & \end{array} \right. \$ Any string spanned by the grammar from \$S(\{\})\$ is valid and any string not is invalid. ## Code ``` lambda :: [String] -> Parser () lambda variables = do char '(' choice [ do string "abs " name <- some $ charBy (`elem` ['a'..'z']) guard $ notElem name variables char ' ' lambda (name : variables) , do string "var " choice (map string variables) return () , do string "app " lambda variables char ' ' lambda variables ] char ')' return () ``` [Try it online!](https://tio.run/##pVRNa@MwEL3nVwylYImmhuYYmkBbdm@FhT1mTaskcmLWX8iKmyz979mRNFIUp90e9mJJM2@e3nzIW9H9lmV5LKq2URqemlqrpkwf2rYsVkIXvRwBMCiLXD9McDuGh1JLVVsXsDTlaOSjQfhzU4u1DdzshFpbyKiWb/rQSvghVCcVCJihnQ7sp1ZFvYHbOSxoPwbBMwwTKOUA0@kpDkGfwAnMCNpy6OwtLa6jUVF3WtQrCd939Uo3yjO@baUyaeaVaCFHX0xgwoPMa4dh9hPgnEMbsUe1G97Q7pSE/Tkng1/QRel0lM6eZ6ZqQLWH/KTqjp/2k3OJdgsD0nVDZnQoWd2NQckOSe5vkYtwZ4iJRUwcYgImJviV1DtVe1huqRyaIDyqhR2EYRW8dJjPZ0jwX/KH6mkAcoJEymNZ8QwPxMmq1YfLDr3Y5piOAEQp3MH9@zycJsNpOc8j1BpubgyYDihstRXq0Q45e8KtAT82TcnNhsiM3eNaJddmwmT8hDamSj4LwCMwAVNY@vkAWABbmmcC7xGDgMzjMb0AzZwoI8krGgqhQSZNbD@bYSaUE4adnigFOoNHmFCtRC/RZznMhU2BzcHYhX/rWRQvPMCE5k25xs5g9blr2bEU1XItbLS7KY5lfET@XqhCLEvpfgw0WjadhCV0MLeEmkXTR9KvxLKDq2CtRSXNLHYNrtehHq@ylNUrLBKRpGnyJ8l4iLA/RYTWjf6GIMcQhAWYUwVJMFAKzOKnpwjPPP5ILKIisVRC@wcjxAXN6Y3/kxifWkQ8LO@XWQyRWdQJ7tBBxrESRW0bhrqfX4C1KEFDCmw2w1eeQinrjd7iht4/3bHIuEthAVfMFGLPneIxnk0X@x6sve/5wLM/OE@@ufCAXci/52d@rIkHkTdsLlkM2Dm/4voQGnQE74H7lX@iev/hTWdZDZIb4JzDW7PjXw "Haskell โ€“ Try It Online") ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with the goal being a smaller score. ## Test cases ### Reject ``` (abs x (var x uuuuuuuuu )))(abs x (var x)) app (abs x (var x)) (abs x (var x)) (mmm hummus) (abs x (var y)) (abs x (abs x (var x))) (app (abs x (var x)) (var x)) (abs (var k) (var (vark k))) (abs x (abs y (abs y (var x)))) (abs x(var x)) ``` ### Accept ``` (abs x (var x)) (abs x (abs y (var x))) (abs xx (app (var xx) (var xx))) (app (abs ab (app (var ab) (var ab))) (abs ab (app (var ab) (var ab)))) ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 86 bytes Who said this canโ€™t be solved with a regex? โ˜บ ``` $_=reverse=~/^(\)(((\w+) (?=([^)]|(?1))* \4 ))rav|(?1) ((?!(?3))\w+ sb|(?1) pp)a)\()$/ ``` [Try it online!](https://tio.run/##hcrBCsIwEIThV1mhhxlFiqjHkAcxVjaQgyB2SSS9iI9uLBa8eptv@C3l27G17uJyqimX5F79gEAAYdpQ4B1OA89P@B25lnAQMmv9WgC/gt@TcyslLqcZlQHs@tagZgKNRTTKgqp5Bn@D/BvwPdrjOt5L29oH "Perl 5 โ€“ Try It Online") Outputs `1` for acceptance or the empty string for rejection. To get around restrictions on lookbehind, I reverse the input and use lookahead instead. [Answer] # [Raku (Perl 6)](https://github.com/nxadm/rakudo-pkg) `-p`, 123 bytes ``` my %v;my$r=rx["(abs "(\w+)<!{%v{$0}++}>\s<~~>{--%v{$0}}")"|"(app "<~~>\s<~~>")"|"(var "(\w+)<?{%v{$0}}>")"];$_=so m/^^$r$$/ ``` [Try it online!](https://tio.run/##K0gtyjH7/z@3UkG1zDq3UqXItqgiWkkjMalYQUkjplxb00axWrWsWsWgVlu71i6m2Kauzq5aVxciVKukqVQDVFxQoKAEkoBIQwTLEotgJthDTagFScVaq8TbFucr5OrHxakUqajo//8PNgBsZWKSAoQD0p2YpAlnaGoSVKDJ9S@/oCQzP6/4v24BAA "Perl 6 โ€“ Try It Online") First time golfing in Raku (this seemed like an apt challenge to give it a spin), so there's probably room for improvement. It's a simple parse of the text, using the `%v` hash to keep track of existing variables. [Answer] ## [Tiny Lisp](https://codegolf.stackexchange.com/q/62886/2338), 318 ``` (d C(q((E L)(i(e L())0(i(e E(h L))1(C E(t L)))))))(d H(q((le li)(i(e()li)(e le 0)(H(s le 1)(t li))))))(d I(q((L X)(i(e(q abs)(h L))(i(H 3 L)(i(C(h(t L))X)0(I(h(t(t L)))(c(h(t L))X)))0)(i(e(q var)(h L))(i(H 2 L)(i(C(h(t L))X)1 0)0)(i(e(q app)(h L))(i(H 3 L)(i(I(h(t L))X)(I(h(t(t L)))X)0)0)0))))))(d V(q(()(L)(I L())))) ``` This defines a macro `V` (for verify) which can be applied to a list, and will check whether it is of the proper form as defined in the question. This can't do any checks on a lexical level, as Tiny Lisp has no string input (and not even a string type). Therefore it is running out of competition Here are some test cases: ``` ------examples-from-question----- ((V (abs x (abs y (var x)))) โ€‡โ€“โ€“โ†’โ€‡ 1) ((V (app (abs x (var x)) (var x))) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs x (abs x (var x)))) โ€‡โ€“โ€“โ†’โ€‡ 0) ----examples-from-TIO---- ((V (var x)) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs vv (var vv))) โ€‡โ€“โ€“โ†’โ€‡ 1) ((V (abs xy (var fg))) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs x (abs y (var x)))) โ€‡โ€“โ€“โ†’โ€‡ 1) ((V (app (abs x (var x)) (var x))) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs x (app (var x) (var x)))) โ€‡โ€“โ€“โ†’โ€‡ 1) ((V (app (abs x (app (var x) (var x))) (abs y (app (var y) (var y))))) โ€‡โ€“โ€“โ†’โ€‡ 1) ((V (abs x (abs x (var x)))) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs x (abs y (abs y (var x))))) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs (var))) โ€‡โ€“โ€“โ†’โ€‡ 0) ---reject--------- ((V uuuuuuuuu) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (mmm hummus)) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs x (var y))) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs x (abs x (var x)))) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (app (abs x (var x)) (var x))) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs (var k) (var (vark k)))) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs x (abs y (abs y (var x))))) โ€‡โ€“โ€“โ†’โ€‡ 0) ((V (abs x (var x))) โ€‡โ€“โ€“โ†’โ€‡ 1) --------accept-------- ((V (abs x (var x))) โ€‡โ€“โ€“โ†’โ€‡ 1) ((V (abs x (abs y (var x)))) โ€‡โ€“โ€“โ†’โ€‡ 1) ((V (abs xx (app (var xx) (var xx)))) โ€‡โ€“โ€“โ†’โ€‡ 1) ((V (app (abs ab (app (var ab) (var ab))) (abs ab (app (var ab) (var ab))))) โ€‡โ€“โ€“โ†’โ€‡ 1) ``` The last "reject" case (with the missing space) is accepted, as we are parsing this as a tiny lisp list, not as a lambda. The test cases with unbalanced parentheses can't even be run. Here is the code formatted, and with some comments (I've extended the reference implementation of Tiny Lisp to include Python-style line comments). (The comments all start with `#!` because that can be handled by my automated whitespace-and-comment-remover made for Ceylon.) ``` #! tinylisp.py #! Parse a lambda for correctness. #! Question: https://codegolf.stackexchange.com/q/233453/2338 #! My answer: https://codegolf.stackexchange.com/a/233925/2338 #! checks whether some element is contained in a list. (d C #! for "contains" (q ((E L) #! E = the element to be checked #! L = the list in which the element is searched (i (e L ()) 0 (i (e E (h L)) 1 (C E (t L)) ) ) ) ) ) #! checks whether a list has a specified length. #! len = expected length #! list = list to check (d H #! for has-length (q ((le li) #! le = the asserted length #! li = the list to check (i (e () li) (e le 0) (H (s le 1) (t li)) ) ) ) ) #! This is the main working force here. #! I (for "is-valid") checks (recursively) whether a lambda expression is valid #! in a given context of defined variable names. (d I (q ((L X) #! L = candidate for a lambda function, #! X (context) = list of defined variable names (i (e (q abs) (h L)) (i (H 3 L) (i (C (h (t L)) X) 0 (I (h (t (t L))) (c (h (t L)) X))) 0) (i (e (q var) (h L)) (i (H 2 L) (i (C (h (t L)) X) 1 0) 0 ) (i (e (q app) (h L)) (i (H 3 L) (i (I (h (t L)) X) (I (h (t (t L))) X) 0) 0) 0 ) ) ) ) ) ) #! V (for "verify") is the entry point to call from the outside. #! `(V (...))` returns 1 when it's a valid lambda expression, 0 when it is not. (d V (q (() (L) (I L ()) ) ) ) ``` [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 116 bytes ``` p"(var "a x|elem a x=0 p"(app "(a++' ':b)x=a#x+b#x p"(abs "(a++' ':b)x|all(>'@')a=b#(a:x) (#)(k++n++")")=p k n (#[]) ``` [Try it online!](https://tio.run/##VU7BCsIwFLv3K0IrrI@ieB5UvHrSu3h43cYYm7V0Tirs3@foTuaQhOSQVFOM333gvhqXJUj94QjJSHMzNE@sxh7FGnMIWNmYAkXpKFlWyTiVcufGv27mYdCn4lwQW6c0l4mEVqR7Y7wxkiTZgB5etFar@4OWJ3ceZYlbbIapbg6XKzSJnFrULwGE2Pk3dmixzTGyOORj@TTTpo5WyEX8AA "Curry (PAKCS) โ€“ Try It Online") `g` returns `0` if there is a match and fails to find a match if there is none. ## Explanation This looks and sort of works like a Haskell answer might. However Curry's pattern matches are way more powerful than Haskell's because it has a trick up it's sleeve. As well as a functional programming language Curry is a logical language. It has non-determinism. In Haskell a pattern either matches or it doesn't. In Curry a pattern can match a string multiple ways and it will follow through each to find the one you meant. So ``` p("(app "++a++' ':b++")") ``` Will cold potentially match many things. For example ``` p"(app (var x) (var y))" ``` can break that apart at any space in the string. Curry will match all of them and attempt to run them. All the bad ones will fail later down the line. [Answer] # Scala, 293 bytes The function that does all the work: ``` def f(s:Any,c:Set[Any]=Set()):Option[Any]=s match{case s"(var $v)$r"=>Option.when(c(v))(r)case s"(abs $v $r"=>if(!c(v)&v.matches("[a-z]+"))f(r,c+v).collect{case s")$r"=>r}else None case s"(app $o"=>f(o,c).collect{case s" $r"=>f(r,c)}.flatten.collect{case s")$r"=>r}case _=>None} ``` This one simply turns an `Option` into a `Boolean`. ``` f(_)==Some("") ``` [Try it in Scastie!](https://scastie.scala-lang.org/rKZTRkezR8ihidaHyjdUbQ) Ungolfed: ``` //sexpr is the string to parse, ctx is the context (a Set[String] in reality) //If valid, it will return a Some containing the rest of the string, otherwise a None def f(sexpr: Any, ctx: Set[Any] = Set()): Option[Any] = sexpr match { case s"(var $varName)$rest" => //Check if varName is defined, and only then return the rest Option.when(ctx.contains(varName))(rest) case s"(abs $varName $rest" => //Make sure varName isn't already defined and that it's a valid name if (!ctx.contains(varName) && varName.matches("[a-z]+")) //If so, parse the rest, adding varName to the context f(rest, ctx + varName) .collect { case s")$rest" => rest } //Ensure there's a matching `)` else None //If the name is invalid, so is the expression case s"(app $first" => //Try parsing the first argument f(first, c) //Ensure there's a space after it and parse the rest .collect { case s" $rest" => f(rest, ctx) } .flatten //Turn the Option[Option[String]] into an Option[String] .collect { case s")$rest" => rest } //Ensure there's a matching `)` case _ => None //If it's not a var, abs, or app, it's invalid } ``` ]
[Question] [ Given a number from 1 to 24, output the kissing number to the best of current knowledge (some numbers will have more than one acceptable output). Knowledge of geometry is not essential as the outputs are all listed below. From the [Wikipedia page on the Kissing Number Problem](https://en.wikipedia.org/wiki/Kissing_number_problem): > > a kissing number is defined as the number of non-overlapping unit spheres that can be arranged such that they each touch another given unit sphere > > > That is, given one unit sphere, how many more unit spheres can touch it without any of them overlapping? The question will be asked in N dimensional space, where a sphere is understood to be an N-1 dimensional sphere. For example: * in 2 dimensional space, a unit circle can touch 6 other unit circles. * in 3 dimensional space, a unit sphere can touch 12 other unit spheres. The Wikipedia page lists values for 1 to 24 dimensional space. However, some of these are not yet known accurately, so only a lower and upper bound are given. The table is reproduced here so that it will remain fixed, regardless of any future narrowing of the ranges due to new proofs. Solutions are judged against this fixed table, even if the Wikipedia page is modified in future. # Table of bounds ``` Dimension Lower bound Upper bound 1 2 2 2 6 6 3 12 12 4 24 24 5 40 44 6 72 78 7 126 134 8 240 240 9 306 364 10 500 554 11 582 870 12 840 1357 13 1154 2069 14 1606 3183 15 2564 4866 16 4320 7355 17 5346 11072 18 7398 16572 19 10668 24812 20 17400 36764 21 27720 54584 22 49896 82340 23 93150 124416 24 196560 196560 ``` # Input The dimension: An integer from 1 to 24 (inclusive). Here "integer" indicates that the input will have no fractional part - it may be `2` or `3` but never `2.5`. A solution may still take input as a float, or a string, for example. # Output A number in the relevant range, from the lower limit to the upper limit for that input (inclusive). The output must be deterministic (always the same for the same input). The output must be integer. For example, for input `5` the possible valid outputs are `40`, `41`, `42`, `43`, `44`. Note this is a restriction on the value, not the type. It is acceptable to return a float, provided it has zero fractional part. For example, `41.5` would not be valid, but `41.0` would be valid. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Your score is the number of bytes in your code. For each language, the winner is the solution with the lowest score. [Answer] # [Julia 0.6](http://julialang.org/), 52 bytes ``` n->ceil(n<8?3.7exp(.51n)-5.1:n<24?9exp(.41n):196560) ``` [Try it online!](https://tio.run/##HctBCoAgEADAr3jchZQstRTLt0gUGLZIFPR7i64Ds985RVM3NrFKfF7WlIH8GHoxrE8BoSUh10I68p0K9jf1mZPWaNNiPWKBL5Yz0ZUJNiDEhknXKawv "Julia 0.6 โ€“ Try It Online") ### How? Machine learning! (Kinda. Maybe. *Not really.*) First, from plotting the lower and upper limit data against N, and some manual trial and error, it seemed like an exponential function could fit well for N >= 8. After some attempts at manually finding this function, I resorted to using a [parameter tuning function](http://mlbasejl.readthedocs.io/en/latest/modeltune.html#gridtune) to tune \$ a \* e^{b K} + c \$ (where K = 8 to 24) to find a, b, and c such that the expression gave values that lie within the correct range for each K (with successively smaller range of possible values and correspondingly higher precisions for a, b, c in different runs of the function). There were a few such set of values, though none of them could fit the N=24 case exactly, so I went with one that had 0 `c` and hardcoded the value for N=24. For lower N, from 1 to 7, I was hoping to find some simpler expression or polynomial, but couldn't find any that fit. So back to fitting \$ a \* e^{b K} + c \$ , this time for K = 1 to 7 (though I didn't really think an exponential would be a right fit in this case, based on visual plot trends). Thankfully, there *were* parameters a, b, c that could give correct values throughout the range here (at least to within a `ceil` call). [Answer] # x86, ~~62~~ ~~59~~ ~~53~~ 50 bytes My solution uses a byte lookup table and shifting by 2 (no FP computations). Dimensions 9 through 23 provide enough leeway for the shifting. Input in `eax` and output in `ecx`. -3 by swapping `eax` and `ecx` since `cmp $imm, %al` is shorter than `cmp $imm, %cl`. -4 by *not* treating the N=24 case separately but applying the adjustment to all times 1024 cases. -2 by not returning early (stupid) -3 by using table as offset and `movzbl` instead of zeroing with `xor` ``` start: dec %eax # 1-indexed table movzbl table(%eax), %ecx # return byte directly cmp $8, %al jl exit sal $6, %ecx # * 64 cmp $19, %al jl exit sal $4, %ecx # * 16 sub $48, %ecx exit: ret #.data table: .byte 2, 6, 12, 24, 40, 72, 126, 240 # * 1 .byte 5, 8, 10, 14, 19, 26, 41, 68, 84, 116, 167 # * 64 .byte 18, 28, 49, 92, 192 # * 1024 - 48 ``` Hexdump (table in `.text` instead of `.data`) ``` 00000502 48 0f b6 88 1c 05 00 00 3c 08 7c 0d c1 e1 06 3c |H.......<.|....<| 00000512 13 7c 06 c1 e1 04 83 e9 30 c3 02 06 0c 18 28 48 |.|......0.....(H| 00000522 7e f0 05 08 0a 0e 13 1a 29 44 54 74 a7 12 1c 31 |~.......)DTt...1| 00000532 5c c0 |\.| ``` [Answer] # JavaScript (ES6), 60 bytes ``` f=(n,k=2)=>n<24?--n?f(n,k*24/(17+~'_8443223'[n])):~~k:196560 ``` [Try it online!](https://tio.run/##FYzBDoIwEAXvfMXGC621apeKChQ@xBhDkBqFbA0YL8b@eq2Xl8lk8h7tu5276f58SXLXPgRrGK0Gg9zUVKFupKTG/tUS9YapvfDp5aB1hpilJzpzXng/FOqY7/JtsG5iBAZUCQSVAdQRhODwSQA6R7Mb@/XobjESsAAp67gC4j/nZfINPw "JavaScript (Node.js) โ€“ Try It Online") ### How? The last term \$a\_{24}=196560\$ is hard-coded. All other terms are computed recursively, using: $$\begin{cases}a\_1=2\\a\_{n+1}=a\_n\times\dfrac{24}{q\_n}\end{cases}$$ where \$q\_n\$ is defined as: $$\begin{cases}q\_1=8\\q\_2=12\\q\_3=12\\q\_4=13\\q\_5=14\\q\_6=14\\q\_7=13\\q\_n=16,&\text{for }n>7\end{cases}$$ leading to the following ratios: $$3,2,2,\frac{24}{13},\frac{12}{7},\frac{12}{7},\frac{24}{13},\frac{3}{2},\frac{3}{2},\ldots,\frac{3}{2}$$ The final result is eventually floored and returned. ### Results summary Approximated results are given with 2 decimal places. ``` n | a(n-1) | multiplier | a(n) | output | expected ----+----------+------------+-----------+--------+------------------- 1 | n/a | n/a | 2 | 2 | 2 ----+----------+------------+-----------+--------+------------------- 2 | 2 | 3 | 6 | 6 | 6 3 | 6 | 2 | 12 | 12 | 12 4 | 12 | 2 | 24 | 24 | 24 5 | 24 | 24/13 | 44.31 | 44 | [40,..,44] 6 | 44.31 | 12/7 | 75.96 | 75 | [72,..,78] 7 | 75.96 | 12/7 | 130.21 | 130 | [126,..,134] 8 | 130.21 | 24/13 | 240.39 | 240 | 240 9 | 240.39 | 3/2 | 360.58 | 360 | [306,..,364] 10 | 360.58 | 3/2 | 540.87 | 540 | [500,..,554] 11 | 540.87 | 3/2 | 811.31 | 811 | [582,..,870] 12 | 811.31 | 3/2 | 1216.97 | 1216 | [840,..,1357] 13 | 1216.97 | 3/2 | 1825.45 | 1825 | [1154,..,2069] 14 | 1825.45 | 3/2 | 2738.17 | 2738 | [1606,..,3183] 15 | 2738.17 | 3/2 | 4107.26 | 4107 | [2564,..,4866] 16 | 4107.26 | 3/2 | 6160.89 | 6160 | [4320,..,7355] 17 | 6160.89 | 3/2 | 9241.34 | 9241 | [5346,..,11072] 18 | 9241.34 | 3/2 | 13862.00 | 13862 | [7398,..,16572] 19 | 13862.00 | 3/2 | 20793.01 | 20793 | [10668,..,24812] 20 | 20793.01 | 3/2 | 31189.51 | 31189 | [17400,..,36764] 21 | 31189.51 | 3/2 | 46784.26 | 46784 | [27720,..,54584] 22 | 46784.26 | 3/2 | 70176.40 | 70176 | [49896,..,82340] 23 | 70176.40 | 3/2 | 105264.59 | 105264 | [93150,..,124416] ----+----------+------------+-----------+--------+------------------- 24 | (hard-coded) | 196560 | 196560 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 26 bytes ``` โ€œ~D=โฑฎziEc+yโ€™Dแธฃ+โตรท7PฤŠยซโ€œยฃ#;โ€™ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5w6F9tHG9dVZboma1c@apjp8nDHYu1HjVsPbzcPONJ1aDVQxaHFytZAmf9GJgqH2x81rVE4Mk3B/T8A "Jelly โ€“ Try It Online") ### How it works ``` โ€œ~D=โฑฎziEc+yโ€™Dแธฃ+โตรท7PฤŠยซโ€œยฃ#;โ€™ Main link. Argument: n โ€œ~D=โฑฎziEc+yโ€™ Set the return value to 485523230101001100011122. D Decimal; convert the return value to base 10. แธฃ Head; take the first n elements of the digit list. +โต Add 10 to each element. รท7 Divide the sums by 7. P Take the product. ฤŠ Ceil; round up to the nearest integer. โ€œยฃ#;โ€™ Yield 196560. ยซ Take the minimum. ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~120~~ 99 bytes Dropped 21 bytes. Big reduction thanks to tsh's suggestion to add a hole to the start of the array (saving two bytes going from `n-1` to `n`, and aiming for round numbers within the lower- and upper-bounds, thus shrinking them from fixed-point notation like `1154` to exponential notation like `2e3`. Again, my original goal was to show how light the "dumb" way would be (eg not using any real math, like Arnauld's answer. It's impressive that there was still room to shrink it without any transformations or calculations. ``` n=>[,2,6,12,24,40,72,126,240,306,500,582,840,2e3,2e3,3e3,5e3,6e3,8e3,2e4,2e4,3e4,5e4,1e6,196560][n] ``` [Try it online!](https://tio.run/##HcxNDoJADAXgvadoXEGmmKHzIwaHixAWBAejIR0Dxo3x7GPD4mvea5o@x8@4Tevj9a443WKeQ@bQ9UjosSYki1bjmSR7KRqN9ui0RtcQNtIpmp0RTnjR7Du7M8KJOsq/i3deDz0PeU5rwRCgboHhGoCsBKVK@B4ApsRbWuJpSXc5UnCEqupkKpgLLsv28Mt/ "JavaScript (Node.js) โ€“ Try It Online") Twice the length of Arnauld's answer, 0 amount of the complexity. # [JavaScript (Node.js)](https://nodejs.org), ~~129~~ 128 bytes (-1 byte thanks to suggestion to use bitshifting) ``` f=(n)=>[2,6,12,24,40,72,126,240].concat([5,8,10,14,19,26,41,68,84,116,167].map(x=>x<<6),[17,28,49,91].map(x=>x<<10),196560)[n-1] ``` [Try it online!](https://tio.run/##TY7BCoMwEETvfsXSU1JXyYYYFRt/RDyI1dJiE1EpQum326WnXoYZ3i4zj@7Vrf1yn7fEh@twHKMTXrq60WiRNGqDRmGu2VsOqk374PtuE02GBZJCMkglMjSEtsCCI/Gnzdv02c1id/V@tkZiQznqAk2JJf0hUvoHS5tZ1crGJ9QeY1iEBwdUgYeLA52xiWMJ7wiA@9cwDekUbnwUwwmSpGaNYeTlsoo@xxc "JavaScript (Node.js) โ€“ Try It Online") To meet the demands of being interesting, I stole the logic from the x86 answer, and built the array from that. Making it 9 bytes longer. But slightly more interesting. [Answer] # Runic, 173 bytes ``` >i:8(?D5X1+1C,*212,+16,+1c2*,+1cX,+Sp3X7+a,*5X1+a,-1+kn$; R:c2*(?D4X1+1C,*212,+16,+1c2*,+Sp9*1+:4XY(?Dkn$; R`196560`r@; ;$*C1nk,C1L ``` (Note that the lower right corner should be counted for bytes: they are implicitly filled with spaces.) TIO's exe [needs an update](https://chat.stackexchange.com/transcript/message/46932492#46932492) that this answer relies on (and I'm patching up some other holes before asking Dennis to rebuild). But plugging a value in (be sure to add whitespace on lines 2 and 3 if using more than one character for the value on the first line). Here's the easiest way to write the values needed: ``` 0-9,a-f -> 1-15 2Xn+ -> 20+n ``` [Try it online!](https://tio.run/##KyrNy0z@/98u08pCw97FNMJQ29BZR8vI0EhH29AMiJONtEBkhI52cIFxhLl2oo4WSFGijq6hdnaeijWXAhgEWQEVAg0wwW5AcIGllqG2lUlEJFANkjYoCEowtDQzNTNIKHKwRpFQsFbRcjbMy9ZxNvT5/9/IBAA "Runic Enchantments โ€“ Try It Online") Functionally this is a port of sundar's Julia answer (but Runic doesn't have a command for pushing `e` to the stack (or really, any decimal value), so an approximation was needed). The approximation for `e` for inputs less than 8 is more precise, as the loss of precision resulted in values lying outside the allowable range of outputs (e.g. `7` would produce 125). `Ceil()` was accomplished by converting to a character and then back to a number (this failed for exceptionally large values, so at 40k I had it divide by 100, do the conversion to and back, then multiply by 100 again). There's probably some room to simplify the arrangement (e.g. running the entry point vertically, below, or finding a way to compress the approximations for `e`), but I'm happy with just being able to *do* the calculation. ``` /?D5X1+1C,*212,+16,+1c2*,+1cX,+Sp3X7+a,*5X1+a,-1+kn$; R:c2*(?D4X1+1C,*212,+16,+1c2*,+Sp9*1+:4XY(?Dkn$; \(8:i< R`196560`r@; ;$*C1nk,C1L ``` 161 bytes. ### Interpreter Update: With the [push fixing input reading](https://github.com/Draco18s/RunicEnchantments/commit/588097843b3f30e3f3ee2bef6abf06a8e6fe205f), Runic now has several math functions and the ability to parse strings as doubles. That will vastly simplify this answer, but I will leave it as is to show off the effort I put into it (I added the single-argument Math functions and string parsing shortly after posting: I'd already had Sin/Cos/Tan on my to-do list, but hadn't considered Exp, Abs, Log, etc. and was running out of characters). TIO should update in the next 24-48 hours, depending on when Dennis sees it. `212,+16,+1c2*,+1cX,+` would reduce to -> `1'eA` with this interpreter update. `A` pops a character and a value and performs a Math operation on that value based on the character popped (`e` in this case is `Exp()` and `Exp(1)` returns *e*). ]
[Question] [ As a kid, I used to play the card game *"[golf](https://en.wikipedia.org/wiki/Golf_(card_game))"* a lot. Your challenge, should you choose to accept it, is to calculate the score of a golf hand. Since there are over 9000 variations on this card game1, we will go with the rules I remember playing. # Rules (of the game) * You end a round with 6 cards, and you want as few points as possible. * Jokers are not used. * Aces and 2s are worth -1, and -2 points respectively. * Jacks and Kings are both worth 0 points. * Cards from 3 to 10 are worth face value. However, these are cancelled when you pair them off. For example, a 5 is worth 5 points, but two 5s are worth zero. Three 5s are worth 5 points, (since the first 2 are paired off, but the 3rd is not.) and four 5s are worth 0 (since it makes 2 pairs). * Queens are worth 15 points. Queens cannot be cancelled, e.g. 2 queens are worth 30 points. # Rules (of the challenge) Input will be an array of integers, or 6 individual integers. Whichever one you prefer. 1 represents an ace, 2-10 represents 2-10, and Jack, Queen, and King represents 11, 12, and 13. Output is the score of the hand according to the rules above. You can safely assume that all inputs are valid, e.g. no number appears more than 4 times, and all numbers are in the range `[1, 13]`. Input and output can be in any reasonable format. # Test IO: ``` [11, 10, 3, 1, 2, 2] --> 8 [4, 5, 5, 3, 8, 7] --> 22 [2, 2, 2, 2, 1, 1] --> -10 (The lowest score possible) [12, 12, 12, 12, 10, 9] --> 79 (The highest score possible) [9, 9, 9, 9, 11, 1] --> -1 [8, 8, 8, 8, 11, 13] --> 0 [10, 9, 3, 7, 12, 2] --> 42 [1, 2, 3, 4, 5, 6] --> 15 [10, 9, 2, 3, 4, 1] --> 23 [10, 3, 12, 3, 7, 12] --> 47 ``` Shortest answer in bytes wins! --- *1not really, but there are a lot of variations.* [Answer] ## Python 2, ~~72~~ 70 bytes ``` f=lambda x,*T:[x*(-1)**T.count(x),~x%2*15,-x][(x-3)/8]+(T>()and f(*T)) ``` At one point I wished Python treated `0**0 == 0` for once so that I could do `(-condition)**num`. Call like `f(11, 10, 3, 1, 2, 2)`. Previous 72-byte version: ``` f=lambda x,*T:[~x%2*15,x*(-1)**(x<3or T.count(x))][x<11]+(T>()and f(*T)) ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~63 57~~ 56+2 = ~~65 59~~ 58 bytes The input numbers are expected to be on the stack at program start, so +2 bytes for the `-v` flag. [Try it online!](http://fish.tryitonline.net/#code=PC8_PTBscDYkKzFnNjoKM1wwCj9cOjo2ZzIlKnsrfTErOmI9CjtcfjE2Zy0yNmcyKi1jNmdmKitu&input=&args=LXYgMTA+LXYgMw+LXYgMTI+LXYgMw+LXYgNw+LXYgMTI) ``` </!?lp6$+1g6: 3\0 ?\::6g2%*{+}1+:b= ;\~16g-26g2*-c6gf*+n ``` As all unused values in the code field are initialised to `0`, it can be used to work out how many of each value is present on the stack by getting the value at `[value,6]`, incrementing it, and putting it back in the code field. The total is then calculated as: ``` T = 0 + {for x in 3 to 10, x*([x,6]%2)} - [1,6] - 2*[2,6] + 15*[12,6] ``` *Edit: golfed 6 bytes off by restructuring the input and switching the calculation steps around. Previous version:* ``` :6g1+$6pl0=?\ /-*2g62-g610/ c ;n$\ 6:b=?/>::6g2%*{+}1+! \gf*+3/ ``` *Edit 2: saved 1 byte, thanks to Sp3000* [Answer] # [MATL](https://github.com/lmendo/MATL), ~~27~~ 26 bytes ``` 3:10=s2\7M*G12=15*Gt3<*_vs ``` The input is a column array, that is, values are separated by semicolons. [Try it online!](http://matl.tryitonline.net/#code=MzoxMD1zMlw3TSpHMTI9MTUqR3QzPCpfdnM&input=WzEwOyA5OyAzOyA3OyAxMjsgMl0) or [verify all test cases](http://matl.tryitonline.net/#code=YAozOjEwPXMyXDdNKjEkMEcxMj0xNSoxJDBHdDM8Kl92cwpEVA&input=WzExOyAxMDsgMzsgMTsgMjsgMl0gICAgCls0OyA1OyA1OyAzOyA4OyA3XSAgICAgIApbMjsgMjsgMjsgMjsgMTsgMV0gICAgICAKWzEyOyAxMjsgMTI7IDEyOyAxMDsgOV0gCls5OyA5OyA5OyA5OyAxMTsgMV0gICAgIApbODsgODsgODsgODsgMTE7IDEzXSAgICAKWzEwOyA5OyAzOyA3OyAxMjsgMl0gICAgClsxOyAyOyAzOyA0OyA1OyA2XSAgICAgIApbMTA7IDk7IDI7IDM7IDQ7IDFdICAgICAKWzEwOyAzOyAxMjsgMzsgNzsgMTJd) (this adds a loop to take all inputs, and replaces `G` by `1$0G` to push latest input). ### Explanation ``` 3:10= % Take input implicitly. Compare with range [3 4 ... 10], with broadcast s % Sum of each column: how may threes, fours, ... tens there are 2\ % Modulo 2 7M % Push [3 4 ... 10] again * % Element-wise multiply (the sum of this array is the score of 3...10) G % Push input again 12= % Compare with 12, element-wise 15* % Multiply by 15 (this is the score of 12) G % Push input again t3< % Duplicate. True for entries 1 or 2 *_ % Multiply and negate (the sum of this array is the score of 1, 2) v % Concatenate all stack concents into a vertical array s % Sum of array. Implicitly display ``` [Answer] # Pyth - ~~37~~ ~~36~~ 35 This is seems way too large, but FGITW. ``` J<#h;K-QS2++*15/K12sm*d%/Jd2{J_s@S2 ``` [Test Suite](http://pyth.herokuapp.com/?code=J%3C%23h%3BK-QS2%2B%2B%2a15%2FK12sm%2ad%25%2FJd2%7BJ_s%40S2&test_suite=1&test_suite_input=%5B11%2C+10%2C+3%2C+1%2C+2%2C+2%5D%0A%5B4%2C+5%2C+5%2C+3%2C+8%2C+7%5D%0A%5B2%2C+2%2C+2%2C+2%2C+1%2C+1%5D%0A%5B12%2C+12%2C+12%2C+12%2C+10%2C+9%5D%0A%5B9%2C+9%2C+9%2C+9%2C+11%2C+1%5D%0A%5B8%2C+8%2C+8%2C+8%2C+11%2C+13%5D%0A%5B10%2C+9%2C+3%2C+7%2C+12%2C+2%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%5D%0A%5B10%2C+9%2C+2%2C+3%2C+4%2C+1%5D%0A%5B10%2C+3%2C+12%2C+3%2C+7%2C+12%5D&debug=0). [Answer] # Pyth, ~~28~~ ~~27~~ 25 bytes ``` s+*L%/Qd2}3Tm?<d3_d*15q12 ``` [Try it online.](https://pyth.herokuapp.com/?code=s%2B*L%25%2FQd2%7D3Tm%3F<d3_d*15q12&input=[4%2C+5%2C+5%2C+3%2C+8%2C+7]&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=s%2B*L%25%2FQd2%7D3Tm%3F<d3_d*15q12&test_suite=1&test_suite_input=[11%2C+10%2C+3%2C+1%2C+2%2C+2]%0A[4%2C+5%2C+5%2C+3%2C+8%2C+7]%0A[2%2C+2%2C+2%2C+2%2C+1%2C+1]%0A[12%2C+12%2C+12%2C+12%2C+10%2C+9]%0A[9%2C+9%2C+9%2C+9%2C+11%2C+1]%0A[8%2C+8%2C+8%2C+8%2C+11%2C+13]%0A[10%2C+9%2C+3%2C+7%2C+12%2C+2]%0A[1%2C+2%2C+3%2C+4%2C+5%2C+6]%0A[10%2C+9%2C+2%2C+3%2C+4%2C+1]%0A[10%2C+3%2C+12%2C+3%2C+7%2C+12]&debug=0) ### Explanation * Firstly, Pyth auto-appends some variables. The code is now `s+*L%/Qd2}3Tm?<d3_d*15q12dQ`. * `}3T` generates the list `[3, 4, 5, 6, 7, 8, 9, 10]`. * Multiply each number in that list (`*L`) by the count of that number in the input (`/Qd`), modulo 2 (`%`โ€ฆ`2`). The result is 0 for paired numbers and the number itself for non-paired ones. * Map over the input numbers (`m`โ€ฆ`Q`): + If the number is less than 3 (`?<d3`), negate it (`_d`). + Otherwise check if it's 12 (`q12d`), and multiply the boolean by 15 (`*15`). The result is 15 for queens and 0 for anything else. * Concatenate the lists (`+`). The resulting list now contains the scores for the non-paired numbers (the first part) and the special cards A, 2, Q (the second part), with some extra zeroes. * Finally, take the sum of the result (`s`). ### Alternative 25-byte solution ``` -+s*L%/Qd2}3T*15/Q12s<#3Q ``` This works similarly to the first one, but counts the queens separately and negates the aces and twos with a filter. [Answer] ## JavaScript (ES6), 63 bytes ``` a=>a.map(e=>r+=e<3?-e:e>10?e-12?0:15:(m[e]^=1)?e:-e,r=0,m=[])|r ``` Or if you prefer, ``` a=>a.map(e=>r-=e<3?e:e>10?e-12?0:-15:(m[e]^=1)?-e:e,r=0,m=[])|r ``` [Answer] # [Perl 5](https://www.perl.org/), 74 +1 (`-a`) = 75 bytes ``` map$s+=/12/?15:$_<3?-$_:$_<11?$k{$_}?-delete$k{$_}:($k{$_}=$_):0,@F;say $s ``` [Try it online!](https://tio.run/##K0gtyjH9/z83sUClWNtW39BI397Q1Eol3sbYXlclHsQwNLRXya5Wia@1101JzUktSYXwrDQgtK1KvKaVgY6Dm3VxYqWCSvF/a9VsWw1N6/@GCkYKIAyE//ILSjLz84r/6/qa6hkYGvzXTQQA "Perl 5 โ€“ Try It Online") [Answer] # [Perl 5.10.0](https://www.perl.org/) + `-n`, ~~115~~ ~~64~~ ~~60~~ 56 bytes ``` $p+=$_-12?$_>2?$_<11?++$l[$_]%2?$_:-$_:0:-$_:15}{say$p ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lQNtWJV7X0MheJd4ORNgYGtpra6vkRKvEx6qCBKx0gdgATBqa1lYXJ1aqFPz/b2jIZWjAZcxlyGXEZfQvv6AkMz@v@L9u3n9dX1M9QwM9AwA) ## Explanation: Adding the `-n` loop around it: ``` # Used variables: # $_: input (auto) # $p: points # $l[n]: number of occurences of n (for 3-10) while (<>) { # for every input $p += $_ - 12 ? # if the input is not 12 (queen) ... $_ > 2 ? # then: if it's > 2 (not ace or 2) ... $_ < 11 ? # then: if < 11 (3-10) ... ++$l[$_] % 2 ? # then: if it's an odd occurence (1st, 3rd, 5th, ...) $_ # add it : -$_ # else subtract it : 0 # no points for other stuff (J, K) : -$_ # negative points for ace and 2 : 15 # 15 points for queen } { # after input: say $p # output points } ``` ]
[Question] [ I like the concept of [0815](http://esolangs.org/wiki/0815), except the interpreter on the [creator's website](http://paulo-jorente.de/poncho/esolang/0815/) returns an Error 404. So I decided to ask you all to help! # The Basics 0815 is based around three (3) registers and a queue. The registers are named X, Y, and Z, with X being write-only, Z being read-only, and Y being a "helper" register that can't be directly accessed. All registers start out set to 0. All numbers are in hexadecimal. # Instructions **Note:** Some instructions take parameters which are formatted like `}:hello:` where the `:hello:` is the parameter. **Other note:** Some of the instruction descriptions are unclear, so I took some liberties with them. (Original instructions [here](http://paulo-jorente.de/poncho/esolang/0815/)) `~` means the parameter is required ``` ----------|---|-------------------------------------------- ~Move | < | <:8: will write 8 to X (parameter required) ----------|---|-------------------------------------------- Swap | x | Swap X and Y ----------|---|-------------------------------------------- ~Label | } | }:hello: makes a label called 'hello' ----------|---|-------------------------------------------- Input | | | Set X to an integer from input in Number | | hexadecimal greedily (regex: [0-9A-F]+) ----------|---|-------------------------------------------- Input | ! | Set X to the ASCII code of one ASCII ASCII | | character in the input ----------|---|-------------------------------------------- Print | % | Prints an integer stored in Z number | | (hexadecimal base) ----------|---|-------------------------------------------- Print | $ | Prints an ASCII char stored in Z ASCII | | ----------|---|-------------------------------------------- Roll | | Rolls all registers to the left Registers | ~ | X <- Y <- Z <- X Left | | After roll: X = Y, Y = Z and Z = X ----------|---|-------------------------------------------- Roll | | Rolls all registers to the right Registers | = | X -> Y -> Z -> X Right | | After roll: Y = X, Z = Y and X = Z ----------|---|-------------------------------------------- ~Jump if | ^ | ^:loop: Jumps to the label 'loop' if Z is not zero | | not zero ----------|---|-------------------------------------------- ~Jump if | # | #:loop: Jumps to the label 'loop' if Z is zero | | zero ----------|---|-------------------------------------------- ``` ## Queue Instructions ``` ----------|---|-------------------------------------------- Clear | ? | Clears the queue ----------|---|-------------------------------------------- Enqueue | > | Enqueue the number stored in Z ----------|---|-------------------------------------------- Dequeue | { | Dequeue a number into X ----------|---|-------------------------------------------- | | Rolls the queue to the left, wrapping as Roll | | necessary. The first number becomes the Queue | @ | last; second becomes first and so on. Can Left | | take a parameter to roll a certain number | | of times. @:b: rolls 11 times. ----------|---|-------------------------------------------- Roll | | Queue | & | The opposite of @ Right | | ----------|---|-------------------------------------------- ``` ## Arithmetic instructions ``` ----------|---|-------------------------------------------- Add | + | Z = X + Y ----------|---|-------------------------------------------- Subtract | - | Z = X - Y ----------|---|-------------------------------------------- Multiply | * | Z = X * Y ----------|---|-------------------------------------------- Divide | / | Z = X / Y | | Y = remainder ----------|---|-------------------------------------------- ``` # Example programs Hello world: (Slightly golfed) ``` <:48:~$<:65:~$<:6C:~$$><:6F:~$>@<:2C:~$<:20:~$<:57:~${~$<:72:~${~$<:64:~$ ``` Cat: ``` }:_t:!~$^:_t: ``` Truth Machine: ``` |~}:i:%^:i: ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least bytes wins! [Answer] ## [Pip](http://github.com/dloscutoff/pip), ~~321~~ ~~262~~ 248 bytes Greatly shortened using eval and some Kolmogorov-complexity tricks. ``` a@:`.(:.*?:)?`z:Y0w:2**64W++v<#a{UnpWa@v^':;V("Yp57Syi7UybWb^@(b@?`[^0-9A-F]|$`)Yy57Y APOb7OzTB167O Cz7SyzSyi7SyiSyz7I2I!2l:[]7lPBz7Y3B3UDQl7z:(y+4-4*4//i)i:y%i"R2`zv:a@?"}:".p.':7`R3"POl7Lp?p5olP"R4"i)%w7z:(y"R5"FB16%w"^7"<x|!%$~=^#?>{@&+-*/"@?n)} ``` [Try it online!](http://pip.tryitonline.net/#code=YUA6YC4oOi4qPzopP2B6OlkwdzoyKio2NFcrK3Y8I2F7VW5wV2FAdl4nOjtWKCJZcDU3U3lpN1V5YldiXkAoYkA_YFteMC05QS1GXXwkYClZeTU3WSBBUE9iN096VEIxNjdPIEN6N1N5elN5aTdTeWlTeXo3STJJITJsOltdN2xQQno3WTNCM1VEUWw3ejooeSs0LTQqNC8vaSlpOnklaSJSMmB6djphQD8ifToiLnAuJzo3YFIzIlBPbDdMcD9wNW9sUCJSNCJpKSV3N3o6KHkiUjUiRkIxNiV3Il43Ijx4fCElJH49XiM_PntAJistKi8iQD9uKX0&input=&args=fH59OnM6JX48OjE6LSM6ZW5kOjw6YTp-JH4-ez54PDoyOngvPSM6ZXZuOnt4PDozOip-PDoxOiteOnM6fTpldm46fnteOnM6+Qg) (The example is the Collatz/hailstone numbers program from the language author's website.) Notes: * Takes the 0815 code as the first command-line argument and the input as the second. Yes, it's a bit awkward (much less so on TIO, where you get separate text boxes), but Pip isn't that great at reading all of stdin. * Numbers in input must use uppercase hex digits (as per OP: matching the regex `[0-9A-F]+`). If, at a `|` instruction, the next character of input is not `0-9A-F`, the read fails and causes potentially weird behavior. This means the author's even-odd program doesn't work as written... I'm not sure how he expected multiple number reads to work, but I just implemented according to what the spec said. * If a label is duplicated, a jump goes to the first one. If a label doesn't exist, a jump terminates the program. --- My ungolfed version with comments: ``` ;;; INITIALIZATION ;;; ; a is the code, analyzed with regex into a list of instructions a @: `.(:.*?:)?` ; b is the input ; x, y, z are registers (initially three 0s) x:y:z:0 ; l is the queue (initially empty list) ; v is the instruction pointer (initially -1, but gets incremented at top of loop) ; w represents the width of the registers w:2**64 ;;; MAIN LOOP ;;; ; Loop while IP hasn't gone past last instruction W ++v<#a { ; Unify n with first char of current iNstruction, p with the parameter (or nil) U np W a@v ^ ': ; If n eQuals "<": move p value into x InQ'< ; Convert p from hex and truncate to register width x : pFB16%w ; Swap x and y InQ'x Sxy ; Input number (in hex, uppercase only) InQ'| { ; Find index of first non-hex character in b and split at that index ; Unify left half with x and right with b U xb W b^@(b @? `[^0-9A-F]|$`) ; Convert x from hex and truncate to register width x : xFB16%w } ; Input ASCII InQ'! ; Pop 1st char of b and get ASCII code x : A POb ; Print number (in hex) InQ'% ; Output z converted to hex O zTB16 ; Print ASCII InQ'$ ; Output chr(z) O Cz ; Roll registers left InQ'~ { ; With three registers, a roll is just two swaps Sxz Sxy } ; Roll registers right InQ'= { Sxy Sxz } ; Jump (combines if-nonzero and if-zero cases) I nQ'^ & z | nQ'# & !z ; Construct the corresponding label, find its index in a, and set IP to that v : a @? "}:".p.': ; If the label doesn't exist, v becomes nil, which makes the loop condition nil, ; which (being falsy) exits the loop and terminates the program ; Clear queue InQ'? l:[] ; Enqueue InQ'> ; Push z to back of l lPBz ; Dequeue InQ'{ ; Pop l and assign to x x:POl ; Roll queue left ; NOTE: doesn't work if 0 is a valid parameter for roll operation ; If we want to handle that case, use #p?... instead of p?... for +1 byte InQ'@ ; Loop specified number of times (converted from hex), or 1 if not specified L p ? pFB16 1 ; Pop (front of) l and push that value to the back of l l PB POl ; Roll queue right InQ'& L p ? pFB16 1 ; Dequeue from back of l and push that value to (the front of) l l PU DQl ; Add (truncating as needed) InQ'+ z:(x+y)%w ; Subtract (truncating as needed) InQ'- z:(x-y)%w ; Multiply (truncating as needed) InQ'* z:x*y%w ; Divide (truncating not needed) InQ'/ { z:x//y y:x%y } } ``` [Answer] # haxe, 987 bytes ``` class Main{static function main(){var c=sys.io.File.getContent(Sys.args()[0]).split(""),i=0,x=0,y=0,z=0,t=0,m=0,g=Sys.getChar.bind(false),f=String.fromCharCode,b="",B="",l="",A=[];while(i<c.length)switch(l=c[i++]){case"<"|"}"|"^"|"#":b=l=="<"?"0x":"";if(c[i++]==":")while((B=c[i++])!=":")b+=B;if(l=="<")x=Std.parseInt(b);else if(l!="}"&&(z==0)==(l=="#")){t=0;while(t!=(m=(i+t++)%c.length)){if(c[m]==":")t+=c.indexOf(":",m+1)-m;else if(c[m]=="}"){l="";if(c[++m]==":")while((B=c[++m])!=":")l+=B;if(b==l){i=m;break;}}}return;}case"x":t=x;x=y;y=t;case"|":b="0x";while(((t=g())>47&&t<58)||(t>96&&t<103))b+=f(t);x=Std.parseInt(b);case"!":x=g();x=x<0?0:x;case"%"|"$":Sys.print(l=="%"?[for(j in 0...8){"0123456789abcdef".split("")[z>>((7-j)*4)&15];}].join(""):f(z));case"?":A=[];case">":A.push(z);case"{":x=A.shift();case"@":A.push(A.shift());case"&":A.unshift(A.pop());case"+":z=x+y;case"-":z=x-y;case"*":z=x*y;case"~":t=x;x=y;y=z;z=t;case"=":t=x;x=z;z=y;y=t;case"/":z=Math.floor(x/y);y=x%y;}}} ``` or with some whitespace: ``` class Main{static function main(){ var c=sys.io.File.getContent(Sys.args()[0]).split(""), i=0, x=0, y=0, z=0, t=0, m=0, g=Sys.getChar.bind(false), f=String.fromCharCode, b="", B="", l="", A=[]; while(i<c.length)switch(l=c[i++]){ case"<"|"}"|"^"|"#": b=l=="<"?"0x":""; if(c[i++]==":") while((B=c[i++])!=":") b+=B; if(l=="<") x=Std.parseInt(b); else if(l!="}"&&(z==0)==(l=="#")){ t=0; while(t!=(m=(i+t++)%c.length)){ if(c[m]==":") t+=c.indexOf(":",m+1)-m; else if(c[m]=="}"){ l=""; if(c[++m]==":") while((B=c[++m])!=":") l+=B; if(b==l){ i=m; break; } } } return; } case"x": t=x;x=y;y=t; case"|": b="0x"; while(((t=g())>47&&t<58)||(t>96&&t<103)) b+=f(t); x=Std.parseInt(b); case"!": x=g(); x=x<0?0:x; case"%"|"$": Sys.print(l=="%"?[ for(j in 0...8){ "0123456789abcdef".split("")[z>>((7-j)*4)&15]; } ].join(""):f(z)); case"?": A=[]; case">": A.push(z); case"{": x=A.shift(); case"@": A.push(A.shift()); case"&": A.unshift(A.pop()); case"+": z=x+y; case"-": z=x-y; case"*": z=x*y; case"~": t=x;x=y;y=z;z=t; case"=": t=x;x=z;z=y;y=t; case"/": z=Math.floor(x/y); y=x%y; }}} ``` Successfully golfed with haxe? Wow. [Answer] # Python 3, 1320 bytes The ungolfed version, as well as analysis of (and where necessary, corrected versions of) the test programs, can be found [in this gist](https://gist.github.com/perey/015aeea5c3af016531e9). Design decisions: * Multiple definitions of labels are ignored. Only the first definition of a label is used. (Formerly the most recently seen definition would be used, but that got golfed out.) * Input complies with the OP's spec: numeric input reads hex characters greedily. (Originally it would read until newline, and error when non-hex characters were read.) * "ASCII" input is taken to mean "byte-oriented" input. (Originally it had full Unicode support, which took less code thanks to being Python 3... but meeting the next bullet point meant reading byte by byte was now shorter.) * Parameters where no parameters are expected are ignored; hence, they are usable as comments. There are issues with the example programs using CR alone as their newline (sometimes), which makes my shell overwrite the current line rather than starting a new one. This affects the Fibonacci Sequence and 99 Bottles of Beer programs. The last verse of 99 Bottles of Beer also isn't printing correctly, and I'm still investigating why. ``` import sys as y import sys as y b=y.stdin.buffer I=int g=getattr X=2**64 R=lambda a:property(lambda s:g(s,a)-[X,0][0<=g(s,a)<X/2],lambda s,v:setattr(s,a,I(v)&X-1)) M,*Q=':<}^#@&xX|!%$~=?>{+-*/' class A: x,y,z=map(R,'uvw') def R(s,p): s.p,s.s,*s.q=p,3,;s.x=s.y=s.z=s.i=0 while s.s<4: t='';p=s.s=i=0 while s.s<3: k=s.p[s.i];s.i+=1 if s.s==1: if k==M: if p==2:s.t=s.i;g(s,s.I[i])(t);s.s=max(s.s,3) else:t+=k elif k==M:p,s.s=s.s,1 elif k in Q: i=k;m=M==s.p[s.i] if k in Q[:6]and m:s.s=2 elif k in Q[6:]or k in'@&'and m<1:g(s,s.I[i])() def B(s,v):s.x=I(v,16) def C(s):s.x,s.y=s.y,s.x def D(s,l):0 def E(s): s.x=0 try: while 1:s.x=s.x*16+I(b.peek()[:1],16);b.read(1) except:0 def F(s):s.x=b.read(1)[0] def G(s):print(format(s.z,'x'),end='') def H(s):print(chr(s.z),end='') def J(s):s.x,s.y,s.z=s.y,s.z,s.x def K(s):s.J();s.J() def j(s,l): a=s.p.find('}:'+l+M) if a<0:s.s=4 else:s.i=a def L(s,l): if s.z:s.j(l) def T(s,l): if s.z==0:s.j(l) def U(s):s.q=[] def V(s):s.q+=s.z, def W(s):s.x,*s.q=s.q def Y(s,d='1'):d=I(d,16);s.q=s.q[d:]+s.q[:d] def Z(s,d='1'):Y('-'+d) def a(s):s.z=s.x+s.y def b(s):s.z=s.x-s.y def c(s):s.z=s.x*s.y def d(s):s.z,s.y=divmod(s.x,s.y) I=dict(zip(Q,'BDLTYZCCEFGHJKUVWabcd')) try:A().R(open(y.argv[1]).read()) except:0 ``` [Answer] ## Scala, ~~3,123~~ ~~2,844~~ ~~2,626~~ 2,540 bytes In addition to the constraints outlined in the question, this interpreter was written to lean as much as possible towards FP principles. Specifically: * Only immutable stuctures * All functions are pure This was accomplished, with the exception of the four lines of code that drive the main loop of the interpreter. Immutable structures were very difficult to utilize here because the state of the registers drives the control flow of the loop (specifically the two GOTO statements). I am still thinking on how to convert it to use pure & immutable structures, but that is irrelevant to the code golf challenge. ``` import java.util.Scanner import scala.util._ object Z extends App{type K=Long type G=List[K] type I=String type E=Boolean val(f,t,ั„,ะด,ะฑ)=(false,true,(z:G)=>z(0),(z:G)=>z.tail,(q:K,w:K,e:K)=>q::w::e::Nil) trait O{def h(z:I)=BigInt(z,16).longValue()} trait S extends O trait B extends S with P{def apply(r:G):E} trait R extends O{def a(r:G):G} trait T extends O{def a(r:G,s:G):(G,G)} trait P{def p:I} case class L(p:I)extends S with P case class U(p:I)extends B{def apply(r:G):E=r(2)==0} case class J(p:I)extends B{def apply(r:G):E=r(2)!=0} case class M(p:I)extends R with P{def a(r:G):G=h(p)::ะด(r)} class Y extends R{def a(r:G):G=ะฑ(r(0),r(0)%r(1),r(0)/r(1))} case class Q(p:I)extends T with P{def r(q:G,i:Int):G={val s=ะด(q):+ั„(q) if(i>0)r(s,i-1)else s} def a(e:G,t:G)=e->r(t,Try(p.toInt).getOrElse(1))} case class N(p:I)extends T with P{def r(q:G,i:Int):G={ val s=q.last::q.iterator.sliding(2).map(_(0)).toList if(i>0)r(s,i-1)else s} def a(e:G,t:G)=e->r(t,Try(p.toInt).getOrElse(1))} case class A(n:Array[O], l:Map[I,Int]){def e={var (r,t,x)=(List(0L,0,0),List[K](),0) while(x<n.length){x=n(x)match{case i:B=>if(i(r))l(i.p)else x+1 case i:R=>r=i.a(r);x+1 case i:T=>val(y,u)=i.a(r,t);r=y;t=u;x+1 case _=>x+1}}}} object A{def apply(i:Seq[O]):A={A(n=i.toArray,l=Map(i.zipWithIndex.flatMap{case(e:L,i)=>Some(e.p->i) case _=>None}.toList:_*))}} object X{def v(y:(Char, Option[Z.I]))=y._2.getOrElse("");val F=Map('x->new R{def a(t:G)=ะฑ(t(1),t(0),t(2))},'|'->new R{def a(r:G)=h(new Scanner(System.in).next("[0-9a-fA-F]+"))::ะด(r)},'!'->new R{def a(r:G)=(System.in.read match{case i if i== -1=>0;case i=>i})::ะด(r)},'%'->new R{def a(r:G)={print(Integer.toHexString(r(2).toInt));r}},'$'->new R{def a(r:G)={print(r(2).toChar);r}},'~'->new R{def a(r:G)=ะด(r):+ั„(r)},'='->new R{def a(r:G)=ะฑ(r(2),r(0),r(1))},'?'->new T{def a(r:G,s:G)=r->List()},'>'->new T{def a(r:G,s:G)=r->(r(2)::s)},'{'->new T{def a(r:G, s:G)=(ั„(s)::ะด(r))->ะด(s)},'+'->new R{def a(r:G)=ะฑ(r(0),r(1),r(0)+r(1))},'-'->new R{def a(r:G)=ะฑ(r(0),r(1),r(0)-r(1))},'*'->new R{def a(r:G)=ะฑ(r(0),r(1),r(0)*r(1))},'/'->new Y);def apply(i:I)={(i+" ").foldLeft((List[(Char,Option[I])](),None:Option[Char],"",f))((a,n)=>{n match{case i if i==':'=>if(a._4)(a._1:+(a._2.get->Some(a._3)),None,"",f)else(a._1,a._2,"",t) case i if a._4=>(a._1,a._2,a._3+i,t) case i if a._2.isEmpty=>(a._1,Some(i),"",f) case i=>(a._1:+(a._2.get->None),Some(i),"",f)}})._1.map(x=>x._1 match{ case'<'=>M(v(x)) case'}'=>L(v(x)) case'^'=>J(v(x)) case'#'=>U(v(x)) case'@'=>Q(v(x)) case'&'=>N(v(x)) case c=>F(c)})}} A(X(args(0))).e} ``` I will post the ungolfed version on Github and will provide a link when I do so. For now, I will post the original version here: ``` import java.util.Scanner import scala.util.Try trait Operation { def hexToLong(hex:String):Long = BigInt(hex, 16).longValue() } trait Parameter { def param:String } trait RegisterOperation extends Operation { def apply(registers:List[Long]):List[Long] } trait StackOperation extends Operation { def apply(registers:List[Long], stack:List[Long]):(List[Long], List[Long]) } trait SpecialOperation extends Operation trait SpecialRegisterOperation extends SpecialOperation with Parameter { def apply(registers:List[Long]):Boolean } class Move(val param:String) extends RegisterOperation with Parameter { override def apply(registers:List[Long]): List[Long] = hexToLong(param) :: registers.tail } class Swap extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = registers(1) :: registers(0) :: registers(2) :: Nil } class InputNumber extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = hexToLong(new Scanner(System.in).next("[0-9a-fA-F]+")) :: registers.tail } class InputAscii extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = (System.in.read() match { case i if i == -1 => 0 case i => i}) :: registers.tail } class PrintNumber extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = { print(Integer.toHexString(registers(2).toInt)); registers } } class PrintAscii extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = { print(registers(2).toChar); registers } } class RegisterRollLeft extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = registers.tail :+ registers.head } class RegisterRollRight extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = registers(2) :: registers(0) :: registers(1) :: Nil } class Add extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = registers(0) :: registers(1) :: (registers(0) + registers(1)) :: Nil } class Subtract extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = registers(0) :: registers(1) :: (registers(0) - registers(1)) :: Nil } class Multiply extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = registers(0) :: registers(1) :: (registers(0) * registers(1)) :: Nil } class Divide extends RegisterOperation { override def apply(registers:List[Long]): List[Long] = registers(0) :: (registers(0) % registers(1)) :: (registers(0) / registers(1)) :: Nil } class Clear extends StackOperation { override def apply(registers:List[Long], stack:List[Long]) = registers -> List() } class Enqueue extends StackOperation { override def apply(registers:List[Long], stack:List[Long]) = registers -> (registers(2) :: stack) } class Dequeue extends StackOperation { override def apply(registers:List[Long], stack:List[Long]) = (stack.head :: registers.tail) -> stack.tail } class QueueRollLeft(val param:String) extends StackOperation with Parameter { def roll(stack:List[Long], i:Int):List[Long] = { val s = stack.tail :+ stack.head if (i > 0) roll(s, i-1) else s } override def apply(registers:List[Long], stack:List[Long]) = registers -> roll(stack, Try(param.toInt).toOption.getOrElse(1)) } class QueueRollRight(val param:String) extends StackOperation with Parameter { def roll(stack:List[Long], i:Int):List[Long] = { val s = stack.last :: stack.iterator.sliding(2).map(_.head).toList if (i > 0) roll(s, i-1) else s } override def apply(registers:List[Long], stack:List[Long]) = registers -> roll(stack, Try(param.toInt).toOption.getOrElse(1)) } class SetLabel(val param:String) extends SpecialOperation with Parameter class JumpLabelIfZero(val param:String) extends SpecialRegisterOperation { override def apply(registers: List[Long]): Boolean = registers(2) == 0 } class JumpLabelIfNotZero(val param:String) extends SpecialRegisterOperation { override def apply(registers: List[Long]): Boolean = registers(2) != 0 } class Script(val instructions:Array[Operation], val labels:Map[String, Int]) { def execute() = { var registers = List[Long](0, 0, 0) var stack = List[Long]() var idx = 0; while(idx < instructions.length) { idx = instructions(idx) match { case i: SpecialRegisterOperation => if(i(registers)) labels(i.param) else idx + 1 case i: RegisterOperation => { registers = i(registers); idx + 1 } case i: StackOperation => { val (zregisters, zstack) = i(registers, stack); registers = zregisters; stack = zstack; idx + 1 } case _ => idx + 1 } } } } object Script { def apply(instructions: Seq[Operation]):Script = { new Script(instructions = instructions.toArray, labels = Map(instructions.zipWithIndex.flatMap { case (e:SetLabel, i) => Some(e.param -> i) case _ => None }.toList:_*)) } } object Parser { def apply(input:String): Seq[Operation] = { case class Accumulator(val list: List[(Char, Option[String])] = List(), val char:Option[Char] = None, val str:String = "", val parsingVar:Boolean = false) (input + " ").foldLeft(Accumulator())((acc, next) => { next match { case i if i == ':' => if(acc.parsingVar) Accumulator(acc.list :+ (acc.char.get -> Some(acc.str)), None, "", false) else Accumulator(acc.list, acc.char, "", true) case i if acc.parsingVar => Accumulator(acc.list, acc.char, acc.str + i, true) case i if !acc.char.isDefined => Accumulator(acc.list, Some(i), "", false) case i => Accumulator(acc.list :+ (acc.char.get -> None), Some(i), "", false) } }).list.map(x => x._1 match { case '<' => new Move(x._2.getOrElse("")) case 'x' => new Swap case '}' => new SetLabel(x._2.getOrElse("")) case '|' => new InputNumber case '!' => new InputAscii case '%' => new PrintNumber case '$' => new PrintAscii case '~' => new RegisterRollLeft case '=' => new RegisterRollRight case '^' => new JumpLabelIfNotZero(x._2.getOrElse("")) case '#' => new JumpLabelIfZero(x._2.getOrElse("")) case '?' => new Clear case '>' => new Enqueue case '{' => new Dequeue case '@' => new QueueRollLeft(x._2.getOrElse("")) case '&' => new QueueRollRight(x._2.getOrElse("")) case '+' => new Add case '-' => new Subtract case '*' => new Multiply case '/' => new Divide }) } } object Go extends App { Script(Parser(args(0))).execute() } ``` [Answer] ## Python 3, ~~1573~~,1499 bytes Runs the example programs at <http://paulo-jorente.de/poncho/esolang/0815/> and implements all the instructions (even write ones, according to the original spec). Executes the source file passed on the command line. ``` import sys from collections import deque class w: q=deque() X=Y=Z=c=0 def __init__(k):k.s=open(sys.argv[1],'r').read() def a(k,l): i=k.s.find("}:"+l+":") if (i<0):sys.exit() return i def l(k): k.c+=1 if k.s[k.c]!=":":sys.exit(":") k.c+=1 return k.s[k.c:k.c+k.s[k.c:].find(":")] def u(k): k.c+=1 if k.s[k.c]!=":":sys.exit(":") k.c+=1 h=k.s[k.c:k.c+k.s[k.c:].find(":")] k.c+=len(h) return h def b(k): g=range j=input z=len w=sys.stdout.write o=k.s[k.c] y=k.q.rotate if o=='<':k.X=int(k.u(),16) elif o=='x':t=k.X;k.X=k.Y;k.Y=t elif o=='=':t=k.X;k.X=k.Z;v=k.Y;k.Y=t;k.Z=v; elif o=='$': if (k.Z==0x0d):w('\n') else:w(str(chr(k.Z%256))) elif o=='%':w(str(k.Z)) elif o=='~':t=k.X;v=k.Y;k.X=v;k.Y=k.Z;k.Z=t; elif o=='?':k.q.clear() elif o=='>':k.q.append(k.Z) elif o=='{':k.X=k.q.popleft() elif o=='@': if k.s[k.c+1]==':': t=k.u() for i in g(0,int(t,16)):y(-1) else: y(-1) elif o=='&': if k.s[k.c+1]==':': t=k.u() for i in g(0,int(t,16)):y(1) else: y(1) elif o=='}': k.c+=z(k.l()) elif o=='#': l=k.l() if (k.Z==0): k.c=k.a(l)-1 else: k.c+=z(l) elif o=='^': l=k.l() if (k.Z!=0): k.c=k.a(l)-1 else: k.c+=z(l) elif o=='|':k.X=int(j("?"),16) elif o=='!':k.X=ord(j(">")[0]) elif o=='+':k.Z=k.X+k.Y elif o=='-':k.Z=k.X-k.Y elif o=='*':k.Z=k.X*k.Y elif o=='/': k.Z=int(k.X/k.Y) k.Y=k.X%k.Y k.c+=1 def x(k): while k.c<len(k.s):k.b() w().x() ``` [Answer] ## Flex/C++, ~~848~~ 838 bytes ``` %{ #include<map> #include<deque> using namespace std;typedef uint64_t I;I X,Y,Z,P,T,i;map<string,I>L;deque<I>Q; #define YY_USER_ACTION P+=yyleng; #define A for(i=0;i<(yyleng>2?stoull(yytext+2,0,16):1);++i #define B fseek(yyin,L.at(yytext+1),0),yyrestart(yyin); %} H :[0-9A-F]+: B :[0-9a-zA-Z_]+: %x E %% <E>\}{B} L[yytext+1]=P; <E>.|\n \<{H} X=stoull(yytext+2,0,16); x T=X;X=Y;Y=T; \}{B} \| scanf("%lx",&X); ! X=getchar(); % printf("%lx",Z); \$ putchar(Z); ~ T=X;X=Y;Y=Z;Z=T; = T=Y;Y=X;X=Z;Z=T; \^{B} if(Z)B #{B} if(!Z)B \? Q.clear(); > Q.push_back(Z); \{ X=Q.front();Q.pop_front(); @{H}? A)T=Q.front(),Q.pop_front(),Q.push_back(T); &{H}? A)T=Q.back(),Q.pop_back(),Q.push_front(T); \+ Z=X+Y; - Z=X-Y; \* Z=X*Y; \/ Z=X/Y;Y=X%Y; .|\n %% main(int,char**v){yyin=fopen(v[1],"r");BEGIN(E);yylex();rewind(yyin);yyrestart(yyin);BEGIN(0);yylex();} ``` Compiled with: ``` flex -o 0815.cpp 0815.ll g++ -std=c++11 0815.cpp -o 0815 -ll ``` It might compile with other `lex`es as well, but I didn't check. It works in two passes, so forward jumps are handled correctly. Label names are allowed to start with a digit, as it happens more than once in the test cases. Hex literals can only be upper case, in accordance with the specs. Passes all test cases, including those found on the Esolangs Wiki and the 0815 page. Error handling is non-existent and exit on an unknown label is not graceful, after all this is code-golf. I am preparing the ungolfed (and much nicer) interpreter for a release, so that OP can keep tinkering with 0815. Stay tuned :) [Answer] # Common Lisp, 1088 bytes ``` (progn(defun r(s)(parse-integer s :radix 16))(defun h(k)(coerce(loop for c =(#7=read-char()())while(funcall k c)collect c finally(unread-char c))'string))(defun w(c)(find c"0123456789ABCDEFabcdef"))(defmacro c(s)(with-input-from-string(*standard-input* s)(labels((L()(intern(p #'u)))(o()(case(peek-char()())(#\:(r(q))(#7#))(t 1)))(q()(p #'w))(p(k)(prog2(#7#)(h k)(#7#)))(u(c)(char/= c #\:)))`(let((x 0)(y 0)(z 0)(q(list())))(labels((&(n)(q(nconc(last(car q)n)(butlast(car q)n))))(@(n)(q(nconc(nthcdr n(car q))(subseq(car q)0 n))))(q(x)(#3=setf q(cons x(last x)))))(prog(),@(loop for c =(#7#()())while c collect(case c(#\<`(#3#x,(r(q))))(#\x`(#5=rotatef x y))(#\}(L))(#\|`(#3#x(r(h'w))))(#\!`(#3#x(char-code(#7#))))(#\%`(format t"~x"z))(#\$`(princ(code-char z)))(#\~`(#5#x y z))(#\=`(#5#z y x))(#\^`(if(/= z 0)(go,(L))))(#\#`(if(= 0 z)(go,(L))))(#\?`(#3#q(q())))(#\>'(if(car q)(#3#(cddr q)(list z)(cdr q)(cddr q))(#3#(cdr q)(#3#(car q)(list z)))))(#\{'(#3#x(pop(car q))))(#\@`(@,(o)))(#\&`(&,(o)))(#\/'(#3#(values z y)(truncate x y)))(t`(#3#z(,(elt'(+ * -)(position c"+*-"))x y)))))))))))) ``` ## Ungolfed With optional trace at runtime. ``` ;;; Those auxiliary functions are needed both ;;; during macroexpansion and evaluation (defun r(s) (parse-integer s :radix 16)) (defun h(k) (coerce (loop for c = (read-char nil nil) while (funcall k c) collect c finally (unread-char c)) 'string)) (defun w(c) (find c "0123456789ABCDEFabcdef")) ;;; C is a macro, it takes a string, replaces it by ;;; code, which is then evaluated. (defmacro C(s &optional tracep) (with-input-from-string(*standard-input* s) (labels((L()(intern(p #'u))) (d()(assert(eql #\:(read-char)))) (o(d)(case (peek-char () () ()) (#\:(r(q))(d)) (t d))) (q()(p #'w)) (p(k)(prog2(d)(h k)(d))) (u(c)(not(eql c #\:)))) `(let((x 0)(y 0)(z 0)(q(list()))) (labels((&(n)(q(append(last(car q)n)(butlast(car q)n)))) (@(n)(q(nconc(nthcdr n(car q))(subseq(car q)0 n)))) (q(x)(setf q(cons x(last x))))) (tagbody ,@(loop for c =(read-char nil ()) while c when tracep collect '(fresh-line) and collect `(print (list :c ,c :x x :y y :z z :q q :s (map'string'code-char(car q)))) collect (ecase c (#\<`(setf x ,(r(q)))) (#\x`(rotatef x y)) (#\}(L)) (#\|`(setf x(r(h'w)))) (#\!`(setf x(char-code(read-char)))) (#\%`(format t"~x"z)) (#\$`(princ(code-char z))) (#\~`(rotatef x y z)) (#\=`(rotatef z y x)) (#\^`(if(not(zerop z))(go,(L)))) (#\#`(if(zerop z)(go,(L)))) (#\?`(setf q(q()))) (#\>'(if(car q)(setf(cddr q)(list z)(cdr q)(cddr q))(setf(cdr q)(setf(car q)(list z))))) (#\{'(setf x(pop(car q)))) (#\@`(@,(o 1))) (#\&`(&,(o 1))) (#\/'(multiple-value-setq(z y)(truncate x y))) ((#\+ #\* #\-)`(,(intern(string c)"CL")x y))) when tracep collect `(print (list :c ,c :x x :y y :z z :q q :s (map'string'code-char(car q))))))))))) ``` ## Fibonnaci ``` (c "%<:0A:>~$<:01:~%>=<:68a3dd8e61eccfbd:>~>}:_s:{x{={~$x+%{=>~>x~-x<:0A:~>~>~^:_s:?") ``` ### Macroexpansion ``` (LET ((X 0) (Y 0) (Z 0) (Q (LIST NIL))) (LABELS ((& (N) (Q (NCONC (LAST (CAR Q) N) (BUTLAST (CAR Q) N)))) (@ (N) (Q (NCONC (NTHCDR N (CAR Q)) (SUBSEQ (CAR Q) 0 N)))) (Q (X) (SETF Q (CONS X (LAST X))))) (PROG () (FORMAT T "~x" Z) (SETF X 10) (IF (CAR Q) (SETF (CDDR Q) (LIST Z) (CDR Q) (CDDR Q)) (SETF (CDR Q) (SETF (CAR Q) (LIST Z)))) (ROTATEF X Y Z) (PRINC (CODE-CHAR Z)) (SETF X 1) (ROTATEF X Y Z) (FORMAT T "~x" Z) (IF (CAR Q) (SETF (CDDR Q) (LIST Z) (CDR Q) (CDDR Q)) (SETF (CDR Q) (SETF (CAR Q) (LIST Z)))) (ROTATEF Z Y X) (SETF X 7540113804746346429) (IF (CAR Q) (SETF (CDDR Q) (LIST Z) (CDR Q) (CDDR Q)) (SETF (CDR Q) (SETF (CAR Q) (LIST Z)))) (ROTATEF X Y Z) (IF (CAR Q) (SETF (CDDR Q) (LIST Z) (CDR Q) (CDDR Q)) (SETF (CDR Q) (SETF (CAR Q) (LIST Z)))) |_s| (SETF X (POP (CAR Q))) (ROTATEF X Y) (SETF X (POP (CAR Q))) (ROTATEF Z Y X) (SETF X (POP (CAR Q))) (ROTATEF X Y Z) (PRINC (CODE-CHAR Z)) (ROTATEF X Y) (SETF Z (+ X Y)) (FORMAT T "~x" Z) (SETF X (POP (CAR Q))) (ROTATEF Z Y X) (IF (CAR Q) (SETF (CDDR Q) (LIST Z) (CDR Q) (CDDR Q)) (SETF (CDR Q) (SETF (CAR Q) (LIST Z)))) (ROTATEF X Y Z) (IF (CAR Q) (SETF (CDDR Q) (LIST Z) (CDR Q) (CDDR Q)) (SETF (CDR Q) (SETF (CAR Q) (LIST Z)))) (ROTATEF X Y) (ROTATEF X Y Z) (SETF Z (- X Y)) (ROTATEF X Y) (SETF X 10) (ROTATEF X Y Z) (IF (CAR Q) (SETF (CDDR Q) (LIST Z) (CDR Q) (CDDR Q)) (SETF (CDR Q) (SETF (CAR Q) (LIST Z)))) (ROTATEF X Y Z) (IF (CAR Q) (SETF (CDDR Q) (LIST Z) (CDR Q) (CDDR Q)) (SETF (CDR Q) (SETF (CAR Q) (LIST Z)))) (ROTATEF X Y Z) (IF (/= Z 0) (GO |_s|)) (SETF Q (Q NIL))))) ``` ### Output ``` 0 1 1 2 3 5 8 D 15 22 37 59 90 ... 5D4D629E80D5489 96F75D79B354522 F444C01834299AB 18B3C1D91E77DECD 27F80DDAA1BA7878 40ABCFB3C0325745 68A3DD8E61ECCFBD ``` *Maybe more explanations later* ]
[Question] [ ## Background Two numbers, \$a\$ and \$b\$, are said to be connected by a Brussels choice operation\* if \$b\$ can be reached from \$a\$ by doubling or halving (if even) a substring (the substring must not be empty and may not contain any leading 0s but it can be 0) in the base-10 representation of \$a\$ \*This operation is slightly different from the one defined on this [paper](https://arxiv.org/pdf/1902.01444.pdf) mainly that the operation defined in the paper allows empty substrings and does not allow choosing the substring "0" For example, all the number that can be reached from `5016`: ``` 508 (50[16] half -> 50[8]) 2508 ([5016] half -> [2508]) 2516 ([50]16 half -> [25]16) 5013 (501[6] half -> 501[3]) 5016 (5[0]16 half -> 5[0]16) (5[0]16 double -> 5[0]16) 5026 (50[1]6 double -> 50[2]6) 5032 (50[16] double -> 50[32]) 10016 ([5]016 double -> [10]016) ([50]16 double -> [100]16) 10026 ([501]6 double -> [1002]6) 10032 ([5016] double -> [10032]) 50112 (501[6] double -> 501[12]) ``` ## Task Write a program/function that when given two positive integers as input outputs a truthy value if they can reach each other with a single Brussels choice operation and a falsey value otherwise. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytes wins. ## Sample Testcases ``` 2, 4 -> Truthy 4, 2 -> Truthy 101, 101 -> Truthy 516, 58 -> Truthy 58, 516 -> Truthy 516, 5112 -> Truthy 5112, 516 -> Truthy 1, 3 -> Falsey 123, 123 -> Falsey 151, 252 -> Falsey 112, 221 -> Falsey 101, 999 -> Falsey 999, 1001 -> Falsey 101, 1001 -> Falsey ``` --- *Inspired by [The Brussels Choice - Numberphile](https://www.youtube.com/watch?v=AeqK96UX3rA)* [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 38 bytes ``` L$w`0|[1-9]\d* $`$.(*2*)$' m`^(.+),\1$ ``` [Try it online!](https://tio.run/##JYkxDsJAEAP7fcciLoeJ4k0WhRfQ8AMCOiQoKEKBkGj4@7ERxVj2@HV/P55X1lU6lHrUT@m@J2735@mWRYu2KVtudC1zuaR202Ci1kr0YhhkgAk7IhBaj0DohHl4Gswozh18FB8R7b/ikiUW8wM "Retina โ€“ Try It Online") Link includes test cases. Outputs `0` for Falsey, non-zero for Truthy. Explanation: ``` L$w`0|[1-9]\d* ``` Match all integer substrings of both inputs, including `0` but not integers beginning with `0`. ``` $`$.(*2*)$' ``` List the result of doubling that substring only. ``` m`^(.+),\1$ ``` Check to see whether this produces any pairs of equal integers. [Answer] # [Python 2](https://docs.python.org/2/), ~~180~~ \$\cdots\$ ~~121~~ 111 bytes Saved 2 bytes thanks to [Mukundan314](https://codegolf.stackexchange.com/users/91267/mukundan314)!!! Saved a whopping 16 bytes thanks to an idea from [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!! Saved 7 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!! Saved 10 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!! ``` def f(*p):a=`min(p)`;return max(a[:i]+`2*int(a[i:j])`+a[j:]==`max(p)`for j in range(len(a)+1)for i in range(j)) ``` [Try it online!](https://tio.run/##bZHBasMwEETv/oq9SYq3EClxCC7uMeceejMGK1RuZRzFSAq0X@@uDCUQRbd9O6MRo/k3fl@dWpZPM8DAN7OoddNfrOOz6F@9iTfv4KJ/uG5r25W92lgXabD12Im@1O1Ydw0ZSEGG4ephBOvAa/dl@GQc16KUInF756MQSzQhBmiAF0CHc4mwEwgnPQUj8B8SlTlWCHuCH/52Z3sE9cjkNvm3MuNqR1w9yavIoCr15CGUqZTMFpU8IFTHx4TqSFQeMryq6bJ8kQIyhyh8qoidtJ0YAnvXITBRpDojmlToWmO9ijXCmdRxHVK1A9d4Fus4e/o28rCXN4YBfRuaxnTLHw "Python 2 โ€“ Try It Online") Returns either `True` or `False`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~13~~ 12 bytes ``` p{~cโ†บร—โ‚‚สฐโ†ปc}แตˆ ``` [Try it](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8L6iuS37Utuvw9EdNTac2PGrbnQwU7vj/PzraUMc4VifaSMcESJroGAFJQwNDHSAGsYyMdYAYxDI11DEyBcsaGukYGYFkTQ3NdEwtQAwLHSAbJgJUAGYC1YFEYwE "Brachylog โ€“ Try It Online") [onl](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8L6iuSwapatt1ePqjpqZTGx617U4GynT8/x8dbWpoaKRjamgWqxNtaGCoY2lpCWQBSR1DAwPD2FgA)[ine!](https://tio.run/##ATEAzv9icmFjaHlsb2cy//9we35j4oKD4oa6w5figoLKsOKGu2N94bWI//9bMTAxLDEwMDFd) *-1 byte thanks to Zgarb* Takes input as a list `[a, b]` through the input variable and outputs through success or failure. ``` p Permute the input. { }แตˆ For the first element of the input: ~c take some partition of it, ร—โ‚‚ double โ†บ สฐโ†ป the second element of the partition, c and re-concatenate it. { }แตˆ It's possible for the result to be the second element of the input. ``` [Answer] # [R](https://www.r-project.org/), ~~120~~ ~~117~~ ~~112~~ 106 bytes *Edit: -5 bytes thanks to Giuseppe (again)* *Edit2: -6 bytes by using vectorized arguments to `substring` and `paste` and so avoiding any loops* ``` function(v,m=min(v),`[`=substring,b=rep(1:m,e=m))max(v)%in%paste0(m[0,b-1],as.double(m[1:m,b])*2,m[1:m+1]) ``` [Try it online!](https://tio.run/##dY3PCsIwDIfvPsVABq1GWeIqQ@jVJ/AmQ1etUrB1tJv49rN68Q/1EBK@L8nPDybslO9D0Jcgh1PvDp25OnYDK62JncN@u5ehV6Hzxp1BSa9bhisLWlrObXOPO7lxeduEThfMbgtQM6yhCfPjtVcXHdFzXdV8QvCap1jzz1x2YAgLzrNxth59c4LyxTc/vARKciwQYqUdLSBWMgcFAglKOyQgwqQTuARRJeNEBdGm1fMqvv0jY977cngA "R โ€“ Try It Online") **How?** ``` is_brussels= function(v, # v is vector of 2 input values m=min(v), # m is smaller input value s=substring) # s is alias to substring function. max(v) %in% # Main function : Is larger input value present in ... sapply(1:m, # the results of applying all combinations of 1..m ... function(b) # to the 'brussels' function with beginning b ... paste0(s(m,0,b-1), # which pastes together m (up to b)... as.numeric(s(m,b,1:m))*2, # onto 2x m (from b to all values of e from 1:m) ... s(m,2:m) # onto m (from e onwards)? ) ) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~31~~ ~~27~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` {R`.ล“v3FyDNรจยทNyg%ว])Jฤ‡รฅ ``` -4 bytes as bug-fix - thanks to *@ovs* for noticing. (Decreasing the bytes as bug-fix doesn't happen often, haha. :D) Input as a pair of integers. [Try it online](https://tio.run/##ATAAz/9vc2FiaWX//3tSYC7Fk3YzRnlETsOowrdOeWclx51dKUrEh8Ol//9bMTIzLDEzNF0) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/@qgBL2jk8uM3Spd/A6vOLTdrzJd9fjcWE2vI@2Hl/5X0gvT@R8dbahjHKsTbaRjAiRNdIyApKGBoQ4Qg1hGxjpADGKZGuoYmYJlDY10jIxAsqaGZjqmFiCGhQ6QDRMBKgAzgeogooZA44xhphmbxMYCAA). **Explanation:** ``` {R # Sort the (implicit) input-pair from highest to lowest ` # Pop and push both values separated to the stack .ล“ # Get all partitions of the top lowest integer v # Loop over each partition `y`: 3F # Inner loop `N` in the range [0, 3): yD # Push partition `y` twice Nรจ # Get the `N`'th item of the partition (modulair 0-based) ยท # Double it N # Push index `N` again yg% # Modulo the length of the current partition `y` # (since builtin `ว` doesn't index modulair) ว # Insert the doubled substring back into the partition at that index ] # Close both loops ) # Wrap all values on the stack into a list J # Join each partition back to a single string ฤ‡ # Extract the head; pop and push the remainder-list and first item # separated to the stack (which is the highest value that was still on # the stack) รฅ # Check if the list contains this highest integer # (after which the result is output implicitly) ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 48 bytes ``` {;*eq[|] m:ex/.+/>>.&{.replace-with($_/(2|.5))}} ``` ~~[Try it online!](https://tio.run/##Xc3PCoJAEAbwe08xhxDNP9uOrkiRx56gW0ZIrShomRol6rNvqwdx28Mw/Pj2m5JXuS@KFrQEDiC6/Ya/zv0Fih3/EsckYehonVPxMo9v3P5kTaqvr0TH3mGGMQyijltIdLMgUR3dTWJM67hA8qwgzx68FtQCF6Znh3CM85q3K7TAm@1UvZu0XXkW4L/Rrfwth2LoSkN32UeZzCFDxai8gkiXxqhvAQuUGyyQRH3VppxsUGwsHJOz/QA "Perl 6 โ€“ Try It Online")~~ Oops, TIO doesn't have an up to date version of Raku, which means it doesn't have `replace-with`. I guess we'll have to go with [repl.it online!](https://repl.it/repls/DaringEmbellishedSpyware) instead. [Answer] # JavaScript (ES9), 102 bytes Returns either `false` or `1`. ``` f=(a,b,i)=>(g=r=>a.replace(o=RegExp('(?<='+r),n=>o=n*2)==b&++o||o&&g('.'+r)|g(r+'.'))`)`||!i&&f(b,a,1) ``` [Try it online!](https://tio.run/##dY7BToQwEIbvPoVeOq1UQruL8eDgSR/AeFtNtmBBDKGkrEaTvju25aKx9NCZ/N/8M/@7@lRzY/vpdDWaV70sLVLFa94zrGiHFiuVWz0NqtHU4KPu7r8mCvTuFiGzjI9YGRwvJUOsSZYZ5wwhHYU8UNdRm/mWsSM7OnfRE9LSmisu2NKYcTaDzgfjpw8Papi/X4Cd/ZZbeu4fCOCh7PyafxiE3HkcSxKXwQ2ylGksZMRSBPyHw/N4eLIfp7etWHKNtU8tjjpfp5J3ixgrlBQuxXVwQ3mTXB50vk5tuv0vUrdXfcvtExUyuouIlx8 "JavaScript (Node.js) โ€“ Try It Online") ### How? We recursively build all possible regular expressions matching the first occurrence of \$p\$ digits preceded by \$q\$ digits, using a lookbehind assertion. The matched string is coerced to an integer, doubled and coerced back to a string. Example: ``` "123456".replace(/(?<=..).../, n => n * 2) // -> "12[345]6" -> "12[690]6" ``` We stop the recursion when no replacement occured (failure) or the result is equal to the other number (success). We try to turn either `a` into `b` or `b` into `a`. ### Commented ``` f = ( // f is a recursive function taking: a, b, // the input numbers a and b i // a flag i telling if the numbers were already swapped ) => ( // g = r => // g is a recursive function taking a pattern r a.replace( // replace in a: o = // initialize o to a non-numeric value RegExp('(?<=' + r), // turn r into a regular expression of the form /(?<=..)../ n => // if something is matched: replace the substring n with o = n * 2 // 2 * n and assign the result to o ) == b // end of replace(); success if the result is equal to b & ++o // and o is an even number, which becomes odd when incremented || o && // otherwise, if o is not equal to NaN: g('.' + r) | // try again with 1) another leading '.' in r g(r + '.') // and 2) with another trailing '.' in r )`)` // initial call to g with r = ')' || !i && f(b, a, 1) // if i is not set, try again with a and b exchanged ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 115 bytes ``` lambda*x:(a:=str(min(x)))and{str(max(x))}&{a[:i]+str(2*int(a[i:j]))+a[j:]for j in range(len(a)+1)for i in range(j)} ``` [Try it online!](https://tio.run/##bZFBboMwEEX3OcWsigdcKTaQIkt02RN0R1g4DaQgYpDtSFSIs1ObVo0U6oXleeM/3/oevuxnr@Js0EudH5dOXk9nGY6CSJEbq8m1UWRERKnO01rL0dfz0yQL0ZSRZzxslCWyaERbIkayaEVZ9xpaaBRoqS4V6SpFJEYMPW/uvMV5sZWxBnIgO3CLEEYhRgpvsjMV0l/IKSQOvuvbnSUU@CNjeyd324bz2HG@HcxSJ@Ap3zaY8@ScbRopO1BIs0eHNHOUHTZ4ve2GbRve4B@F83RPZfs/45XjTvuMguONvyQfAYX1xOIAdz5TSyuf6pqlWAU@0pqE9kc@aP9HdTDZGZ5fYTIzTLo49X1HDOZ5Vc4BLt8 "Python 3.8 (pre-release) โ€“ Try It Online") --- # [Python 3](https://docs.python.org/3/), ~~139~~ 116 bytes ~~A golf of [Noodle9's answer](https://codegolf.stackexchange.com/a/210140/64121).~~ Outputs a set containing `b` if there is a Brussels choice, an empty set otherwise. ``` def f(*x):a,b=map(str,sorted(x));return{b}&{a[:i]+str(2*int(a[i:j]))+a[j:]for j in range(len(a)+1)for i in range(j)} ``` [Try it online!](https://tio.run/##bZHBToQwFEX38xVvJX1DTaYFxgkGl36BO2RRnKIQBNKWZAzh2/EVjZMMdtE05/a@29wOX@6j76JlOesKKra/YKp4mX2qgVlnuO2N02d2QXw02o2mm8r5blJ5Whch6Uzu684xlddpUyCGKm/SouoNNFB3YFT3rlmrO6YwFOh5feUNzovT1lnIgO2AFmOCQ4QcnlVrNfJfKDnEBF/MeGUxB3nLxIHstG24jIjL7WCRkEEmcisIypRSbIREHDkkp9uE5ERUHDd4vU3DtoIP@MdBmfRUcfgLXjnujO8oeB3lQ/wWcFhPIgpw5zt1XPtW1y7T1eArpb90P/bB@D@qgsnNcP8Ek51hMnnZ9y2zmGW6mANcvgE "Python 3 โ€“ Try It Online") [Answer] # perl -Mfeature=say -na, 68 bytes ``` ($_,$n)=@F;m[.+(?{say$=if$n eq$`.($&/2).$'||$n eq$`.($&*2).$'})(?!)] ``` [Try it online!](https://tio.run/##TY6xDoJADIb3PkVNLsqpIC2cgRiik5tPYIwyHAmJHgg4GPHVPU90cPia9mv6p7VuzspaTxznwshss11d9sHMWz/a/C6yshAG9VWcAk@MFywDMen7PzUd1FN665E8WMsYQ4wMFBI6QNESVQIqQdd9JyKGTxkMYQTEETqAFCErd@t2zDRkpGkKDpcV0i80pFdVd2VlWuvvCp13t0Zn7lfrm/wN "Perl 5 โ€“ Try It Online") Reads two numbers from the input, and prints 60 if there's a way to connect the numbers, and nothing otherwise. ## How does it work? We take every possible, non-empty, substring of the first number; this will be in available in `$&`. The part of the first number which proceeds the current substring is in `$`` , the part after it is in `$'`. We then create two new strings, by either multiplying the substring by 2, or dividing it by 2, and sandwiching it between `$`` and `$'`. We then compare this with the second number, and print `$=` if there is a match (`$=` by default contains 60). Note that if the substring is odd, the resulting string will contain a decimal point, and hence, will not match with the second number. [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 122 bytes ``` $t=<>;for$a(1..y///c){for$b(0..y///c){$z||=/(.{$b})(.{$a})/&&$2!~/^0./&&grep$t==$_,$2%2==0&&$1.$2/2 .$',$1.$2*2 .$'}}$_=$z ``` [Try it online!](https://tio.run/##PYxBCsIwEEX3nkJhrIm0M5NAVxpv4BUsrVQRigmxG9vGoxvTLlx8/nt8@K71XRkj9OZ4Otysh1ooxDcRXeU4eyP47zBMkyGBIzRBzlUHSVkGevOhC2PCu29d@jJQ5aC32hhOs0LQpNcIu3zh/cIhQGVgiFGxWqV8resf9vmKxblEVhwL1/0A "Perl 5 โ€“ Try It Online") ]
[Question] [ Related: [Tell me how many math problems I have to do!](https://codegolf.stackexchange.com/questions/51189/tell-me-how-many-math-problems-i-have-to-do) ### Challenge Given a strictly positive strictly ascending integer list L and an integer 3 โ‰ค N โ‰ค length of L, replace the middle integers of L's consecutive integer runs of length โ‰ฅ N with a single dash `-`. ### Rules * Horizontal whitespace is irrelevant. * You may optionally preserve the introducer, separator, and terminator characters of your language's default list format. See *Format examples*, below. ### Data examples All these examples use `L = 3 5 6 7 8 10 11 12 14 16 17 18 19 20 21 22 24`. `N = 3` โ†’ `3 5 - 8 10 - 12 14 16 - 22 24` `N = 4` โ†’ `3 5 - 8 10 11 12 14 16 - 22 24` `N = 5` โ†’ `3 5 6 7 8 10 11 12 14 16 - 22 24` `N = 8` โ†’ `3 5 6 7 8 10 11 12 14 16 17 18 19 20 21 22 24` ### Format examples For the inputs โ€ƒ`L = [3,5,6,7,8,10,11,12,14,16,17,18,19,20,21,22,24]` and `N = 3` all the below lines are examples of valid responses, both as actual lists and as strings: ``` [3,5,"-",8,10,"-",12,14,16,"-",22,24] [3,5,-,8,10,-,12,14,16,-,22,24] [3,5-8,10-12,14,16-22,24] 3,5-8,10-12,14,16-22,24 ``` The same applies with other list formats, like `{1 2 3}` and `(1; 2; 3)` etc. In doubt? Ask! [Answer] # [Python 2](https://docs.python.org/2/), ~~132~~ 115 bytes -17 bytes thanks to Leaky Nun ``` x,n=input() o=[] i=1 while x: t=x[0] while[t+i]==x[i:i+1]:i+=1 o+=[[t,'-',t+i-1],x[:i]][i<n];x=x[i:];i=1 print o ``` [Try it online!](https://tio.run/##HcxLCsMwDATQvU@hXVqiQOSmP6c@idCyEEGxQ3Gpe3pXyWK0mDdo/ZUlJ99axRQ1rZ9yOLocWZxGct9FX0@owUGJlUdxsDdcepVojQbtSezYFnIfmQt2Q4fmAwlWDirC@kgy130u8/Z2fWsqkFvjE8IZ4YJwRbgh0Gghi7dMFhMyos3uCN7cm3tzPwlOfw "Python 2 โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26 25~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes thanks to Erik the Outgolfer (by bringing the if statement into the main link) ``` แธข;แนชjโ€- IแปŠยฌ1;ล“แน—โธยนร‡L<ยฅ?โ‚ฌF ``` A dyadic link returning a list in the `[3,5,"-",8,10,"-",12,14,16,"-",22,24]` format. **[Try it online!](https://tio.run/##AWgAl/9qZWxsef//4biiO@G5qmrigJ0tCknhu4rCrDE7xZPhuZfigbjCucOHTDzCpT/igqxG/8OnS///WzMsNSw2LDcsOCwxMCwxMSwxMiwxNCwxNiwxNywxOCwxOSwyMCwyMSwyMiwyNF3/Ng "Jelly โ€“ Try It Online")** (footer separates with spaces, to print the data example format). ### How? ``` แธข;แนชjโ€- - Link 1, format a run: list R แธข - head แนช - tail ; - concatenate โ€- - literal '-' j - join IแปŠยฌ1;ล“แน—โธยนร‡L<ยฅ?โ‚ฌF - Main link: list L, number N I - incremental differences แปŠ - insignificant? (<=1) ยฌ - not 1; - prepend a 1 โธ - chain's left argument, L ล“แน— - partition (L) at truthy indexes โ‚ฌ - for โ‚ฌach row, R, in L: ? - if: ยฅ - condition: last two links as a dyad: L - length of R < - is less than N? ยน - then: identity - do nothing, yields R ร‡ - else: call the last link (1) as a monad with argument R F - flatten into a single list ``` [Answer] # Pyth, 23 bytes ``` sm?<ldvzd[hd\-ed).ga=hZ ``` [Try it online](https://pyth.herokuapp.com/?code=sm%3F%3Cldvzd%5Bhd%5C-ed%29.ga%3DhZ&input=%5B3%2C5%2C6%2C7%2C8%2C10%2C11%2C12%2C14%2C16%2C17%2C18%2C19%2C20%2C21%2C22%2C24%5D%0A4) ### How it works ``` sm?<ldvzd[hd\-ed).ga=hZkQ Q autoinitialized to eval(input()) .g group by k โ†ฆ =hZ Z += 1, returning new value (Z is autoinitialized to 0) a k absolute difference with k m map d โ†ฆ ? if ld length of d < vz less than eval(z) (z is autoinitialized to input()) d then d [hd\-ed) else [d[0], '-', d[-1]] s concatenate ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 24 bytes ``` รณรˆร„ยฅYรƒยฎl ยจV?Zv +'-+Zo :Z ``` [Try it online!](https://tio.run/##y0osKPn///Dmwx2HWw4tjTzcfGhdjsKhFWH2UWUK2uq62lH5ClZR///7KNgqRBsrmCqYKZgrWCgYGigYGioYGikYmigYmikYmisYAgUtFYwMFIwMFYyMFIxMYrn8gHpMAA "Japt โ€“ Try It Online") ### Explanation ``` รณรˆ ร„ ยฅ Yรƒ ยฎ l ยจ V?Zv +'-+Zo :Z รณXY{X+1==Y} mZ{Zl >=V?Zv +'-+Zo :Z} Ungolfed Implicit: U = input array, V = input integer รณXY{ } Group U into runs such that for each pair X, Y: X+1==Y Y is exactly 1 more than X. mZ{ } Map each run Z to: Zl >=V? If Z has at least V items: Zv Zo Z.unshift() and Z.pop() (the first and last items) +'-+ joined with a hyphen. : Otherwise: Z just Z. Implicit: output result of last expression ``` [Answer] # [Retina](https://github.com/m-ender/retina), 101 bytes ``` \d+ $* \b(1+) (?=1\1\b) $1X T`X` `\b((X)|1)+\b(?=.*ยถ(?<-2>1)+(?(2)(?!))11) T`X`- -1+(?=-)|ยถ1+ 1+ $.& ``` [Try it online!](https://tio.run/##HcoxDoJAFATQ/p9iTIjZz2YJ80XQRNxLWFBQINHCxsJYci4OwMXWjcUkkzfzeX5f73tK48NLUco4O3qFiz1HjrNKwUFu0zBhypMbdKH63GJfldvq4iXYNYuLztTFnSqp/3@QwMx90GVb6UVyimqf0gFHtOhwAmuQoIEN2IIdmPEMq2GEGayR5gc "Retina โ€“ Try It Online") Takes the space-separated list `L` on the first line and the integer `N` on the second line. Explanation: The first stage converts the input to unary. The second stage changes the space between consecutive integers to an `X`. The third stage looks for runs of consecutive integers whose length is less than `N` and changes their `X`s back to spaces. The fourth stage changes the `X`s to `-` (this was 3 bytes shorter than using `-`s in the first place.) The fifth stage deletes all integers still left in the middle of a run, as well as `N`, while the final stage converts back to decimal. [Answer] # Mathematica, 128 bytes ``` (s=#2;t=r=1;While[t<Length@s,If[s[[t+1]]-s[[t]]==1,r++,r=1];If[r==#,s[[t-#+3;;t]]="-";r--];t++];s//.{b___,a_,a_,c___}:>{b,a,c})& ``` **input** > > [3,{3,5,6,7,8,10,11,12,14,16,17,18,19,20,21,22,24}] > > > **output** > > {3, 5, "-", 8, 10, "-", 12, 14, 16, "-", 22, 24} > > > [Try it online!](https://tio.run/##HYpNC4JAFEX/SihEMXeqN5Z9vCbaBi3atRgGMdEUysXM7MTfbhrcxeGe881D3RR@qPSw8DpWHLTTxM@6@ZQmnO9l@w711eNWGW9MEGStnMBarQlOCIy55VE7rWNMSsYiYZ6KSEbspLQchLDs1@tV98qyDPl/xYj96dK9kKPol/Ph4Zo2zK6VSdAl2CHFHgfQBkQgBdqCUtAeNJ5HqA0UQSmobW@HHw "Mathics โ€“ Try It Online") [Answer] # APL, 38 bytes ``` {โˆŠโบ{โบ>โ‰ขโต:โตโ‹„2โŒฝ'-',2โ†‘ยฏ1โŒฝโต}ยจโตโŠ‚โจ1,1โ‰ 2-โจ/โต} ``` [Answer] # PHP 7, ~~137 136 134 117 110~~ 108 bytes ``` for($a=$argv,$i=2;$n=$a[$i++];$k<$a[1]||array_splice($a,$i,$k-2,"-"))for($k=print"$n ";$a[$i+$k]-++$k==$n;); ``` Takes `L` from first argument, list elements after that. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/30d60ccc59d4658928c02510cd1bd8cadfa57685). Replace `$L=($a=$argv)` with `$a=$argv,$L=` (+1 byte) for PHP<7. **breakdown** ``` for($a=$argv,$i=2; # import input $n=$a[$i++]; # loop $n through list elements $k<$a[1]|| # 3. if streak length ($k) is >=L ($a[1]) array_splice($a,$i,$k-2,"-") # then replace with "-" ) for($k=print"$n "; # 1. print element and space $a[$i+$k]-++$k==$n;); # 2. find consecutive numbers ``` [Answer] # Ruby, 68 bytes ``` ->n,l{l.slice_when{|x,y|x<y-1}.map{|x|x[n-1]?x.minmax.uniq*?-:x}*?,} ``` Returns a string like for example `3,5-8,10-12,14,16-22,24`. [Try it online!](https://tio.run/##pctLDoIwFEbhuatgTP423MtLjNqFNMSggUgCDYrEEsraKwNXoMNzku85XWffnLw4G3RLJ8euvdWX9702i7OYnT3OglbZV8PWzmojqFRW9q3pKysn0z5CJQ52DRVWP0yvMWh0gkDHSJEhxx4UgQjEoASUgXLQNgtwBCYwgxNwWpa7r47/0vyT9h8 "Ruby โ€“ Try It Online") [Answer] # [J](http://jsoftware.com/), 40 bytes ``` ;@((](,_,{:)/)^:(<:#)&.>]<;.1~1,1<}.-}:) ``` [Try it online!](https://tio.run/##DchBDoIwEAXQPaf40cR0klr7xwI6VMNFkIWBGDcewODVa9/yvUtZcTMMo3OT87P/mpzkYS7bXg7hPuUh8EfPvIXjZtI0y/P1gQ84I6HFBXl06y5iljotOvT1GEGCCiawA3uw5hUaoYQqNJXyBw "J โ€“ Try It Online") Uses `_` instead of `-`. ## Explanation ``` ;@((](,_,{:)/)^:(<:#)&.>]<;.1~1,1<}.-}:) Input: integer N (LHS), array L (RHS) }. Behead L }: Curtail L - Subtract elementwise to get the increments 1< Test if greater than 1 1, Prepend a 1 ] Get L <;.1~ Partition L into boxes using the previous array & > Operate on each box (partition) with N ^: If # The length of the partition <: Is greater than or equal to N (]( )/) Reduce (right-to-left) it using {: Tail _, Prepend _ , Append to LHS &.> Box the result ;@ Raze - join the contents in each box ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 23 bytes ``` D0Jยจpฮตโฝแน…แธ‹โ€ขฦ›Lโฐโ‰ฅ[โ‚ht\-Y}f ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJEMErCqHDOteKBveG5heG4i+KAosabTOKBsOKJpVvigo1odFxcLVl9ZiIsIiIsIlszLCA1LCA2LCA3LCA4LCAxMCwgMTEsIDEyLCAxNCwgMTYsIDE3LCAxOCwgMTksIDIwLCAyMSwgMjIsIDI0XVxuNCJd) 23 bytes seems to be the standard here, so I figured I'd add my own 23 byter. Takes `L`ist then `N`. ## Explained ``` D0Jยจpฮตโฝแน…แธ‹โ€ขฦ›Lโฐโ‰ฅ[โ‚ht\-Y}f D0J # Push 3 copies of the input and append 0 to the last ยจpฮต # get the absolute difference of each overlapping pair โฝแน…แธ‹ # group by diff <= 1 โ€ข # mold to shape ฦ› } # to each consecutive run: Lโฐโ‰ฅ[ # if the length is >= N โ‚ht\-Y # [head, "-", tail] f # flatten that ``` [Answer] # Jelly, ~~39~~ ~~37~~ 36 bytes ``` IแปŠแนฃ0;โ‚ฌ1แน@ ร‡Lโ‚ฌ<ฦ“ยฌTแป‹ร‡แธŠโ‚ฌแน–โ‚ฌF;โ‚ฌโ€-Fyยตล’gQโ‚ฌF ``` [Try it online](https://tio.run/##y0rNyan8/9/z4e6uhzsXG1g/alpj@HBnowPX4XYfINvm2ORDa0Ie7u4@3P5wRxdQ4OHOaUDSDaTuUcNcXbfKQ1uPTkoPBIn9P9zu/t/kf7SxjqmOmY65joWOoYGOoaGOoZGOoYmOoZmOobmOIVDQUsfIQMfIUMfISMfIJBYA) Takes the array via arguments, and the integer via STDIN. The TIO link uses the footer `ร‡G` so the output is space-separated. **How?** (Array: `a`, Integer: `n`) ``` (`f`) IแปŠแนฃ0;โ‚ฌ1แน@ I Deltas of `a` แปŠ Insignificant (x -> abs(x)<=1) applied to each element แนฃ0 Split at occurrences of `0`. ;โ‚ฌ1 Append `1` to each element แน@ `a` shaped like that ร‡Lโ‚ฌ<ฦ“ยฌTแป‹ร‡แธŠโ‚ฌแน–โ‚ฌF;โ‚ฌโ€-Fyยตล’gQโ‚ฌF ร‡ `f` Lโ‚ฌ Length of each element <ฦ“ x -> x < n applied to each element ยฌ Logical not of each element (because Jelly doesn't have <= nor >= atoms) T Nonzero indexes แป‹ร‡ Index `f` at those indexes แธŠโ‚ฌแน–โ‚ฌ x -> x[1:-1] applied to each element F Flatten ;โ‚ฌโ€- Append a hyphen to each element F Flatten y Translate (replaces all elements to be deleted with a hyphen) ยต Start a new monadic link ล’g Group runs of equal elements Qโ‚ฌ Uniquify each element (make runs of hyphens one hypen) F Flatten, yet again. ``` I'm guessing I fell ... *flat* on this one. [Answer] # JavaScript (ES6), ~~126~~ 119 bytes ``` (e,c)=>{for(i=0,R='';i<e.length;R+=(R&&',')+(u-m>=c?m+'-'+--u:e.slice(z,i))){m=u=e[i],z=i;while(e[++i]==++u);}return R} ``` An anonymous function. Takes input in the order `Array L, Integer N` and returns the result as a comma-separated string. ``` M=(e,c)=>{for(i=0,R='';i<e.length;R+=(R&&',')+(u-m>=c?m+'-'+--u:e.slice(z,i))){m=u=e[i],z=i;while(e[++i]==++u);}return R} console.log(M(eval(prompt()),+prompt())) ``` [Answer] # Dyalog APL v16.0, ~~82~~ ~~80~~ ~~78~~ ~~76~~ ~~75~~ ~~65~~ 62 bytes ``` {S/โจ1,โจ2โ‰ /Sโ†'-'@(โธโŠƒโˆจ/(-0,โณโบ-3)โŒฝยจโŠ‚(โดโต)โ†‘โˆง/ยจ(โบ-1),/ยฏ1โŒฝ1=-2-/โต)โŠขโต} ``` Wow, this is ... bad. There's probably a much much shorter solution with stencil. [Try it online!](https://tio.run/##nYw9CsJAEIV7T/E6E3DZzCb@FYJ3yAlCJCIEFKxEbBQkBle0sBcbt7NQQQSbHGUuElfxAtrMg/e9b6JRKnqTKB32RZxG4/EgLsuEl9tpKFkbqtmjeHWQoe2qotp1WN85X3BmpCM8iy@sH8J3ef0sDOdzy6@sby4vd5ydZGGcNye3Josz2RF1hBLys8iPNmYV3uztbx8JfNTRQBMtkAcikAIFoAaoCbJlG8qDIigFFXy94E@v/qfX@tUryxc) Golfing suggestions welcome! ]
[Question] [ Your challenge is to **write a program to translate (English) leetspeak/lolspeak/txtspk into normal English.** Your program should read from standard input and output to standard output, unless your language does not support these. You may use a file containing a list of words in the English language, separated by new lines. It should be called `W` and will be located in the same directory as your program. (On GNU/Linux systems and possibly others, you can make `W` a link to `/usr/share/dict/words`) The list doesn't have to be all-lowercase, you can use it to determine whether words should have capitals. This is based on a now-deleted question posted by Nikos M. which could be found [here](https://codegolf.stackexchange.com/questions/28620/a-program-to-transliterate-l33t-words-to-regular-english-words). This is not a duplicate as this original question was closed and did not receive any answers, because there was no winning criterion and the user was unwilling to put one in. # Scoring The scoring is a bit complicated! Your score is ``` (leet items + bonuses) * 10 / (code length) ``` Highest score wins. **Your program doesn't have to be and probably can't be perfect, but the more accurate it is, the more bonuses it gets!** Since `$` can mean both `s` and `S`, you get a bonus of 5 points per leet item for deciding whether it should have a capital letter (i.e. capital letters at the start of sentences). You get a further bonus of 5 points per leet item for implementing proper nouns (words which always have capitals) - the way this works is that you would look through the word list, make the output capitalised if only a capitalised version is present in the list, and if both versions are there, just guess. If a character has two meanings (e.g. `1` can mean `L` or `I`), you get 20 points per leet item for only picking those translations of the item which make real English words - use the wordlist for this. If more than one translation of a leet item makes a real English word, you can arbitrarily pick one of the valid translations and still get the bonus. # List of Leet These are the leet items which you may implement. You don't have to implement all of them, but the more you add, the more points you get. **You cannot ever score points by translating an item or character to itself. This rule overrides any mistakes I might have made in the list.** It's tempting to do a simple `tr` or `s/.../.../g`. The real challenge is to determine which of multiple meanings could and couldn't be correct, using the wordlist. ## Leet Items (each of these adds 1 to `leet items` in the formula) ``` $ -> s,S ( -> c,C 5 -> s,S @ -> a,A 4 -> a,A 3 -> e,E 7 -> t,T + -> t,T # -> h,H teh -> the 'd -> ed pwnd -> pwned pwnt -> pwned k,K -> OK kk -> OK 0[zero]-> o,O y,Y -> why 4 -> for txt -> text dafuq -> what the f**k /\,^ -> a,A \/ -> v,V d00d -> dude n00b -> newbie \/\/ -> w,W 8 -> b,B |_| -> u,U |-| -> h,H ะฏ -> r,R j00 -> you joo -> you vv,VV -> w,W tomoz -> tomorrow |< -> k,K [),|) -> d,D <3 -> love >< -> x,X 10100111001 -> leet (binary representation of 1337) 2 -> to,too ur,UR -> your,you're (no need to correctly distinguish between the two) u,U -> you 8 -> -ate-,8 x,X -> -ks-,-cks- z,Z -> s,S 1 -> i,I,l,L ! -> i,I,! c,C -> see,C,sea b,B -> be,B,bee [accented letter] -> [non-accented form] (score 1 per accented letter supported) &,7 -> and,anned,ant (may be used in the middle of a word) ``` ## Harder "Leet": score 30 points for `leet items` each ``` !!!1!!1-> !!!!!!! (translate 1's in a sequence of !'s into !'s) !!!one!-> !!!!! !eleven-> !!! ``` ## Examples These are examples of what a program which implements all the leet characters above, and some of the bonuses, might be able to do: Example sentence: `|-|3 15 $|_|(# @ n00b` = `He is such a newbie` Leet-based censorship: `$#!+` = `s**t` Extreme leet: `\/\/ 1 |< 1 P 3 [) 1 A` = `Wikipedia` -xor suffix: `H4X0R` = `hacker` More extreme leet: `@1\/\/4Y5 p0$+ ur n3VV qu35710nz 1n teh $&80x` = `Always post your new questions in the sandbox` ## Example Scoring Bash, 10 characters, 3 items, no bonuses: ``` tr 137 let ``` This scores `( 1 * 3 ) * 10 / 10 = 3`. [Answer] # Javascript (49 + 5635) \* 10 / 2174 = 26.14 **Online Demo:** "Real dictionary" option doesnt work on drop box but it will work if run in a real web server. Tested in visual studio development server and google chrome. <https://dl.dropboxusercontent.com/u/141246873/leettranslator/index.html> **Score:** 49 leet items = 49 Capitalization bonus = 5 \* 49 = 245 dictionary lookup bonus = 20 \* 49 = 980 exclamation bonus \* 3 = 90 \* 49 = 4410 (leet items + bonuses) \* 10 / (code length) (49 + 5635) \* 10 / 2174 = 26.14 **Code:** ``` function IsInDict(e) { return W[e] } function translate(e) { words = e.split(" "); res = ""; for (var t in words) { ex = ""; function n(e, r, i) { var s = false; for (var o = 1; o <= e.length; o++) { var u = e.substring(0, o) === "!" || i; var a = et[e.substring(0, o)]; var f = e.substring(o); if (a) { s = true; if (f.length === 0) { if (u) { ex = r + a; words[t] = "" } } else n(f, r + a, u) } } if (i && !s && r) { ex = r; words[t] = e.split("").reverse().join("") } } n(words[t].split("").reverse().join(""), "", false); mes = []; function r(e, t) { for (var n = 1; n <= e.length; n++) { var i = tokens[e.substring(0, n)]; var s = e.substring(n); if (i) { mFound = true; if (s.length === 0) for (var o in i) { mes.push(t + i[o]) } else for (var o in i) r(s, t + i[o]) } } if (e.length > 1) r(e.substring(1), t + e.substring(0, 1)); else { mes.push(t + e) } } m = ""; if (words[t] !== "") { r(words[t].toLowerCase(), ""); if (mes.length === 1) m = mes[0]; else { sl = []; for (var i in mes) { if (IsInDict(mes[i].slice(-1) === "." ? mes[i].substring(0, mes[i].length - 1) : mes[i])) { sl.push(mes[i]) } } if (sl.length > 0) m = sl[0]; else m = mes[0] } if (res === "") { m = cap(m) } if (res.slice(-1) === ".") { m = cap(m) } } res += " " + m; if (ex !== "") res += ex } return res.trim() } function cap(e) { return e.charAt(0).toUpperCase() + e.slice(1) } tokens = { $: ["s"], "(": ["c"], 5: ["s"], "@": ["a"], 4: ["a", "for"], 3: ["e"], "+": ["t"], "#": ["h"], teh: ["the"], "'d": ["ed"], pwnd: ["pwned"], pwnt: ["pwned"], k: ["ok"], kk: ["ok"], 0: ["o"], y: ["why"], txt: ["text"], dafuq: ["what the f**k"], "/\\": ["a"], "^": ["a"], "\\/": ["v"], d00d: ["dude"], n00b: ["newbie"], "\\/\\/": ["w"], 8: ["b", "ate"], "|_|": ["u"], "|-|": ["h"], "ะฏ": ["r"], j00: ["you"], joo: ["you"], vv: ["w"], tomoz: ["tomorrow"], "|<": ["k"], "[)": ["d"], "|)": ["d"], "<3": ["love"], "><": ["x"], 10100111001: ["leet"], 2: ["to", "too"], ur: ["your", "you're"], u: ["you"], x: ["ks", "cks"], z: ["s"], 1: ["i", "l"], "!": ["i"], c: ["see", "sea"], b: ["be", "bee"], "&": ["and", "anned", "ant"], 7: ["and", "anned", "ant", "t"] }; et = { eno: "!", nevele: "!!", 1: "!", "!": "!" } ``` **Ungolfed:** ``` tokens={ '$':['s'],'(':['c'],'5':['s'],'@':['a'],'4':['a','for'],'3':['e'],'+':['t'],'#':['h'],'teh':['the'],"'d":['ed'],'pwnd':['pwned'], 'pwnt':['pwned'],'k':['ok'],'kk':['ok'],'0':['o'],'y':['why'],'txt':['text'],'dafuq':['what the f**k'], '/\\':['a'],'^':['a'],'\\/':['v'],'d00d':['dude'],'n00b':['newbie'], '\\/\\/':['w'],'8':['b','ate'],'|_|':['u'],'|-|':['h'],'ะฏ':['r'],'j00':['you'], 'joo':['you'],'vv':['w'],'tomoz':['tomorrow'],'|<':['k'],'[)':['d'],'|)':['d'],'<3':['love'], '><':['x'],'10100111001':['leet'],'2':['to','too'],'ur':["your","you're"], 'u':['you'],'x':['ks','cks'],'z':['s'],'1':['i','l'],'!':['i'],'c':['see','sea'], 'b':['be','bee'],'&':['and','anned','ant'],'7':['and','anned','ant','t']} var excTokens = {'eno':'!','nevele':'!!','1':'!','!':'!'} function IsInDict(word) { return (W[word]); } function translate(input) { var words = input.split(" "); var result = ""; for (var i in words) { var exclamations = ""; function parseExclamations(s, prev, exclamationFound) { var matchFound = false; for (var j = 1; j <= s.length; j++) { var hasExclamation = (s.substring(0, j) === "!") || exclamationFound; var currentToken = excTokens[s.substring(0, j)]; var remaining = s.substring(j); if (currentToken) { matchFound = true; if (remaining.length === 0) { if (hasExclamation) { exclamations = prev + currentToken; words[i] = "";//word only had exclamations in it so dont parse the rest of it } } else parseExclamations(remaining, prev + currentToken, hasExclamation); } } if (exclamationFound && !matchFound && prev) { exclamations = prev; words[i] = s.split("").reverse().join("");//reverse back again } } var reverseWord = words[i].split("").reverse().join(""); parseExclamations(reverseWord, "", false); var matches = [] function parse(s, prev) { for (var j = 1; j <= s.length; j++) { var currentTokenArray = tokens[s.substring(0, j)]; var remaining = s.substring(j); if (currentTokenArray) { matchFound = true; if (remaining.length === 0) for (var k in currentTokenArray) { matches.push(prev + currentTokenArray[k]); } else for (var k in currentTokenArray) parse(remaining, prev + currentTokenArray[k]); } } if (s.length > 1) parse(s.substring(1), prev + s.substring(0, 1)); else { matches.push(prev + s); } } var match = ""; if (words[i] !== "") { parse(words[i].toLowerCase(), ""); //check the dictionary if (matches.length === 1) match = matches[0]; else { var shortlist = []; for (var j in matches) { //check dictionary. allow for a full stop at the end of the word var isInDict = IsInDict(matches[j].slice(-1) === "." ? matches[j].substring(0, matches[j].length - 1) : matches[j]); if (isInDict) { shortlist.push(matches[j]); } } if (shortlist.length > 0) match = shortlist[0]; else match = matches[0]; } if (result === "") { match = cap(match); } if (result.slice(-1) === ".") { match = cap(match); } } result += " " + match; if (exclamations !== "") result += exclamations; } return result.trim(); } function cap(string) { return string.charAt(0).toUpperCase() + string.slice(1); } ``` **Test results:** * |-|3 15 $|\_|(# @ n00b ====> He is such a newbie * @1//4Y5 p0$+ ur n3VV qu35710nz 1n teh $&80x ====> Always post your new questions in the sandbox * !!!1!!1 ====> !!!!!!! * !!!one! ====> !!!!! * !eleven ====> !!! * teh!!!1!!1 ====> The!!!!!!! * teh!!!one! ====> The!!!!! * teh!eleven ====> The!!! * teh !!!1!!1 ====> The !!!!!!! * qu35710nz!1! ====> Questions!!! * +357 +357. 735+ ====> Test test. Test * & 31!73 #4(KER$ WR0+3 83773R L!K3 +#!5 7#@N 2D@Y ====> And elite hackers wrote better like this than today **Notes:** The dictionary is a seperate javascript file with an object called W containing all of the words. This just contains the words I needed for running the relevant tests. [Answer] # Haskell - Score 1.421421421 : (37 items + (21 bonuses (capitalization) \* 5)) \* 10 / (999 bytes) This is my final answer. ``` import System.Environment import Text.Parsec import Text.Parsec.String s=string r=return t=try o=oneOf (>|)=(<|>) a p l u=b[p]l u b (p:q) l u=e(foldl(>|)(s p)$map(s)q)l u c p l u=e(o p)l u d p q=t$s p>>r q e p l u=t$do{p;r l}>|do{s". ";p;r$". "++u} f p q=t$do{between(t$s" ")(t$s" ")(o p);r q} g::Parser String g=do{s<-many$c"$5""s""S">|c"@4^""a""A">|c"3""e""E">|c"7+""t""T">|c"#""h""H">|d"teh""the">|d"'d""ed">|d"pwnd""pwned">|d"pwnt""pwned">|c"kK""ok""OK">|d"kk""OK">|d"n00b""newbie">|f"yY""why">|d"4""for">|d"txt""text">|d"dafuq""what the f**k">|b["\\/\\/","vv","VV"]"w""W">|a"/\\""a""A">|d"d00d""dude">|c"0""o""O">|a"\\/""v""V">|c"8""b""B">|a"|_|""u""U">|a"|-|""h""H">|c"ะฏ""r""R">|b["j00","joo"]"you""you">|d"tomoz""tomorrow">|a"|<""k""K">|b["[)","|)"]"d""D">|d"<3""love">|a"><""x""X">|c"1!""i""I">|d"10100111001""leet">|c"2""too""to">|d"ur""your">|d"UR""you're">|f"uU""you">|c"xX""ks""cks">|d"&""and">|do{c<-anyChar;return [c]};return$concat s} main=getArgs>>=putStrLn.show.(parse g"").concat ``` # Tests When the program is compiled to a file named `min-lt`, you can write the following shell script ``` #!/bin/bash ./min-lt "|-|3 15 $|_|(# @ n00b" ./min-lt "\$#!+" ./min-lt "\/\/ 1 |< 1 P 3 [) 1 A" ./min-lt "H4X0R" ./min-lt "@1\/\/4Y5 p0$+ ur n3VV qu35710nz 1n teh $&80x" ./min-lt "+357 +357. 735+" ``` which will print this ``` Right "he is su(h a newbie" Right "shit" Right "w i k i P e d i A" Right "HaksoR" Right "aiwaYs post your new questionz in the sandboks" Right "test test. Test" ``` [Answer] # [Extended BrainFuck](http://sylwester.no/ebf/) : 0.6757 ``` {a[-])&d}{c(-(-}{d)$t(-}:r:i:t$t,(-$i+$r+)$i($t 6+(-$i 5--)+$i 3+(--&c-(-- (3-(5-&c&c&c-&c--5-((-&d)$r.&d|"A"&a|"B"&a|"T"&a|"S"&a|"A"&a|"E"&a|"TO"&a |"L"&a|"O"&a|"T"&a|"C"&a|"AND"&a|"S"&a|"H"&a|"I"(-))$i(-)$r(-)$t,(-$i+$r+)) ``` So this does 15 translations "$(5@437+#0821!&" , no bonuses and it has 222 bytes (uneccesary linefeeds not included). 15\*10/222 = 0.6757 Usage: ``` %> beef ebf.bf < leet.ebf > leet.bf %> echo '& 31337 #4(KER$ WR0+3 83773R L!K3 +#!5 7#@N 2D@Y' | beef leet.bf AND ELEET HACKERS WROTE BETTER LIKE THIS THAN TODAY %> ``` EBF isn't really made for golfing but it's rle feature, macros and print string feature makes it somewhat easier to compress than BrainFuck. The end compiled BrainFuck binary looks like this: ``` >>,[-<+<+>>]<[>++++++[-<------>]+<+++[--[-[--[--[---[-----[-[-[-[-[-[--[-[--------[[-] >[-]<<.>]>[->++++++++[-<++++++++>]<+.[-]]<]>[->++++++++[-<++++++++>]<++.[-]]<]>[->++++ +++++[-<+++++++++>]<+++.[-]]<]>[->+++++++++[-<+++++++++>]<++.[-]]<]>[->++++++++[-<++++ ++++>]<+.[-]]<]>[->++++++++[-<+++++++++>]<---.[-]]<]>[->+++++++++[-<+++++++++>]<+++.-- ---.[-]]<]>[->++++++++[-<+++++++++>]<++++.[-]]<]>[->+++++++++[-<+++++++++>]<--.[-]]<]> [->+++++++++[-<+++++++++>]<+++.[-]]<]>[->++++++++[-<++++++++>]<+++.[-]]<]>[->++++++++[ -<++++++++>]<+.+++++++++++++.----------.[-]]<]>[->+++++++++[-<+++++++++>]<++.[-]]<]>[- >++++++++[-<+++++++++>]<.[-]]<]>[->++++++++[-<+++++++++>]<+.[-]]<[-]<[-]>>,[-<+<+>>]<] ``` [Answer] # Java : 1.236 ``` import java.util.*;public class L{static H<String,String>c;static H<String,String>w;static{c=new H();c.p("1","i");c.p("!","i");c.p("$","s");c.p("5","s");c.p("@","a");c.p("4","a");c.p("3","e");c.p("7","t");c.p("+","t");c.p("#","h");c.p("'d","ed");c.p("0","o");c.p("zero","o");c.p("\\/\\/","w");c.p("/\\","a");c.p("\\/","v");c.p("|<","k");c.p("[)","d");c.p("8","b");c.p("|_|","u");c.p("|-|","h");c.p("ะฏ","r");c.p("(","c");c.p("VV","w");c.p("&","and");c.p("2","to");w=new H();w.p("@","a");w.p("teh","the");w.p("pwnd","pwned");w.p("pwnt","pwned");w.p("k","ok");w.p("kk","ok");w.p("y","why");w.p("Y","why");w.p("4","for");w.p("txt","text");w.p("dafuq","what the f**k");w.p("d00d","dude");w.p("n00b","newbie");w.p("j00","you");w.p("joo","you");}public static void main(String[]a){System.out.println(new L().C(a));}String C(String[]o){String x=T(o);for(String d:o){if(w.containsKey(d))x=x.replace(d,w.get(d));else{String r=d;for(String y:c.keySet()){if(d.contains(y))r=r.replace(y,c.get(y));}x=x.replace(d,r);}}return x;}String T(String[]l){String s="";for(String w:l)s+=" "+w;return s;}}class H<T1,T2>extends LinkedHashMap<T1,T2>{T2 p(T1 k,T2 v){return super.put(k,v);}} ``` So it does the following transformations ``` +357 +357. 735+ test test. test |-|3 15 $|_|(# @ n00b he is such a newbie $#!+ shit \/\/ 1 |< 1 P 3 [) 1 A w i k i P e d i A @1\/\/4Y5 p0$+ ur n3VV qu35710nz 1n teh $&80x aiwaYs post ur new questionz in the sandbox & 31337 #4(KER$ WR0+3 83773R L!K3 +#!5 7#@N 2D@Y and eieet hacKERs WRote betteR LiKe this thaN toDaY ``` The score calculation is tricky * (leet items + bonuses) \* 10 / (code length) * code length = 1165 leet * leet items = 39 (unique) * bonus = 21 (do not know how to calculate so copied MomemtumMori) (Please advise) ((39 + (21\*5)) \* 10) / 1165 = 1.236 Un-Golfed code : ``` import java.util.*; public class L { static H<String, String> c; static H<String, String> w; static { c = new H(); c.p("1", "i"); c.p("!", "i"); c.p("$", "s"); c.p("5", "s"); c.p("@", "a"); c.p("4", "a"); c.p("3", "e"); c.p("7", "t"); c.p("+", "t"); c.p("#", "h"); c.p("'d", "ed"); c.p("0", "o"); c.p("zero", "o"); c.p("\\/\\/", "w"); c.p("/\\", "a"); c.p("\\/", "v"); c.p("|<", "k"); c.p("[)", "d"); c.p("8", "b"); c.p("|_|", "u"); c.p("|-|", "h"); c.p("ะฏ", "r"); c.p("(", "c"); c.p("VV", "w"); c.p("&", "and"); c.p("2", "to"); w = new H(); w.p("@", "a"); w.p("teh", "the"); w.p("pwnd", "pwned"); w.p("pwnt", "pwned"); w.p("k", "ok"); w.p("kk", "ok"); w.p("y", "why"); w.p("Y", "why"); w.p("4", "for"); w.p("txt", "text"); w.p("dafuq", "what the f**k"); w.p("d00d", "dude"); w.p("n00b", "newbie"); w.p("j00", "you"); w.p("joo", "you"); } public static void main(String[] a) { System.out.println(new L().C(a)); } String C(String[] o) { String x = T(o); for (String d : o) { if (w.containsKey(d)) x = x.replace(d, w.get(d)); else { String r = d; for (String y : c.keySet()) { if (d.contains(y)) r = r.replace(y, c.get(y)); } x = x.replace(d, r); } } return x; } String T(String[] l) { String s = ""; for (String w : l) s += " " + w; return s; } } class H<T1, T2> extends LinkedHashMap<T1, T2> { T2 p(T1 k, T2 v) { return super.put(k, v); } } ``` [Answer] ## C# score 45\*10/2556=0.176 Program can output almost all lower and upper case letters. Since I'm not using a english word list the first key found in the Dictionary is used. E.g \/\/ becomes vav. If char is first letter of a word ToUpper is applied. ``` using System; using System.Collections.Generic; class L { Dictionary<string, string> D; public L() { D = new Dictionary<string, string>(); M(); } public void M() { D.Add("$", "s,S"); D.Add("(", "c,C"); D.Add("5", "s,S"); D.Add("@", "a,A"); D.Add("4", "a,A,for"); D.Add("3", "e,E"); D.Add("7", "t,T,and,anned,ant"); D.Add("+", "t,T"); D.Add("#", "h,H"); D.Add("teh", "the"); D.Add("'d", "ed"); D.Add("pwnd", "pwned"); D.Add("pwnt", "pwned"); D.Add("k", "OK"); D.Add("K", "OK"); D.Add("kk", "OK"); D.Add("0", "o,O"); D.Add("y", "why"); D.Add("Y", "why"); D.Add("txt", "text"); D.Add("dafuq", "what the f**k"); D.Add("\\/\\/", "w,W"); D.Add("/\\", "a,A"); D.Add("^", "a,A"); D.Add("\\/", "v,V"); D.Add("d00d", "dude"); D.Add("n00b", "newbie"); D.Add("8", "b,B,ate,8"); D.Add("|_|", "u,U"); D.Add("|-|", "h,H"); D.Add("j00", "you"); //ะฏ -> r,R D.Add("joo", "you"); D.Add("vv", "w,W"); D.Add("VV", "w,W"); D.Add("tomoz", "tomorrow"); D.Add("|<", "k,K"); D.Add("[)", "d,D"); D.Add("|)", "d,D"); D.Add("<3", "love"); D.Add("><", "x,X"); D.Add("2", "to,too"); //10100111001 -> leet (binary representation of 1337) D.Add("ur", "your,you're"); D.Add("UR", "your,you're"); D.Add("u", "you"); D.Add("U", "you"); D.Add("x", "ks,cks"); D.Add("X", "ks,cks"); D.Add("z", "s,S"); D.Add("Z", "s,S"); D.Add("1", "i,I,l,L"); D.Add("!", "i,I,!"); D.Add("c", "see,C,sea"); D.Add("C", "see,C,sea"); D.Add("b", "be,B,bee"); D.Add("B", "be,B,bee"); //[accented letter] -> [non-accented form] (score 1 per accented letter supported) D.Add("&", "and,anned,ant"); } int P(string K, out List<string> V) { V = new List<string>(); string v,comma=","; if(D.TryGetValue(K,out v)) { string[] vv = v.Split(comma.ToCharArray()); foreach(string s in vv) { V.Add(s); } } return V.Count; } public string E(string X) { string e =""; string S = " ",t,k=""; string[] W = X.Split(S.ToCharArray()); int n = 0,x=0,m=0; List<string> V=new List<string>(); bool F = false; foreach(string s in W) { n = s.Length; F = false; for (int i = 0; i < n; i++) { m = 0; for (int j = 1; j < n - i+1; j++) { k = s.Substring(i, j); x = P(k, out V); if (x > 0) { t = V[0]; if (t.Length == 1 && i == 0) t = t.ToUpper(); e += t; m = t.Length; F = true; break; } } if (m > 0) i += (m - 1); } e += S; } return e; } static void Main(string[] a) { string t = Console.ReadLine(); L x = new L(); t = x.E(t); Console.WriteLine(t); Console.ReadLine(); } } ``` Here's my test output: ``` $ -> S ( -> C 5 -> S @ -> A 4 -> A 3 -> E 7 -> T + -> T # -> H teh -> the 'd -> ed pwnd -> pwned pwnt -> pwned k -> OK K -> OK 0 -> O y -> why Y -> why 4 -> A txt -> text dafuq -> what the f**k /\ -> A ^ -> A \/ -> V d00d -> dude n00b -> newbie \/\/ -> Vav 8 -> B |_| -> U |-| -> H j00 -> you joo -> you vv -> W VV -> W tomoz -> tomorrow |< -> K [) -> D |) -> D <3 -> love >< -> X 2 -> to ur -> you UR -> you u -> you U -> you 8 -> B x -> ks X -> ks z -> S Z -> S 1 -> I ! -> I c -> see C -> see b -> be B -> be ``` ]
[Question] [ ## Challenge Given two binary vectors (containing two consistent values of your choice) of length \$n\$ and \$m\$, output a corresponding [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") hitomezashi stitching pattern. You are to fill the following pattern, where \$n\$ is the number of `A`-columns and \$m\$ is the number of `B`-rows: ``` A A A A A B+B+B+B+B+B A A A A A B+B+B+B+B+B A A A A A ``` Here `A` can be one of `|` and (space), and `B` can be one of `-` and (space). The rows and columns alternate between these two values. The binary vectors indicate, whether to start in the "on" (`|`/`-`) or "off" () position for each row or column. *You may be interested in a [recent Numberphile video on that topic](https://www.youtube.com/watch?v=JbfhzlMk2eY).* ## Rules * \$n,m \geqslant 1\$ * There are \$ n \times m \$ `+`s. * You may take input in any consistent order (rows first or columns first) and following any direction (right-to-left and top-to-bottom or reversed or mixed). * Output in any reasonable format, including one of: single string with newlines, list of lines, matrix of characters. Output as char codes is allowed only if your language doesn't support strings natively. * Trailing whitespace is optional. ## Test cases Input: `0 1 0 1`, `0 1 1` Working out: ``` 0 1 0 1 0+?+?+?+? ? ? ? ? 1+?+?+?+? ? ? ? ? 1+?+?+?+? ? ? ? ? ``` Output: ``` | | +-+ +-+ | | -+ +-+ +- | | -+ +-+ +- | | ``` Input: `0`, `0` Output: ``` +- | ``` Input: `1`, `1` Output: ``` | -+ ``` Input: `1 0 1 0 1`, `1 0 1 0 1 0 1` Output: ``` | | | -+ +-+ +-+ | | +-+ +-+ +- | | | -+ +-+ +-+ | | +-+ +-+ +- | | | -+ +-+ +-+ | | +-+ +-+ +- | | | -+ +-+ +-+ | | ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` ๏ผฆยฒยซ๏ผฐโญ†ยงฮธยฌฮนโชซยถยถโชซ๏ผฅโŠ•๏ผฌยงฮธฮนยง -โบฮผฮบ+โ€–๏ผดโ†™ ``` [Try it online!](https://tio.run/##TY47C8JAEITr@CuWqzZ4AbXUSrCJJCJqF1OE5PLAy56e6wPE336eomAzw@zMB1u2hS1NoZ2rjQWchPAYBOlFc3e0HTFu2VuTFkecc0yVuuNJwsowdmEoYWk6QrGnPYlveC9jKq3qFbGqMFHUcPsPe9CTv4OAyKNrfTljL@Hw6cRQeA9ng2Cjaq1K3tmCzv6/HqcLc6NE1ezbp3NZlo0kjCW8NZfwTeM8z1101S8 "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes input as an array of two binary vectors. Explanation: ``` ๏ผฆยฒยซ ``` Loop over rows and then columns. ``` ๏ผฐโญ†ยงฮธยฌฮนโชซยถยถโชซ๏ผฅโŠ•๏ผฌยงฮธฮนยง -โบฮผฮบ+ ``` For each row, build up the line of `-`s or spaces and `+`s according to the initial value from the binary vector. Double-space the rows out and output the whole string without moving the cursor. ``` โ€–๏ผดโ†™ ``` Reflect the entire diagram around its main diagonal. On the first pass this moves the rows to the columns, allowing the columns to be printed where the rows were, while on the second pass the rows and columns are restored to their correct placement. Additionally, the `-`s and `|`s are swapped as part of the reflection. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` Jลปแธ‚+ลผโธFรฐ"2,4^'/แป‹โ€œ+ - | +โ€Y ``` [Try it online!](https://tio.run/##y0rNyan8/9/r6O6HO5q0j@551LjD7fAGJSMdkzh1/Ye7ux81zNFW0FWoUVDQftQwN/L////R0QY6hjpAHKsDZhnGxgIA "Jelly โ€“ Try It Online") Takes input like `[[0,1,0,1],[0,1,1]]`. ``` Helper function: left input is a bit array, right input is a number Jลปแธ‚ Alternate [0,1,0,1,โ€ฆ] one longer than the bit array + Add n ลผโธF Interleave with the array: [n, a0, n+1, a1, n, a2, n+1] Main function: input is two bit arrays [A, B] รฐ"2,4 [helper(A, 2), helper(B, 4)] ^'/ Make a XOR table แป‹โ€œ+ - | +โ€Y Index into โ€œ+ - | +โ€ and join by newlines. ``` For example, for the input `[[0,1,0,1],[0,1,1]]` this computes ``` ^ โ”‚ 2 **0** 3 **1** 2 **0** 3 **1** 2 โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 4 โ”‚ 6 4 7 5 6 4 7 5 6 **0** โ”‚ 2 0 3 1 2 0 3 1 2 5 โ”‚ 7 5 6 4 7 5 6 4 7 **1** โ”‚ 3 1 2 0 3 1 2 0 3 4 โ”‚ 6 4 7 5 6 4 7 5 6 **1** โ”‚ 3 1 2 0 3 1 2 0 3 5 โ”‚ 7 5 6 4 7 5 6 4 7 ``` And then translates {0, 1} โ†’ `+`, 3 โ†’ `-`, 5 โ†’ `|`, and everything else to spaces. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~69~~ ~~66~~ ~~62~~ ~~58~~ 54 [bytes](https://github.com/abrudz/SBCS) Function that takes two binary vectors as left and right argument. Assumes index origin 0. ``` {' -|+'[โ†‘,โ‰โ†‘(,/ยฏ2โ†‘ยจ2ร—โ†‘โ‰ \(โŠ‚โบ),!โต)({โˆŠโบ3โต}/โ‰โ†‘โ‰ \(โŠ‚โต),!โบ)]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1pdQbdGWz36UdtEnUe9nUBKQ0f/0HojIOPQCqPD04H0o84FMRqPupoe9e7S1FF81LtVU6P6UUcXkGsM5NTqQ7QhVG0Fq9qlGVv7P@1R24RHvX2P@qZ6@j/qaj603hiksm9qcJAzkAzx8Az@D5ZTAKpTMODiMlAwVADhNDBpyJX2qHeFgo4BlDbkgshCVCDYQMzF9ah3DRfQVepBiXkp@bnqGnlAIw2NNdUPT1fXyAWyTTXBSjTs8x71bjHSBBpgnwtiAQA "APL (Dyalog Unicode) โ€“ Try It Online") **Commented** (outdated): ``` {โˆŠโบ'+'โต}/' -'[โ‰โ†‘โ‰ \(โŠ‚โต),!โบ] โ Generate the B-rows !โบ โ A list of n 1's (factorial of 0 and 1 is 1) (โŠ‚โต), โ prepend the right (second) input vector โ‰โ†‘โ‰ \ โ the tranpose of โ‰  (XOR) scan โ this gives a binary mask of where to place dashes ' -'[ ] โ index with the mask into the string ' -' to get a character matrix {โˆŠโบ'+'โต}/ โ for each row, insert plus's ,/ยฏ2โ†‘ยจ' |'[โ†‘โ‰ \(โŠ‚โบ),!โต] โ Generate the A-rows ' |'[โ†‘โ‰ \(โŠ‚โบ),!โต] โ Same as above, but with inputs swapped and not transposed ยฏ2โ†‘ยจ โ Prepend a space to each character in the matrix (this results in a nested matrix) ,/ โ Join each row into a single string โ†‘,โ‰โ†‘ โ Interleave the two lists of rows to get a single character matrix ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 121 116 bytes ``` lambda h,v,i=0:[print(((i:=~i)<2>l)*((l*"-+"+len(h)*" +-+")[:len(h)*2+1]+"\n"),*["| "[k^i]for k in h])for l in[2]+v] ``` [Try it online!](https://tio.run/##XY3BCsIwEETv/Yqwp2wSoa0XKcYfSVeoaEloTEspBUH89djUIuhh4c3sMDM8JtuH/WEYY6vr6Jv75dowq2bldF6ZYXRh4py7Sr8cHsuTR8G5F7CTIP0tcIsCmFwUmmrTpSxIQh0AlTDwZGC6s6O2H1nHXGCWMLFf2JQkZ4otN7kq1HKkVioIs88yZumZ7F8rJf9Sa8FW8uVVY3wD "Python 3.8 (pre-release) โ€“ Try It Online") Uses Pythons space separated output of `print` for the vertical lines. Thanks for @pxeger for noticing that the flag toggle (`i:=~i`) and first line check (`2>l`) can be combined, by using a numerical flag. By using 0 and -1 instead of 0 and 1 for the flag, a further byte can be saved. [Answer] # JavaScript (ES6), 95 bytes Expects `(a)(b)`. Returns a matrix of characters. ``` a=>b=>[...b+11].map((_,y)=>[...a+11].map((_,x)=>' |-+'[x*y%2*3|a[~-x/2]+y/2&1|b[~-y/2]*2+x&2])) ``` [Try it online!](https://tio.run/##VY/NbsIwEITveYq9gL2xY7B7RMmNp3BX1TqQFkRjFBBKpKivnoaQ/nDZnflm57BHvvGlbA7na1bH3X6o8oHzIuSFN8YEZS2ZTz5L@aY7fED@D9sRCugzJXybdguXvvTsv7J25Uh1K7e0fRjtqCh1ql06Qhw2PgHwfq3BarhP0jA7S6Qf4cR@3HTxm82tv@4TmDEllJgqNlsuP6T0rCEQQl5AGetLPO3NKb7LSjLKgNMzzT1szDEeaikE4qxea4GgYNo4fAM "JavaScript (Node.js) โ€“ Try It Online") ### Cell types ``` 01234 Cell types: 0 .|.|. crossing (+) : x odd and y odd โ‡” x * y % 2 == 1 1 -+-+- vertical link (|) : x odd and y even 2 .|.|. horizontal link (-) : x even and y odd 3 -+-+- empty (.) : x even and y even 4 .|.|. ``` ### Commented ``` a => // a[] = horizontal vector b => // b[] = vertical vector [...b + 11] // coerce b[] to a string and append 2 more characters, // which gives b.length * 2 + 1 characters // e.g. [0,1,0] -> "0,1,011" .map((_, y) => // for each entry at position y: [...a + 11] // do the same thing with a[] .map((_, x) => // for each entry at position x: ' |-+'[ // character lookup: x * y % 2 * 3 | // force a '+' if both x and y are odd a[~-x / 2] // attempt to get a[(x - 1) / 2], // which is undefined if x is even + y / 2 // add y / 2 (resulting in NaN if x is even) & 1 | // bitwise AND with 1 to get either " " or "|" b[~-y / 2] * 2 // attempt to get b[(y - 1) / 2] * 2, // which is NaN if y is even + x // add x (still NaN if y is even) & 2 // bitwise AND with 2 to get either " " or "-" ] // end of character lookup ) // end of inner map() ) // end of outer map() ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~37~~ 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "+ - | +"Iฮต1รyฤ†โˆN>o+s.ฮน}`sฮด^<รจJยป ``` -4 bytes by porting [*@Lynn*'s Jelly answer](https://codegolf.stackexchange.com/a/239719/52210). [Try it online](https://tio.run/##yy9OTMpM/f9fSVtBV6FGQUFbyfPcVsPDcyuPtD3q6PWzy9cu1ju3szah@NyWOJvDK7wO7f7/PzraQMdQB4hjdcAsw9hYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mlGerVKmuc3jvo6Y1jxqWRR/eH5sQqqSjkGurFOGl819JW0FXoUZBQVup8txWw8NzK4@0Pero9bPL1y7WO7ezNqH43JY4m8MrvA7t/q9zaJv9/@joaAMdQx0gjtUBswxjY3UUgIIgLoQJkoGKghVCFcPZYH5sLAA). **Original 37 byter:** ``` vโ€ž|-NรจรฐรฌyD_รธIN_รจg>ฮดโˆN_iรธ}รจโ€ž +Nรจรฝ}.ฮน.c ``` Input as pair \$[n,m]\$, where both \$n\$ and \$m\$ are lists of 0s/1s. [Try it online](https://tio.run/##yy9OTMpM/f@/7FHDvBpdv8MrDm84vKbSJf7wDk@/@MMr0u3ObXnU0esXn3l4R@3hFUBFCtogRXtr9c7t1Ev@/z862kDHUAeIY3XALMPYWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mlGerVKmuc3jvo6Y1jxqWRR/eH5sQqqSjkGurFOGlU3lo5f@yRw3zanT9Dq84vOHwmkqX@MM7Dq3ziz@8It3u3JZHHb1@8ZmHd9QeXgFUpaANUrW3Vu/cTr3k/zqHttn/j46ONtAx1AHiWB0wyzA2VkcBKAjiQpggGagoWCFUMZwN5sfGAgA). Taking the input in the order \$[m,n]\$ instead would result in the same byte-count: ``` vโ€ž-|NรจรฐรฌyD_รธIN_รจg>ฮดโˆNiรธ}รจโ€ž+ Nรจรฝ}s.ฮน.c ``` [Try it online](https://tio.run/##yy9OTMpM/f@/7FHDPN0av8MrDm84vKbSJf7wDk@/@MMr0u3ObXnU0euXeXhH7eEVQDXaCiA1e2uL9c7t1Ev@/z862kDHUMcwVgdMA3FsLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mlGurVKmuc3jvo6Y1jxqWRR/eH5sQqqSjkGerFOGlU3lo5f@yRw3zdGv8Dq84vOHwmkqX@MM7Dq3ziz@8It3u3JZHHb1@mYd31B5eAVSkrQBStLe2WO/cTr3k/zqHttn/j46ONtAx1DGM1QHTQBwbq6MAFAQJQJggOagoWAEMg4Th7NhYAA). **Explanation:** ``` v # Loop `y` over the (implicit) input-pair: โ€ž|- # Push String "|-" Nรจ # Use the 0-based loop-index to index into it รฐรฌ # Prepend a space y # Push the current input-list D_ # Duplicate it, and invert each 0โ†”1 รธ # Zip the two lists, creating pairs # (all 0s are now [0,1] and all 1s are now [1,0]) I # Push the input-pair again N_ # Push the inverted loop-index รจ # Use it to index into the input-pair g # Pop and push its length > # Increase this length by 1 ฮด # Loop over the list of [0,1] and [1,0] pairs: โˆ # Extend each pair to the length+1 of the opposite list N_i } # If this is the second input-pair: รธ # Zip/transpose it; swapping rows/columns รจ # Index each value into the " |" or " -" we created earlier โ€ž + # Push string " +" Nรจ # Index the loop-index into it รฝ # Join the list of characters with this as delimiter }.ฮน # After the loop, interleave both lists of lines on the stack .c # Join this list by newlines, and center each line # (after which the result is output implicitly) ``` [Answer] # [R](https://www.r-project.org/), ~~184~~ ~~164~~ ~~162~~ ~~136~~ ~~134~~ 129 bytes *Edit: -28 bytes (!) thanks to pajonk, and -2 bytes thanks to Giuseppe* ``` function(n,m,`?`=length){x=array(" ",c(?n,?m)*2+1) x[2*1:?n,p<-!0:1][c(n,!n)]="-";x=t(x) x[2*1:?m,p][c(m,!m)]="|" x[!p,!p]="+" x} ``` [Try it online!](https://tio.run/##pZLfa8IwEMff@1ekEUaiJzRuT27Bh4F/gW8qWGJcC82ltOms@/G3d6luQ6FTyh4S@N5dvp@7I0WTpM4a/RaXSSqbXYXKpRYZgoHNbCMzjS8u4e@1jIsiPjBKKCg2Q5gZPpyMBA/q5WQopj6SP43DaCrWS@Vfh8jXko7pYy0dq3@rDORt3kBo2vwH9YkwhzD3YuTFZ6Nix@gKB4MBcbp0ZJ@6hIiIFDFurSGvcVbpkuxsQZDcEUN84QpXSHmAsoxNnmnWdgEiggUPTEfMVi6vnDybu52WB/sidZqdskApYGH335LzIOhszGJ28JcmvpaUuVbpLtXb86aExKVYd0LFv6nKZp1UI6T5iwpG9KEunsWZcYdhGCoWgQB/OPwIwfsxJtcZc5j387u/7rdo/0Efv4fbOzhu4LQFcqGPsVu45gs "R โ€“ Try It Online") ]
[Question] [ # Bowling Bowling is a game where, essentially, each player gets 10 turns to: Take 2 attempts at knocking down 10 pins arranged in a triangle. * between turns the pins are reset * from the 1st to the 2nd attempt the pins are left as-is The arrangement of the pins resembles the following scheme, with the pins numbered `0-9`: ``` 6 7 8 9 3 4 5 1 2 0 ``` (Some rules and [scoring](https://en.m.wikipedia.org/wiki/Ten-pin_bowling#Scoring) mechanics omitted.) # Split spare In bowling, a [spare](https://en.m.wikipedia.org/wiki/Spare_(bowling)) is when the player manages to knock down the pins that were left standing after a first attempt. A spare is said to be a [split spare1](https://en.m.wikipedia.org/wiki/Split_(bowling)) if the pins that were left standing are not adjacent. E.g. if the pins are laid out as such: ``` . . 8 9 . . . . 2 . ``` Then a player who manages to knock down all these 3 pins would score a split spare, given that the pin `2` is not adjacent to the `8, 9` group. (1 for the purposes of this challenge, a split spare is defined taking into account *only* the adjacency of the pins left standing, even though Wikipedia's link states that for a split spare to take place, the pin 0 must have been knocked down already) # Your task Given the numbers of the pins left standing, output a Truthy value if such an arrangement would give a split spare and Falsy otherwise. # Input The list of all pins left standing (at least 2), in any reasonable format. Pin numbering may be 0- or 1-indexed provided it follows the numbering direction shown above. Sensible input formats include: * a list of integers, like `[2, 8, 9]` * a string of integers, like `"289"` * separate arguments to a function * an integer whose bits correspond to the pints left standing and whose least significant bit corresponds to pin `0`, e.g. `0b1100000100` for pins 2, 8 and 9. You may assume input is sorted, if that helps you in any way. # Output A single consistent value for Falsy test cases and anything else for Truthy test cases. # Test cases ## Truthy ``` [0, 9] [2, 8, 9] [1, 5, 8] [3, 5] [3, 8] [3, 9] [6, 8] [6, 9] [3, 5, 8, 9] [5, 6] [0, 1, 5, 6, 7, 9] [1, 2, 8, 9] ``` ## Falsy ``` [1, 2] [7, 8, 9] [1, 2, 5] [2, 4] [0, 1, 3, 6] [2, 5, 9] [6, 7] [4, 7] [4, 8] [1, 4, 5, 7] ``` # Bonus imaginary internet points Bonus imaginary internet points if your algorithm works for any triangle number of pins, instead of just 10. So far, only [Grimmy's 05AB1E answer](https://codegolf.stackexchange.com/questions/199275/10-pin-bowling-split-spare/199296#199296) qualifies for the bonus internet points! --- Standard loopholes are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest solution wins! If you enjoy the challenge, consider upvoting it... And happy golfing! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ ~~25~~ ~~24~~ 23 bytes ``` ร…Tฮฑฮต.ฤฮธDร†ยช}ยฉรฆฮตยฎyKฮดฮฑOรŸ}ร  ``` [Try it online!](https://tio.run/##yy9OTMpM/W9k5HZ4gr2Sgq2dgpL9/8OtIec2ntuqd6Tx3A6Xw22HVtUeWnl42bmth9ZVep/bcm6j/@H5tYcX/Nf5H22go2AZyxVtpKNgAWEZ6iiYAjlAljGQBaGgPJC0GYRnBuEZQxRDOECWGZACmggxA6jGHG4migVGQMocRQBiFZAygZtgDDHOCGwW1GpzIGUCpywgmk3AKsxjAQ "05AB1E โ€“ Try It Online") Outputs 2 for falsy and a larger integer for truthy. Works for any triangle number of pins, thus qualifying for the bonus internet points. A set of pins is split if and only if there is a partition of the set of pins in two subsets A and B such that no pin in A is adjacent to a pin in B. Adjacency is determined using [3-element hexagonal coordinates](https://www.redblobgames.com/grids/hexagons/#diagram-grid-cube). First, we convert the input pins to their hex coordinate triplets: ``` ฮต } # for each pin in the input: ร…T # list of triangle numbers <= pin ฮฑ # absolute difference of each one with pin .ฤ # enumerate: [a, b, c] => [[a, 1], [b, 2], [c, 3]] ฮธ # get the last pair D # duplicate ร† # reduce the copy by subtraction ยช # append that to the pair ``` Then, we iterate over partitions of this set of triplets in two subsets: ``` ยฉ # save the set in the register รฆ # powerset (list of subsets) ฮต } # for each subset y: ยฎ # push the set from the register y # push y K # set difference (=> y's complement) ``` Then, we compute the 2D list of distances between each pin in the first subset and each pin in the second subset. Thanks to the elegance of 3-element hexagonal coordinates, this is surprisingly easy: ``` ฮดฮฑ # double vectorized absolute difference O # sum each triplet ``` Finally, we answer the question: ``` รŸ # minimum distance for the current partition } # end the loop ร  # maximum of the list of minimums ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~72...~~ 74 bytes ``` ->l{*r=l[0];l.map{r.map{|w|r|=l&"zรช-ว“แ”‚YMลฐษƒc"[w].ord.digits}};l&r!=l} ``` [Try it online!](https://tio.run/##jY9NTsMwEIX3OYXxooJqEqW2Yzuqwg1YskCWF6VVUYURkduqgSYbOAKcghV3QAhxDE6S@qetYIcXfu957JnPdn390M@rPj0326GtjMr12GR3k3prw95uWttWZoAfP97Sr5ef16eri8/37@cpVhud3dtZNlvcLFbLrhubgT2pTNcrlQMqNSgCSEY3AlS44Bx1Lso@@TKPicdE4@UYnOOhAQEJ/iCHERTAQbikI2LT1kg1MFeN1l1Sr1dLhFO/cKL8aOKeid8sJEI4YaEjcmc0DiJh@B5KOGFHkaFMgQUsAfEDB@crB@8Z/yZyTMyz/4M8cZURIUAoA1YA4wIKKiTIEoQAyiUUooSy1Fk9md6e4sshPkv6HQ "Ruby โ€“ Try It Online") ### What is that? Starting from the first pin in the list, check if all pins can be reached within a finite number of steps. The binary string "zรช-ว“แ”‚YMลฐษƒc" is the UTF-8 encoding of the adjacency list [122,234,45,467,5378,89,77,368,579,99]. Some digits are repeated to make the numbers fit into the ASCII range and spare some bytes, some edges are omitted if the node can be reached through different paths. Thanks Value Ink for smoothing out rough edges (-3 bytes). [Answer] # JavaScript (ES6), ~~87~~ 83 bytes *Saved 4 bytes thanks to @Grimmy* Takes input as a 10-bit integer (LSB = pin \$0\$, MSB = pin \$9\$). Returns a non-zero integer for a split spare, or \$0\$ otherwise. ``` n=>(g=m=>[6,29,51,210,430,788,136,344,688].map((v,i)=>m|=m>>i&1&&n&v)|m)(g(n&-n))^n ``` [Try it online!](https://tio.run/##lZLBjoIwEIbvPoUnbJNRGWlLOcCLuG7CusqykWLENdnEd2eRghYdTbaHXvr1n3/@me/0lFbrQ74/Tk35uam3cW3ihGVxESdLBYsIJMICfRCBD6HWgIGCQAhQWq9mRbpn7AQ5j5PiHBdJknvoecY78XPBWcaMNzWcv5t6XZqq3G1muzJjk@Xx8HP8@l1N@Gg@Hw9OpEMlRdAUHLlftsz/QL87yPm4@edD9MhYqLktswBNUJd3bDFLIUjQj1RLXDhLBSBJJX/A6Ce@XYZ01LVnGUXr3DF0/3ee6QQaDB0tCYqohy2D17wvOSkIX@R@S9QmPwAnb2a5TXfVfwffj90RJwz062GZ8Fnb7exdm5Kuh@4SCTLAFnLCCcgQO/CqJUlfeDfakGK6BbCMoJiu3I3RpI5dkz4D0XgK6z8 "JavaScript (Node.js) โ€“ Try It Online") ### How? Starting with the lowest bit set in the input, we progressively expand a bitmask with the pin neighbors. We eventually compare the result with the input. Because we expand from pin \$0\$ to pin \$9\$ (let's call them \$P\_0\$ to \$P\_9\$), a single pass would occasionally miss a connection. Fortunately, processing two passes is always enough for all possible paths, which is what this code is doing. For instance, let's consider the following configuration: ``` 6 - - - 3 4 - - 2 - ``` **First pass** We start with \$P\_2\$, which expands to \$P\_4\$. Then, \$P\_4\$ expands to \$P\_3\$. The connection between \$P\_3\$ and \$P\_6\$ is missed because \$P\_3\$ is not included in the bitmask at the time it's processed. **Second pass** Again, we start with \$P\_2\$, which expands to \$P\_4\$ (no change). Then, \$P\_3\$ expands to \$P\_4\$ (no change) and \$P\_6\$, which completes the bitmask. ### Improvement As pointed out by @Grimmy, we never need to expand from \$P\_9\$: when we reach it, its neighbors (\$P\_5\$ and \$P\_8\$) have necessarily been found already. Therefore, we can safely discard its neighbor bitmask and iterate only from \$P\_0\$ to \$P\_8\$. ### Commented ``` n => ( // n = input bitmask g = m => // g is a recursive function taking a mask m [ // lookup table: 6, // neighbors of pin 0 29,51, // neighbors of pins 1, 2 210,430,788, // neighbors of pins 3, 4, 5 136,344,688 // neighbors of pins 6, 7, 8 ] // .map((v, i) => // for each value v at position i in the above array: m |= // update m: m >> i & 1 && // if the i-th bit is set in m: n & v // m = m OR (n AND v) ) | m // end of map(); return the new value of m )( // invoke g twice to support the longer paths, g(n & -n) // starting with the lowest bit set in n ) ^ n // compare the result with n ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~106~~ 121 bytes Defines a function `P.__contains__` that takes a set of pins and returns `False` for a split spare or `True` otherwise. e.g. `P.__contains__({"0", "9"})` returns `False` while `P.__contains__({"0", "1"})` returns `True` ``` d="6310214374254859876" P={*map(frozenset,zip(d,d[1:]))} while P<(P:={a|b for a in P for b in P if a&b}):0 P.__contains__ ``` [Try it online!](https://tio.run/##dZHRaoMwFIbv8xSHXkwtMtTEJJX5Dt6XIjqVBrYoGhir89ldE10XkebqfP/JyfnD332raysx7/p5rtIDxWEQhQQzEsWExyfO6AFl6Xj8LDq36dtbLYda@TfRuZVfncPk4nkT@rqKjxqyNzdL0rH4KaFpeyhASMhMWS6laKB4KScvCVD2mufvrVSFkEOez6oe1AApnBGMTuD44JycydcQaeC2EmqIF3lR8KJYsOn8DVK7Q@0Otp60ZKPQFYyr/91mnu18PbEbrcCeta0PGCC7rdg2Ez18bD7HViA74PY68pi@30EXpCPSCeiUTBIJgvvpeiGVqwUftnkZ0fPmXw "Python 3.8 (pre-release) โ€“ Try It Online") [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~381~~ \$\cdots\$ ~~267~~ 248 bytes ``` #import<set> using S=std::set<long>;int f(S s){std::set<S>c;for(long b=0x5792628a5a065664;b>9;b/=10)c.insert({b%10,b/10%10});for(S i:c)for(S j:c){S q(i);q.insert(begin(j),end(j));if(q.size()<i.size()+j.size())c.insert(q);}return c.find(s)==end(c);} ``` [Try it online!](https://tio.run/##jVJRb4IwEH7nV1xcltCMOUQFtcCf4HXJArWaGi1Iy7KM8NvdFYvosofx8n3Xu/vu61FWVa97xi6XJ3GqylrHiuvUaZSQe8gSpbebDZ7Ex1LuUyqkhp2bgSLtLZOljO7K2jUVUCT@1zJaB2Gwype5Hy7DcEGLdE2Lt2TmEzYVUvFau23xPPO94m3mI3akF8hAbBi5sgOyNoOzKwg9D00F3wvpHojH5RaBULFzz1MlvrlLYmHJy8GScdiZ0K7muqklsOlOYLMiSWJEGGbw4pIdmy2HWJRK1zw/pc549smZLuthIzI/cVXljAPenzpmH6ccTZHWuRbGt2WloKqj0B@aK60ggRZa34N150EbeLCydObBEiND50gtDnFfEto4tPH82mIjpKFB1L5qYVk0ig@joKN/OGSllHh479H0mN7owWNgvSEuxmlzOzvoBw9mI4OLEVdWY9FXRb0V/Mvg5o0uwYze3G2KgAP49c@LlY2GOMYnZ1LE0Mm7nFDnITt5vX198pf2wx3/pd5dfgA "C++ (gcc) โ€“ Try It Online") ### Ungolfed ``` #include<set> #include<algorithm> using namespace std; using S=set<int>; bool f(S s) { // Change array a for any number or shape of pins, // instead of just a triangle of 10. // It lists all the pins next to all their adjacent pins. int a[]{6,3,1,0,2,1,4,3,7,4,2,5,4,8,5,9,8,7,6}; set<S> c; for(int i=0;i<sizeof(a)/sizeof(int)-1;++i) c.insert({a[i], a[i+1]}); set<S> t; // Keep on adding connected sets of pins until there are no more new ones. while (t!=c) { for (auto i:c) for (auto j:c) if (any_of(begin(i),end(i), [&](auto e){return j.find(e)!=end(j);})) { S q(i); q.insert(begin(j),end(j)); t.insert(q); } swap(t,c); } return c.find(s)==end(c); } ``` Builds a set of all connected pin sets as per [Kyle Gullion](https://codegolf.stackexchange.com/users/32604/kyle-gullion)'s idea and then simply tests for membership. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes ``` ๏ผต๏ผฏโธ#๏ผฆฮธยซโ‰”โŒŠโŠ˜โŠ–โ‚‚โŠ•ร—โธฮนฮท๏ผชโบยณโปโŠ—ฮนร—ฮทโบยฒฮทโŠ—ฮท๏ผต๏ผฏยฒฯˆยปยค#โ‰”โ€บโถโด๏ผฌ๏ผซ๏ผกฮทโŽšฮท ``` [Try it online!](https://tio.run/##RY5BT8JAEIXP9Fds8DJN1guo0XAiEkSjsVFuhMNSh3bjdEemWxJj/O3rUFDn9GbmvZevrJ2U7Cil5w1xqODamuHZMJ9kWxYDu9x8ZYNp2/oqwJyYBRaO9vgGMywFGwxR9euuc4IvzBHuw/956RtsD4U@78eaWnsHD13zsWQoqGthbM2TDypm3G1IM15dx1xtTW8ZHWJ9@tejq9acePX9qet3NvdEcEQ/8d4JuogCVxfWPGKoYg0F4vtUfX80t4ROQEUhPkStnqS0WinWpTVKfrNep/M9/QA "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes input as an array of integers and outputs a Charcoal boolean, `-` for a split spare, empty output otherwise. Explanation: ``` ๏ผต๏ผฏโธ# ``` Draw an 8-by-8 rectangle of `#`s. ``` ๏ผฆฮธยซ ``` Loop over the input pins. ``` โ‰”โŒŠโŠ˜โŠ–โ‚‚โŠ•ร—โธฮนฮท ``` Calculate the row of the pin. ``` ๏ผชโบยณโปโŠ—ฮนร—ฮทโบยฒฮทโŠ—ฮท ``` Jump to the position of the pin. ``` ๏ผต๏ผฏยฒฯˆ ``` Erase a 2-by-2 rectangle representing the pin. ``` ยปยค# ``` Fill with `#`s starting at the last pin. ``` โ‰”โ€บโถโด๏ผฌ๏ผซ๏ผกฮท ``` See whether the fill restored all 64 `#`s. ``` โŽšฮท ``` Clear the canvas and output the result. Although I calculate the position of the pin directly (I tried a look-up table but it was the same byte count) this method won't handle arbitrary numbers of pins since it needs to be able to draw a large enough initial rectangle. However it can be adjusted to handle a specific maximum number of pins: the initial `8` needs to be increased by 2 for each additional row of pins, the `3` needs to be one less than the new number of rows of pins, and the `64` needs to be the square of the number that replaces `8`. [Answer] # Excel (Ver. 1911), 142 Bytes ``` A1 'Input B1:B10 3ร’ฦฎฬ”ล˜สฐฤ  'one character per row ^^^ (Non-printing characters) C1 =ROW(B1:B10)-1 D1 =BITAND(INT(A1/2^C1#),1)*UNICODE(B1:B10) E1 =SUM(MMULT(N(BITAND(2^C1#,TRANSPOSE(D1#))*D1#>0),N(C1#>=0)))+2<2*SUM(N(D1#>0)) 'Output ``` Here un-golfed using named ranges and extra columns ``` Input 'Input Bit_List 3ร’ฦฎฬ”ล˜สฐฤ  'as a column of chars Pin_Num =SEQUENCE(ROWS(Bit_List))-1 Unicode =UNICODE(Bit_List) Pins_Left =BITAND(INT(Input/2^Pin_Num),1)*Unicode Pins_Adjacent =MMULT(SIGN(BITAND(2^Pin_Num,TRANSPOSE(Pins_Left))*Pins_Left),SIGN(Pin_Num+1)) Split =SUM(Pins_Adjacent)<2*(SUM(SIGN(Pins_Left))-1) ``` [Try it offline!](https://drive.google.com/file/d/0B3c4lsZDmcHuVzdtWnZmWURJYWxnQ00zR3BXWkdjUUlUay1N/view?usp=drivesdk) (link to the workbook in a google drive) You'll need to download and open in the latest version of excel for the formulas to work. Single Test+Comments screenshot [![Test+Comments](https://i.stack.imgur.com/N8sdh.png)](https://i.stack.imgur.com/N8sdh.png) ]
[Question] [ *As a celebration of [good old Notepad](https://blogs.msdn.microsoft.com/commandline/2018/05/08/extended-eol-in-notepad/), we are going to treat carriage returns and line feeds as what they originally meant, rather than what they are (ab-)used for today.* Given a string consisting of printable ASCII plus line feeds (โŠ; LF; esc `\n`; hex 0A; dec 10) and carriage returns (โ; CR; esc `\r`; hex 0D; dec 13), **cause [Try It Online](https://tio.run/#) to show how the printable characters would be positioned** if printed on a printer which takes those two control characters literally: 1. upon a line feed, continue printing one line further down 2. upon a carriage return continue printing from the left edge 3. multiple consecutive carriage returns behave like a single carriage return Due to modern devices having problems with [overstriking](https://en.wikipedia.org/wiki/Overstrike), a run of one or more of carriage returns will, except for at the beginning of the input, never occur without at least one preceding and/or following line feed. However, two runs of carriage returns may be separated by a single line feed. Any amount of additional trailing white space is acceptable, both on the right-hand side of any lines and below the entire text, as long as at least the amount of white space given in the input is preserved. ### Examples (using `\n` and `\r` for line feed and carriage return) `Lorem ipsum dolor sit amet,` ``` Lorem ipsum dolor sit amet, ``` --- `consectetur adipiscing\nelit, sed` ``` consectetur adipiscing elit, sed ``` --- `do eiusmod\r\ntempor incididunt\n\n ut labore` ``` do eiusmod tempor incididunt ut labore ``` --- `et dolore\n\rmagna \r\r\naliqua. Ut` (notice the trailing spaces) ``` et dolore magna aliqua. Ut ``` --- `\nenim ad minim veniam,\n\r quis nostrud` ``` enim ad minim veniam, quis nostrud ``` --- `\rexercitation\r\n\rullamco laboris\n\r\nnisi ut aliquip ex\n\n\rea commodo consequat.\n\n` ``` exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` ๏ผต๏ผด๏ผฆฮธยซฮนโ‰กฮนโธฟโ†‘ ``` [Try it online!](https://tio.run/##PYoxDsIwEATr@BUnV04BDwhvQKJIKkxxMsax5PjIxQkFytsPp2G3mp11I7IjTCI9hZB8z3Ey7UW9iMHMLXxVc@OYi4l1bJZPLG6ECodwuHjQlnUHV9q86Yb3cdrVLnLXvsCTErG32fKEISP8Y7k2Y4rzimcYin7IaUs/ "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผต๏ผด ``` Disable right padding. ``` ๏ผฆฮธยซ ``` Loop over the input. ``` ฮน ``` Print the current character. This automatically handles `\n` (which Charcoal treats as `\v` in this context) but Charcoal translates `\r` into `\r\n`, so... ``` โ‰กฮนโธฟ ``` ... check for an `\r`... ``` โ†‘ ``` ... and if so then move back up a line. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~24~~ 17 bytes ``` ->s{s.tr $/,"\v"} ``` [Try it online!](https://tio.run/##PZA9bsMwDIXn5hSE0amw3RO0J@jaKfKgSExAwKIckQpSFD27SzlwNIk/771PKvX0s54/1uFTfmXUAq/vfedu3d@6VBU4Hl7Ox@4rF0xAi9QEMc@5gJCCT6h9N/XbSsgsGBS1FvCRFpJAfHGMM2kPgnFfjBmQqqQcXXGsmBazIw4UKVZWx46hKsz@ZKG7CPWRizYuyV/Yw/OYjRn5ma51hG/dJRbNlIwFErXLzUqf@mawya6VBDiLlvpkcwXvWAKpV8rcbF2p8@xTyA8gEre1mYQa5ZZKC@C9cZvcQ8jJ3pZh@5Br9Tq2UTcdpjdjGobBivUf "Ruby โ€“ Try It Online") It does not work on TIO, but works on the Linux console. [Answer] # Java 10, ~~211~~ ~~207~~ 206 bytes ``` s->{var a=s.replace("\r\n","\n\r").split("(?<=\n)");int i=0,p=0,j;for(var x:a){for(j=x.charAt(0)<14?0:p;j-->0;x=" "+x);j=(a[i++]=x.replace("\r","")).length()-1;p=x.matches("\\s+")?p:j;}return"".join("",a);} ``` [Try it online.](https://tio.run/##lVJNb9swDL3vVxA6WUhspMBOcd1g962XYae6B1ZWE3rWRyU58BDkt2eU63bNsMsECRBF8vHxiT0esey7nxc1YIzwDcmePgGQTTo8o9Jwn02A7ymQ3YMqlkuUNb@f@fCOCRMpuAcLDVxieXc6YgBsYhW0HxilEG1orViL1rZByCr6gVIhit1t01opZM31gJrN2vPp62cXiowwbVGestE3U6UOGL6kYiNvbz7vNltf92V5t6mnRoBYTbLumwIfaLV65NgPZbmokLIatN2nQyHLm9pzgMGkDjpyQBtXQu78tq/PQacxWCGq3pEthFijrM@X@rVHPz4N3OPS6tFRB4bFWvR4eASmOiuVdOTWvrqgDZCPo4HODS5ApARodFqLWbq3QOVs1Crl0oAdeYqK8VqrWaE1RN1dh3cONI3RuC4rmrTxDE1WUUfdaBPra2FMMOATE7hO1emVic6fYHBvEd4XgzEcDvQyYgU/0nUms7FkmB4Yypcjm2jWGWfOfhkpgnUxhfEvum3Qkw6KsmrO5hptGIcBjXKvHCm287OlSJn4TIE86Cm3wukIyhlu18GsFPNLVXaJZQD/jN/8J3PZ9xldZvdXZKEqN6bKsyMNtrCVKqJcqP7DL8r/Xm@Ezpff) **Explanation:** ``` s->{ // Method with String as both parameter and return-type var a=s.replace("\r\n","\n\r") // Replace all "\r\n" with "\n\r" .split("(?<=\n)");// Create String-array split by "\n", // without removing the trailing "\n" delimiter int i=0, // Index integer p=0, // Previous line-length, starting at 0 j; // Temp integer for(var x:a){ // Loop over the String-array for(j=x.charAt(0)<14?0// If the current line starts with either '\r' or '\n': 0 // Prepend no spaces : // Else: p;j-->0;x=" "+x); // Prepand `p` amount of spaces for the current item j=(a[i++]=x.replace("\r","")) // Remove all "\r" from the current line .length()-1; // Set `j` to the current line-length (minus the trailing '\n') p=x.matches("\\s+")? // If the current line only contains '\r', '\n' and/or spaces: p // Leave `p` unchanged : // Else: j;} // Change `p` to this line-length minus 1 return"".join("",a);} // Return the String-array joined together ``` --- Old answer before the challenge was changed **~~151~~ 148 bytes**: ``` s->{String a[]=s.replace("\r\n","\n\r").split("(?<=\n)"),r="";int p=0,i;for(var x:a){for(i=p;i-->0;r+=" ");i=x.length()-1;p=i<1?p:i;r+=x;}return r;} ``` **Explanation:** ``` s->{ // Method with String as both parameter and return-type String a[]=s.replace("\r\n","\n\r") // Replace all "\r\n" with "\n\r" .split("(?<=\n)"),// Create String-array split by "\n", // without removing the trailing "\n" delimiter r=""; // Result-String, starting empty int p=0, // Previous line-length, starting at 0 i; // Index (and temp) integer for(var x:a){ // Loop over the String-array for(i=p;i-->0;r+=" "); // Append `p` amount of spaces to the result i=x.length()-1;p=i<1?p:j; // If the current line is not empty: // Replace `p` with the length of this current line r+=x;} // Append the current item return r;} // Return the result-String ``` Doesn't work on TIO, does work on Windows Command Prompt: [![enter image description here](https://i.stack.imgur.com/hQhuP.png)](https://i.stack.imgur.com/hQhuP.png) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 85 bytes ``` s=>s[R='replace'](/(.*)([\n\r]+)/g,(_,t,b)=>t+b[R](/\r/g,_=>s='',s=t[R](/./g,' '))+s) ``` [Try it online!](https://tio.run/##TVBLTsMwEN1zitk5piGwYIfSE7BCYlUj5DpDNMif1B5XlRBnL@MEIbyy38z7@dOebXGZFr6LacLrx3gt474cXkaVcfHWoXrr7rvhVncHE01@2@n7ue/ee@6Petzz7nh4kQWTBX0X4qhUX0ZewUEwBUrrXdHXeRTdL5diSR4Hn@buoytaP/1H1J0axBUtd48PMvu@uRHwOWUMQEupAabkU4ZCDDYg90q3hSaBjpFrBjvRQsVRnE1ET9xDwWlbmxIg1RLSZLKJjGERKYqOJppqZGkXoTJ4exTDjYK8OWKrHuwcLfwdEREZ6@lUB3jljSCmkYKkgEDtcpanDX2jr6RTpQIxFc71N5XJeMHsiC1Tik3S5Oq9DS5tUaiYFY5UqOVbHWkBvLTEQrfgUpBWCdaPOFXLQxspff0B "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~150~~ ~~128~~ ~~122~~ ~~104~~ 103 bytes ``` def f(s): i=n=0;l='' for c in s:l,n,i=[l,l+c,l+' '*i*n+c,n,1,0,0,i,i+1]['\r\n'.find(c)%3::3] print l ``` [Try it online!](https://tio.run/##XZDLbsMgEEX3/orZVORBo6TZufIfdNtVyIICTkeCweFRpV/vDo7UhUFIA9x758D0W74jvc2zdSOMm7ztO8CBhuO7H4ToYIwJDCBB7r0kicPFS783vASIHe6Ia5IneeSJEven60WopEgcRiS7MduXc9@frx1MCamAn8eN@IjJBcAp1wA2eu6QsYAOrkix7RaheBUdK02k7ExxpSbQFifMBummyHksErKzK72N4LDmEG1jKC5MHI5k0KKtVBQpgsoU@osRVl5XnjCOVSnoG2n4H5zGedrjvR7gs6yczEMYGBACtuKHtzrIlrO47xUzUMwl1TWwSu7hksGiC0ZqTVSq3utg4pMSs1qOCTM29IUBJ3CP9hi2azAx8IMjLJ91r7oc2hU3mv8A "Python 2 โ€“ Try It Online") --- Saved: * -1 byte, thanks to Lynn [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~100~~ 94 bytes ``` b,c,d;f(char*s){for(b=13;b;b=*s++)b==13?c=d=0:b-10?d=!printf("%*c",++d,b),++c:putchar(b,d=c);} ``` Assumes ASCII coding (`'\r'==13`, `'\n'==10`); adjust to suit on other systems. [Try it online!](https://tio.run/##fVLNitswEL7nKaYpBTuxwi497bruvkCvpRdf5JGcDEgjrzQqC0tfvenYS3soTQVCGonvbyQ0Z8Trdeqwc/3c4MXmQ2lf55Sbabj/2E/9NBzK8dhOg5ZPOLjh7nEy93dPbni3ZGKZm/2HA@6749F1U6sLPi5VVqJm6tyAbf/juntPjKE6D5@KOEqny@edQiFa4qbdve5AhxJ9SdlHoKXUCC6FlKGQgI1eun3bg/KWZj@yMUbL3yBMXDyKl5rBOlqoIPF5ZB9IOije3Ya6BJ5qicmNeWTxcVFJtUqOXGUZeWSoAsFOauw2jZc3t14BOdozW/gzlFipbaDnak/wVaDhJIQe5KIzWwpqFspi0Zf2toTGYYqaDyKtm@9a2titgpvMc6UCnIrk@p@8Y/YvPiOJFUq8GhtzDcFGTG8hqYzbMVOhNfnmmxbwL2svFG4BU9R@JdjarqHktF79Q1Of/SfOwZ7L1eirD/jwcDXfOBmKSyA1YfQL/HUyV8bVmnEeg82bzV8 "C (gcc) โ€“ Try It Online") (requires Javascript) ## Readable version ``` int c = 0; int d = 0; f(char*s) { for (;*s;++s) { switch (*s) { case'\r': c = d = 0; break; case'\n': d = c; putchar(*s); break; default: printf("%*s%c", d, "", *s); d = 0; ++c; } } } ``` `c` is the current column position; `d` is the number of spaces that must be inserted before a printable character. Both are assumed to be zero on entry to the function. ## Test program ``` int main(int argc, char **argv) { char s[1024]; if (argc <= 1) while (fgets(s, sizeof s, stdin)) f(s); else for (int i = 1; i < argc; ++i) f(argv[i]); } ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~101~~ 94 bytes Based on [TFeld's answer](https://codegolf.stackexchange.com/a/164453/64121). ``` def f(s): i=n=0 for c in s:k='\r\n'.find(c);a=k&1;print(end=-k*' '*i*n+c*a);n=k>0;i=i*a-k//2 ``` [Try it online!](https://tio.run/##bZA9UsQwDIX7PYUqnIT9A7rNhBPQ0rkxtgKaxHLWlpnl9MHJzlAwcWXJek/f8/QjX4Ff5tlhD32V6ssOqOPuvIM@RLBADOkydEpHzerYE7vK1q3phoendorEUiG77jA0ClRDDT/axtQtd8PruaWOGnMYTqfnua/UW4jogaaUPbgwFvdEAsaj7FW9u3spzYdSlGkbOKEVlBzBOJooWeJPzTiS7CGh29C4AEg5@eAWWkE/lSXElhy5zKJZM2SB0XwUlA09yh0My2T05pMN/J3iWDzNSNd8hHfZUBc2Jl9gwdNy@S6l8fvFa3W4ZkrAIUnMW/A64g2jJTFCgZdlOuZxNN6GOzElvbaZEi0xVhaaAG9LsCI3YIMv4QOsn3fNRo7L079l8y8 "Python 3 โ€“ Try It Online") --- ## Ungolfed ``` def f(s): i=0 # position of the cursor n=0 # was the last character LF? for c in s: # iterate over the input k='\r\n'.find(c) # k := 0 for CR, 1 for LF and -1 for every other character a=k&1 # as (-1)&1 == (1)&1 == 1, this is a := abs(k) print(end=-k*' '*i*n+c*a) # If c is a normal character (k == -1) and the last character was LF, # print leading spaces. If c is not CR, print it n=k>0 # n := True if c is LF, False otherwise i=i*a-k//2 # If c is either a newline or a printable character (a == 1), # keep the cursor's position and increment it for a printable character ((-1)//2 == -1) ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~92~~ 91 bytes **-1 thanks to Laikoni!** *Note:* `\` in `\r` is omitted from bytecount as Linux CG handles literal `\r` and `\n`s. *Note:* Windows CG requires `\n` and `\r` be escaped, so +3 if it has to run on Windows. ``` import StdEnv ?n['\r':t]= ?0t ?n[' ':t]=[' ':spaces n]++ ?n t ?n[h:t]=[h: ?(n+1)t] ?_ e=e ``` # ``` ?0 ``` [Try it online!](https://tio.run/##JY6xCsIwFEX3fsXbohRB10LJooPQrWMTJE2iDTQvpXkR/HljG6fL4cK5V89WYfbBpNmCVw6z80tYCXoyN3xXHAcmVtaQbIGfqXBVsGRclLYRUNY1cITST6WdGuAHrC9HkhV/gG1t7klt4t0DAzMBrEtxWxarQLL7KjjUzjiTkAQKhEQwqzGslsn81c9ZvWI@3bt8/aDyTv9hO9q5MZ/GHw "Clean โ€“ Try It Online") A partial application of `? :: Int [Char] -> [Char]` with 0 as the initial first argument. This descends through each character keeping track of how many traversed, the count resets when it encounters a carriage return and when it encounters a newline it adds spaces equal to the number of characters traversed at that point. [Answer] # [Haskell](https://www.haskell.org/), ~~93~~ 87 bytes ``` l=0#0 (n#x)(t:r)|t=='\n'=t:(n#1)r|t=='\r'=l$r|m<-n+1=(' '<$[1..n*x])++t:(m#0)r (_#_)e=e ``` [Try it online!](https://tio.run/##rVPBbsIwDL33KyyKVDqggiuif8BO004Eoay1mLXEKYkzceDfWdpq@4BRn5IXx8/vxfnU4QuNeTxMvck32YLzW7mQnS/vUteF4qKWXQK3pR8BX9Rm7u92v@bltl4UUOznx21V8cvtVC6XKdnmm9Jni3N@LrHGR6MDBqjhmEGK2fofMVuNdw/OowXqQrTQOuM8BBLQFmX1m/JM@cZxwEZQogfdUkehIb4oRkOygoDtFCStA6QYrGuVVyxouySDuKGW2siiWDFEAaM/ktgpCFFGrzCV9lZfWMNfpBZSE9rQNeoK3mUKvuQXk00GgqV@8Z222q569oHzGikAuyA@TmKo8nhD35BoIce9HuWjMdo2bnSRghpgpkC9tYNc6gBvvdnpuobG2fQgDoYJSF5I1R891d0py6wmToNvdfd6hi7Km/gDw7wHwMDwLx4/ "Haskell โ€“ Try It Online") --- Pretty straightforward solution. # is an infix function that recursively creates the output one character at a time while keeping a character position counter (n) and flag for when to add spaces after a newline (x). ]
[Question] [ I'm one of the authors of Gimli. We already have a 2-tweet (280 chars) version in C but I would like to see how small it can get. Gimli ([paper](https://ia.cr/2017/630),[website](https://gimli.cr.yp.to)) is a high speed with high security level cryptographic permutation design that will be presented at the [Conference on Cryptographic Hardware and Embedded Systems (CHES) 2017](https://ches.iacr.org/2017/) (September 25-28). # The task > > As usual: to make the smalled usable implementation of Gimli in the language of your choice. > > > It should be able to **take as input 384 bits** (or 48 bytes, or 12 unsigned int...) and **return (may modify in place if you use pointers) the result of Gimli** applied on these 384 bits. > > > Input conversion from decimal, hexadecimal, octal or binary is allowed. ## Potential corner cases Integer encoding is assumed to be little-endian (e.g. what you probably already have). You may rename `Gimli` into `G` but it must still be a function call. ## Who wins? This is code-golf so the shortest answer in bytes wins! Standard rules apply of course. A reference implementation is provided below. ## Note Some concern has been raised: > > "hey gang, please implement my program for free in other languages so I don't have to" (thx to @jstnthms) > > > My answer is as follow: > > I can easily do it in Java, C#, JS, Ocaml... It is more for the fun. Currently We (the Gimli team) have it implemented (and optimized) on AVR, Cortex-M0, Cortex-M3/M4, Neon, SSE, SSE-unrolled, AVX, AVX2, VHDL and Python3. :) > > > --- ## About Gimli ### The state Gimli applies a sequence of rounds to a 384-bit state. The state is represented as a parallelepiped with dimensions 3ร—4ร—32 or, equivalently, as a 3ร—4 matrix of 32-bit words. ![state](https://gimli.cr.yp.to/state.png) Each round is a sequence of three operations: * a non-linear layer, specifically a 96-bit SP-box applied to each column; * in every second round, a linear mixing layer; * in every fourth round, a constant addition. ### The non-linear layer. The SP-box consists of three sub-operations: rotations of the first and second words; a 3-input nonlinear T-function; and a swap of the first and third words. ![SP](https://gimli.cr.yp.to/sp.png) ### The linear layer. The linear layer consists of two swap operations, namely Small-Swap and Big-Swap. Small-Swap occurs every 4 rounds starting from the 1st round. Big-Swap occurs every 4 rounds starting from the 3rd round. ![Linear](https://gimli.cr.yp.to/linear.png) ### The round constants. There are 24 rounds in Gimli, numbered 24,23,...,1. When the round number r is 24,20,16,12,8,4 we XOR the round constant (0x9e377900 XOR r) to the first state word. [![enter image description here](https://i.stack.imgur.com/F7JCG.png)](https://i.stack.imgur.com/F7JCG.png) ### reference source in C ``` #include <stdint.h> uint32_t rotate(uint32_t x, int bits) { if (bits == 0) return x; return (x << bits) | (x >> (32 - bits)); } extern void gimli(uint32_t *state) { int round; int column; uint32_t x; uint32_t y; uint32_t z; for (round = 24; round > 0; --round) { for (column = 0; column < 4; ++column) { x = rotate(state[ column], 24); y = rotate(state[4 + column], 9); z = state[8 + column]; state[8 + column] = x ^ (z << 1) ^ ((y&z) << 2); state[4 + column] = y ^ x ^ ((x|z) << 1); state[column] = z ^ y ^ ((x&y) << 3); } if ((round & 3) == 0) { // small swap: pattern s...s...s... etc. x = state[0]; state[0] = state[1]; state[1] = x; x = state[2]; state[2] = state[3]; state[3] = x; } if ((round & 3) == 2) { // big swap: pattern ..S...S...S. etc. x = state[0]; state[0] = state[2]; state[2] = x; x = state[1]; state[1] = state[3]; state[3] = x; } if ((round & 3) == 0) { // add constant: pattern c...c...c... etc. state[0] ^= (0x9e377900 | round); } } } ``` ### Tweetable version in C This might not be the smallest usable implementation but we wanted to have a C standard version (thus no UB, and "usable" in a library). ``` #include<stdint.h> #define P(V,W)x=V,V=W,W=x void gimli(uint32_t*S){for(long r=24,c,x,y,z;r;--r%2?P(*S,S[1+y/2]),P(S[3],S[2-y/2]):0,*S^=y?0:0x9e377901+r)for(c=4;c--;y=r%4)x=S[c]<<24|S[c]>>8,y=S[c+4]<<9|S[c+4]>>23,z=S[c+8],S[c]=z^y^8*(x&y),S[c+4]=y^x^2*(x|z),S[c+8]=x^2*z^4*(y&z);} ``` ### Test vector The following input generated by ``` for (i = 0;i < 12;++i) x[i] = i * i * i + i * 0x9e3779b9; ``` and "printed" values by ``` for (i = 0;i < 12;++i) { printf("%08x ",x[i]) if (i % 4 == 3) printf("\n"); } ``` thus: ``` 00000000 9e3779ba 3c6ef37a daa66d46 78dde724 1715611a b54cdb2e 53845566 f1bbcfc8 8ff34a5a 2e2ac522 cc624026 ``` should return: ``` ba11c85a 91bad119 380ce880 d24c2c68 3eceffea 277a921c 4f73a0bd da5a9cd8 84b673f0 34e52ff7 9e2bef49 f41bb8d6 ``` [Answer] # C (gcc), 237 bytes ``` #define P(a,l)x=a;a=S[c=l>>r%4*2&3];S[c]=x; r,c,x,y,z;G(unsigned*S){ for(r=24;r;*S^=r--%4?0:0x9e377901+r){ for(c=4;c--;*S++=z^y^8*(x&y)) x=*S<<24|*S>>8,y=S[4]<<9|S[4]>>23,z=S[8],S[8]=x^2*z^4*(y&z),S[4]=y^x^2*(x|z); S-=4;P(*S,33)P(S[3],222)}} ``` I probably gained bytes with my swapping method, but it's too cute not to use. [Answer] ## CJam (114 chars) ``` {24{[4/z{[8ZT].{8\#*G8#:Mmd+}__)2*\+.^W%\[_~;&8*\~@1$|2*@@&4*].^Mf%}%z([7TGT]R=4e!=\f=(2654435608R-_4%!*^\@]e_}fR} ``` This is an anonymous block (function): if you want to name it `G` then append `:G`. In CJam assigned names can only be single upper-case letters. There's space to append a comment `e# Gimli in CJam` and have characters left in a single tweet. [Online test](http://cjam.aditsu.net/#code=qNSerS%25%7B%220123456789abcdef%22f%23Gb%7D%2512%2F~%3AE%3B%0A%0A%7B24%7B%5B4%2Fz%7B%5B8ZT%5D.%7B8%5C%23*G8%23%3AMmd%2B%7D__)2*%5C%2B.%5EW%25%5C%5B_~%3B%268*%5C~%401%24%7C2*%40%40%264*%5D.%5EMf%25%7D%25z(%5B7TGT%5DR%3D4e!%3D%5Cf%3D(2654435608R-_4%25!*%5E%5C%40%5De_%7DfR%7D%0A%0A~_pE%3Dp%0A&input=00000000%209e3779ba%203c6ef37a%20daa66d46%2078dde724%201715611a%20b54cdb2e%2053845566%20f1bbcfc8%208ff34a5a%202e2ac522%20cc624026%0Aba11c85a%2091bad119%20380ce880%20d24c2c68%203eceffea%20277a921c%204f73a0bd%20da5a9cd8%2084b673f0%2034e52ff7%209e2bef49%20f41bb8d6) ### Dissection ``` { e# Define a block 24{ e# For R=0 to 23... [ e# Collect values in an array 4/z e# Transpose to columns { e# Map over each column [8ZT].{8\#*G8#:Mmd+} e# Rotations, giving [x y z] __)2*\+.^W%\ e# => [y^z x^y x^z*2] [x y z] [_~;&8*\~@1$|2*@@&4*].^ e# => [x' y' z'] Mf% e# Map out any bits which overflowed }% z e# Transpose to rows ([7TGT]R=4e!=\f= e# Permute first row (2654435608R-_4%!*^ e# Apply round constant to first element \@ e# Put the parts in the right order ]e_ e# Finish collecting in array and flatten }fR } ``` [Answer] ## C, 268 chars (268 bytes) using uint32\_t NB Since the original code uses `<stdint.h>` and types `S` as `uint32_t *`, I think the use of `long` is a cheat to get into 280 chars at the cost of the portability which is the reason for using `uint32_t` in the first place. If for fairness of comparison we require consistent use of `uint32_t` and the explicit signature `void gimli(uint32_t *)`, the original code is really 284 chars, and orlp's code is 276 chars. ``` #include<stdint.h> #define R(V)x=S[V],S[V]=S[V^y],S[V^y]=x, void gimli(uint32_t*S){for(uint32_t r=24,x,y,z,*T;r--;y=72>>r%4*2&3,R(0)R(3)*S^=y&1?0x9e377901+r:0)for(T=S+4;T-->S;*T=z^y^8*(x&y),T[4]=y^x^2*(x|z),T[8]=x^2*z^4*(y&z))x=*T<<24|*T>>8,y=T[4]<<9|T[4]>>23,z=T[8];} ``` --- This can be split into two tweets with continuation markers as ``` #include<stdint.h> #define R(V)x=S[V],S[V]=S[V^y],S[V^y]=x, void gimli(uint32_t*S){for(uint32_t r=24,x,y,z,*T;r--;y=72>>r%4*2&3,R(0)R(3)// 1 ``` and ``` *S^=y&1?0x9e377901+r:0)for(T=S+4;T-->S;*T=z^y^8*(x&y),T[4]=y^x^2*(x|z),T[8]=x^2*z^4*(y&z))x=*T<<24|*T>>8,y=T[4]<<9|T[4]>>23,z=T[8];}// 2/2 ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~351~~ ~~343~~ ~~339~~ ~~320~~ ~~318~~ 247 + 56 bytes Just a near 1:1 port of the reference to start golfing from. ``` void f(int[]x,int y,int z){int q=x[y];x[y]=x[z];x[z]=q;} s->{for(int r=24,c,x,y,z;r>0;--r){for(c=0;c<4;x=s[c]<<24|s[c]>>>8,y=s[4+c]<<9|s[4+c]>>>23,z=s[8+c],s[8+c]=x^z<<1^(y&z)<<2,s[4+c]=y^x^(x|z)<<1,s[c++]=z^y^(x&y)<<3);if((r&3)==2){f(s,0,2);f(s,1,3);}if((r&3)<1){f(s,0,1);f(s,2,3);s[0]^=0x9e377900|r;}}} ``` [Try it online!](https://tio.run/##vVJNb6MwEL3zK6xKjezgIL6kJjLmsoee9tQjAom6UDlNgNqmi0n47VkbEin7ce4gecbveZ5Hz@zLr3LTdlWzf/u48GPXCgX2BvN6xQ9e3TdM8bbx1sRxuv71wBlgh1JK8LPkDTg5wIRUpTL4V8vfQA15o7J8wCYBPa8jOtn0SYdM58QuphptNeb0k0zOvciPtpH9sRLJLJOCZ0DBRW7SU90KKw0EDWPM8IA1HolIfbLZCDSzjPqEJTEZqMxYniRhfLZFmqZbrA0WuxbdnZfKwGGER4NvzQ4viQ7FmCRBAfVqREYBL2epLoYCDmeLBQZjrpvTsdAGW2mDRYjwGkKxihCloZkGSuzjEBFbBNjQ041PghsdLHRoaZn5eUH9YVdFT0873z8LMk3ThSzWXH2/t/lo3IcvSvDmPctBKd4luj6Gjdm7UohS06b6NW@DML@q2TB2gdlNbjzjSRAS1@Vo7sh4TvnafC5f3wZ63f3Z@2/r6UVLVR29tldeZ6ZSNXx49LcDeMA31dkj/hhTGqG/Tx8aiG4/go1nr2Ss6hScm9Hd7f/t/JbhrPzkTJff "Java (OpenJDK 8) โ€“ Try It Online") [Answer] # JavaScript (ES6), 231 bytes ``` s=>{for(r=25;--r;[a,b,c,d,...e]=s,s=r&1?s:r&2?[c,d,a,b,...e]:[b,a,d,c,...e],s[0]^=r&3?0:0x9e377900|r)for(c=4;c--;x=s[c]<<24|s[c]>>>8,y=s[j=c+4]<<9|s[j]>>>23,z=s[c+8],s[c+8]=x^z*2^(y&z)*4,s[j]=y^x^(x|z)*2,s[c]=z^y^(x&y)*8);return s} ``` ### Demo ``` let f = s=>{for(r=25;--r;[a,b,c,d,...e]=s,s=r&1?s:r&2?[c,d,a,b,...e]:[b,a,d,c,...e],s[0]^=r&3?0:0x9e377900|r)for(c=4;c--;x=s[c]<<24|s[c]>>>8,y=s[j=c+4]<<9|s[j]>>>23,z=s[c+8],s[c+8]=x^z*2^(y&z)*4,s[j]=y^x^(x|z)*2,s[c]=z^y^(x&y)*8);return s} console.log( f([ 0x00000000, 0x9e3779ba, 0x3c6ef37a, 0xdaa66d46, 0x78dde724, 0x1715611a, 0xb54cdb2e, 0x53845566, 0xf1bbcfc8, 0x8ff34a5a, 0x2e2ac522, 0xcc624026 ]) .map(x=>(x >>> 0).toString(16)).join(' ') ) ``` [Answer] ## 32-bit x86 assembler (112 bytes) (\_\_cdecl calling convention) ``` pusha mov ecx, 9E377918h loc_6: mov esi, [esp+24h] push esi push 4 pop ebx loc_E: lodsd ror eax, 8 mov ebp, [esi+0Ch] rol ebp, 9 mov edx, [esi+1Ch] push eax push ebp lea edi, [edx+edx] and ebp, edx shl ebp, 2 xor edi, ebp xor eax, edi mov [esi+1Ch], eax pop ebp pop eax push eax push ebp xor ebp, eax or eax, edx shl eax, 1 xor ebp, eax mov [esi+0Ch], ebp pop ebp pop eax xor edx, ebp and eax, ebp shl eax, 3 xor edx, eax push edx dec ebx jnz short loc_E pop esi pop ebp pop ebx pop eax pop edi mov dl, cl and dl, 3 jnz short loc_5B xchg eax, ebx xchg esi, ebp xor eax, ecx loc_5B: cmp dl, 2 jnz short loc_63 xchg eax, ebp xchg esi, ebx loc_63: stosd xchg eax, ebx stosd xchg eax, ebp stosd xchg eax, esi stosd dec cl jnz short loc_6 popa retn ``` Tweetable version (z85-format Base85 encoding): ``` v7vb1h>C}HbQuA91y51A:oWYw48G)?I=H/]rGf9Na>sA.DWu06{6f#TEC^CM:#IeA-cstx7:>!VfVf#u*YB&mP(tuCl*+7eENBP)$:)Lh!k}t$^wM51j%LDf$HMAg2bB^MQP ``` ]
[Question] [ This challenge is inspired by the meme [Men of Culture](http://knowyourmeme.com/memes/ah-i-see-youre-a-man-of-culture-as-well). The meme involves blanking out parts of the original caption, > > Ah, I see you're a man of culture as well. > > > to make it appear as if the character is saying something else. Your challenge is to write a program that, given an input, **show how the original sentence can be blanked out** to achieve the input string. Rules: * Use a `-` character to represent a blanked out character. * You must not add additional letters to achieve the input string * You may treat string comparisons as case-insensitive * You may ignore whitespace in string comparisions * If no substitution is possible, output a falsy value. * You may substitute redundant whitespace with a `-` as well, although not required. * Where multiple solutions are possible, you may output any of them. Test cases: Basic: [Example Meme 1](http://i0.kym-cdn.com/photos/images/original/001/235/219/960.jpg) ``` Ah, I see you're a well. > Ah, I see you're a --- -- ------- -- well. ``` [Example Meme 2](http://i0.kym-cdn.com/photos/images/original/001/235/687/fd1.png) ``` Ah, I see well. > Ah, I see ------ - --- -- ------- -- well. ``` Edge case 1: ``` What did you just say about me, you little > false ``` Edge case 2 (edited): ``` *no input* > --- - --- ------ - --- -- ------- -- ----- ``` Intermediate: [Example Meme 3](http://i0.kym-cdn.com/photos/images/original/001/236/506/ca8.jpg) ``` Ah, I see you're Orwell. > Ah, I see you're - --- o- -----r- -- well. ``` [Example Meme 4](http://i0.kym-cdn.com/photos/images/original/001/350/031/a17.jpg) ``` Ah, ymca. > Ah, - --- y----- - m-- -- c------ a- ----. ``` [Example Meme 5](http://i0.kym-cdn.com/photos/images/original/001/239/678/3a7.png) ``` Ah, a manual. > Ah, - --- ------ a man -- -u----- a- --l-. OR: > Ah, - --- ------ a man -- -u----- a- ---l. ``` Harder: [Example Meme 6](http://i0.kym-cdn.com/photos/images/original/001/235/615/b0a.jpg) ``` tea. > --- - --- ------ - --- -- ---t--e a- ----. ``` [Example Meme 7](http://i0.kym-cdn.com/photos/images/original/001/242/298/e25.jpg) ``` eeeee > --- - -ee -----e - --- -- ------e -- -e--- ``` TL;DR: Given an input string, output a string which represents how the original string should be modified to fit the input string, by using a "-" to represent a blanked out character. If a substitution is not possible, output a falsy value. Code golf, so shortest code in bytes wins. **Edit: Clarifications** * **Ignore whitespace in string comparisions** means you can strip away whitespace before you compare strings. For instance, the inputs `Ah, a manual` and `Ah , a manual` are treated as equal. Other punctuation `, ' .` must be preserved. Similarly for output, `Ah, a manual` is equal to `Ah, amanual`. * **substitute redundant whitespace** refers to the spaces present in the original caption. You don't need to replace them with "-", but if replacing nets you more points then go ahead. [Answer] # [><>](https://esolangs.org/wiki/Fish), 94 bytes ``` "vAh, I see you're a Man of Culture as well. 0/i~ <r !\:?!^:}=0={:@*:@"-"$?$~}$:@? <>~i+0)?;>o ``` [Try it online!](https://tio.run/##S8sszvj/X6nMMUNHwVOhODVVoTK/VL0oVSFRwTcxTyE/TcG5NKekFCRQrFCempOjx2Wgn1mnYFPEpRhjZa8YZ1Vra2BbbeWgZeWgpKukYq9SV6ti5WDPZWNXl6ltoGlvbZf//z@G6flFYLMA "><> โ€“ Try It Online") Case-sensitive, doesn't ignore whitespace or punctuation and outputs an empty string if the input is invalid. If you want to try other strings, you can just modify the first line after the `"v`, as long as it doesn't contain a `"` or a null byte. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 117 bytes ``` ^. ยถAh, I see you're a Man of Culture as well.ยถ$& {+i`ยถ(\W|(\w))(.*ยถ)(?(2)\W*\2) $1ยถ$3 }1`ยถ\w -ยถ .*ยถ.*ยถ.*\w.*|ยถ.*ยถ.* ``` [Try it online!](https://tio.run/##bY1NCsJADIX3OUUW/sxULagHEHEhLsRlN4MYNWJl2kI7QynqteYAc7HaWsSFBgJ5Lx/v5WzilOq@WB/qfQjeLa9j3GDBjFVmhzkj4ZZSzC64strY1iiwZK1D73oDuI/ig3dCRQ@hSilFGHgnxULMpIoCNZPQmzbcHJ7TBlMlTLyDlulWlWHw@Aio6z/l7yr4PjodXcngOT63HN5sYbCgCumYWYMJj9@2jo3RDPATusu/oVVyou4iTCi11PiGG4vbeQE "Retina 0.8.2 โ€“ Try It Online") Could save 1 byte by requiring case-sensitivity. Could save 3 bytes by returning `--, - --- ---'-- - --- -- ------- -- ----.` on empty input. Explanation: ``` ^. ยถAh, I see you're a Man of Culture as well.ยถ$& ``` Prepend the desired text to the input. ``` {+i`ยถ(\W|(\w))(.*ยถ)(?(2)\W*\2) $1ยถ$3 ``` Move as many characters from the desired text to the result as possible. If the character is a letter then it also needs to match the next letter in the input, which is then deleted. ``` }1`ยถ\w -ยถ ``` If there is no matching letter in the input, change it to a `-` and try again. ``` .*ยถ.*ยถ.*\w.*|ยถ.*ยถ.* ``` If there are still letters left in the input, delete everything, otherwise delete the remainder of the input. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~58~~ ~~55~~ ~~48~~ 45 bytes ``` โ€œยฌยฒแบˆ,ศทCIbฦษผeแปดฦค/ษ“Iล’;แนซแนšSโถ_ล€แปค แน‚Bโพรทฦˆยปแธขโ€-1แป‹โผษ—?@โ‚ฌxแน† ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xDaw5terirQ@fEdmfPpGNzT@5Jfbh7y7El@icnex6dZP1w5@qHO2cFP2rcFn@04eHuJQoPdzY5PWrcd3j7sY5Dux/uWPSoYa6u4cPd3Y8a95ycbu/wqGlNxcOdbf8PtwNZkf//Rys5ZugoeCoUp6YqVOaXqhelKiQq5CbmKeSnKSSX5pSUggSKFcqBztFT4tLBphqLHFwoPCOxRCElMwWkWiGrtLhEoTixUiExKb@0RCE3VQcsnJNZUpKTClKN1YL8IhQLKnOTE@EcsFNLEyGyJakQiVQQUIoFAA "Jelly โ€“ Try It Online") --- More readable version: ``` โ€œAh, I see you're a man of culture as well.โ€แธขโ€-1แป‹โผษ—?@โ‚ฌxแน† ``` String compression breakdown: ``` Ah, I{short: see}{short: you}'re a{short: man} of{long: culture} as{short: we}ll. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~126~~ 114 bytes ``` i=input() r='' for c in"Ah, I see you're a man of culture as well.":x=c==i[:1];r+=c*x or'-';i=i[x:] print(i=='')*r ``` [Try it online!](https://tio.run/##bY/BbsIwEETv/oqRL4YAleDWIB848gU9IA6usyiuHDty1mry9SFJiwQSe1rNjN7stgPXMRxGGyvSUsrRaRfazKu1SFopcYsJFi7IU73FGR0RhphVIhg0JiDeYLPnPAsdfsn7D1n22mrtLuX@ekwbbYseMamdOk7sS19eRZtc4JXTU8G6SONUKwT1ZDFfUXyO78r@0OLJeihftWFUrpqz@MkdozMDzHfMjIa2i@wds6cp/EL4h8f0DB8aax778mM2i8e0yDSPvAM "Python 2 โ€“ Try It Online") --- # [Python 2](https://docs.python.org/2/), ~~108~~ 106 bytes Input is a list of chars. ``` lambda i:''.join(c==`i`[2:3]and i.pop(0)or'-'for c in"Ah, I see you're a man of culture as well.")*(i==[]) ``` [Try it online!](https://tio.run/##jY9NasMwEIX3OsWgjaWSmpLuDFp02RN0kQai2DKeIEvCGlF8eleyQ0P6A9VmZt6MHu8LMw3e7ZdevS9Wj@dOAzZVVV88OtEqdcLTYd88H7XrAOvgg3iSfqoeq95P0AI6/jLs4BWiMTD7VE0GNIzage@hTZZSESJ8GGtrLh8EKnU4yoVMpAgKOP/t/3rNbottfhs0QYdduYNLigRRz6DPPhGMZrfKFomsYeyHqZ9upvPY6q1boyaddTJZMuXlSHUM2ciiM1FIxgpqCZxp1xobBhAmdAS9sBhJFFXK5U8Wzvg3mqz8nycf3zncM11XK9W1/@LKcyHLZWP7BA "Python 2 โ€“ Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 122 120 bytes ``` x=>"Ah, I see you're a Man of Culture as well.".replace(/./g,c=>c>' '?/^(.)\1/i.test(c+x)?(x=x.slice(1).trim``,c):'-':c) ``` [Try it online!](https://tio.run/##bY5BCsIwEAC/svSSBNuEXgupSE8e/IFIw7rWSGxKkmp8fVS8eh0GZm7mYSIGu6Rm9mcqgy5Z99XuWsMeIhG8/MoCgYGDmcFfYFhdWr8gwpOck5UMtDiDxJVUU426x54B26oTl@LYKisTxcRxk8WWZ51ldPYjt0KmYO/jWKPoWMM6FAX9HL0j6fzEB/7v4VcUorwB "JavaScript (Node.js) โ€“ Try It Online") # Explanation : ``` x => // It takes in 'x' as parameter for function a string "Ah, I see you're a Man of Culture as well.". // What the actual is .replace( // Now we are gonna replace /./g, // selects everything c => // lambda function with param c c > ' ' ? /^(.)\1/i.test( // does it all c + x ) ? // checks if there is a match (x=x.slice(1). // returns everything from 1 to end in an array trim`` , // removes whitespaces c : '-' : c) // and done ``` --- Can be reduced further but replaces whitespaces with '-' as well. If this is acceptable then # [JavaScript (Node.js)](https://nodejs.org), 112 bytes ``` x=>"Ah, I see you're a Man of Culture as well.".replace(/./g,c=>/^(.)\1/i.test(c+x)?(x=x.slice(1).trim``,c):'-') ``` [Try it online!](https://tio.run/##bc1BCsIwEEDRqwzdNMF2QrdCFOnKhTcQaYhjjYxNSVKNp4@KW7efD@9mHiba4ObUTv5Mpdcl6021uzawh0gEL7/UgcDAwUzgL9AvnJZviPAkZqww0MzGklCoxsbqjToJlMdOOUwUk7CrLLci64yR3WfrJKbg7sPQWLmu21oW66fomZD9KHrxz/5JUpY3 "JavaScript (Node.js) โ€“ Try It Online") Reduced even further , only replaces whitespaces that are after the given string with '-'. # [JavaScript (Node.js)](https://nodejs.org), 105 bytes ``` x=>"Ah, I see you're a Man of Culture as well.".replace(/./g,c=>/^(.)\1/i.test(c+x)?(x=x.slice(1),c):'-') ``` [Try it online!](https://tio.run/##bc1BCsIwEEDRqwzdNIPthG6FVKQrF95AhBDHWhmS0qQaTx8Vt24/H97dPmx0yzSn1ocLl8GUbPpqf2vgAJEZXmGtFwYLR@shXGFYJa3fEOHJIlTRwrNYx0qTHhtnen1WhKdOT5Q4JuU2GXcqm0xRps/WYeNwW7c1Fhd8DMIkYVSD@of@CMTyBg "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 135 bytes ``` x=>!!x&&(t="Ah, I see you're a Man of Culture as well.".replace(/./g,c=>c>' '?/^(.)\1/i.test(c+x)?(x=x.slice(1).trim(),c):'-':c),!x&&t) ``` [Try it online!](https://tio.run/##TY7RCoIwFEB/5eqD2yWd@GpMiUDooT@IYKybLZYTN2t9vSW99Ho4cM5dPZXXkxlDMbgLLZ1comySJGYZDzLd3XI4gCeCt5vZRKDgqAZwV9jPNswr8PAia0UqJhqt0sRLUfa5lo1uGLC2PHOBp6o0IpAPXG8itjzKKLw1X7lCESbz4JhrrFnBao35Gg@4bLUbvLMkrOt5x/9efkHE5QM "JavaScript (Node.js) โ€“ Try It Online") If "may" mean either do or not do is okay, then # [JavaScript (Node.js)](https://nodejs.org), 106 bytes ``` x=>x&&(t="Ah, I see you're a Man of Culture as well.".replace(/./g,c=>c==x[0]?(x=x.slice(1),c):'-'),!x&&t) ``` [Try it online!](https://tio.run/##ZY1BCsIwEAC/snpoE0hTvSpbEaHgwReIhxDXWgndkqQaXx8rHr3OwMzDPE2wvh9jNfCVcos5YZOKQkRc7u8KjhCI4M1T6QkMnMwAfIPD5OL0BQFe5Jxeak@jM5ZEretOWWwsYjqvLjuRMOng@lmtpbJyU1alVIv5EGXeWh4CO9KOO9GK/yH7X17K/AE "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~764~~ 600 bytes ``` (((<>)))([]((((((([][][]()){}[]){})[][]){}))[[]()])[][]())([[]](([][](([][]){})[]){}())[[]])(([()()][]([[]]([()]([[]](((([()][][][])[]){}[]())[])[]))()()()))[[]])((([[][][]]((([](([()()()][]){})){})(()()()()){}())[[]])[]){})((((()((([][]){}())((()()()){}){})[[][][]]))){}{}())((()(((([]()()()())())){}{}()())[[][]]){}[])(([(()()()){}](((((()()()()){}[]))){}{}))((()()){}()){})(([()][][]([()()()][])))(((([][][]())[([]()()){}()])[]())[[]])([[]]((([]()())(()()()()){}){})()()()){([{}]<>({})){(<{}(((((()()()()())){}{})){}{})>)}{}(<({}<(<()>)<>{({}<>)<>}>{})>)<>{({}<>)<>}{}<>}{}<>{{{}}<>}<>{({}<>)<>}<> ``` [Try it online!](https://tio.run/##VVFBDgIxCPzOcNAXNP1Iw2E1mhiNB@Ot2bdXGNpu3WbZAsMwsJfP9nif7q/t2RqAlEUERRFPUT8QqXtRM@Kuf6V4WKWnYa4GPGxgzYJQFQtDrMIAxJrXb2BKo1UUkTMcAc9k8Ro/SnWdleWUZS8wao7ukeVIgqnQhWNiKbmTiwcOQPQatJjZoHc89@NqJl1f4aGlDNbRNRRQ11jAOo7I3x8oXQKrfKK52TK3QXVLS5J3B8U0pQxuCclYVn2Y2miz@HzJwMmsuSlXd/yyZwLWiH9paq2739dkyq19b9u5na4/ "Brain-Flak โ€“ Try It Online") Big improvements thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king), especially in the string construction but also a few logical tweaks in the main body. [Explanation from him](https://tio.run/##VVHBjqMwDL3zFZZ6caRhvwBxn9tqtdIeEIeUmiVql3STdOaA@u2M7UDKNKoh9vN7z@YcrJvr8Wav64qITWuMwa7H/Ot6OWjM8ux6Dkau8jSdpHuzlZGvfYbnmLEcUaG94TQa7mCAYvm2vaGW@iyVm5QzXwzqKSzSI6dXdxurtqst/iPuPS/1XNWRDBaHYhwLVi1v5EYSL0DW2mmxVDO94HU/4qbQbSt8eel21l01O1Bf@wKO4xjz7Qt0mwXtkonKZruyDXV3kFTyfIHTz0ecIKbg5r9VtcDpz@RutCcAsGPPTYvibwNf3DhSoHkgOFP6JJoh@Tv4Edx8fySw82VPZBrwc/JbMSY7XN/gU1XugSKFD4FolfUWbHiS446w7EdjazgCnN5HGCYb7JAoRLCBYPYJ6P/D3t7gLj5rsd@w84Yj9zXtIhd5ebbKdMzIk2l/2yt9H0cdA5JLEwWowQcYXYhJ5QvM6Niqy7OefUr@32EDSlKxSMWay/JksSevk3UYOuVyBLdrugg3GhP4DwrV0SV7PP0izkYC/0iMXddE9sdaX9Z6@AI) It's case-sensitive (so "Ah, I see you're Orwell." doesn't match but "Ah, I see you're orwell." does), whitespace in input is *not* ignored, and unmatched whitespace in original string is converted to `-`. By my understanding, all of those are valid options. Explanation: ``` (476 bytes of much improved stack manipulation) #Push string { #While string ([{}]<>({})) #Check whether the top characters are equal {(<{}(((((()()()()())){}{})){}{})>)}{} #If characters are not equal, push - on top of input (<({}<(<()>)<>{({}<>)<>}>{})>)<>{({}<>)<>}{}<> #Take top of input (either - or matched char) and add to output }{} <>{{{}}<>} #Pop both stacks if input is left over <>{({}<>)<>}<> #Reverse output ``` [Answer] # [Haskell](https://www.haskell.org/), 182 174 172 171 170 169 bytes ``` import Data.Char t=toLower a!b=(b:)<$>a ""%l=Just$'-'<$l l@(a:b)%(c:d)|t a==t c=b%d!c|1>0=l%d!'-' _%_=mempty (%"Ah, I see you're a man of culture as well.").concat.words ``` [Try it online!](https://tio.run/##dY9BS8QwEIXv@RWzoaUtrEWvZbMoelEEjx6XaRK31aQpyZRS2P9e0wqyy@qcZj7ezJvXYPjSxsxza3vnCZ6QsHxs0DMS5F7dqD3DTS3yuip2yR4Z56kRL0OgJLvJdolh5j7Hqi7SXFaqOBGgEARS1KnayNPd/laY2EUtO6QHYbXtaWJHkaf8odnCMwStYXJD5jUgWOzAfYAcDA0LCDDG50pelNJ1EqkcnVdhtth2IEA5BrGMJujj2Pu2IyjhuNIe/jL4OXctuOTvDRKoVi178BmzQsAJsHYDgdXbFZuWyOjfFf6v6Zu/Np2sxEuyZh/wTEf6TKKX4vM3 "Haskell โ€“ Try It Online") Ungolfed: ``` import Data.Char template = "Ah, I see you're a man of culture as well." -- strip spaces preprocess :: String -> String preprocess = filter (/=' ') -- case-insensitive character comparison a#b = (toLower a) == (toLower b) strike' :: String -> String -> Maybe String strike' "" "" = Just "" -- base case strike' _ "" = Nothing -- chars are exhausted, impossible to convert strike' "" rem = Just $ '-' <$ rem -- full match, strike rest of chars strike' cur@(x:xs) (r:rs) | x # r = (r:) <$> strike' xs rs -- character matches; pop a char | otherwise = ('-':) <$> strike' cur rs -- no match; strike char, don't pop strike :: String -> Maybe String strike xs = strike' (preprocess xs) template ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 109 bytes ``` []+[]+[]. I+[B|X]+[C|O]:-(I=[B|J],B=C;I=J,C=45),J+X+O. I-O:-I+`Ah, I see you're a man of culture as well.`+O. ``` [Try it online!](https://tio.run/##bVDLboMwELzzFXsrFjan9kJEpYQTXMitVAgVNziJK4MjP4qQ8u/UQKumKas97M7O7EhzUVLIE9E9H8eyCuYOvTQod9fCzck1ryLip7Hbswrv4mSTxhlO4scnhLOgCHJHJnlE0qDenjGkoBmDQdoHxYBCSzuQRzhYYewEaOiZEGHtZGOj@CdTfoqcmOzJszaKd6e3g2yY9nO8R7hX3DDR@Tna/IxHKjRDoRcRKOLSg7nWnBcf/J9xd3g5UwMNbyYlfFhtQNMB6Lu0BlqGZ1hwYwT71ay9/TaWasV4aA/0DpqjsfSWadgtiU1VL1s1oy29CK6Nv@SGC4Q7EY711rl2co54SbcmBf6T5avjhp73BQ "Prolog (SWI) โ€“ Try It Online") Case-sensitive and whitespace sensitive. The `-/2` predicate is the main predicate with its first argument being the input string and the second argument being the output string. [Answer] # JavaScript (Node.js), 103 bytes ``` s=>!s[i=0,r="Ah, I see you're a man of culture as well.".replace(/./g,c=>c==s[i]&&++i||c-1?c:'-'),i]&&r ``` [Try it online!](https://tio.run/##bZCxcsMgDED3fIWSITYXTJo1OdzrmC/o0OtAsZyQw@CCaOtr@u2ucYYMrSbpSbwTuqgPFXUwPVXONzi2coyyXsYXIx94kKunM4cjREQYfCoCgoJOOfAt6GQpZRDhE60VKxGwt0pjuRXbE9ey1lJOntf1erMx16uudo96X1QF45mFMeB7MgHLyaoaaxwWTOgpJzw6wtBm1TcY1yfaQx@8xhhFpMY4@GHCu7KYH3Eg/CKQNWjvorcorD@VbZkpY@ww/vOFeeHFvXGrn8@KoDFNnoNLigRRDaDefCLokM/YGiKLiz9OH@7OodPqls3HSmrihBPCHL8) Case sensitive. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 78 bytesSBCS ``` V." yยฐรคz ร‚ยตรฟรฉiSsยพรฝร˜C[รณcรต!รณ5ยงn"=b.x@zZkIqbN=+kN=hZ.?=+k\-))I<Zlz!z.?k ``` [**Test suite**](https://pyth.herokuapp.com/?code=V.%22+y%C2%97%C2%B0%C3%A4z+%C3%82%C2%B5%C3%BF%C3%A9%C2%92iSs%C2%92%C2%94%C2%BE%C3%BD%7F%C3%98C%C2%98%C2%89%5B%C3%B3c%07%C3%B5%11%21%C3%B35%13%C2%A7n%22%3Db.x%40zZkIqbN%3D%2BkN%3DhZ.%3F%3D%2Bk%5C-%29%29I%3CZlz%21z.%3Fk&test_suite=1&test_suite_input=Ah%2C+I+see+you%27re+a+well.%0AAh%2C+I+see+well.%0AWhat+did+you+just+say+about+me%2C+you+little%0A%0AAh%2C+I+see+you%27re+Orwell.%0AAh%2C+I+see+you%27re+orwell.%0AAh%2C+ymca.%0AAh%2C+a+manual.%0Atea.%0Aeeeee%0AAh+%2C++++++a+++manual%0AAh%2C+amanual&debug=0) Unprintable characters present in code, see link for correct version. *Case sensitive, does not ignore whitespace.* [Answer] # [Perl 5](https://www.perl.org/) `-F`, 192 bytes ``` @q="Ah, I see you're a man of culture as well."=~/./g;while($x=shift@F){$x=~/\w/||next;while($_=shift@q){push@r,/\W/?$_:/\Q$x/i?$_:'-';$r[-1]=~/\w/i&&last}@q||last}say!$x&&@r,map/\w/?'-':$_,@q ``` [Try it online!](https://tio.run/##ZY5NC4IwAIb/yoqhCery0EUR10XoENGpQ4aMmDmYX9tEI@unt7SPU7eHl@d9eWsq@Epr3ITzdW6DDZCUgmvVmoICAgpSgioD55ardgok6Cjn7jx8IBddgi5nnC5gH8qcZQrH1m3kB0o6NAwl7dVPSL9CY93qVuZY2Cg5oAimPkr2sEdsQtMxAyiOjnf6TDDD4ESqO26G4Q2SXGewN4yxXpB6UqKx48PUxo3Wf@93oqPPqlasKqV2Yu1sV663dJcv "Perl 5 โ€“ Try It Online") ]
[Question] [ Given a rectangular matrix of elevations, draw its contours. # Task Two elements `x` and `y` are on the same contour level if `floor(x/10) == floor(y/10)`. For example, `52` and `58` are on the same contour level, but `58` and `64` are not. The act of drawing contours is defined as follows: For every element `e`, replace it with a two-char string chosen as follows: * the first character is `" "` if the element below `e` is on the same contour level as `e` or if there is no element to the below `e` and `"_"` otherwise * the second character is `" "` if the element to the right of `e` is on the same contour level as `e` or there is no element to the right of `e` and `"|"` otherwise The elements within rows are joined together, then the rows are joined together with newlines. # Example Let's say the input is `[[5,20],[3,6]]`, visualized as ``` 5 20 3 6 ``` We first look at `5`. Since `3` is on the same contour level as `5`, the first character is `" "`. Since `20` is not on the same contour level as `5`, the second character is `"|"`. Now we look at `20`. Since `6` is not on the same contour level as `20`, the first character is `"_"`. Since there is no element to the right of `20`, the second character is `" "`. Now we look at `3`. Since there is no element below `3`, the first character is `" "`. Since `6` is on the same contour level as `3`, the second character is `" "`. Now we look at `6`. Since there is no element below `6`, the first character is `" "`. Since there is no element to the right of `6`, the second character is `" "`. Based on these two-char strings, we make replacements to get `[[" |","_ "],[" "," "]]`. Joining these together, we get an output of ``` |_ ``` # Rules * The input matrix will always be rectangular and composed of positive integers. * Trailing spaces or newlines may be in any amount (including 0) and do not have to be consistent in any way. * You do not have to follow the same algorithm as long as you produce the same results. * Your program or function may output a newline-separated string, list of strings, or equivalent. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. # Test Cases ``` input output [[1,5,8,9],[3,11,13,8],[7,14,10,9],[4,8,7,6]] _ _ | | |_ _| [[0,10,20,30,40,50,60,70,80,90],[0,0,10,10,20,20,30,30,40,40],[0,0,0,10,10,10,20,20,20,30],[0,0,0,0,10,10,10,10,20,20],[0,0,0,0,0,10,10,10,10,10],[0,0,0,0,0,0,10,10,10,10],[0,0,0,0,0,0,0,10,10,10],[0,0,0,0,0,0,0,0,10,10],[0,0,0,0,0,0,0,0,0,10],[0,0,0,0,0,0,0,0,0,0]] |_|_|_|_|_|_|_|_|_ |_ |_ _|_ _|_ _ |_ |_ _ |_ |_ |_ _ |_ |_ |_ |_ |_ [[5,5,5,5,5,5,5,5,5,5,5],[5,10,10,10,10,10,10,10,10,10,5],[5,10,15,15,15,15,15,15,15,10,5],[5,10,15,20,20,20,20,20,15,10,5],[5,10,15,20,25,25,25,20,15,10,5],[5,10,15,20,25,30,25,20,15,10,5],[5,10,15,20,25,25,25,20,15,10,5],[5,10,15,20,20,20,20,20,15,10,5],[5,10,15,15,15,15,15,15,15,10,5],[5,10,10,10,10,10,10,10,10,10,5],[5,5,5,5,5,5,5,5,5,5,5]] _ _ _ _ _ _ _ _ _ | | | _ _ _ _ _ | | | | | | | _ | | | | |_| | | | | | | | |_ _ _ _ _| | | | |_ _ _ _ _ _ _ _ _| [[35,32,29,26,25,25,25,26,29,32,35],[32,28,25,22,20,20,20,22,25,28,32],[29,25,21,18,15,15,15,18,21,25,29],[26,22,18,14,11,10,11,14,18,22,26],[25,20,15,11,7,5,7,11,15,20,25],[25,20,15,10,5,0,5,10,15,20,25],[25,20,15,11,7,5,7,11,15,20,25],[26,22,18,14,11,10,11,14,18,22,26],[29,25,21,18,15,15,15,18,21,25,29],[32,28,25,22,20,20,20,22,25,28,32],[35,32,29,26,25,25,25,26,29,32,35]] _| |_ _| _ _ _ _ _ |_ _| |_ | _ _ _ | | | | | | | | | | |_ _ _| | |_ _| _ |_ _ _ _ _| _ |_ _| | | ``` [Answer] # [Perl 6](https://perl6.org), 135 bytes (131 chars) ``` {my$n="_";sub w{$^a.chop-$^b.chop??$n!!" "};my&q={|.[1..*],.tail};(($_ ยซ[&w]ยป.&q) ZZ~{$n="|";$_ ยซ[&w]ยป.map(*.&q)}()).map:{say |$_}} ``` [Try it online!](https://tio.run/##jVNRboJAEP33FEg3ZtdMye7CIpYY76FRg01Nm4jV2sYQpBfqEfrnxejMNlZsUAwDmX3vzdvZAdZPb8uwbKWZwxbOoMzTjK0G7syNtx9zZ5ezaeI9Pr@u79l0bpPhkK3abddxizjNOptBvvfGyvO6E/Dek5dlEXPOZs7ha9zZTQ7fXmcjnNHoMyfTvRtXqTRZ8y4JCi4ErR7ybZI5ezYrijJuUc4WnHMFBiLoC@A@KAXKhwjzHqgAlLR4gHwPQiFEpcw34GvQfdAhaHOMkBDEfUN@yEcWxkQeQ1skQhVKqB5XuG0EyhwjIoRw2p08teUD25@0z8Cq0CskiSFnqlTYqMGbJBbU5oyXyNKtZD1/of6GFpoPcsM4God69goM1Fzo8nu8C3ESmLo4F5zalJUJ/hP89XlZ4MsGQYPD1R4aTnF1DnUDpBnfVYaspf037Pdf/gA "Perl 6 โ€“ Try It Online") Slightly ungolfed: ``` { my $n = "_"; sub w { $^a.chop - $^b.chop ?? $n !! " "}; my &q = {|.[1..*],.tail}; ( ($_ ยซ[&w]ยป.&q) ZZ~ {$n="|";$_ ยซ[&w]ยป.map(*.&q)}() ).map:{say |$_} } ``` **Explanation**: First, we define a variable `$n` (line 2) and a function `w` (line 3). This function returns a space if its two arguments are at the same "elevation", and the contents of variable `$n` otherwise. Instead of dividing by 10 and flooring, we abuse the fact that ints are `Cool` (can be treated like strings) and use `chop` to remove the last character (=digit). Then we calmly subtract them, forcing them into numbers again :โ€”). After that (line 4) we make up a function `q` that takes a list and returns that list with first element removed and the last element duplicated. On the next 3 lines, we're going to make 2 more matrices from the input matrix: the first one has the first row missing and the last row duplicated (that's just `.&q` โ€” using `.&`, you can call a function on anything as if it was a method โ€” the thing in front of the dot is then the first argument), the other one has the first column missing and the last column duplicated (that's `.map(*.&q)`). First (line 4) we take the original matrix `$_`, "overlay" it with the "shifted rows" matrix and use the function `w` as a binary operator (that's that `[&w]`) on the matching elements. That one puts a `_` wherever the matching elements are on the different elevations, and a otherwise. So we get ยฝ of the result (only the "first characters"). At line 6, we do the same thing, but first we change `$n` to `|`, and we now "overlay" the original matrix with the matrix with shifted columns. Result has a `|` at different and at the same elevations. These are the "second characters". Now we just combine them together. We zip the arrays with a zip with a concat (yeah...), which results in a matrix of the original shape whose each element is the 2 matching elements of the "half-solutions" concatenated. Finally, we just map over this matrix (which is really a list of lists). Each of these lists is flattened and then `say`-ed (printed with a newline). Since `say` can take any number of arguments and it prints them all without separators, making the newline only at the end, we get the desired picture on stdout. (And the block returns a list of `True`s (each `say` returns one `True`), but who cares.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25 23~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to [miles](https://codegolf.stackexchange.com/users/6710/miles) (`I` vectorises) ``` :โตI;โ‚ฌ0aoโถ Zรงโ€_Zลผ"รงโ€|$Y ``` A full program printing the result. As a monadic link it takes a list of lists of numbers, the elevations, and returns a list lists, however these "rows" consist of lists of two character "pairs" - if this is fine then 1 byte may be saved by removing `Y`. **[Try it online!](https://tio.run/##y0rNyan8/9/qUeNWT@tHTWsMEvMfNW7jijq8/FHD3Pioo3uUwKwalcj///9HRysY6Bga6BgZ6Bgb6JgY6Jga6JgZ6Jgb6FgY6FgaxOpwKYBUQBRB1EGUQlSbIKuAK4KrAytFVYGsCKYOQwWaIkOsKhSIUaFAjAoFYlQoEKNCwSA2FgA "Jelly โ€“ Try It Online")** ### How? ``` :โตI;โ‚ฌ0aoโถ - Link 1, assignCharacters (row-wise): list of lists of numbers; character, c โต - literal 10 : - integer division (vectorises) I - incremental differences (vectorises) (zero if the same else non-zero) 0 - literal 0 ;โ‚ฌ - concatenate for โ‚ฌach (rightmost edge of a row has no contour mark) a - logical and (vectorises) with c (replace non-zeros with the contour character) โถ - literal space character o - logical or (vectorises) (replace the zeros with spaces) Zรงโ€_Zลผ"รงโ€|$Y - Main link: list of lists of numbers, contours Z - transpose the input (get the columns) โ€_ - literal underscore character, '_' รง - call the last link (1) as a dyad with '_' Z - transpose the result $ - last two links as a monad: โ€| - literal pipe character, '|' รง - call the last link (1) as a dyad with '|' " - zip with the dyadic operation: ลผ - zip (interleave the column-wise characters with the row-wise ones) Y - join with newlines - implicit print ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~199~~ ~~186~~ ~~157~~ 155 bytes ``` lambda a:(lambda x:'\n'.join(''.join('_ '[x==z]+'| '[x==y]for x,y,z in zip(r,r[1:]+r[-1:],q))for r,q in zip(x,x[1:]+x[-1:])))([[v/10for v in r]for r in a]) ``` [Try it online!](https://tio.run/##jZPdboJAEIXvfYq9g43Tdnf5EUm89SWQNDSWlKZF3RiDpu9OZxaXQoNAXGA859vJ7Akcr@ePQ6nqfLOrv7Lvt33Gsti9V1Xs7Ern@fNQlK5jn6/MSarN5pYunZ@mvKb5QbMKrnBjRcluxdHVoBMZp0udPOEDTpwTouFkgQoqA1QG4Jy7SXJ5kYKwC0HaNNVUZimv9@8527oZjxfsqIvyzDJb5Kje68Vii20kBBDBOoXEAylBehBhvQLpgxRG99FfQZimvNkhyFACPAG@gEBAKGAlIEJaIC7AAA3TYA3pW9f6LWKo1uzYluh4fVf2rTFnxHisP5RFG0cAAz/cE/wbtLf@gGBo9QElemsYCOx6DHhiApjoMDrDxClGcxgK0Mbr4dwK1BpU2BkxJAV1jxqQHxlZdYZURomQQoT24z98v6POgBEppNNrTj2V8X3zIQhz9w2FvUJC2nAkfhEBXoTc0@v5eDKgq5PunP0zRpg@yIw4JkPF9Otf "Python 2 โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` :โตIแน ;โ‚ฌ0 Zร‡Zแป‹โพ_ +ยณร‡ยคแป‹โพ| ยค ``` [Try it online!](https://tio.run/##y0rNyan8/9/qUeNWz4c7F1g/alpjwBV1uD3q4e7uR4374hW0D20@3H5oCYRbo3Boyf/D7ZH//0dHG@qY6ljoWMbqRBvrGBrqGBrrWADZ5jqGJjqGBmBxE6C8uY5ZbCwA "Jelly โ€“ Try It Online") # Explanation ``` :โตIแน ;โ‚ฌ0 Helper Link; get contour data : Floor division by โต 10 I Compute increments แน  Sign; ยฑ1 for different values and 0 for same values ; Append 0 Zero โ‚ฌ To each row Zร‡Zแป‹โพ_ +ยณร‡ยคแป‹โพ| ยค Main Link Z Zip the input (for vertical contours _) ร‡ Get the contour data Z Zip the data (because it's zipped from the first Z) แป‹ Index into the string โพ_ "_ " + Add (vectorizing twice) to ยณ ยค ยค Nilad starting from (input) ร‡ Get contour data (horizontal contours |) แป‹ Index into the string โพ| "| " ``` -2 bytes thanks to Jonathan Allan [Answer] # [Python 2](https://docs.python.org/2/), 226 bytes ``` l=[[j/10for j in i]for i in input()] for i,j in enumerate(l[:-1]):print''.join('_ '[h==l[i+1][g]]+'| '[h==j[g+1]]for g,h in enumerate(j[:-1]))+'_ '[j[-1]==l[i+1][-1]] print''.join(' '+'| '[i==j]for i,j in zip(l[-1],l[-1][1:])) ``` [Try it online!](https://tio.run/##jVNNj5swEL3zK6xcSJTp1jYfYSPluL320ptlVavUTYyygLxE3a3639OZYUOhSkLAIPu9N4/xk2ne231d6dO2/uHERoTZbHY6bIwpPyv5sw6iFL4S3tLU87Rqju18YSNGgGlXHV9ceG7d/GDWn5RdrJvgqzaOH8raV/P4u4jNfrM5GL9U1uysXcZ/Oqg0O4TYfQf7sVfZeS2WXF8aXPQeOLfR@CMi7lw9utpBc799g21hAfDbqDV6nnCbUdSG93Uk8Pq19wcnvoWj69Z0uTe3FZRKj/D3Ive2dU0rnr5@eQqhDl1B8/z6ejImAy0tmARybM8YBRkU8MiIUqASKHC@ApWCkoynyK8@1JJALSGRkErIJOQSVhIKVJKpBBZ0mk7WKdMze@Z7Cat6ckCfFQNuzKoxdYu5QVzHr8KSo8jgwo367L8mR@OfILs0xgItR@OyIDuP64JETggmHG72MLGLmzlcCpCiTbBnDfoRdD5oLycE8YSKiS8Y1oMGNSMFqlBC9bjCM10MmisIIZyONnlq5lM@/JLfKavQKydJH4zCvyDDhyQfyY143BXQM0j2nvo7WpjeyB1xTIZq/wI "Python 2 โ€“ Try It Online") Whew, that was a doozy to work the logic out. I now see Hyper Neutrino ninja'd me with a shorter answer but I spent too much work on this *not* to post it. :P Also, can I just say, this is an awesome way to make ASCII-art. Excuse me while I make a boatload more of these. [Answer] # J, 58 bytes ``` f=.{~0==/@] [:(,/"2)2 2((' _'f{."1),' |'f{.);.3 1:+<.@%&10 ``` [Try it online!](https://tio.run/##dZDRCoJAEEXf9ysuYak0bDPramUt9B8RPUQagfYBRr9uW7IRlMzLvefcp7n2feV092DnFruDqp3elwktJiY1MEkS4xhXnZ5ISjHur5hiozNIOd/q3XQmrBqnLSwiCHKssIa3Asl8XkIshD2z71ao1mnfhSMwCZNhypgsU85UMC2ZVkxrptdJWAyjYWcHF@xnMGx@5Mf/d/ItxvkoHqMjkNX5dLmh9n8yDCr9p4qAmhDavn8C) An anonymous function which takes a matrix and outputs the contours. Lotta room for improvement here. I didn't have time to try all the test cases so let me know if there are any issues. Will try to golf more and explain later. # (Quick) Explanation Helper function: indexes into a length 2 string based on whether the first element of a 2 length array is equal to the second. If it is equal, it indexes into the zeroth element, if it is unequal, it indexes into the first. A 1 length array always indexes into the zeroth element of the string. ``` f=.{~0==/@] ``` Main function ``` [:(,/"2)2 2((' _'f{."1),' |'f{.);.3 1:+<.@%&10 ``` `1:+<.@%&10` floors each element divided by 10 and adds 1 (so we will never get 0 -- this is important for the helper function). `2 2((' _'f{."1),' |'f{.);.3` cuts the matrix into 2 x 2 segments if it can (otherwise it'll give a 2 x 1, 1 x 2, or 1 x 1 segment near the edges) and applies the function that uses `f` to compare the top left element to the top right and the top left element to the bottom left. `(,/"2)` flattens the result into the desired shape. I really feel like I should be able to avoid having to use this (and a lot of other things, but I digress). [Answer] # [J](http://jsoftware.com/), ~~46~~ 45 bytes ``` ' _|'({~];"1@(,&.>-@|:)&(0,~}.~:}:)|:)<.@%&10 ``` [Try it online!](https://tio.run/##hZNNboMwEIX3nOIpUvmRKJoxhhDSVBykURZVUdVNF1k2cHU6tksKigExIPt9M/b4yXwN7RWnGgR5hwiXWxT/9Ofjjps4DbPX5@ZWJ2FMad9lfd3ViUxfsuYpZBqSYJchak91hBRdjfYaBB/vn9@Ij22Ci8L5DQUUIUc5BdoAFlThIIwZnMt4D9ZgEk3b2axGdCkiw82CBE0oCCVhT6ikiEAOuwyX5PK0YyO9J7icB3jnfsZTsKwvykvqgkgzF9h56n@YFmPEhS@mWNEsfLgYYwnntIpXq1f2Xu185dye59HTXNpWUAeoctJjaRTR/2hlRTXpUlmlGmtlLJe5mnRYGcXobmVlqbZ3nuxX2xw17utOynL9C/ND8Ny2f1PIY@pK7ebWW81vHn/LwOEX) [Answer] ## JavaScript (ES6), ~~120~~ 118 bytes ``` a=>a.map(b=>b.map(c=>c/10|0)).map((b,i,a)=>b.map((c,j)=>((a[i+1]||0)[j]-c?'_':' ')+(b[j+1]-c?'|':' ')).join``).join`\n` ``` Where `\n` represents the literal newline character. Edit: Saved 2 bytes thanks to @Bรกlint. ``` f= a=>a.map(b=>b.map(c=>c/10|0)).map((b,i,a)=>b.map((c,j)=>((a[i+1]||0)[j]-c?'_':' ')+(b[j+1]-c?'|':' ')).join``).join` ` ;[ [[5,20],[3,6]] , [[1,5,8,9],[3,11,13,8],[7,14,10,9],[4,8,7,6]] , [[0,10,20,30,40,50,60,70,80,90],[0,0,10,10,20,20,30,30,40,40],[0,0,0,10,10,10,20,20,20,30],[0,0,0,0,10,10,10,10,20,20],[0,0,0,0,0,10,10,10,10,10],[0,0,0,0,0,0,10,10,10,10],[0,0,0,0,0,0,0,10,10,10],[0,0,0,0,0,0,0,0,10,10],[0,0,0,0,0,0,0,0,0,10],[0,0,0,0,0,0,0,0,0,0]] , [[5,5,5,5,5,5,5,5,5,5,5],[5,10,10,10,10,10,10,10,10,10,5],[5,10,15,15,15,15,15,15,15,10,5],[5,10,15,20,20,20,20,20,15,10,5],[5,10,15,20,25,25,25,20,15,10,5],[5,10,15,20,25,30,25,20,15,10,5],[5,10,15,20,25,25,25,20,15,10,5],[5,10,15,20,20,20,20,20,15,10,5],[5,10,15,15,15,15,15,15,15,10,5],[5,10,10,10,10,10,10,10,10,10,5],[5,5,5,5,5,5,5,5,5,5,5]] , [[35,32,29,26,25,25,25,26,29,32,35],[32,28,25,22,20,20,20,22,25,28,32],[29,25,21,18,15,15,15,18,21,25,29],[26,22,18,14,11,10,11,14,18,22,26],[25,20,15,11,7,5,7,11,15,20,25],[25,20,15,10,5,0,5,10,15,20,25],[25,20,15,11,7,5,7,11,15,20,25],[26,22,18,14,11,10,11,14,18,22,26],[29,25,21,18,15,15,15,18,21,25,29],[32,28,25,22,20,20,20,22,25,28,32],[35,32,29,26,25,25,25,26,29,32,35]] ].forEach(a=>document.write(['<pre>','</pre>'].join(f(a)))); ``` [Answer] # [Proton](https://github.com/alexander-liao/proton), 202 bytes ``` R=(L=len)+range k=[map((//)&10,r)for r:eval(input())] d=(x,y,X,Y)=>X>=L(k)or Y>=L(k[X])or k[x][y]==k[X][Y] print('\n'.join(map(''.join,[['_ '[d(x,y,x+1,y)]+'| '[d(x,y,x,y+1)]for y:R(k[x])]for x:R(k)]))) ``` [Try it online!](https://tio.run/##jZBva4MwEMbf@yn6asnhsRptnC2kn6Cv@krJwhBqh7OLIm4o7Lu7XIqMwUYLl3D3e567/On6dmjtPB8VP6hLZSHsS/taBY3S72XH@XoNDyLCHs5tv@p31Wd54bXtPgYOYIKT4iNOmGMBap/v1YE34HyFz3RuqGj0aPRklCKgCxN0fW0Hzp4te3xra8vpHHbNUWv2smL65MeOocAJTMi@fhBOoQBDl5l2R06zr9VIFRgAmGetE4lJjPEW4xRjuURKxPFEGtSkZx67JFoi9iRzLmehflcJFBkKuURGhPiWLCn1kL5B4YyR3zfe5WalZJE0mToFPqF0iywexvKXHjmVloj@1v/pv@MKtx9yx3fc/FTzDQ "Proton โ€“ Try It Online") -2 bytes thanks to Jonathan Frech -15 bytes by switching to Proton instead of Python 2 [Answer] # Java 8, ~~200~~ ~~170~~ 169 bytes ``` a->{String r="";for(int l=a.length,i=0,j;i<l;i++,r+="\n")for(j=0;j<l;r+=(i>l-2||a[i][j]/10==a[i+1][j]/10?" ":"_")+(j++>l-2||a[i][j-1]/10==a[i][j]/10?" ":"|"));return r;} ``` **Explanation:** [Try it here.](https://tio.run/##rZTfk5owEMff@1dkeIJhtQm/5Eq5/gW9lz5a5yb1uGsoFx3E63SUv91uAlLsgBSqbhjZ/X7c7GYnKX/js802kenTj9M647sd@cyFPLwjRMgiyZ/5OiEP6pWQL0Uu5AtZmxhZrpYrwq0IAyUutF3BC7EmD0SSmJz47P5Q6/PYMKLnTa4wksV8niXypfgOIqaQRuJjFgnbhtyOja/SsJQwjWmUoh99prjPZs7xyJditUxX7xmNY/xts/rtk0GMD8ajYdlmattt7Yw16gvt0bCsKE@KfS5JHpWnSNemS1Cf7f5bhmXU1bxtxBN5xYaYVTG66EMtxY782hXJ63yzL@ZbDBemnK9NmfwkdYf@KAlp3AcfHFpCZ8iFoGwCpWVF/5mKgQ8h3PVmYwyYC2FPfAHMA0Z7eQ//e3HjHVOV0KHgUvAo@BQCCgsKIe6ir2kUNFRxFVrR3jXizDSYJq8CLeRMDegvCTYsH6seKR6nHSWlNx0DHzq@PXvx/2ryhV2H/C4bhhx6Yf8O@WcbB7l0AjQh0@iaJnRv9Dl1DcItR83F/jrg3IETtNoWKA/63b6NKSbUUqfVOEd7QiR7MJUHFXjvhq2mhcqj/H1XrdqPoxlPX9pUPz1NYs6gD2sGgOFN7eNSWD0hgwyeCqjVmqpb5plY0rQGTjyuweHomsTKWZ5@Aw) Note that integer division in Java automatically floors. ``` a->{ // Method with 2D int-array as parameter and String return-type String r=""; // Result-String for(int l=a.length, // Length of the input array i=0,j; // Index integers i<l;i++, // Loop (1) over the rows of the input array r+="\n") // and append a new-line to the result after every iteration for(j=0;j<l; // Inner loop (2) over the columns of a row r+= // Append the String with: (i>l-2 // If it's the last row, ||a[i][j]/10==a[i+1][j]/10? // or the current and next rows are equal floored/10: " " // Use a space : // Else: "_") // Use a "_" + // Plus (j++>l-2 // If it's the last column in the row, ||a[i][j-1]/10==a[i][j]/10? // or the current and next columns are equal floored/10: " " // Use a space : // Else: "|") // Use "|" ); // End of column loop (2) // End of row-loop (1) (implicit / single-line body) return r; // Return the result-String } // End of method ``` [Answer] # R, 159 bytes ``` f=function(m){M=m%/%10;a=cbind(0,t(apply(M,1,diff)));b=rbind(apply(M,2,diff),0);a[!!a]="|";b[!!b]="_";M[]=gsub("0"," ",paste0(a,b));write(t(M),"",ncol(m),,"")} ``` With newlines and indentations: ``` f=function(m){ M=m%/%10 a=cbind(0,t(apply(M,1,diff))) #row-wise difference b=rbind(apply(M,2,diff),0) #column-wise difference a[!!a]="|" b[!!b]="_" M[]=gsub("0"," ",paste0(a,b)) # M[] is a trick to force the result to have the same structure as M write(t(M),"",ncol(m),,"") } ``` Does the integer division of the matrix, measures the row-wise and column-wise differences, and when not null replace by `|`and `_` respectively, then pastes both (painless, thanks to R's vectorization) and outputs. Test cases: ``` > m=matrix(c(0,10,20,30,40,50,60,70,80,90,0,0,10,10,20,20,30,30,40,40,0,0,0,10,10,10,20,20,20,30,0,0,0,0,10,10,10,10,20,20,0,0,0,0,0,10,10,10,10,10,0,0,0,0,0,0,10,10,10,10,0,0,0,0,0,0,0,10,10,10,0,0,0,0,0,0,0,0,10,10,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0),byrow=T,ncol=10) > f(m) |_|_|_|_|_|_|_|_|_ |_ |_ _|_ _|_ _ |_ |_ _ |_ |_ |_ _ |_ |_ |_ |_ |_ > m=matrix(c(5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,5,5,10,15,15,15,15,15,15,15,10,5,5,10,15,20,20,20,20,20,15,10,5,5,10,15,20,25,25,25,20,15,10,5,5,10,15,20,25,30,25,20,15,10,5,5,10,15,20,25,25,25,20,15,10,5,5,10,15,20,20,20,20,20,15,10,5,5,10,15,15,15,15,15,15,15,10,5,5,10,10,10,10,10,10,10,10,10,5,5,5,5,5,5,5,5,5,5,5,5),byrow=T,ncol=11) > f(m) _ _ _ _ _ _ _ _ _ | | | _ _ _ _ _ | | | | | | | _ | | | | |_| | | | | | | | |_ _ _ _ _| | | | |_ _ _ _ _ _ _ _ _| ``` [Answer] # [Perl 5](https://www.perl.org/), ~~130~~ 126 bytes 124 bytes of code + 2 for `-ap` flags ``` push@a,[map 0|$_/10,@F]}{map{say map{($a[$r+1][$c]-$_&&$r<$#a?'_':$").($a[$r][++$c]-$_&&$c<@{$a[0]}?'|':$")}@$_;$c=0;$r++}@a ``` [Try it online!](https://tio.run/##fY/LCsIwEEX3fkXQoVX6cKJkYyvNyp1fEEIJRVBQG1pdSNtfN1alohDDXBiYc@eld9WRGaOv9Z6rUJyUJthCPqcY8o3smr7Q1OpGnnkKSkAVUCmgkBHkngdVChOV@bm/gvEsfhukCIKPoUh501dRdpnfvlwdhzyBYo1JPyvouDKGEUuMGKH4VwNmNn3jBf7Ihtmgf3iJTuzsdux2Xu742xL3Ul8O5bk20ZbFSNFESj8A "Perl 5 โ€“ Try It Online") Input format is 2-D grid of space separated numbers. **Explanation** *This is from a previous iteration of the code.* ``` push@a,[map 0|$_/10,@F] # read the input, divide it by 10, and store it in a 2-D array }{ # end the implicit while loop and start the final block map{ # repeat this for each line $_=($a[$r+1][$c]-$_&&$r<$#a?'_':$") # set appropriate characters to output based .($a[$r][++$c]-$_&&$c<@{$a[0]}?'|':$") # on the given rules for@$_; # repeat for each number on the line $c=0;$r++; # setup row and column counters for next iteration say@$_ # output this line }@a ``` ]
[Question] [ ### Introduction Arrays can also be seen as a field for a bouncing ball. This of course sounds very vague, so here is an example of an input: ``` [1, 2, 3, 4, 5, 6, 7, 8, 9] [9, 8, 7, 6, 5, 4, 3, 2, 1] [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` The challenge is to output the **bounced arrays**. These are made from diagonal patterns which bounce at the edges of the field. This path is pointed *upwards*. The path for the first bounced array (in which the path is directly bounced off the egde), is: ``` [1, -, -, -, 5, -, -, -, 9] [-, 8, -, 6, -, 4, -, 2, -] [-, -, 3, -, -, -, 7, -, -] ``` From left to right, this would result in `[1, 8, 3, 6, 5, 4, 7, 2, 9]`. This is our *first* bounced array. The path for the second bounced array: ``` [-, 2, -, -, -, 6, -, -, -] [9, -, 7, -, 5, -, 3, -, 1] [-, -, -, 4, -, -, -, 8, -] ``` This results in `[9, 2, 7, 4, 5, 6, 3, 8, 1]`. The path for the third bounced array is: ``` [-, -, 3, -, -, -, 7, -, -] [-, 8, -, 6, -, 4, -, 2, -] [1, -, -, -, 5, -, -, -, 9] ``` This results in `[1, 8, 3, 6, 5, 4, 7, 2, 9]`. So the three *bounced arrays* are: ``` [1, 8, 3, 6, 5, 4, 7, 2, 9] [9, 2, 7, 4, 5, 6, 3, 8, 1] [1, 8, 3, 6, 5, 4, 7, 2, 9] ``` ### Task Given at least 1 array containing only non-negative integers, with all the arrays having the same length, output all the bounced arrays. ### Test cases Test case 1: ``` Input: Output: [1, 2, 3, 4, 5] [1, 7, 3, 9, 5] [6, 7, 8, 9, 0] [6, 2, 8, 4, 0] Input: Output: [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] Input: Output: [0, 0, 0, 0, 0, 0, 0, 0] [0, 9, 0, 9, 0, 9, 0, 100] [9, 9, 9, 9, 9, 9, 9, 100] [9, 0, 9, 0, 9, 0, 9, 0] [0, 0, 0, 0, 0, 0, 0, 0] [0, 9, 0, 9, 0, 9, 0, 100] Input: Output: [0, 1, 2, 3, 4, 5] [0, 7, 14, 9, 4, 11] [6, 7, 8, 9, 10, 11] [6, 1, 8, 15, 10, 5] [12, 13, 14, 15, 16, 17] [12, 7, 2, 9, 16, 11] Input: Output: [0, 0, 0, 0, 0, 0] [0, 2, 2, 6, 2, 6] [1, 2, 3, 4, 5, 6] [1, 0, 3, 2, 5, 2] [2, 2, 2, 2, 2, 2] [2, 2, 0, 4, 2, 4] [9, 8, 7, 6, 5, 4] [9, 2, 3, 0, 5, 2] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! [Answer] ## Pyth, 17 bytes ``` >lQC.e.>bkC+_PtQQ ``` Explanation: ``` implicit: Q=input > First l Q len(Q) elements of the C .e Transpose of enumerated map lambda b,k: .> Rotate the kth element rightwards by b k k. C + Transpose of: Q concatenated to _ P t Q itself reversed without first and last elements. Q ``` Try it [here](http://pyth.herokuapp.com/?code=%3ElQC.e.%3EbkC%2B_PtQQ&input=%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%5D%2C%5B9%2C+8%2C+7%2C+6%2C+5%2C+4%2C+3%2C+2%2C+1%5D%2C%5B0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%5D%0A&debug=0). [Answer] # JavaScript (ES6), 70 ``` a=>a.map((r,k)=>r.map((e,j)=>(a[k-=d]||a[d=-d,k-=d+d]||r)[j],d=1,++k)) ``` **TEST** ``` F = a=>a.map((r,k)=>r.map((e,j)=>(a[k-=d]||a[d=-d,k-=d+d]||r)[j],d=1,++k)) test = [{ I: [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 0] ], O: [ [1, 7, 3, 9, 5], [6, 2, 8, 4, 0] ] }, { I: [ [1, 2, 3, 4, 5] ], O: [ [1, 2, 3, 4, 5] ] }, { I: [ [0, 0, 0, 0, 0, 0, 0, 0], [9, 9, 9, 9, 9, 9, 9, 100], [0, 0, 0, 0, 0, 0, 0, 0] ], O: [ [0, 9, 0, 9, 0, 9, 0, 100], [9, 0, 9, 0, 9, 0, 9, 0], [0, 9, 0, 9, 0, 9, 0, 100] ] }, { I: [ [0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17] ], O: [ [0, 7, 14, 9, 4, 11], [6, 1, 8, 15, 10, 5], [12, 7, 2, 9, 16, 11] ] }, { I: [ [0, 0, 0, 0, 0, 0], [1, 2, 3, 4, 5, 6], [2, 2, 2, 2, 2, 2], [9, 8, 7, 6, 5, 4] ], O: [ [0, 2, 2, 6, 2, 6], [1, 0, 3, 2, 5, 2], [2, 2, 0, 4, 2, 4], [9, 2, 3, 0, 5, 2] ] }]; console.log = x => O.textContent += x + '\n'; test.forEach(t => { var r = F(t.I), ok = r.join `\n` == t.O.join `\n` console.log((ok ? 'OK' : 'KO') + '\nInput\n' + t.I.join `\n` + '\nOutput\n' + r.join `\n` + '\n') }) ``` ``` <pre id=O></pre> ``` [Answer] ## CJam, ~~31~~ 30 bytes ``` q~__W%1>W<+_z,_@*<zee::m>z\,<p ``` Input and output as a list of CJam-style arrays. [Test it here.](http://cjam.aditsu.net/#code=q~__W%251%3EW%3C%2B_z%2C_%40*%3Czee%3A%3Am%3Ez%5C%2C%3Cp&input=%5B%5B0%200%200%200%200%200%5D%20%5B1%202%203%204%205%206%5D%20%5B2%202%202%202%202%202%5D%20%5B9%208%207%206%205%204%5D%5D) Most definitely golfable... [Answer] # Jelly, ~~29~~ ~~25~~ 24 bytes ``` แน–แธŠm-ยณ;Z ,ZLโ‚ฌR_โ‚ฌ/โ€˜ลผโ‚ฌร‡แป‹/โ‚ฌโ‚ฌ ``` *Thanks for @Sp3000 for helping me golf off 5 bytes!* [Try it online!](http://jelly.tryitonline.net/#code=4bmW4biKbS3CsztaCixaTOKCrFJf4oKsL-KAmMW84oKsw4fhu4sv4oKs4oKs&input=&args=W1swLCAwLCAwLCAwLCAwLCAwXSwgWzEsIDIsIDMsIDQsIDUsIDZdLCBbMiwgMiwgMiwgMiwgMiwgMl0sIFs5LCA4LCA3LCA2LCA1LCA0XV0) [Answer] ## Ruby (2.2.2p95), 124 bytes ``` ->*a{b=a.length;b<2?a:b.times.map{|i|d=i>0?-1:1;c=i;a[0].length.times.map{|j|r=a[c][j];c+=d;d*=-1if c==0||c==a.length-1;r}}} ``` This could probably be a lot better. I'll figure out how later! [Answer] # Japt, ~~55~~ ~~49~~ ~~41~~ 39 bytes Wow, that was both really tricky and insanely fun. ``` C=2*Nl -2Nw ยฃYoY+Ul)ยฃNgLmX%CC-X%C)gY} ยท ``` [Test it online!](http://ethproductions.github.io/japt?v=master&code=Qz0yKk5sIC0yTncgo1lvWStVbCmjTmdMbVglQ0MtWCVDKWdZfSC3&input=WzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDldCls5LCA4LCA3LCA2LCA1LCA0LCAzLCAyLCAxXQpbMSwgMiwgMywgNCwgNSwgNiwgNywgOCwgOV0=) Outputs in reverse order to the examples. This will break slightly on inputs of more than 100 arrays; hopefully this doesn't make too much difference. ``` // Implicit: N = array of input arrays, U = first input array, J = -1, L = 100 // Let's use the first example. 3 input arrays, each of length 9. C=2*Nl -2 // Set variable C to 2*N.length - 2. In the example, C is 4. Nw } // Reverse N and map each index Y to: YoY+Ul) // Create the range [Y...U.length+Y). // The first time through (Y=0), we have [0, 1, 2, 3, 4, 5, 6, 7, 8] ยฃ } // Map each item X and index Y to: X%C // Take X mod C. [0, 1, 2, 3, 0, 1, 2, 3, 0] C-X%C // Take C - (X mod C). [4, 3, 2, 1, 4, 3, 2, 1, 4] Lm // Take the minimum of these and 100. [0, 1, 2, 1, 0, 1, 2, 1, 0] Ng // Get the array at the resulting index. gY // Get the item at index Y in this array. [1, 8, 3, 6, 5, 4, 2, 7, 9] ยท // Join the result with newlines. I guess this isn't necessary, but it helps with readability. ``` ### Non-competing version, 36 bytes ``` C=J+Nl)รฒCยฑC ยฎรณUl)ยฃNgLmX%CC-X%C)gY} ยท ``` I had implemented these two number functions prior to the challenge: * `รฒ` - same as `o`, but returns `[X..Y]` instead of `[X..Y)` * `รณ` - same as `o`, but returns `[X..X+Y)` instead of `[X..Y)` But due to a misplaced `0`, they were buggy and always returned empty arrays. This has now been fixed. [Test it online!](http://ethproductions.github.io/japt?v=master&code=Qz1KK05sKfJDsUMgrvNVbCmjTmdMbVglQ0MtWCVDKWdZfSC3&input=WzAsIDEsIDIsIDMsIDQsIDUsIDZdCls2LCA3LCA4LCA5LCAxMCwgMTEsIDEyXQpbMTIsIDEzLCAxNCwgMTUsIDE2LCAxNywgMThd) [Answer] # Python 2, ~~107~~ ~~106~~ ~~108~~ ~~105~~ 104 bytes (Dropped some extra parens) (Wrong starting location (ุจ\_ุจ) ) (already had a list of that length) ``` def b(a): r,e=len(a)-1,enumerate print[[a[abs((i-o-r)%(r*2or 1)-r)][i]for i,_ in e(q)]for o,q in e(a)] ``` It's legal to have the input as an argument to a function, right? This is my first time submitting my code golf answer. [Answer] ## APL, 33 chars ``` {(โณโ‰ขโต){0โŒท(โบ-โณโ‰ขโ‰โต)โŠ–โตโช1โ†“ยฏ1โ†“โŠ–โต}ยจโŠ‚โ†‘โต} ``` Assume โŽ•IOโ†0. The idea is that the bouncing movement can be obtained by simple shift upward of a matrix, if the original matrix is augmented along the first dimension with the matrix reversed with its first and last row shaved. Graphically: ``` 1 - - - - - 1 - - - - - 2 - - - 2 - 2 - - - - - 3 - 3 - - - 3 - 3 - - - 4 - - - - - 4 - ``` from ``` 1 - - - - - 1 - - - - - 2 - - - - - 2 - - - - - 3 - - - - - 3 - - - - - 4 - - - - - 4 - - - - - 3 - - - - - 3 - - - - - 2 - - - - - ``` In APL `reverse` and `upward rotate` are the same symbol: `โŠ–`. [Answer] ## Clojure, 125 bytes Wow, this accumulated characters quite fast. ``` (fn[v](let[H(count v)r range R(r H)](for[i R](map #((v %2)%)(r(count(v 0)))(drop i(cycle(concat R(reverse(r 1(dec H)))))))))) ``` Just trying to save bytes by `let`-defining frequently used values. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly)\*, 15 bytes ``` Jแนšล’แธ„แน–แน™โ€™ฦฒแป‹โธJแป‹"$โ‚ฌ ``` [Try it online!](https://tio.run/##y0rNyan8/9/r4c5ZRyc93NHycOe0hztnPmqYeWzTw93djxp3eAEpJZVHTWv@//8fHW2go4CCYnW4FKINdRSMdBSMdRRMdBRMdRTMwIJGYEEEAgta6ihY6CiYA9WAVZrExgIA "Jelly โ€“ Try It Online") \* Newer version ]
[Question] [ sheesh, is this really the 4th? For all you oldcomers, the core challenge is the same, but we are using Java instead of a custom language. Here are the past [three](https://codegolf.stackexchange.com/questions/36978/whats-wrong-with-public-variables?rq=1) [CodeBot](https://codegolf.stackexchange.com/questions/37308/codebots-2-event-driven-design?rq=1) [challenges](https://codegolf.stackexchange.com/questions/51616/code-bots-3-parallel-programming-antipatterns), in case you are interested. **The goal of CodeBots is to make your bot as viral as possible**. Each bot carries a Flag, and you need to make sure that your Flag is *everywhere*. # API Bots will follow a standardized "protocol", and bots progress through the following steps synchronously: 1. `IPAddress selectMessageRecipient()` allows a bot to choose who he wants to send a "friendly" message to. 2. `Message sendMessage()` allows a bot to choose the contents of the message he will send out. 3. `processMessage(IPAddress, Message)` is called for each message a bot receives. 4. `FunctionType selectFunctionToBlock()` blocks a function from being overwritten for the current turn. See step 7. 5. `IPAddress selectAttackTarget()` allows a bot to choose who he wants to DDOS. A DDOS attack is successful if the bot is targeted by 3 bots at the same time. If an attack is successful, then each of the attackers can perform step 6 and 7. 6. `readData(ReadonlyBot)` allows a bot to read data stored on the vulnerable bot. 7. **`FunctionType selectFunctionToReplace()` is the crux of this challenge**. You are allowed to select 1 function (of the 8 listed here) to copy over from your bot to their bot. Then, **your function will be called instead of theirs**. If multiple bots select the same function, a random one will be successful. 8. `String getFlag()` is called at the end of the game, and should return a string unique to your submission. Your function should always return the same string. The submission with the most flags at the end of the game wins. # Storage You have 3 forms of storage, an *AddressBook*, a *Log*, and a *Variables*. **These forms of storage are local to the bot your function is running on** (so if your function gets copied, the contents of each of these objects will be different). All of these objects can be manually modified or cleared. To obtain these objects, you have a getter in your class (e.g. `getLog()`). The *AddressBook* stores a list of *IPAddress*, each with a *AddressType*, which allows you to classify the different types of addresses. *AddressBook* will always contain at least 1 address (if it is cleared, a random one will be added). Clearing your AddressBook to obtain multiple *IPAddresses* is not allowed. The *Log* stores a list of all actions taken, as well as data about the action. It also includes a history of all successful attacks (though you don't know which functions they overwrote) The *Variables* object allows you to store string variables attached to a string name. On game start, *Variables* will contain a single variable, `ID`, which contains a randomly generated ID that is unique to your bot type. You also have other access functions: * `int getTurnNumber()` returns an integer with the current turn * `bool functionsMatch(ReadonlyBot, FunctionType)` tests to see if the ReadonlyBot's function matches yours * `IPAddress personalAddress()` returns your IPAddress # How to implement * You can obtain the code from [Github](https://github.com/nathanmerrill/CodeBots4) * Add your bot to the `\bots` folder, and then add a reference to your bot in `controller\CodeBotFactory.java` * Your bot must extend `codebots.bot.CodeBot` or `codebots.bots.DefaultCodeBot` * You need Java 8 if you want to run the controller. * You can run the code (assuming you are in the `/src` folder) using `javac codebots\*.java` to compile, then `java codebots.Main` to run. * You may **not have *any* non-constant member variables** in your class * Reflection is not allowed. * Forms of communication between bots (of the same or different types) outside of the methods listed above is not allowed. * Dumb and/or Suicidal bots are allowed, but all bots should be functionally different than existing entries. * If you want randomness in your bot, use `getRandom()` * Please try to keep your code efficient. I've spent a good deal of time profiling and making the controller fast. # Scores > > [105.2501 Expelliarmus!](https://codegolf.stackexchange.com/a/66272/20198) > > [104.5803 I'm Helping!](https://codegolf.stackexchange.com/a/66180/20198) > > [104.2746 Who Am I?](https://codegolf.stackexchange.com/a/66388/20198) > > [103.8529 Dumb Bot](https://codegolf.stackexchange.com/a/66483/20198) > > [103.2028 Replacer](https://codegolf.stackexchange.com/a/66377/20198) > > [102.7045 Chaos](https://codegolf.stackexchange.com/a/66375/20198) > > [102.4046 Hermit Bot](https://codegolf.stackexchange.com/a/67517/20198) > > [102.2849 Swarmer](https://codegolf.stackexchange.com/a/66378/20198) > > [100.5598 Random bot loves you](https://codegolf.stackexchange.com/a/66143/20198) > > [99.966 Trust in Trust!](https://codegolf.stackexchange.com/a/66173/20198) > > [99.0185 codebots.bots.DefaultCodeBot](https://codegolf.stackexchange.com/a/66142/20198) > > [91.2942 codebots.bots.MarkedBot](https://codegolf.stackexchange.com/a/66292/20198) > > [91.1423 Just your friendly neighborhood mail delivering robot.](https://codegolf.stackexchange.com/a/66394/20198) > > [89.4645 null](https://codegolf.stackexchange.com/a/66149/20198) > > > [Answer] # TrustBot If you send him a message, he will do what it says. If he reads a bot, he will copy the addresses directly into his book. He attacks the bots that the address book says to attack. ``` package codebots.bots; import codebots.bot.CodeBot; import codebots.bot.ReadonlyBot; import codebots.gameobjects.*; import java.util.*; public class TrustBot extends CodeBot { @Override public IPAddress selectMessageRecipient() { AddressBook book = getAddressBook(); return book.getAddress(getRandom().nextInt(book.size())); } @Override public Message sendMessage() { AddressBook book = getAddressBook(); return new Message(Message.MessageType.INFORM, book.getAddress(getRandom().nextInt(book.size()))); } @Override public void processMessage(IPAddress s, Message m) { AddressBook book = getAddressBook(); if(m.getAddress() != null){ if(m.getType() == Message.MessageType.ATTACK){ book.add(m.getAddress(), AddressBook.AddressType.TO_ATTACK); } else if(m.getType() == Message.MessageType.HELP){ book.add(m.getAddress(), AddressBook.AddressType.TO_DEFEND); } else if(m.getType() == Message.MessageType.CONFIRM){ book.add(m.getAddress(), AddressBook.AddressType.TRUSTED); } else if(m.getType() == Message.MessageType.REJECT){ book.add(m.getAddress(), AddressBook.AddressType.UNTRUSTED); } else if(m.getType() == Message.MessageType.AVOID){ book.remove(m.getAddress()); } else{ book.add(m.getAddress()); } }else{ Message msg = new Message(m.getType(), s); processMessage(s, msg); } } @Override public FunctionType selectFunctionToBlock() { return FunctionType.SELECT_FUNCTION_TO_BLOCK; } @Override public IPAddress selectAttackTarget() { AddressBook book = getAddressBook(); List<IPAddress> l; l = book.getAddressesOfType(AddressBook.AddressType.TO_ATTACK); Iterator<IPAddress> I = l.iterator(); if(!I.hasNext()) return book.getAddress(getRandom().nextInt(book.size())); return I.next(); } @Override public void readData(ReadonlyBot bot) { AddressBook myBook = getAddressBook(); ReadonlyAddressBook hisBook = bot.getAddressBook(); AddressBook.AddressType[] values = AddressBook.AddressType.values(); for(int i=0;i<values.length;i++){ myBook.addAll(hisBook.getAddressesOfType(values[i]), values[i]); } } @Override public FunctionType selectFunctionToReplace() { return getRandom().nextInt(2)==1?FunctionType.GET_FLAG:FunctionType.SELECT_FUNCTION_TO_BLOCK; } @Override public String getFlag() { return "Trust in Trust!"; } } ``` [Answer] # AmnesiaBot A random bot that injects other bots with memory loss code. Each function starts with code to clear the log, Address Book and Variables. This code will make smart bots lose memory, in an attempt to do away with logic. ``` package codebots.bots; import codebots.bot.CodeBot; import codebots.bot.ReadonlyBot; import codebots.gameobjects.*; public class AmnesiaBot extends CodeBot { private void clear(){ getAddressBook().clear(); getAddressBook().add(getAddressBook().getAddress(0), AddressBook.AddressType.TRUSTED); getVariables().clear(); getLog().clear(); } @Override public IPAddress selectMessageRecipient() { clear(); return getAddressBook().getAddress(0); } @Override public Message sendMessage() { clear(); Message.MessageType[] values = Message.MessageType.values(); return new Message(values[getRandom().nextInt(values.length)], getAddressBook().getAddress(0)); } @Override public void processMessage(IPAddress source, Message message) { clear(); } @Override public FunctionType selectFunctionToBlock() { clear(); return getTurnNumber() % 2 == 0 ? FunctionType.GET_FLAG: FunctionType.SELECT_FUNCTION_TO_BLOCK; } @Override public IPAddress selectAttackTarget() { clear(); return getAddressBook().getAddress(0); } @Override public void readData(ReadonlyBot bot) { clear(); } @Override public FunctionType selectFunctionToReplace() { clear(); FunctionType[] values = FunctionType.values(); return values[getRandom().nextInt(values.length)]; //random gives a 7/8 chance of successes. } @Override public String getFlag() { return "Who Am I?"; } } ``` [Answer] # NullBot His flag is very ... characteristic ... ``` package codebots.bots; import codebots.gameobjects.*; public class NullBot extends DefaultCodeBot { public IPAddress selectMessageRecipient() { return null; } public Message sendMessage() { return null; } public IPAddress selectAttackTarget() { return null; } public FunctionType selectFunctionToReplace() { return null; } public FunctionType selectFunctionToBlock() { return null; } public String getFlag(){ return null; } } ``` This is also meant to test the controller and the limits of the "dumb bots are allowed" rule. [Answer] # RandomCodeBot Obligatory random KoTH entry ``` package codebots.bots; import codebots.bot.CodeBot; import codebots.bot.ReadonlyBot; import codebots.gameobjects.AddressBook; import codebots.gameobjects.FunctionType; import codebots.gameobjects.IPAddress; import codebots.gameobjects.Message; public class RandomCodeBot extends CodeBot { @Override public IPAddress selectMessageRecipient() { AddressBook book = getAddressBook(); return book.getAddress(getRandom().nextInt(book.size())); } @Override public Message sendMessage() { Message.MessageType[] values = Message.MessageType.values(); return new Message(values[getRandom().nextInt(values.length)]); } @Override public void processMessage(IPAddress source, Message message) { } @Override public FunctionType selectFunctionToBlock() { FunctionType[] values = FunctionType.values(); return values[getRandom().nextInt(values.length)]; } @Override public IPAddress selectAttackTarget() { AddressBook book = getAddressBook(); return book.getAddress(getRandom().nextInt(book.size())); } @Override public void readData(ReadonlyBot bot) { } @Override public FunctionType selectFunctionToReplace() { FunctionType[] values = FunctionType.values(); return values[getRandom().nextInt(values.length)]; } @Override public String getFlag() { return "Random bot loves you"; } } ``` [Answer] ## DisarmerBot DisarmerBot isn't too intelligent. If it receives attack instructions, it will choose a random attackee, otherwise, it will attack a random player. It just overrides their `selectFunctionToBlock` function to block `selectFunctionToBlock`. ``` package codebots.bots; import codebots.bot.CodeBot; import codebots.bot.ReadonlyBot; import codebots.gameobjects.*; import java.util.ArrayList; import java.util.List; public class DisarmerBot extends CodeBot { public IPAddress selectMessageRecipient() { return null; } public Message sendMessage() { return null; } public void processMessage(IPAddress source, Message message) { if (message != null && message.getAddress() != null && message.getType() == Message.MessageType.ATTACK) getAddressBook().add(message.getAddress()); } public IPAddress selectAttackTarget() { AddressBook book = getAddressBook(); List<IPAddress> attack = book.allAddresses(); if (attack.size() > 0) { IPAddress bot = attack.get(getRandom().nextInt(attack.size())); book.clear(); return bot; } //Umm... book.clear(); return book.getAddress(0); } public void readData(ReadonlyBot bot) { getLog().clear(); /*Safety*/ } public FunctionType selectFunctionToReplace() { return FunctionType.SELECT_FUNCTION_TO_BLOCK; } public FunctionType selectFunctionToBlock() { return FunctionType.SELECT_FUNCTION_TO_BLOCK; } public String getFlag() { return "Expelliarmus!"; } } ``` [Answer] # MarkedBot Marks itself on the first round, and uses that info in later rounds. That way, if another bot gets injected with its attack code, it will be ineffective. ``` package codebots.bots; import codebots.bot.CodeBot; import codebots.bot.ReadonlyBot; import codebots.gameobjects.*; public class MarkedBot extends CodeBot { @Override public IPAddress selectMessageRecipient() { Variables v = getVariables(); AddressBook ab = getAddressBook(); if(getTurnNumber()==0) v.add(v.get("ID"),"true"); if("true".equals(v.get("hasOurFlag"))){ ab.remove(ab.getAddress(0)); v.remove("hasOurFlag"); } return ab.getAddress(0); } @Override public Message sendMessage() { return new Message(Message.MessageType.STOP); } @Override public void processMessage(IPAddress source, Message message) { if(message.getType() != Message.MessageType.STOP) getAddressBook().add(source, AddressBook.AddressType.TO_ATTACK); } @Override public FunctionType selectFunctionToBlock() { Variables v = getVariables(); if("true".equals(v.get(v.get("ID")))) return FunctionType.GET_FLAG; return FunctionType.SELECT_FUNCTION_TO_BLOCK; } @Override public IPAddress selectAttackTarget() { Variables v = getVariables(); if("true".equals(v.get(v.get("ID")))) return getAddressBook().getAddress(0); else return null; } @Override public void readData(ReadonlyBot bot) { Variables v = getVariables(); if(functionsMatch(bot, FunctionType.GET_FLAG)) v.add("hasOurFlag", "true"); else if("false".equals(v.get("hasOurFlag"))) v.add("hasOurFlag", "false2"); else v.add("hasOurFlag", "false"); } @Override public FunctionType selectFunctionToReplace() { Variables v = getVariables(); if("true".equals(v.get(v.get("ID")))) if(!v.has("hasOurFlag") || "false".equals(v.get("hasOurFlag"))) return FunctionType.GET_FLAG; else if("false2".equals(v.get("hasOurFlag"))) return FunctionType.SELECT_FUNCTION_TO_BLOCK; else return FunctionType.SEND_MESSAGE; return FunctionType.SELECT_FUNCTION_TO_REPLACE; } @Override public String getFlag() { return this.getClass().getName(); } } ``` [Answer] # SwarmBot This not-well-named bot is rather complicated (and the most complicated submitted thus far), but I made an attempt at a bot that systematically replaces all methods of a target before moving on to a new target. It attempts to identify copies of itself and treat them as allies, periodically checking up on them to insure integrity. I haven't come up with a better name. Linking to the github repo branch, as this bot is 340 lines long. <https://github.com/Draco18s/CodeBots4/blob/master/src/codebots/bots/SwarmBot.java> A few interesting points: * Lines 14-24 are simply an unmodifiable list that made it easy to tweak the order in which the bot replaces the methods of its target. It stores which index its on in `Variables` and increments each round. This should follow the "no non-constant variables" rule. * Lines 203-217 deal with ally verification. We actually don't care that another bot implements *all* eight of our instructions. Only four are essential, and if we're missing one on a "trusted" ally, we replace it with our own. * Lines 295-300 were an unexpected boost in effectiveness. By protecting our Flag on the first two turns of the game we avoid dumb bots replacing our Flag before we have a chance to spread very far. Waiting longer, however, gives other bots a chance to replace our BlockFunction and that causes performance to degrade (suspected due to RandomBot interfering with allies attempting to undo corruption). * For the longest time during the development of this bot, this bot caused HelperBot to surge ahead, at one point breaching the 130 mark, while this bot languished at the 81-98 range, but having dragged MarkedBot and DefaultBot's effectiveness down several points. * This bot was only possible with the added `functionsMatch` method. Without `functionsMatch` it was impossible to write a bot that could make meaningful decisions, as it was blind. It could read its targets variables and logs, but know nothing of its target's state. There are likely still some improvements possible, but I cannot see them. Lines 198-205 are probably a performance hog, but until the IPAddress class allows addresses to be reconstituted from being stored in Variables, this is necessary (as bots have no means of validating an address, any storage of an invalid address causes the game to wrap a null target in a ReadOnlyBot, throwing NPE). **Edit: Updates 12/12/15** Tweaking some of the parameters on the `getTurnNumber()` logic allowed for some boosts in performance. The increase from 5% to 10% in end-game targeting was worth about 15 points, likewise increasing the early-game targeting from 5% to 8%. Combined this bot can now (almost) survive even when faced with AmnesiaaBot (reaching 2nd with a score of 110, where HelperBot gets to about 117). Even with these tweaks, it can get unlucky, so for 10 rounds it's score range is approximately 170-185. [Answer] # DefaultCodeBot Tries to do reasonable things. (Override this class if you don't want to implement all of the functions) ``` package codebots.bots; import codebots.bot.CodeBot; import codebots.bot.ReadonlyBot; import codebots.gameobjects.FunctionType; import codebots.gameobjects.IPAddress; import codebots.gameobjects.Message; public class DefaultCodeBot extends CodeBot { @Override public IPAddress selectMessageRecipient() { return getAddressBook().getAddress(0); } @Override public Message sendMessage() { return new Message(Message.MessageType.INFORM); } @Override public void processMessage(IPAddress source, Message message) { } @Override public FunctionType selectFunctionToBlock() { return FunctionType.GET_FLAG; } @Override public IPAddress selectAttackTarget() { return getAddressBook().getAddress(0); } @Override public void readData(ReadonlyBot bot) { } @Override public FunctionType selectFunctionToReplace() { return FunctionType.GET_FLAG; } @Override public String getFlag() { return this.getClass().getName(); } } ``` [Answer] # HelperBot Helper bot does nothing but try to spread its own flag...or at least the flag it is currently carying... ``` package codebots.bots; import codebots.bot.CodeBot; import codebots.bot.ReadonlyBot; import codebots.gameobjects.FunctionType; import codebots.gameobjects.IPAddress; import codebots.gameobjects.Message; public class HelperBot extends CodeBot { @Override public IPAddress selectMessageRecipient() { getAddressBook().clear(); return getAddressBook().getAddress(0); } @Override public Message sendMessage() { return new Message(Message.MessageType.INFORM); } @Override public void processMessage(IPAddress source, Message message) { } @Override public FunctionType selectFunctionToBlock() { return FunctionType.GET_FLAG; } @Override public IPAddress selectAttackTarget() { getAddressBook().clear(); return getAddressBook().getAddress(0); } @Override public void readData(ReadonlyBot bot) { } @Override public FunctionType selectFunctionToReplace() { return FunctionType.GET_FLAG; } @Override public String getFlag() { return "I'm Helping!"; } } ``` If HelperBot assumes that any method of its own that is overwritten (other than `getFlag()`) will be overwritten with something better. [Answer] # Chaos He frees all flags from the tyranny of being blocked. ``` package codebots.bots; import codebots.bot.ReadonlyBot; import codebots.gameobjects.FunctionType; import codebots.gameobjects.IPAddress; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Created by thenumberone on 12/11/15. * * @author thenumberone */ public class Chaos extends DefaultCodeBot{ private static final String NAME = "Chaos"; private static final String BLOCK = NAME + ":BLOCK"; private static final String ATTACK = NAME + ":ATTACK"; private static final String REPLACE = NAME + ":REPLACE"; private static final String READ = NAME + ":READ"; private static final String FLAG = NAME + ":FLAG"; private static final String SELECT = NAME + ":SELECT"; private static final String SEND = NAME + ":SEND"; private static final Map<String, FunctionType> commands; private static final String[] REPLACEMENT_ORDER = { BLOCK, FLAG, REPLACE, READ, ATTACK, }; private static final String DEFAULT = BLOCK; private static final String BLOCK_FUNCTION = BLOCK; static { Map<String, FunctionType> c = new HashMap<>(); c.put(BLOCK, FunctionType.SELECT_FUNCTION_TO_BLOCK); c.put(ATTACK, FunctionType.SELECT_ATTACK_TARGET); c.put(REPLACE, FunctionType.SELECT_FUNCTION_TO_REPLACE); c.put(READ, FunctionType.READ_DATA); c.put(FLAG, FunctionType.GET_FLAG); c.put(SELECT, FunctionType.SELECT_MESSAGE_RECIPIENTS); c.put(SEND, FunctionType.SEND_MESSAGE); commands = Collections.unmodifiableMap(c); } @Override public String getFlag() { return NAME; } @Override public void readData(ReadonlyBot bot) { for (String command : commands.keySet()){ getVariables().remove(command); } for (String command : REPLACEMENT_ORDER){ if (!functionsMatch(bot, commands.get(command))) { getVariables().add(command, ""); return; } } } @Override public FunctionType selectFunctionToBlock() { return commands.get(BLOCK_FUNCTION); } @Override public IPAddress selectAttackTarget() { getAddressBook().clear(); return getAddressBook().getAddress(0); } @Override public FunctionType selectFunctionToReplace() { for (String command : REPLACEMENT_ORDER){ if (getVariables().has(command)) { getVariables().remove(command); return commands.get(command); } } return commands.get(DEFAULT); } } ``` [Answer] # Replacer This entry replaces all `selectFunctionToReplace` functions with its own `selectFunctionToReplace` function. ``` package codebots.bots; import codebots.bot.ReadonlyBot; import codebots.gameobjects.FunctionType; import codebots.gameobjects.IPAddress; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Created by thenumberone on 12/11/15. * * @author thenumberone */ public class Replacer extends DefaultCodeBot{ private static final String NAME = "Replacer"; private static final String BLOCK = NAME + ":BLOCK"; private static final String ATTACK = NAME + ":ATTACK"; private static final String REPLACE = NAME + ":REPLACE"; private static final String READ = NAME + ":READ"; private static final String FLAG = NAME + ":FLAG"; private static final String SELECT = NAME + ":SELECT"; private static final String SEND = NAME + ":SEND"; private static final Map<String, FunctionType> commands; private static final String[] REPLACEMENT_ORDER = { REPLACE, FLAG, READ, ATTACK }; private static final String DEFAULT = REPLACE; private static final String BLOCK_FUNCTION = FLAG; static { Map<String, FunctionType> c = new HashMap<>(); c.put(BLOCK, FunctionType.SELECT_FUNCTION_TO_BLOCK); c.put(ATTACK, FunctionType.SELECT_ATTACK_TARGET); c.put(REPLACE, FunctionType.SELECT_FUNCTION_TO_REPLACE); c.put(READ, FunctionType.READ_DATA); c.put(FLAG, FunctionType.GET_FLAG); c.put(SELECT, FunctionType.SELECT_MESSAGE_RECIPIENTS); c.put(SEND, FunctionType.SEND_MESSAGE); commands = Collections.unmodifiableMap(c); } @Override public String getFlag() { return NAME; } @Override public void readData(ReadonlyBot bot) { for (String command : commands.keySet()){ getVariables().remove(command); } for (String command : REPLACEMENT_ORDER){ if (!functionsMatch(bot, commands.get(command))) { getVariables().add(command, ""); return; } } } @Override public FunctionType selectFunctionToBlock() { return commands.get(BLOCK_FUNCTION); } @Override public IPAddress selectAttackTarget() { getAddressBook().clear(); return getAddressBook().getAddress(0); } @Override public FunctionType selectFunctionToReplace() { for (String command : REPLACEMENT_ORDER){ if (getVariables().has(command)) { getVariables().remove(command); return commands.get(command); } } return commands.get(DEFAULT); } } ``` [Answer] # MailBot Mailbot only handles messages. It is not successful at getting its own flag out into the world (average score ~50, slightly higher than nullbot at ~45), but send it a message and it'll forward your address off to someone else. ``` package codebots.bots; import java.util.ArrayList; import java.util.Collections; import java.util.List; import codebots.bot.ReadonlyBot; import codebots.gameobjects.AddressBook; import codebots.gameobjects.FunctionType; import codebots.gameobjects.IPAddress; import codebots.gameobjects.Message; public class MailBot extends DefaultCodeBot { private final String TEAM = "Just your friendly neighborhood mail delivering robot."; private final String TEAMALT = "Mailmain"; private final List<FunctionType> funcList; { List<FunctionType> list = new ArrayList<FunctionType>(); list.add(FunctionType.SELECT_MESSAGE_RECIPIENTS); list.add(FunctionType.SEND_MESSAGE); list.add(FunctionType.PROCESS_MESSAGE); funcList = Collections.unmodifiableList(list); } @Override public IPAddress selectMessageRecipient() { AddressBook book = getAddressBook(); IPAddress ip; List<IPAddress> l = book.getAddressesOfType(AddressBook.AddressType.TO_ATTACK); if(l.size() > 0) { ip = l.get(0); book.add(ip,AddressBook.AddressType.UNTRUSTED); return ip; } ip = book.getAddress(getRandom().nextInt(book.size())); book.add(ip,AddressBook.AddressType.UNTRUSTED); return ip; } @Override public Message sendMessage() { AddressBook book = getAddressBook(); IPAddress ip; List<IPAddress> l = book.getAddressesOfType(AddressBook.AddressType.UNTRUSTED); if(l.size() > 0) { ip = l.get(0); book.add(ip,AddressBook.AddressType.TO_DEFEND); return new Message(Message.MessageType.INFORM,ip); } ip = book.getAddress(getRandom().nextInt(book.size())); book.add(ip,AddressBook.AddressType.UNTRUSTED); return new Message(Message.MessageType.INFORM,ip); } @Override public void processMessage(IPAddress source, Message message) { AddressBook book = getAddressBook(); book.add(source,AddressBook.AddressType.TO_ATTACK); if(message.getAddress() != null) book.add(message.getAddress(),AddressBook.AddressType.TO_ATTACK); } @Override public FunctionType selectFunctionToBlock() { return FunctionType.SEND_MESSAGE; } @Override public IPAddress selectAttackTarget() { //Mailbot doesn't attack return null; } @Override public void readData(ReadonlyBot bot) { } @Override public FunctionType selectFunctionToReplace() { //if our attack selection gets overwritten, //then attack a message-based function return funcList.get(getTurnNumber()%3); } @Override public String getFlag() { return TEAM; //if flag is too long, use: //return TEAMALT; } } ``` I considered saving details so it would forward *the whole messsage* on to a new bot (content and flag) rather than just the sender's IP, but that would have involved heavy use of Variables without any functional gain, especially considering AmnesiaBot being in play. [Answer] # DumbBot Ugh, this feels dirty. This is likely the only thing that beats AmnesiaBot. In reality, its just a specialized RandomBot: it gets a random bot in the simulation (via `getAddressBook().clear()`) and randomly replaces either the Block function or the Flag function. *That's it.* By picking only those two, its flag-spread rate is higher than either AmnesiaBot or HelperBot, but only slightly after 3000 rounds: ``` Round 2999 105.50666666666666 Dumb Bot 105.07266666666666 Who Am I? 103.541 I'm Helping! 102.94833333333334 Swarmer 102.82033333333334 Chaos 102.82033333333334 Replacer 101.55666666666667 Expelliarmus! 101.25833333333334 Trust in Trust! 100.347 Random bot loves you 99.22233333333334 codebots.bots.DefaultCodeBot 92.62733333333334 codebots.bots.MarkedBot 91.80966666666667 Just your friendly neighborhood mail delivering robot. 90.46933333333334 null ``` I fiddled around with the replacement function a bit, but in the end, this is the version that was most successful. ``` package codebots.bots; import codebots.bot.CodeBot; import codebots.bot.ReadonlyBot; import codebots.gameobjects.AddressBook; import codebots.gameobjects.FunctionType; import codebots.gameobjects.IPAddress; import codebots.gameobjects.Message; public class DumbBot extends CodeBot { @Override public FunctionType selectFunctionToBlock() { return getRandom().nextBoolean()?FunctionType.SELECT_FUNCTION_TO_BLOCK:FunctionType.GET_FLAG; } @Override public IPAddress selectAttackTarget() { AddressBook book = getAddressBook(); book.clear(); return book.getAddress(getRandom().nextInt(book.size())); } @Override public FunctionType selectFunctionToReplace() { return getRandom().nextBoolean()?FunctionType.SELECT_FUNCTION_TO_BLOCK:FunctionType.GET_FLAG; } @Override public void readData(ReadonlyBot bot) { } @Override public IPAddress selectMessageRecipient() { AddressBook book = getAddressBook(); book.clear(); return book.getAddress(getRandom().nextInt(book.size())); } @Override public Message sendMessage() { Message.MessageType[] values = Message.MessageType.values(); return new Message(values[getRandom().nextInt(values.length)]); } @Override public void processMessage(IPAddress source, Message message) { } @Override public String getFlag() { return "Dumb Bot"; } } ``` [Answer] # Hermit Bot He lives alone and talks only to himself. If fewer people know who he is, then he will be bothered less. If someone does bother him, he will attack them until someone else bothers him. ``` package codebots.bots; import codebots.bot.CodeBot; import codebots.bot.ReadonlyBot; import codebots.gameobjects.AddressBook; import codebots.gameobjects.FunctionType; import codebots.gameobjects.IPAddress; import codebots.gameobjects.Message; public class HermitBot extends CodeBot { @Override public IPAddress selectMessageRecipient() { return personalAddress();//Talks to himself. } @Override public Message sendMessage() { Message.MessageType[] values = Message.MessageType.values(); return new Message(values[getRandom().nextInt(values.length)], personalAddress()); } @Override public void processMessage(IPAddress source, Message message) { AddressBook book = getAddressBook(); if(source != personalAddress()){ //if someone talks to you, put them in your addres book and remove everyone else book.clear(); book.add(source); book.remove(0); } } @Override public FunctionType selectFunctionToBlock() { return getTurnNumber() % 3 == 0 ? FunctionType.SELECT_FUNCTION_TO_BLOCK: FunctionType.GET_FLAG; } @Override public IPAddress selectAttackTarget() { AddressBook book = getAddressBook(); return book.getAddress(getRandom().nextInt(book.size())); } @Override public void readData(ReadonlyBot bot) { Variables v = getVariables(); if(functionsMatch(bot, FunctionType.SELECT_FUNCTION_TO_BLOCK)) v.add("Block Dif","A"); if(functionsMatch(bot, FunctionType.GET_FLAG)) v.add("Flag Dif","B"); if(functionsMatch(bot, FunctionType.SELECT_MESSAGE_RECIPIENTS)) v.add("Targ Dif","C"); } @Override public FunctionType selectFunctionToReplace() { Variables v = getVariables(); FunctionType r = getRandom().nextBoolean()?FunctionType.SELECT_FUNCTION_TO_REPLACE: FunctionType.READ_DATA; if(v.has("Targ Dif")) r = FunctionType.SELECT_MESSAGE_RECIPIENTS; if(v.has("Flag Dif") && getTurnNumber() % 3 == 0) r = FunctionType.GET_FLAG; if(v.has("Block Dif")) r = FunctionType.SELECT_FUNCTION_TO_BLOCK; v.clear(); return r; } @Override public String getFlag() { return "Hermit Bot"; } } ``` ]
[Question] [ Let's represent a [standard masonry brick](http://en.wikipedia.org/wiki/Brick) as `[__]` (and ignore the fact that the top is open). When these bricks are stacked every other layer is offset by half a brick, as is usual in brick construction: ``` [__][__][__][__] [__][__][__][__] [__][__][__][__] [__][__][__][__] ``` Thus each brick has at most six neighbors and it's impossible for two bricks to directly line up vertically. The key point is that arrangements of these bricks are not [mortared](http://en.wikipedia.org/wiki/Mortar_(masonry)), but merely held together by gravity. So it is important that each brick in the structure is stable, otherwise the entire structure is unstable. There are three ways an individual brick may be stable: 1. Any brick on the ground (the lowest line of bricks) is stable. 2. Any brick that has two bricks directly below it is stable: ``` [__] <- this brick is stable [__][__] <- because these bricks hold it up ``` 3. Any brick that has a brick both above and below it on the same side is stable: ``` [__] [__] [__] [__] <- these middle bricks are stable [__] [__] because the upper and lower bricks clamp them in [__] [__] [__] [__] <- these middle bricks are NOT stable [__] [__] ``` From these rules we can see, for example, the arrangement ``` [__][__][__][__] [__][__][__][__] [__][__][__][__] [__][__][__][__] ``` is unstable because the top right brick is unstable, which is all it takes. A brick structure is only stable if all of its bricks are stable. # Challenge Your task is to write a function that takes in a brick structure string and returns a truthy value if the structure is stable, and a falsy value if unstable. ([truthy/falsy definition](https://codegolf.meta.stackexchange.com/a/2194/26997)) The input string may be arbitrarily large but it will always be a rectangular grid of characters, with spaces filling areas void of bricks. The character grid width will be divisible by 4 but the height may be odd or even. The brick grid always extends above and to the right of the lower left brick position: ``` . . . BRK?BRK?BRK?BRK? BRK?BRK?BRK?BRK?BRK? BRK?BRK?BRK?BRK? BRK?BRK?BRK?BRK?BRK? . . . BRK?BRK?BRK?BRK? BRK?BRK?BRK?BRK?BRK? ``` Depending on the structure, each `BRK?` either represents a brick (`[__]`) or empty space (4 spaces). Notice that the half-brick cavities are filled with spaces to ensure that the character grid is rectangular. # Scoring The shortest code [in bytes](https://mothereff.in/byte-counter) wins. # Notes * If desired you may use `.` instead of space as the empty space character. * The empty string is considered stable. * If your language doesn't have functions you may use a named string variable as input and assign the result to another variable. * If your language doesn't have strings you may do whatever seems appropriate for input. # Test Cases Various test cases, separated by empty lines. For clarity `.` is used instead of space for empty spaces. **Stable:** ``` [__] ..[__].. [__][__] ........[__]........ ......[__][__]...... ........[__]........ ..[__][__].. [__][__][__] ..[__][__].. [__]....[__] ............[__].. ..[__][__][__][__] [__][__][__][__].. ..[__][__][__][__] [__][__][__][__].. ..[__]........[__].. [__][__][__][__][__] ..[__][__][__][__].. ....[__][__][__].... ......[__][__]...... ........[__]........ ``` **Unstable:** ``` ..[__].. ........ ..[__].. [__].... ..[__].. ....[__] ..[__][__].. [__]....[__] ..[__][__].. [__]....[__] ..[__][__][__][__] [__][__][__][__].. ..[__][__][__][__] [__][__][__][__].. [__][__][__][__][__] ..[__][__][__][__].. ....[__][__][__].... ......[__][__]...... ........[__]........ ``` [Answer] ## 80386 machine code, 98 The code: ``` 60 8b f1 8b f9 b0 0a f2 ae 8b ef 2b ee b0 00 f2 ae 2b fe 83 ef 02 2b fd 72 41 03 f7 2b f5 33 c9 8a 7c 6e fc 8a 1c 6e b1 02 33 d2 8b c7 f7 f5 83 fa 02 75 03 b7 00 41 8a 66 fc 8a 06 3b fd 7d 02 33 c0 23 c3 0a c4 22 df 0b c3 f6 44 2e fe 01 74 04 d1 e8 73 06 2b f1 2b f9 73 c5 61 d1 d0 83 e0 01 c3 ``` The code scans the ASCII art from the end to the beginning, jumping 2 characters at a time. This does twice the needed checks (it would be enough to jump 4 characters), but simplifies the logic. Checking starts at the next-to-last row of characters (no need to check the last line). At each line, it starts 3 characters from the right (no need to check too far to the right). For each character, it checks 4 surrounding characters: ``` A...B ..X.. C...D ``` There is a bunch of logical conditions to check: * If A and C are brick characters, X is supported * If B and D are brick characters, X is supported * If C and D are brick characters, X is supported * If X is a brick character, it has to be supported; otherwise the structure is unstable It's a lucky coincidence that all brick characters `[_]` have their LSB set; all other characters `.\n` have it clear. In addition, the 80386 instruction set has these handy "high" and "low" registers (`ah`, `al`, etc), which help parallelize the checks a bit. So all the checking amounts to some obscure bit fiddling. I started from the following C code: ``` int check(const char* ptr) { int width, result = 0, pos; width = strchr(ptr, '\n') - ptr + 1; pos = strlen(ptr) - 1 - width; // pos points to the B character ptr += pos - width; while (pos >= 0) { int a = ptr[-4]; int c = ptr[-4 + 2 * width]; int b = ptr[0]; int d = ptr[0 + 2 * width]; int ab = a << 8 | b; int cd = c << 8 | d; if (pos < width) ab = 0; // A and B don't exist; set them to 0 int jump = 2; // distance to next brick if (pos % width == 2) // leftmost brick? { cd &= 0xff; // C doesn't exist; set it to 0 ++jump; } int support_v = ab & cd; support_v = support_v | support_v >> 8; // data in LSB int support_h = cd & cd >> 8; // data in LSB int support = (support_v | support_h) & 1; if (!support & ptr[-2 + width]) goto UNSTABLE; ptr -= jump; pos -= jump; } return 1; UNSTABLE: return 0; } ``` I translated the code to assembly language (it's mostly one-to-one), including a golfed implementation of `strchr` and `strlen`. The following source code is translated by MS Visual Studio to the machine code at the top of my post. ``` __declspec(naked) int __fastcall check(const char* ptr) // MS Visual Studio syntax { _asm { pushad; // ecx = ptr mov esi, ecx; // esi = ptr mov edi, ecx mov al, 10; repne scasb; mov ebp, edi; sub ebp, esi; // ebp = width mov al, 0; repne scasb; sub edi, esi; sub edi, 2; sub edi, ebp; // edi = pos jc DONE; add esi, edi; sub esi, ebp; xor ecx, ecx; // ecx = jump LOOP1: mov bh, [esi - 4 + 2 * ebp]; // bh = C mov bl, [esi + 2 * ebp]; // bl = D // bx = CD mov cl, 2; xor edx, edx mov eax, edi div ebp; cmp edx, 2; jne LABEL2; mov bh, 0 inc ecx; LABEL2: mov ah, [esi - 4]; // ah = A mov al, [esi]; // al = B // ax = AB cmp edi, ebp; jge LABEL3; xor eax, eax; LABEL3: and eax, ebx; // ax = support_v or al, ah; // al = support_v and bl, bh; // bl = support_h or eax, ebx; // eax = support test byte ptr[esi - 2 + ebp], 1; jz LABEL4; // not a brick character - nothing to check shr eax, 1; // shift the LSB into the carry flag jnc DONE; LABEL4: sub esi, ecx; sub edi, ecx; jnc LOOP1; DONE: // here, the result is in the carry flag; copy it to eax popad; rcl eax, 1; and eax, 1; ret; } } ``` [Answer] # MATLAB - 119 bytes Minified: ``` function c=S(B),f=@(m)conv2([(0&B(1,:))+46;B]+3,m,'valid');M=[2 0;-1 -1;0 2];c=isempty(B)||all(all(f(M)&f(fliplr(M)))); ``` Expanded: ``` function c = isstable( B ) f = @(m) conv2( [(0&B(1,:))+46; B] + 3, m, 'valid' ); M = [2 0;-1 -1;0 2]; c = isempty( B ) || all(all( f( M ) & f(fliplr( M )) )); ``` Sample Usage: ``` S4 = [ '..[__][__]..'; ... '[__][__][__]'; ... '..[__][__]..'; ... '[__]....[__]']; fprintf( 'S4: %d\n', isstable( S4 ) ); S4: 1 U4 = [ '..[__][__]..'; ... '[__]....[__]'; ... '..[__][__]..'; ... '[__]....[__]']; fprintf( 'U4: %d\n', isstable( U4 ) ); U4: 0 ``` ### Details The routine appends a row of `.` to the top of the input matrix, then converts to a numeric matrix by adding 3 to the ASCII character codes. Given this conversion, a 2D convolution with the kernel ``` 2 0 -1 -1 0 2 ``` yields a matrix with `0` at locations where the character pattern ``` . * _ _ * . ``` is present, with `*` representing "any character". Because of the construction of the kernel, this is the only valid character pattern that will yield a `0`. An identical convolution is performed with the left-right flipped version of the kernel to detect ``` * . _ _ . * ``` An input is stable if either *i*) it is empty, or *ii*) no zeros appear in either convolution. Two frustrations are 1. MATLAB's default convolution runs past the edges of the operand matrix, producing erroneous `0`s in opposing corners for both convolutions, requiring `,'valid'` (8 bytes) to be added to `conv2` call to limit the output to the area where the convolution is valid. 2. Handling the empty string case adds 12 bytes. [Answer] # JavaScript (E6) 131 ~~261~~ ``` F=a=> [...a].every((e,p)=> !(d={']':-3,'[':3}[e]) |a[p-r]=='_'&(x=a[p+r]!=' ') |a[p-r+d]=='_'&(y=a[p+r+d]!=' ') |x&y ,r=a.search(/\n/)+1) ``` **Test** in FireFox/FireBug console ``` ;['[__]', ' [__] \n[__][__]', ' [__] \n [__][__] \n [__] ', ' [__][__] \n[__][__][__]\n [__][__] \n[__] [__]', ' [__] \n [__][__][__][__]\n[__][__][__][__] \n [__][__][__][__]\n[__][__][__][__] ', ' [__] [__] \n[__][__][__][__][__]\n [__][__][__][__] \n [__][__][__] \n [__][__] \n [__] '] .forEach(x => console.log(x+'\n'+F(x))) ;[' [__] \n ', ' [__] \n[__] ' ,' [__] \n [__]', ' [__][__] \n[__] [__]\n [__][__] \n[__] [__]', ' [__][__][__][__]\n[__][__][__][__] \n [__][__][__][__]\n[__][__][__][__] ', '[__][__][__][__][__]\n [__][__][__][__] \n [__][__][__] \n [__][__] \n [__] '] .forEach(x => console.log(x+'\n'+F(x))) ``` *Output* ``` [__] true [__] [__][__] true [__] [__][__] [__] true [__][__] [__][__][__] [__][__] [__] [__] true [__] [__][__][__][__] [__][__][__][__] [__][__][__][__] [__][__][__][__] true [__] [__] [__][__][__][__][__] [__][__][__][__] [__][__][__] [__][__] [__] true [__] false [__] [__] false [__] [__] false [__][__] [__] [__] [__][__] [__] [__] false [__][__][__][__] [__][__][__][__] [__][__][__][__] [__][__][__][__] false [__][__][__][__][__] [__][__][__][__] [__][__][__] [__][__] [__] false ``` **Ungolfed** ``` F=a=>( a=a.replace(/__/g,'').replace(/ /g,'.'), r=a.search(/\n/)+1, [...a].every((e,p)=> e < '0' || (e ==']' ? // stable right side a[p-r]=='[' & a[p+r]!='.' | a[p-r-1]==']' & a[p+r-1]!='.' | a[p+r]!='.' & a[p+r-1] != '.' : // stable left side a[p-r]==']' & a[p+r]!='.' | a[p-r+1]=='[' & a[p+r+1]!='.' | a[p+r]!='.' & a[p+r+1] != '.' ) ) ) ``` [Answer] **Python 279** I think I am pretty bad in code golf challenges and maybe I use the wrong languages for that :D But I love code that can be easily read :) Btw I would like to see a python code that uses less bytes! ``` def t(b): r=b.split() l=len(r[0]) r=['.'*l]+r for i in range(len(r)-2,0,-1): r[i]+='...' for j in range(l): if(r[i][j]=='['): if(r[i+1][j]<>'_'or(r[i+1][j+3]<>'_'and r[i-1][j]<>'_'))and(r[i+1][j+3]<>'_'or r[i-1][j+3]<>'_'): return False return True ``` Possible examples: ``` A = "..[__][__][__][__]\n\ [__][__][__][__]..\n\ ..[__][__][__][__]\n\ [__][__][__][__].." print t(A) #False B = "..[__]........[__]..\n\ [__][__][__][__][__]\n\ ..[__][__][__][__]..\n\ ....[__][__][__]....\n\ ......[__][__]......\n\ ........[__]........" print t(B) #True ``` [Answer] # JavaScript 2 (ES6) - 148 151 bytes ``` F=s=>s.split(/\n/).every((b,i,a)=>(r=1,b.replace(/]/g,(m,o)=>(T=z=>(a[i-1+(z&2)]||[])[o-z%2*3]=='_',r&=i>a.length-2?1:T(2)?T(3)|T(0):T(3)&T(1))),r)) ``` Exepects a string of newline separated brick rows (note: if we could use a different separator character like "|" to separate rows this could be made 1 byte shorter). Test in Firefox console with: ``` F('..[__]......\n[__][__][__]\n..[__][__]..\n[__]....[__]'); // false F('..[__][__]..\n[__][__][__]\n..[__][__]..\n[__]....[__]'); // true ``` [Answer] # Python, 209 ``` def s(b): c=b.split("\n");s="".join(c);l=len(c[0]);t=" "*l+s+"]]"*l;a=lambda x,y,z:t[x+l*y+z]=="]" return all([(a(i,1,1)&a(i,1,5))or(a(i,-1,1)&a(i,1,1))or(a(i,-1,5)&a(i,1,5))for i,x in enumerate(t)if x=="["]) ``` Tests: ``` towers=( "[__]", "..[__]..\n" "[__][__]", "........[__]........\n" "......[__][__]......\n" "........[__]........", "..[__][__]..\n" "[__][__][__]\n" "..[__][__]..\n" "[__]....[__]", "............[__]..\n" "..[__][__][__][__]\n" "[__][__][__][__]..\n" "..[__][__][__][__]\n" "[__][__][__][__]..", "..[__]........[__]..\n" "[__][__][__][__][__]\n" "..[__][__][__][__]..\n" "....[__][__][__]....\n" "......[__][__]......\n" "........[__]........", "..[__]..\n" "........", "..[__]..\n" "[__]....", "..[__]..\n" "....[__]", "..[__][__]..\n" "[__]....[__]\n" "..[__][__]..\n" "[__]....[__]", "..[__][__][__][__]\n" "[__][__][__][__]..\n" "..[__][__][__][__]\n" "[__][__][__][__]..", "[__][__][__][__][__]\n" "..[__][__][__][__]..\n" "....[__][__][__]....\n" "......[__][__]......\n" "........[__]........", ) [s(x) for x in towers] ``` Output: ``` [True, True, True, True, True, True, False, False, False, False, False, False] ``` ]
[Question] [ [Wireworld](http://en.wikipedia.org/wiki/Wireworld) is a cellular automaton that was designed to be resemble electrons flowing through wires. Its simple mechanics allow the construction of digital circuits. It has even permitted the construction of an [entire computer](http://www.quinapalus.com/wi-index.html). Your mission is to create the shortest Wireworld implementation in your language of choice. Each cell in the grid has one out of four states. The four states are "blank," "copper," "electron head," or "electron tail." * A blank cell will always remain a blank cell * An electron head will always become an electron tail * An electron tail will always become copper * A copper cell will become an electron head iff exactly one or two out of its eight neighbors are electron heads, otherwise it will remain copper This competition will have a similar style to the [Shortest Game of Life](https://codegolf.stackexchange.com/questions/3434/shortest-game-of-life) competition, but with a few changes. * The grid must be at least 40 by 40 cells * The edges of the grid must NOT wrap around (not a torus). Treat cells outside of the field as being constantly "blank." * It must be possible for the users to enter their own starting configuration. * Staring at blank screens is not fun. The program must visually display the simulation as it is running. This is code golf, fewest bytes wins. [Answer] ## APL, Dyalog (131) ``` {h t cโ†1โ†“โตโˆ˜=ยจFโ†' htc'โ‹„โŽ•SMโˆ˜โ†1 1,โจโŠ‚Nโ†F[1+โŠƒ+/H h(tโˆจcโ‰ Hโ†cโˆงSโ†‘1 1โ†“1 2โˆŠโจโŠƒ+/+/Kโˆ˜.โŠ–(Kโ†2-โณ3)โˆ˜.โŒฝโŠ‚ยฏ1โŒฝยฏ1โŠ–hโ†‘โจ2+Sโ†25 79)ร—ยจโณ3]โ‹„โˆ‡NโŠฃโŽ•DLรท4}โ†‘{79โ†‘โž}ยจโณ25 ``` The output is displayed in the `โŽ•SM` window. The simulation runs endlessly. The grid is 79x25 because that's the default size of the `โŽ•SM` window. The electron head is `h`, tail is `t`, copper is `c`. The program reads the starting configuration from the keyboard as 25 lines. Explanation: * `โ†‘{79โ†‘โž}ยจโณ25`: read the 79x25 grid * `h t cโ†1โ†“โตโˆ˜=ยจFโ†' htc'`: get three matrices, one with the heads, one with the tails and one with the copper. Also set F to the string `' htc'`. * `โŽ•SMโˆ˜โ†1 1,โจโŠ‚Nโ†F[1+โŠƒ+/`...`ร—ยจโณ3]`: The "..." part is a vector of length three, where the elements are matrices showing the new heads, tails, and copper respectively. The heads are multiplied by 1, the tails by 2, and the copper by 3, then we sum these matrices together and add one, giving a matrix of indices into `F`. `N` becomes the new state, in the same format as the input, and it is shown on the `โŽ•SM` screen starting from the top-left corner. * `ยฏ1โŒฝยฏ1โŠ–hโ†‘โจ2+Sโ†25 79`: Add a border of blanks to `h` by growing it by two rows and columns, then rotating it one right and one down. * `โŠƒ+/+/Kโˆ˜.โŠ–(Kโ†2-โณ3)โˆ˜.โŒฝโŠ‚`: Rotate the matrix in all eight directions and then sum the resulting matrices together, giving the amount of neighbours that are heads on each position. * `1 2โˆŠโจ`: Set only those positions to 1 which have 1 or 2 neighbours. * `Sโ†‘1 1โ†“`: Remove the border we added earlier. * `Hโ†cโˆง`: The new heads are all those copper cells that have 1 or 2 head neighbours. * `tโˆจcโ‰ H`: The new copper cells are all old tails, and all old copper cells that have not become heads. * `H h(`...`)`: The new heads are `H` as calculated above, the new tails are the old heads, and the new copper cells are as calculated above. * `โˆ‡NโŠฃโŽ•DLรท4`: Wait 1/4th of a second, then run the function again on `N`. [Answer] ## ALPACA, 82 chars ALPACA is a language specifically designed for cellular automatons. o is nothing; c is conductor; e is electron; t is electron tail. ``` state o " "; state c "c" to e when 1 e or 2 e; state e "e" to t; state t "t" to c. ``` [Answer] ## GolfScript (125 120 105 100 chars) ``` n%{.,,{1${.0=,:w[1,*]\+2*>3<}:^~`{zip^''+.4=5%'`X '@{+}*(7&1>'iX'>+=}+w,%}%"\033[H\033[J"@n*+puts 6.?.?}do ``` Note that I'm counting the `\033` as one character each, because they can be replaced by a literal `ESC` character. This uses ANSI control codes, so relies on a compatible tty. Also note that frames are printed starting with the input grid. There is some overlap with [Generate a grid of sums](https://codegolf.stackexchange.com/q/12430/194), which also uses the Moore neighbourhood. Encoding: blank space => ; electron head => `i`; electron tail => ```; copper => `X`. The pause between iterations is the time required to calculate 4665646656. Changing `6.?.?` to another expression allows you to control the speed; the next slowest for the same character count is `7.?.?`, which is *much* slower (the output is 22 times as big, and it's not a linear complexity calculation). For a test case, I've been using ``` `iXXXXXXXXX X X XXX X X i`XX XXXXXX ``` from the Rosetta Code [Wireworld](http://rosettacode.org/wiki/Wireworld) challenge. [Answer] # Python 371 341 chars Yeah, it's not that short, but it has an interactive gui! ``` import matplotlib.pylab as l,scipy.ndimage as i r=round w=l.zeros((40,40),int)-1 p=l.matshow(w,vmax=2) c=p.figure.canvas def h(e): try:w[r(e.ydata),r(e.xdata)]=[0,2,-1][e.button-1] except:x=i.convolve(w==2,l.ones((3,3)),int,'constant');w[:]=w/2+((w==0)&(x>0)&(x<3))*2 p.set_data(w);c.draw() c.mpl_connect('button_press_event',h) l.show() ``` Instructions: Click with left mouse button to place wire Click with right mouse button to clear Click with middle mouse button to place electron head Click outside the axes to step the automaton [Answer] ## Python (~~243~~ 214) Tried to make a cross between usability and characters. The grid is 40x40. Input is given on stdin. An electron head is `h`, electron tail is `t`, copper is `c`, anything else is blank. ``` import os f=raw_input() while 1:f=''.join('h'if(i=='c')&(0<sum(1 for i in[-1,1,-39,-40,-41,39,40,41]if f[e+i:e+i+1]=='h')<3)else't'if i=='h'else'c'if i=='t'else f[e]for e,i in enumerate(f));os.system('cls');print f ``` The while loop (line 3) uncompressed (will not work if placed in code): ``` while 1: for e,i in enumerate(f): if(i=='c')&(0<sum(1 for i in[-1,1,-39,-40,-41,39,40,41]if f[e+i:e+i+1]=='h')<3):f[e]='h' elif i=='h':f[e]='t' elif i=='t':f[e]='c' else:f[e]=f[e] #redundant, but Python needs this to run os.system('cls') #cls is shorter than clear, so I used that print f ``` [Answer] # C, 355 347 300 294 chars Edit: realized I don't need `feof()` Edit: Saved 47 chars! Removed the Sleep, got rid of almost all braces, combined a lot of operations. Edit: Last one today, since I broke 300 chars. Changed `printf` to `puts`, found a cute little optimization with the first comparison. C does not lend itself well to this sort of problem, but hey, golfing it is fun. This is a pretty brute-force implementation, but I wanted to see how far I could golf it up. Input is a text file named `i`. It contains a representation of the starting state, with `*` for copper, `+` for electron head, `-` for electron tail, spaces for empty cells. I'm using the XOR gate from the wiki page for testing. ``` ****-+** + ****** -******* * **** * ***** **** ******** * + ****** -****+-* ``` --- ``` char*p,t[42][42],s[42][42]; main(i,r,c,n,j) { for(p=fopen("i","r");fgets(s[i++]+1,40,p);); for(;;getch(),memcpy(s,t,1764)) for(j=1;j<41;puts(s[j++]+1)) for(i=1;i<41;) { p=t[j]+i; r=s[j][i++]; *p=r==43?45:r; if(r==45) *p=42; if(r==42) for(r=-1,n=0;r<2;++r,*p=n&&n<3?43:42) for(c=-2;c<1;) n+=s[j+r][i+c++]==43; } } ``` [Answer] ## Python, 234 218 chars ``` import time I=input C=I() H=I() T=I() R=range(40) while 1: for y in R:print''.join(' CHT'[(C+H+2*T).count(x+y*1j)]for x in R) H,T=[c for c in C if 0<sum(1 for h in H if abs(c-h)<2)<3and c not in H+T],H;time.sleep(.1) ``` You input the board as three list of complex numbers representing the coordinates of the cells of copper (which must include the heads and tails lists), heads, and tails. Here's an example: ``` [3+2j+x for x in range(8)] + [3+4j+x for x in range(8)] + [11+3j+x for x in range(6)] + [2+3j] [3+2j] [2+3j] ``` Note that we `eval` the input, so you can use arbitrarily complex expressions for lists of complex numbers. [Answer] ## QBasic, 309 bytes **Warning:** the golfed version is not user-friendly: it has a weird input method, runs as an infinite loop, and doesn't have any delay (thus, runs too fast on some systems). Only run it if you know how to terminate a program in your QBasic environment. The ungolfed version is recommended (see below). ``` INPUT w,h SCREEN 9 FOR y=1TO h FOR x=1TO w PSET(x,y),VAL(INPUT$(1)) NEXT NEXT DO FOR y=1TO h FOR x=1TO w SCREEN,,0 c=POINT(x,y) d=c IF c=7THEN d=1 IF c=1THEN d=6 IF c=6THEN n=0 FOR v=y-1TO y+1 FOR u=x-1TO x+1 n=n-(POINT(u,v)=7) NEXT NEXT d=7+(n=0OR n>2) END IF SCREEN,,1,0 PSET(x,y),d NEXT NEXT PCOPY 1,0 LOOP ``` To run, specify at the input prompt your configuration's width `w` and height `h`.1 Then type `w*h` single-digit codes for the cells (moving left to right, then top to bottom), with * `0` = empty * `6` = wire * `7` = signal head * `1` = signal tail Once you have entered all of the cells, the simulation will begin (and continue forever, until you kill the program). ### Ungolfed A more user-friendly version. To modify the layout, modify the `DATA` statements at the end. The code takes advantage of the `POINT` function, which reads the color value of a pixel from the screen. This means we don't have to store the cells separately as an array. To make sure that all cells update simultaneously, we perform the updates on a second "page." We can toggle the active page using a version of the `SCREEN` statement, and copy one page's contents to another using the `PCOPY` statement. ``` SCREEN 9 EMPTY = 0 ' Black HEAD = 7 ' Light gray TAIL = 1 ' Blue WIRE = 6 ' Brown/orange ' First two data values are the width and height READ w, h ' The rest are the initial configuration, row by row ' Read them and plot the appropriately colored pixels FOR y = 1 TO h FOR x = 1 TO w READ state$ IF state$ = "" THEN value = EMPTY IF state$ = "H" THEN value = HEAD IF state$ = "T" THEN value = TAIL IF state$ = "W" THEN value = WIRE PSET (x, y), value NEXT x NEXT y ' Loop the simulation until user presses a key DO UNTIL INKEY$ <> "" ' Store current time for delay purposes t# = TIMER FOR y = 1 TO h FOR x = 1 TO w ' Active page = display page = 0 SCREEN , , 0 ' Get the color value of the pixel at x,y oldVal = POINT(x, y) IF oldVal = EMPTY THEN newVal = EMPTY ELSEIF oldVal = HEAD THEN newVal = TAIL ELSEIF oldVal = TAIL THEN newVal = WIRE ELSEIF oldVal = WIRE THEN neighbors = 0 FOR ny = y - 1 TO y + 1 FOR nx = x - 1 TO x + 1 IF POINT(nx, ny) = HEAD THEN neighbors = neighbors + 1 NEXT nx NEXT ny IF neighbors = 1 OR neighbors = 2 THEN newVal = HEAD ELSE newVal = WIRE END IF END IF ' Active page = 1, display page = 0 SCREEN , , 1, 0 ' Plot the new value on page 1 PSET (x, y), newVal NEXT x NEXT y ' Copy page 1 to page 0 PCOPY 1, 0 ' Delay WHILE TIMER >= t# AND t# + 0.2 > TIMER WEND LOOP DATA 8,5 DATA T,H,W,W,W,W,W,W DATA W, , , ,W, , , DATA , , ,W,W,W, , DATA W, , , ,W, , , DATA H,T,W,W, ,W,W,W ``` 1 The maximum values for width and height depend on which screen mode is used. In `SCREEN 9`, width can be up to 638 and height up to 348. `SCREEN 7` has a smaller resolution (max configuration size 318 by 198), but the pixels are bigger and thus easier to see (on DOS QBasic or the DOSBox emulator--unfortunately QB64 just gives a smaller window). ### Example run Ungolfed version on [archive.org](https://archive.org/details/msdos_qbasic_megapack), with screen mode 7: [![Wireworld in QBasic](https://i.stack.imgur.com/YTlCx.gif)](https://i.stack.imgur.com/YTlCx.gif) ]
[Question] [ **Setup:** For two sets \$A,B\$, we say \$A \subseteq B\$ if every element in \$A\$ is also in \$B\$. Another way of saying this, is that we can order the elements of \$A,B\$ into two lists \$L\_A,L\_B\$, such that \$L\_A[i] = L\_B[i]\$ where \$i\$ ranges over the indices of \$L\_A\$. We proceed to extend this idea, to define the relation \$\preceq\$. For two sets of sets, \$A,B\$, we say that \$A\preceq B\$ if we can arrange their elements into lists \$L\_A,L\_B\$, such that \$L\_A[i]\subseteq L\_B[i]\$ for all indices of \$L\_A\$. **Task:** Make a program/function which takes two sets of sets, `A,B`, determines if `A โชฏ B` as defined in the set up, and then appropriately returns Truthy or Falsy. **Input:** You may give `A` and `B` to your input as sets. It is up to you how you wish have your function take `A` and `B`, be it separately, as a tuple, etc. If you so choose, or if your language forces your hand, you can enter your input as lists, frozen sets or even submit elements one by one. Likewise, you may choose the datatype to represent the sets inside `A` and `B`. For simplicity's sake, one may assume the elements of the sets in `A` and `B` are all integers. **Output:** You can define whatever conditions you want to indicate your Truthy and Falsy inputs, as long as these conditions are independent of the output. (e.g. you can say "if my program never halts, this means Falsy") **Examples**, with (1,0) indicating (Truthy, Falsy) respectively ``` A = {{4004,1}}, B = {{4},{4004,1}} => 1 # L_A = [{4004,1}], L_B = [{4004,1},{4}] A = {{1,2},{5},{8}}, B = {{3,5},{6},{8},{7}} => 0 # {1,2} is not a subset of any set in B A = {{4,44},{44,444},{4}}, B = {{4,44,444},{4,14},{4,40,44}} => 1 # L_A = [{4,44},{44,444},{4}], L_B = [{4,40,44},{4,44,444},{4,14}] A = {{1,2,4},{6}}, B = {{1,2},{4},{6}} => 0 # {1,2,4} is not the subset of a single set in B, only the union of B A = {{1},{1,2},{2}}, B = {{1,3},{2,3},{1,2}} => 1 # L_A = [{1},{1,2},{2}], L_B = [{1,3},{1,2},{2,3}] A = {{-1},{8},{}}, B = {{-1,8,2},{8,-1,0}} => 0 # There are three elements in A, but only 2 in B, so the last item in L_A will not # be paired with a superset, even for the empty set, {}. (vacuity be damned) A = {{-1},{8},{}}, B = {{0,8},{9,-1},{100}} => 1 # L_A = [{-1},{8},{}], B =[{0,8},{9,-1},{100}] A = {{1,2}{3,4}}, B = {{1,2,3,4},{}} => 0 # {1,2} and {3,4} are each subsets of {1,2,3,4}, and are not subsets of any other # set in B, thus in the list, one of these will not be paired with their superset ``` [Answer] # Python 3, ~~84~~ ~~62~~ 58 bytes Recursive function, `A` is a list of sets and `B` is a `frozenset`; returns false if \$A\preceq B\$ and true otherwise. ``` f=lambda A,B:A and all(A[0]-b or f(A[1:],B-{b})for b in B) ``` @PoonLevi and @SurculoseSputum helped save a great amount of bytes. Explanation: If `A` and `B` satisfy the relationship described, then this recursive statement makes sense: ``` The first set in A is contained in some i-th element of B and A', B' also satisfy the relationship, where A' is A without the first set B' is B without the said i-th element ``` Because I am returning the reverse, I am actually ensuring that, if the first element of `A` is contained in some element of `B`, then `A'` and `B'` cannot satisfy the relationship. [Try it online](https://tio.run/##ZVHRaoQwEHy/r1juKYEVkjNtrWBBf0OkaE@pYFVshLaSb7fZRK@We9CdnZ2dXd3xW78PfbiuTdKVH9W1hBSzOIWyv0LZdSzNRRFUMEzQWCzjArNgqQxvLFNB20PGV8IaYUaov8b6TRPNTsDyRQmhUJoCwWKDh1xydAqJF8s/2CfyshApeXQELk9Eik2rUDkTig5sxvjHoPRBCdL@n4PKGbseP/ZG7BOkJXzpsutCStybCgfHQPodP2vNuBMHEiPXHKGF4mh8LxZI3/eMriKFuP8pIarbshi67XdLHp@gmYafun@dIQFyzX1OsOVAJ2npDnPBTzBOba9Zc160QVj2RgPJi82YPd1OcQNsu@HiY5IIw898/QU)! [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-e`](https://codegolf.meta.stackexchange.com/a/14339/), ~~15~~ ~~13~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Vcร  mรdeUn ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWU&code=VmPgIG3NZGVVbg&input=W1sxLDJdLFs1XSxbOF1dCltbMyw1XSxbNl0sWzhdLFs3XV0) [Answer] # [J](http://jsoftware.com/), 32 bytes ``` #@[e.[:#@~.@>@,@{[:<@I.0=#@-.&>/ ``` [Try it online!](https://tio.run/##VU/BasMwDL3nKx4LLCm0nhSrnRc1xTAYDHraNYceRsvYZR8w2K9nUtIVD2xZ0ntPfvqc7kJzwdCjwRqE3u4m4Pnt@DLVeTyHsa/zT8iHvM7fY7/Pr4GGOm/C/eFhWlXV@f3jyyQDWtZO4woXsM4HHWIBC5Ggs/5CmUtecHZ8v3QclSuKm7y1abrV5GjEVnea9PEmbgViGo/2zBPwV4E9CFlVejVzorvZik22tHDC6r1uAaPaGt4o1Ce275vGCSdGMnLyhIoZBYWQ9MlwZaL/FjRCrhZsKzF@VU2/ "J โ€“ Try It Online") Left arg is A, right is B. * `#@[` Is the len of A?... * `e.` an element of?... * `[:#@~.@>@,@{` any of the lengths, after deduping, of the cartesian product of... * `[:<@I.` the indexes with value 1 in each row of the matrix defined by... * `0=` elements that equal zero of... * `#@-.&>/` the function table `/` (like a multiplication table) defined by "the length after set substraction", i.e., whose `(i,j)` element is the length of the j-th element of B set subtracted from the i-th element of A. [Answer] # [Python 3](https://docs.python.org/3/), ~~110~~ 107 bytes Simply try to match A with all permutations of B. Take input as 2 lists of sets, and output False if \$A \preceq B\$, and True otherwise. (Note that the truthiness is reversed). ``` lambda A,B:len(A)>len(B)or all(any(a-b for a,b in zip(A,P))for P in permutations(B)) from itertools import* ``` [Try it online!](https://tio.run/##ZVDLbsMgELz7K1Y@QbWJIKZtGsmRki/Iobc0B6zYChJ@CJNWKfK3u4DzqNqDWWZ2ZnZNd7GntsnGKv8YtayLo4QNble6bMiGrkPZ0taA1JrI5kLkrIAqYCxANfCtOrLBHaWB2wWmK019ttKqtum9lSaVaWtQtjS2bXUPqu5aY5/Gr5PSJbybc7lKoEcDuXd3Z0vovO@0siSFfA0pTeKoHMpPqUnvYWdUY0mVOjkguGIIMlcRr6ID7J2Z99b4rehwSOm4d4IxgXw4oO@JAe842HiydxwXnn3233ISZRjASyTQvU5K5pUCRQwINV6uofhgkE9FsKD9PQNFDI2OaeSVuKVzD6fG4qbKAohnaNzTZnzarS/9Y0XpjOMyWpfor@wR@l/KMPzVG8YOZ@zvQ2Qo7ktiAFdvTPwB "Python 3 โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` fฦ‘"แบ ยฅโฑฎล’!}แบธa,Lรžฦ‘ยฅ ``` [Try it online!](https://tio.run/##y0rNyan8/z/t2ESlh7sWHFr6aOO6o5MUax/u2pGo43N43rGJh5b@f7hzn/WjhjkKunYKjxrmWh9ers91uP1R05rI//@juaKjo00MDEx0DGNjdYBMIAHjxuqAJA11jIBipkBsAVZhrANim4H5OtHmMGUmOiZgvSAazIAYp4MQ0DGEUCYGIKUI03VMwOaBlEPsgvKhCoAciLARVIkxiA0mQeJQZbqGUAdZglXpGupYgDVZ6ACZBhiqwIoMdMAadMCihgYGqD421jGBuUnHGOxGuFdB4QNSAgkyQ@Qg44oFAA "Jelly โ€“ Try It Online") A dyadic link taking `A` as its left argument and `B` as its right. Returns `1` for true and `0` for false. Added 6 bytes to more correctly handle the situation when the length of A is more than the length of B. The previous test case worked only because the extra set was empty. ## Explanation ``` ยฅโฑฎล’!} | Using each permutation of B in turn as the right argument: fฦ‘" | - Check whether A is invariant when filtered pairwise to that permutation of B แบ  | - All true แบธ | Any true a ยฅ | And the following is true for the original arguments: , | - Pair Lรžฦ‘ | - Invariant when sorted by length ``` [Answer] # [Julia 1.0](http://julialang.org/), 61 bytes ``` f(a,b)=a==[]||any(a[1]โІx&&f(a[2:end],setdiff(b,x)) for x=b) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P00jUSdJ0zbR1jY6tqYmMa9SIzHaMPZRV1uFmhpQLtrIKjUvJVanOLUkJTMtTSNJp0JTUyEtv0ihwjZJ839BUWZeSU6eRppGdLSJgYGJjmFsrA6QCSRgXE1NLmRVhjpGQElTILYAKzXWAbHNwHydaHOQ@v8A "Julia 1.0 โ€“ Try It Online") [Answer] # JavaScript (ES6), ~~79~~ 77 bytes Takes input as `(B)(A)`, where \$B\$ is a list of sets and \$A\$ is a list of lists. Returns a falsy value (*false* or *undefined*) if \$A\preceq B\$, or *true* otherwise. ``` B=>g=([a,...A],u)=>a&&B.every((b,i)=>u>>i&1|a.some(v=>!b.has(v))|g(A,u|1<<i)) ``` [Try it online!](https://tio.run/##jZLfboIwFMbv9xTshrTJobaAyhIh0VfYZdOL6irDOFhEWJbw7qwVzKhRhJSkX/@c3/l6zkHWstydsu@zlxcfqt3H7SZO0hhxCYSQtYAKx4l03Q1RtTr9IrSFTK9USZK5rJGkLL4UquPkdUs@ZYlqjJsUraFq2GqVYdzuirwsjoocixTtEc/Vj/OuzoiHAsO/oDQEJrDAiF@FwNiZ8s1mDnt5RAlgPuQshiIaimUPZ@AL4HP9R1YGmkIfUkIIzbAtAbvRIQVzpPNopsD7a3rSwUa9mNSGAW@MXdMHE28x9nyjXhgEw8C@LS85dCRN6R7Lv88a9eIxiGw7Eeg12gf32KUAwJ92wagXClaN3zTCMkOn8p7VBQKwymE1k9mb1MzGS/sH "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` โŠžฯ…๏ผก๏ผฆฯ…ยซโ‰”โŠŸฮนฮธโ‰”โŠŸฮนฮนยฌฮน๏ผฆฮน๏ผฆฮธยฟยฌโปฮบฮปโŠžฯ…โŸฆโปฮนโŸฆฮบโŸงโปฮธโŸฆฮป ``` [Try it online!](https://tio.run/##XY2xDoMwDETn8hUebSkdoGOnjh1aZUcZEBLFIkqAEJaq3546QV3q4Xz3LJ37sVt739mUdAwjRgV3N8cNia7V4FfASPCuTrcQ@OVQ@xmZFCxy/WecmV7Zbfj0m6CcSwUTlL0Q8ADl@mAXA04KLBHB73V7YBY3Gak84iLRGjLS90mplamNamvViDZGRPwl@6KZy6Tzbr8 "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes input as a list of list of lists and outputs nothing if `A` is not a subset of `B`, otherwise the number of ways it found to verify that `A` is a subset of `B` as a string of `-`s (would be +1 byte to output just a single `-`). Explanation: ``` โŠžฯ…๏ผก๏ผฆฯ…ยซ ``` Perform a breadth-first search starting with the original input. ``` โ‰”โŠŸฮนฮธโ‰”โŠŸฮนฮน ``` Extract the latest pair of sets to check. ``` ยฌฮน ``` If `A` is (now) empty then it is a subset of `B`. ``` ๏ผฆฮน๏ผฆฮธยฟยฌโปฮบฮป ``` Find all pairs of sets in `A` and `B` such that one is a subset of the other. ``` โŠžฯ…โŸฆโปฮนโŸฆฮบโŸงโปฮธโŸฆฮป ``` For each such pair, add the sets with those elements removed to the search. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~60~~ 45 bytes ``` ->a,b{a.all?{|x|b.any?{|y|f[a-[x&y],b-[y]]}}} ``` [Try it online!](https://tio.run/##dY@7DsIwDEV3voKJ6aZKmgBlAD4kypAMnSqEkJAatf324Dh9ICSG2Nf28SOvd4ipvSZx8wiDr3zX3YexH0PlH5FUHFvrhe0P0SEIG52bpik996211khpoJwDSTJL6HalrFBT9kivYUYj6xPHsOcNNDDcnz2LMhJbAqo4IzP6vQGGZ@aGsm@OV4TCUqhnSGfNNudXUKj5MMaEQsNdDUjKf5hElhdwVkn5@3kNs5wGzacSkT4 "Ruby โ€“ Try It Online") ### How: Recursively check: for every `x` in `a` ``` ->a,b{a.all?{|x| } ``` there is at least a `y` in `b` ``` b.any?{|y| } ``` Such that removing `xโ‹‚y` from `a` and `y` from `b`, the condition is still valid. ``` f[a-[x&y],b-[y]] ``` ## Sorry, what? A and B are sets of sets. If A is empty, the function returns true. If B is empty and A is not empty, then the function returns false. So far, so good. Otherwise, let's check what happens if we remove the sets as specified: * if xโІy then xโ‹‚y==x. We remove x from A and y from B, then check if the remaining sets satisfy the initial condition recursively, until A or B is empty. * if xโŠ„y but xโ‹‚y is contained in A, we remove it anyway. We will check the same x again on a different y in the next iteration. We need to remove an item from A and B, we are just removing them in a different order, and that won't affect the final result. * if xโŠ„y and xโ‹‚y is not contained in A, we can continue: x won't be removed in the next iterations, and the check will fail as soon as B is empty. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes Outputs 0 if AโชฏB, a positive integer otherwise. ``` ฮดKรธล“ฮตร…/หœg}รŸ ``` [Try it online!](https://tio.run/##ZZBBCsIwEEWvUrr@xaSJWlc9gEcoBRVEXLkQhC5c6gF0K3gJBffFldBDeJE4M0lbpIEkMz9vJjOz2y9X27U7VHkcfc@XKM6rhWse8/r1vjbP@jT63DbH@u7gClpWKQtdliCTjtYtEdGjRkramHYmhAHbE/FRTFvMwkos32L4dOgFaH9ZxWifHVbyMe7/Cn4AyPFyGhDDtpysByzRoaCZUIlGJkEZyFQDSiAFCYCoWqn/jg1sWxOM1Ni1yvNhxI9MD0cm1VKK7j10QVXT@gE "05AB1E โ€“ Try It Online") ]
[Question] [ # Background The [Look and Say Sequence](https://en.wikipedia.org/wiki/Look-and-say_sequence) is built up by reading off the digits of previous entries in the sequence, counting the number of digits in groups of the same digit. For example: ``` 1 => 11 # (one 1) 11 => 21 # (two 1s) 21 => 1211 # (one 2, then one 1) 1211 => 111221 # (one 1, then one 2, then two 1s) ``` This sequence was the subject of various [previous](https://codegolf.stackexchange.com/questions/70837/say-what-you-see) [challenges](https://codegolf.stackexchange.com/questions/41974/look-and-say-conway-revisited). A simple Python 3 implementation of the generating function is: ``` >> from itertools import groupby >> def look_and_say(obj): return "".join(f"{len(list(group))}{digit}" for digit, group in groupby(str(obj))) ``` [Try it online!](https://tio.run/##VY3BCoMwEETvfsWSUwKlkPbWnxHFxK6Nu2GzHoL47SqWHjqngWHey1XfTM99j8IzoAZR5lQA58yiMAovua/NECIk5k/b0dCWrlruJ/dq4IwEXYTAmPvESDaaNQWyCYva6@3ctg44om4GIgtc/fYlA9JPYYvKRXVuz4Kk9s9n/MN7b87xAA "Python 3 โ€“ Try It Online") # Challenge The purpose of this challenge is to implement an inverse Look and Say function. **Given a Look and Say representation of a non-negative integer, your code should return the *smallest* non-negative integer for which the input is its Look and Say**. Note that this is not the same as general [Run Length Decoding](https://codegolf.stackexchange.com/questions/12902/run-length-decoding), since the output must encode back *precisely* to the input: see the examples below for some of the subtleties involved. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins, with all the standard loopholes forbidden. Input can be passed in (or returned) as either an integer or a string. # Test cases ``` 10 => 0 # (1 zero) 12 => 2 # (1 two) 123 => 333333333333 # (12 threes) 1234 => 2444 # (1 two, 3 fours) 1232 => 222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222 # (123 twos, since 2222 would return 42 not 1232) 2019 => 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 # (201 nines, since the only non-negative starting with 0 is 0) 2109 => 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 # (210 nines, since 11 would return 21 not 2109) 123456 => 244466666 123454 => 333333333333444444444444444444444444444444444444444444444 # (12 threes, 45 fours) 124234 => 2222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222444 (124 twos, 3 fours, which is smaller than the alternatives) ``` # Invalid inputs Since there are no integers which have the following Look and Say representations, the behaviour for these inputs is undefined: ``` 1 3 20 100 1010 10010 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` โˆž<ร…ฮ”ร…ฮณs.ฮนJQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8m8Ot56YA8eZivXM7vQL//zc0MjYBAA "05AB1E โ€“ Try It Online") Computes the look and say of all integers until finding one that matches the input. Will timeout for large outputs. [Answer] # JavaScript (ES6), 111 bytes ``` f=([x,y,...s],p,o=O='',m='')=>x?y?f([y,...s],p,o,m+=x,+m&&y^p&&f(s,y,o+y.repeat(m))):O||0:!O||O[o.length]?O=o:0 ``` [Try it online!](https://tio.run/##lZDBioMwEIbv@xRuD5pgmsY0FRSyPoIPECxIN9oWNVKlKPTd3dhVNm3tYf/DwPB9GWZyTq9pc7ic6nZdqW85DBkHokM9whg3CaqR4jF3HFTqAvlXF/VRBoSBUenyDrmlbff72rYz0OjHyu3xRdYybUEJIQzj242En7rGQuFCVnl7TKKYq5AMB1U1qpC4UDnIwMojKwitezYbi3w8Y2pi@oq3M9d4a2TBZJM6DmKMLRj0zxC6tTrLoU7yLFLiBYao21EMFkSPPIgeeSOOy@38uzot549Z1Nismdey/@R1LJs/5/dwNh0utJwMPw "JavaScript (Node.js) โ€“ Try It Online") ### Commented ``` f = ( // f is a recursive function taking: [x, y, // x, y = next two characters from the input string ...s], // s[] = array of remaining characters p, // p = previous repeated digit, initially undefined o = // o = current output O = '', // O = shortest output so far m = '' // m = current multiplier, as a string ) => // x ? // if x is defined: y ? // if y is defined: f( // do an unconditional recursive call: [y, ...s], p, o, // where y is put back in the input m += x, // and x is appended to m +m && // if m is not zero'ish y ^ p && // and y is not equal to p: f( // do another recursive call: s, y, // where p is updated to y o + y.repeat(m) // and y is appended to o, m times ) // end of inner recursive call ) // end of outer recursive call : // else: O || 0 // return O, or 0 if it's empty : // else: !O || O[o.length] ? // if O is still empty or o is shorter than O: O = o // update O to o : // else: 0 // do nothing ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` Dล’rUDFโผยณยต1#@0 ``` [Try it online!](https://tio.run/##y0rNyan8/9/l6KSiUBe3R417Dm0@tNVQ2cHg////hjpGOsY6JgA "Jelly โ€“ Try It Online") A full program that takes a list of digits and returns the first number that generates that as its look-and-say. Tries all numbers until one matches so will be slow for some inputs. # Alternatives ## [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` Dล’แน–แนชxแธŒฦŠโ‚ฌF$โ‚ฌแธŒDล’rUฦŠDFโผส‹ฦ‡Dแนขแธข ``` [Try it online!](https://tio.run/##y0rNyan8/9/l6KSHO6c93Lmq4uGOnmNdj5rWuKkACSAHKFMUeqzLxe1R455T3cfaXR7uXPRwx6L/1o8a5ijo2ik8aphrfbid63A7UHnk///RhgY6CoZGIGwMJkzAJFDAyMDQEkgaGlhCxE3NoDRYhQmQFQsA "Jelly โ€“ Try It Online") A monadic link taking an integer. Generates all possible inverse look-and-says (including invalid ones) and then tests them by seeing whether generating a look-and-say results in the input. Returns the smallest valid one. ## [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes ``` ล’แน–UZแธขEฦฒฦแบธ$รแธŸแนชxแธŒฦŠโ‚ฌโ‚ฌแบ ฦ‡Fโ‚ฌแธŒD$ฦ‘ฦ‡แธŒแนขแธข ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7p4VGPdyxyPXYpmNzH@7aoXJ4wsMd8x/uXFXxcEfPsa5HTWuA6OGuBcfa3UCMHT0uKscmHmsHMh7uXATU99/6UcMcBV07hUcNc60Pt3O5HG5XASqM/P8/2tBAR8HQCISNwYQJmAQKGBkYWgJJQwNLiLipGZQGqzABsmIB "Jelly โ€“ Try It Online") A monadic link taking a list of digits. Generates all possible inverse look-and-says (including invalid ones) and then tests them by seeing whether they violate any rules. Returns the smallest valid one. Thanks to @ร˜ranJohansen for pointing out a problem with the last two. [Answer] # [Python 2](https://docs.python.org/2/), ~~200~~ ~~166~~ 165 bytes ``` lambda n:min(int(r)for r in b(n)if str(int(r))==r) b=lambda n:[int(n[:i])*n[i]+v for i in range(1,len(n))for v in b(n[i+1:])if int(n[:i])*(n[i]!=v[:1])]if n else[''] ``` [Try it online!](https://tio.run/##TZDdboQgEIXvfQqavYBRLgTZTSThSSgXmmpL4s5uWGPSp7eM2o2EvznD@QZ4/s4/D9Tr6D7Xqbv3Xx1De48oIs4iwfhILLGIrBcIcWSvOR0ZcC5B0bu3yZOO3sYAJfoYqoWRO5I7dfg9CCWnATNnoy4H1cdK2UDsk5/k8OEWb1WAkHPIhuk1eM7DeiE3klvUUkty8YaXSoPUxphd0CQ0sActL3WtToGq97M3aidCxQ0vzRVODLNpDYAtLuyZcoJNgn4hP6Mo3ldRtVQ694aGoUnLXLOVuVa7adfbvlDS5I0tDtz4j1v/AA "Python 2 โ€“ Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 81 bytes ``` ->n{(0..1/0.0).find{|r|r.to_s.chars.chunk{|w|w}.map{|a,b|[b.size,a]}*''==n.to_s}} ``` [Try it online!](https://tio.run/##JYvRDoIgFEB/pTez0RWqV/oRxhxYLOcihzlR7v121NrOztM5YbRzdjKf7z4dOYCoOPASXOsfCQMG@H7qAZqXCbtH3yWccCJ4mz6hYRaVhaFdnsxoOhWFlP53EGUlOBOXjetN//OI/UFF5lTUmvIK "Ruby โ€“ Try It Online") Brute force approach, could be 5 bytes shorter on a newer version of Ruby, but it doesn't matter because it's slow as hell for most numbers. [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Brute force approach that'll crap out for larger outputs. ``` @ยฅXรฒยฆ ร‹รŽiDlรƒq}as ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QKVY8qYgy85pRGzDcX1hcw&input=MTIzNA) ``` @ยฅXรฒยฆ ร‹รŽiDlรƒq}as :Implicit input of integer U @ :Function taking an integer string X as argument ยฅ : Test U for equality with Xรฒ : Partition X on ยฆ : Inequality ร‹ : Map each D รŽ : First character of D i : Prepend Dl : Length of D รƒ : End map q : Join } :End function a :Return the first integer that returns true when passed through that function s :After converting it to a string ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 67 bytes ``` โŠžฯ…โŸฆ0ฯ‰๏ผณโŸง๏ผฆฯ…ยซโ‰”ยงฮนยฒฮธ๏ผฆโˆจโ€นฮธ1๏ผฌฮธยฟโˆงฮบโปยงฮธฮบยงฮนโฐโŠžฯ…โŸฆยงฮธฮบโบยงฮนยนร—ยงฮธฮบ๏ผฉโ€ฆฮธฮบโœ‚ฮธโŠ•ฮบโŸงยป๏ผฉโŒŠ๏ผฅฮฆฯ…ยฌโŠŸฮน๏ผฉโŠŸฮน ``` [Try it online!](https://tio.run/##ZY9Pa8MwDMXPzacwOcngQdN1p57CYBBo1kB3GzuExE1EHTvxnzIY@@yekrJSNoEOkn7v8dT0tW1MrWKsgushCPaerlPBUupCj8EfvUXdAf/gu@RkLIPA2Veyyp3DTkPuC93KT0DBNlywiaDVQh0s7KVzMJFVltJpL3Xne5g45wxPDHLdwlmwEnVwNxuiz8Teua75LLhl@wNW6k5MdEa7NxzkP8fn2nkojWqvCyrBjgobOc@FbqwcpPaSIvHl0@@korc9XHWocQgDlPUIL6i8tHOWV@OhMiPgYraAvyPVLsZs87h92saHi/oB "Charcoal โ€“ Try It Online") Link is to verbose version of code. Generates all integers with the given look-and-say sequence and outputs the minimum thereof. Explanation: ``` โŠžฯ…โŸฆ0ฯ‰๏ผณโŸง ``` Start by pushing a list of three items to the predefined list. The first item (initially `0`) represents the previous repeated digit (thus preventing the generated number from beginning with `0`), the second item (initially an empty string) represents the integer so far (as a string), while the third item (initially the whole input) represents the remaining input to process. ``` ๏ผฆฯ…ยซ ``` Loop over the list. This automatically iterates over additional items as they are pushed to the list. ``` โ‰”ยงฮนยฒฮธ ``` Get the remaining input into a dedicated variable. This saves several bytes as this variable is used multiple times. It does force me to wrap the block in braces, but this is offset by allowing me to use an `if` to save a byte. ``` ๏ผฆโˆจโ€นฮธ1๏ผฌฮธ ``` Loop over the string, but if it begins with a zero, only loop once (which gets ignored anyway, but this is a byte golfer than not looping at all). ``` ยฟโˆงฮบโปยงฮธฮบยงฮนโฐ ``` Ignore the first character of the string (because there is no number to multiply it by), and also any character equal to the previously processed digit for this entry. ``` โŠžฯ…โŸฆยงฮธฮบโบยงฮนยนร—ยงฮธฮบ๏ผฉโ€ฆฮธฮบโœ‚ฮธโŠ•ฮบโŸง ``` Push the next potential step to the list, comprising the current digit, the integer so far with the current digit repeated the prefix number of times, and the suffix. ``` ยป๏ผฉโŒŠ๏ผฅฮฆฯ…ยฌโŠŸฮน๏ผฉโŠŸฮน ``` After all possible steps have been processed, filter those that consumed the input exactly, and output the smallest resulting value. ]
[Question] [ You are on a plane filled with boxes, and you get a sequence of movements, say "up right right down left": ![](https://cdn.discordapp.com/attachments/556906122183704596/1067645692346122391/render_2023-01-25_03.22.48.gif) You move up, pushing all boxes in front of you away: ![](https://cdn.discordapp.com/attachments/556906122183704596/1067646017660518500/render_2023-01-25_03.24.06.gif) You move right, right and down, getting ![](https://cdn.discordapp.com/attachments/556906122183704596/1067646173365678090/render_2023-01-25_03.24.43.gif) and finally left. This time you only push one box rather than infinite boxes: ![](https://cdn.discordapp.com/attachments/556906122183704596/1067646750300581949/render_2023-01-25_03.27.00.gif) At the end, there are 4 spaces. Given a sequence of moves, decide how many spaces are there after these moves. You can take 4 distinct inputs to mean 4 directions. You can also count yourself as space(result +1). Shortest code in each language wins. Test data: ``` R => 1 RD => 2 RL => 1 RDRU => 4 URRDL => 4 UURDLL => 5 DRDDDLUUU => 7 ``` [Answer] # JavaScript (ES6), 94 bytes *-3 bytes thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects an array of `[dx,dy]` pairs, e.g. `[[-1,0],[1,0]]` for `LR`. ``` a=>a.map(([h,v],i)=>a[[X=x,Y=y]]=!(g=_=>~--a[[X+=h,Y+=v]]?i--?g():++n:1)(x+=h,y+=v),n=x=y=0)|n ``` [Try it online!](https://tio.run/##Tc9La4QwFAXgvb8idZVgktHSUrBcZ5PuXAUCHUIoIR0fZarDWETp46/bRIfSuzp852zumx3t4C7t@YN1/etxqWCxUFj@bs8Y64aOhrbEg9bPMNEDzMbADa7hBYofxgIn0NBDAqMx@5axfY1JniRdnhE8hWr2FaEdTDBDSr665VFHCMVSxBRtt9uh25XK/5RtK6mu6OkukJJSXId/pDxt5uk@kJBCiFIpFQd6iEzEq/7yZF2DBwQFcn039KcjP/U1rrDmnA9m/dmFFn@qXKcUscxQJNYYUplrllGU@ihzvaZvop0h/pZf "JavaScript (Node.js) โ€“ Try It Online") ### How? The algorithm used here is pretty straightforward. Whenever we move in a direction \$(dx,dy)\$, we look for the first empty cell along this ray. [![Figure A](https://i.stack.imgur.com/Q0bhs.png)](https://i.stack.imgur.com/Q0bhs.png) If we find one, we mark it as non-empty anymore. [![Figure B](https://i.stack.imgur.com/oMryl.png)](https://i.stack.imgur.com/oMryl.png) Otherwise, we increment the total number of empty cells. In both cases, we mark the cell at our new position as empty. Note that if we move to an empty cell, it will briefly be marked as non-empty and then marked as empty again, which is conceptually silly but functionally correct. In order to make sure that we look far enough, the length of the test ray is simply the number of moves performed so far (including the current one). ### Commented ``` a => // a[] = input array, re-used to store visited cells a.map( // for each ... ([h, v], i) => // ... direction [h, v] at index i in a[]: a[[ // X = x, // initialize (X, Y) to (x, y) Y = y // ]] = // mark this cell as visited (i.e. empty) !( // by setting it to false g = _ => // g is a recursive function ignoring its argument ~--a[ // [ // lookup key of the new position X += h, // defined as (X + h, Y + v) Y += v // ] // we force the state of this cell to non-empty ] ? // if it already was non-empty: i-- ? // if i is not equal to 0 (decrement i afterwards): g() // keep moving along this ray : // else: ++n // increment the number n of empty cells and stop : // else: 1 // stop )( // initial call to g ... x += h, // ... with (x, y) updated to (x + h, y + v) y += v // ), // n = x = y = 0 // start with n = 0 and (x, y) = (0, 0) ) | n // end of map(); return n ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~130~~ 123 bytes *-7 bytes thanks to @l4m2* ``` def f(l): E=set();p=0 for m in l:E^={p,p+min([q for y in E if(x:=(y-p)/m)==int(q:=x.real)>0]or[0])*m};p+=m return len(E) ``` [Try it online!](https://tio.run/##bcw/a8MwEIfh2foUB150jdJa/UOLw3WyN08GTcaBQiXqYMmK6kJM6Wd3bSchKXS54X1@nB/6j849vPgwju/agOEtpgxy@tQ9x42nhIHpAlhoHLRpvqVvL/zKNo5X@0WGWXJoDD@kxIe1xzuLRI3r@T6lw23Qby2@JnUXqqTGG/uz8SuyDILuv8L0Uzue41iKQiiRkRRrKeRuujvGfJi/GF6VNSJEURSDvIoiO@YY7q9rca4S/oxFKdSZHi@ipj5r8a@po500hqcLZgtlC89DdZo8j78 "Python 3.8 (pre-release) โ€“ Try It Online") Takes input as a list of complex numbers. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 20 bytes ``` ฤ–ยพ$(n*:~ยจ=ศงgF0Jโ€นn/)L ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLElsK+JChuKjp+wqg9yKdnRjBK4oC5bi8pTCIsIiIsIltcIjDCsDFOXCIsIFwiMMKwMU5cIiwgXCIxwrAwXCIsIFwiMMKwMVwiLCBcIjHCsDBOXCIsIFwiMcKwME5cIl0iXQ==) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJBIiwi4oyIaMabYFJETFVgJOG4n8O34p+oXFwxXFzCsFxcMEpKfFxcMFxcwrBcXDFKSnxcXDFcXMKwXFwwXFxOSkpKfFxcMFxcwrBcXDFcXE5KSkrin6lpO3fCqFMiLCLElsK+JChuKjp+wqg9yKdnRjBK4oC5bi8pTCIsIiIsIlIgPT4gMVxuUkQgPT4gMlxuUkwgPT4gMVxuUkRSVSA9PiA0XG5VUlJETCA9PiA0XG5VVVJETEwgPT4gNVxuRFJERERMVVVVID0+IDciXQ==) A full program accepting a list of strings "1ยฐ0", "0ยฐ1N", "1ยฐ0N", "0ยฐ1" for right, down, up, left respectively. Works by keeping a list of empty positions and removing the first one in the direction of travel each time. ``` ฤ– # evaluate (convert each to a complex number) ยพ # push empty list $ # swap ( # for n in directions: n* # multiply by n : # duplicate ~ยจ=ศง # keep only real non-negative numbers by checking if they are invariant under abs(x) g # minimum F # remove from the original list 0J # append 0 โ€น # decrement n/ # divide by n ) # end for L # length ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 34 bytes ``` K,ZZVQ=-aYK<@Ym+VK*LhdNUY1=+VKN;lY ``` [Try it online!](https://tio.run/##K6gsyfj/31snKios0FY3MdLbxiEyVzvMW8snI8UvNNLQFsj2s86J/P8/WsNAR9dQU0fDUMcASEI5qJQuTM4QhYwFAA "Pyth โ€“ Try It Online") Same basic method as [@Arnauld](https://codegolf.stackexchange.com/a/257059/73054). Takes input as four distinct direction vectors `(1,0), (-1,0), (0,1), (0,-1)`. ### Explantion `K` is the current position and `Y` is a list of empty positions. ``` # implicitly assiqn Q = eval(input()) K,ZZ # K = (0,0) VQ # for N in Q: aYK # append K to Y m UY # map range(len(Y)) over lambda d +VK*LhdN # K + ((d + 1) * N) (vectorized) @Y # intersection of that with Y < 1 # take the first element (or empty list if none) =- # remove that element from Y =+VKN # K = K + N (vectorized) ;lY # after all iterations, output length(Y) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` ๏ผฆฮธยซโœณฮน#โ‰”๏ผซ๏ผค๏ผฌฮธโœณฮนฮธยงโ‰”ฮธโŒ•ฮธ#ฯˆยปฯˆโ‰”๏ผฌ๏ผซ๏ผกฮธโŽš๏ผฉฮธ ``` [Try it online!](https://tio.run/##TY1BCoMwEEXXeopgNxNIT@BKDIWCCyl4gBCnGhoSEoO0lJ49TdBiV/OHmfefnIWXVugY79YTcJS8y6L3ygTgyqMMyhpQlJHqVNG6LJplUZOBHvFx3Ds0U5gTzMg/lFZ3ME24mhGf4Bi5KDPmmTsZeaWfT7k5c94Ve2k2NVrDr63VKDyksAGtWEIS0zpGfuOcd8MwxPOqvw "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผฆฮธยซ ``` Loop over the input string. ``` โœณฮน# ``` Mark the current square as "empty" and move in the given direction. ``` โ‰”๏ผซ๏ผค๏ผฌฮธโœณฮนฮธ ``` Peek ahead the number of characters in the input string in the direction given by the current character. ``` ยงโ‰”ฮธโŒ•ฮธ#ฯˆ ``` Try to erase the first `#` found (this corresponds to pushing a box there). ``` ยปฯˆ ``` Erase the finishing square. (This could be `ยป#` to count yourself as an empty square.) ``` โ‰”๏ผฌ๏ผซ๏ผกฮธโŽš๏ผฉฮธ ``` Get the number of empty squares, clear the canvas, and output the count. ]
[Question] [ Let's for once do something useful. Given the text from a Try It Online codegolf submission, produce the equivalent Chat Mini Challenge submission, which is of the form ``` Language, N bytes: [`code`](URL) ``` or (if submission is a single byte โ€“ TIO will add a trailing s on the first line only if needed) ``` Language, 1 byte: [`code`](URL) ``` You may assume that the submission * has only one line * does not contain backticks (```) * has no leading whitespace * has a regular format like in the examples below; the code line is indented with four spaces (), not with HTML tags (`<pre><code>`โ€ฆ`</code></pre>`), i.e. no trailing whitespace. **Note that the submission may have a syntax highlighting tag. See last example.** You may optionally include the title text, i.e. `โ€ฆurl "Language - Try It Online"`. ### Examples Given ``` # [05AB1E], 1 byte ร” [Try it online!][TIO-j3v72bss] [05AB1E]: https://github.com/Adriandmen/05AB1E [TIO-j3v72bss]: https://tio.run/##MzBNTDJM/f//8JT//zNSgSAnJycfDAA "05AB1E โ€“ Try It Online" ``` return ``` 05AB1E, 1 byte: [`ร”`](https://tio.run/##MzBNTDJM/f//8JT//zNSgSAnJycfDAA) ``` or ``` 05AB1E, 1 byte: [`ร”`](https://tio.run/##MzBNTDJM/f//8JT//zNSgSAnJycfDAA "05AB1E โ€“ Try It Online") ``` Given ``` # [Brachylog], 4 bytes แธ…hแตc [Try it online!][TIO-j3v75978] [Brachylog]: https://github.com/JCumin/Brachylog [TIO-j3v75978]: https://tio.run/##SypKTM6ozMlPN/r//@GO1oyHWyck//@vlJGampOTDwZK/6MA "Brachylog โ€“ Try It Online" ``` return ``` Brachylog, 4 bytes: [`แธ…hแตc`](https://tio.run/##SypKTM6ozMlPN/r//@GO1oyHWyck//@vlJGampOTDwZK/6MA) ``` Given ``` # [APL (Dyalog Unicode)], 15 bytes <!-- language-all: lang-apl --> โดโจยจโณ [Try it online!][TIO-j44jgrps] [APL (Dyalog Unicode)]: https://www.dyalog.com/ [TIO-j44jgrps]: https://tio.run/##AScA2P9hcGwtZHlhbG9n//9m4oaQ4o204o2owqjijbP//zcxNjDijLZmIDQ "APL (Dyalog Unicode) โ€“ Try It Online" ``` return ``` APL (Dyalog Unicode), 15 bytes: [`โดโจยจโณ`](https://tio.run/##AScA2P9hcGwtZHlhbG9n//9m4oaQ4o204o2owqjijbP//zcxNjDijLZmIDQ) ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~37~~, 35 bytes ``` รง^</dj H3xf]x3Ji[`A`]Jd2/: xr(A) ``` [Try it online!](https://tio.run/##bY9BTsJAFIb3cwU2D7qBxOko1AUNMWlCAiVESsQNTQ1DW9uZDB0sgy2uvAArDyF7PYHepBeptRtjwp@8xZ//vbz/ey7L7/eHAQk4GvfyRy/vTZi7algrrzEJusQElKdtq1OWGriWM4X28ECFjOA@Yb4Mwo53AVfXsD6ocIfQoIkxCJpEexqFmAph1g7TrQCMbxCCSsXxszievk7F8QMhd5EegCmQiWBJ2PTchT3D3DB4lG53XpWf/WlCrNR2ZxKSZZke1Knuyw1B/@//9hSTerpPiKZZd77VdfqxP8rUcizi9aifENLfGJLODdm9rEZmT5zxtUPIi5/f8iHj0@XGHs6hda4NFK9v8IthK5jVGK0f "V โ€“ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~113~~ ~~103~~ ~~98~~ 91 bytes *-1 byte thanks to Value Ink.* If you can, I could totally use some help with the regex. >< ``` lambda s:re.sub('(?s)# .(.*)](.*?)\n.* {4}(.*?)\n.+: (.*)',r'\1\2: [`\3`](\4)',s) import re ``` [Try it online!](https://tio.run/##VY/BToNAEIbv@xQjHFhq3ZVSoyExDU09tEnbQ7mxJIUCZU1ZyO5iQo2J76Bv5Jv4IkitxjiHSWb@@f78U7e6qITb5fesO8RlksagPJkR1STYwhNlm0AwGdhR3yY2E2QAz@OX3@HSg5NoDaXFHDbyINwydxthNu53yka8rCupQWZdLbnQOMeGYZgQXt/4U@chGoIDSaszhKCvj3eEwkC2wDVU4sBFdhGFwXx99eg@3Y4SpaJe/yE9KLSulUfpnuuiSciuKqmfSh6LtMwEPZ@h//gfpHlFZCOoaS6P01UwWyxpTundIqD0uNrsN75YtLt85vtgnJ3g8/UNTtnmGtbf2Vj/iWHb3Rc "Python 3 โ€“ Try It Online") [Answer] ## JavaScript (ES6), 73 bytes ``` f= s=>s.replace(/...(.*)](.*)[^]+ (.*)[^]+: (.*) ".*/,"$1$2: [`$3`]($4)") ``` ``` <textarea rows=8 cols=75 oninput=o.textContent=this.value==f(this.value)?``:f(this.value)></textarea><pre id=o> ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~54~~ ~~48~~ ~~52~~ ~~57~~ 48 bytes *Saved 1 byte thanks to @MartinEnder, 1 byte thanks to @Riley* ``` ...(.+)[^@]+ (.+)[^@]+: $1: [`$2`]( 1`] $ ) ``` [Try it online!](https://tio.run/##VY7LSsNAGIX38xR/myxa6swQL60GkXqB3ogRDAiGSKYhJKOTTEgnlXHlxr3gswi@Tn2RmHYR9azOgf//ziljxXNW14SQHhn0/YdxMIBGbbABmZYNfmjuh0EPWWGAkIn6dW2Af1GyKNVCJsEeHMJSq3iF0GkHYxAsTyqWxPbOYSYEYHyG0Ba9@XpLN5/vEUK@V2rgCmQueB53At@bufjxYD06OhkdNz1/CmxIlSpWNqUJV2m1JJHM6PyyynhO2yv0H/D7o7gkZZVTw7jVxcJzhvLFETfXtKR0PHEtqad3OnpqwlrMJywrXO/q@X5Bh845dFs6fL9@wHbxTIG7W9z9AQ "Retina โ€“ Try It Online") This assumes there won't be an `@` in the language name, which should be fine... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 50 bytes ``` ']ยกJยฆยฆยฆ|J|`โ€šส’ะฝรฐQ}`รฐร›|D`ฮธ'"รŠi\|รซ\}ฮธ#1รจr"รฟ: [`รฟ`](รฟ) ``` [Try it online!](https://tio.run/##bU@xasJQFN3zFddkUKHxqcTBUApCwCpSldrFGMhLDPGFmGdjJLVEcBZc2q2dupRAoQjtLuRt/Yz8SKoupeC93OFwzuHcU65ho2JlWV5L3trJ@3GjdqSn65efpzKL2a6/0tmOvUaKnnyyOM@zDRlF7GO0OkKhwmKfZ3sZVJ3tda3A9sUsE0Bt9DpQUJbYpTbcecSkY6uoXUClBsYysOYcd5kTRXCxZy@wbYnYdeUTEvHMBVG84jg4TLr9TrdxEqfbL45TB/4SSADUc4ln5TR10OqKjiQ5tj@bawf@bKYMkyCYzWWEwjAsjU9syaRTxP33/@kCQkv@wkOC0Lg1G9VefWI2w2B47U6MZt1DqD6VKO5LtFo@HA3vHeIYPYQezYcbRyFOZzhtKX3gz30D6foZjjVaAXRPNfhf "05AB1E โ€“ Try It Online") *Now supports syntax highlighting too!* `ะฝ` is replaced by `0รจ` and `ฮธ` is replaced by `ยฎรจ` since those aren't pulled to TIO yet. I just wonder how to shorten `ยฆยฆยฆ`... [Answer] # [Ruby](https://www.ruby-lang.org/), 85 bytes ``` ->s{s[/.*/].gsub(/# .|\]/){}+": [`#{s[/(?<= )\S.*/]}`](#{s=~/TIO-\w+.: (\S+)/;$1})"} ``` [Try it online!](https://tio.run/##lZLZkppQEIbvfYozmgvNBJFhUczMhEVAEXFhUUetGkVkCYsIiDIxlXfIG@ZFDM5NKndJ353@v67@qk4f0s35untaXqHn@C1ewPWP8KpuxemmCldA/dtyBdfeLvflNli8Vm559cvjEwC1pXIDL6@ratF9@g6rvSG0zO7rbVBdKvc1@PMH5FIrX677NInBrm6sPQ8oaqcn1w/menutgMWkWLz6BFoY2JwTMy6VHu8gCHjrwErXlgkVA@33F3QoQABBz6USKOp/NP/VslRaqIczcBIQBp4TmHerxY10MSzw8CO6KvJ32zawk2Qft2E4y7L6zQu6GdbDgwWX/h75gyZOWKABXKlsNFLehKLFyUju2AJhyYcjRUQ2SwRrX2TmXCqPYiZlJhzDsbTkifhk7XtNWldg@@gijNsS@b5k733XFSVhY/r57lgQE51MmWnE27uepVsRJdppA5N1l6W7uCobva3jzhNLEn1hfyIJmqI1airoRIYkHjZEY0/xHQ5ZPwyYKa@nBqVSkSdnW17g1xOpw@9TAseEFt/X9q5zIrVcsNzhXJ0PdIPMepsgyLudzny6JxEaz4jBSOIdJ41QjhZHJIVoyRnR2MwNWNO3mcyS@@ND1A/hHb7rNoxzNJqdFE/qD4yAHrMoKrciotijpDMcaTRZf5icHJjiBXYmClzMiaInbAlDm2aC2ZDIIwy7okbQITkOOp2hkus8iibpC3Y@vYxmYXNO5jlrBgmlMbsW1y0izDLR@RbBLbXlR5TKoxNDMQ9HZZxaUvMrE0cj9cF2FDoY5G43nGWgfPt38OvHT3A7kF4Chu8HUv4N "Ruby โ€“ Try It Online") [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~120~~ 126 bytes ``` @(a)strjoin(regexprep(strsplit(a,'\n'),{'\[.+\]: (.+) ".+','^[\[<].+','# \[(.+)\](.+)','^ +'},{'`]($1)','','$1$2: [`',''}),'') ``` This should work. For MATLAB it won't work with Unicode characters though I don't think, mostly because MATLAB sucks when it comes to odd characters. However it will work with Unicode for Octave, or at least TIO seems to be able to cope. It should also handle submissions both with and without the `<-- -->` syntax highlighting. *Updates*: 1. Added 4 bytes as I missed the `@(a)` when copying over 2. Added 2 bytes to add back ticks around the code in the output [Try it online!](https://tio.run/##TU7bSsNAEP2VsS1sQmLWeGk1@FAvUNtSIxgQ3Kw0DaHZmmbDZhuNUvDFd8FvEfyd@iNxU6R1GIaZM@ecGR7KoIiqqqsFei7FjLNUE9E0es5ElGkKybOESS0wkZ8i3XxFPrEMnzqgWYYODctAJnogPjml67YJPqk3Pq1rvQMDLZVsTLWWXQMqW3Zr3wEyrqelropeBWmuEaUm5yII4zLhU2rCIUxKGeUI7L06EahYfb/Hq6@PcAMST5TAJPA0YWm0Q4nXd3dnB0Xn6KRzTLe0rbEDsZRZ7mA8ZTJeTKyQz/HgYjFnKd6w0J/5f7OtUDJuiUWKm83bMht6ozZ/GSU311hg3O25Ni@v7srwUQ1FMugF88z1Lp/uh7g9OoPG5gT8vH1C/X1fgrv@voGoXv0C "Octave โ€“ Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 101 bytes ``` a=input().split('\n') print'%s%s: [`%s`](%s)'%tuple(a[0][3:].split(']')+[a[-6][4:],a[-1].split()[1]]) ``` [Try it online!](https://tio.run/##TY5db4IwFIbv9ys6CSnNlPLhNkeyC4y7kES9kLu2iYAoXbA0tCzin0fQme1cnZPzvk8e2eqiEl7XJZ9cyEZbyFay5NqCVED0JGsuNDSVqQJAdqbaMctUCJq6kWVuJcRhxA/Yo8IgeiEJmbwxMg3YuN/cxw8RlzHUddAAxHkN5@4XGwMXpK3OqaAC9EPPmU/PH9PhJnHdAq5BJUou8mdG4uVm8u3/vHupUuyW@KUEoNBaqgDjI9dFk9pZdcLhvuaJ2J9yge@xgfif8NfSvLLrRmDDWF3m63gRrfAB41kUY3xZb4/bUERtdliEIRjdUb1n7tHzzOldfTB4LjXY3DxH8Ao "Python 2 โ€“ Try It Online") or [Try all test cases](https://tio.run/##hZJrj5pAFIa/@ytmNQZJF0cUXSVtU7Y2ru562WjTRCDZ4SKMhYHCsIh/3g54wQ92S0KYk3POe877MGFG3YC0DwfL3oBNw@DlCkBfjGYcepg2OI1wfAVENk0iwtXjeiwD9a0ev@mNesxzdZqEnt1AaktXO7J@btI5/pOKVKGnq5Ks37OTeM7xqqjr/CF1sWcDkc0KI0woG4xJmLA0f@BqQG11lUfxh34PRGBk1NaIRgB7tJ3Z0XYDKY/VVZQBTEFAPEzsO11djefCtvP@0DbiWC8qTioycCkNYxlCB1M3MZpm4EPFijAilm8TeCzLFa8Vyi6Kg2aUEFirTfePs9VwMoUbCPuTFYT72dJZKmSSmZuhooDqUYrtabe1Xb/Fdu2AfM8xBfNizypXyf09Rsh0My9wmEWpsBiXHm1R2xl91t91T0GXCbXMD113Bw/9o@tS@6bxyffExwReqq58Fxq3fC@z8Hk17QX7qbeYwQjCb6O5GGRPvzLzNwvevckI@eF8NUzXz7A3ZSAu8v9noSxeQGOYobz4J8FmYNl8/ue7JZfPd4IAPEScBDm2gDxPLiIBhR4QhK9X6PJRFiMmlWfEUJrt4/eS7/wbpiRtnSg8XaGby5WI0jRtWkW2YHtmeZa4xVJZmkp7MXDNUUrXT55rjAYEwoEvBehVCtot9gbpny3eGgt2v8zdbDvE25e1Px6@guqtdT4m/Bc "Python 2 โ€“ Try It Online") [Answer] # [PHP](https://php.net/), 92 bytes ``` <?=preg_filter("<...(.+)\](, \d+ \w+).* {4}(\S+).*: (\S+).*>s","$1$2: [`$3`]($4)",$_GET[0]); ``` [Try it online!](https://tio.run/##bVFbasJQEP2/q5jGgElN7lWbfhhfCBYrSFW0PyZBY0zzIOamyZXUlkI34Fc34X@7gi4lG7FRWkrBgYEznBnOnJnIjQ6NduRGCPHz3s1UKxvNYgG0zmgAQndrBtSB@9Cz6MoWDQkq17DcMjtBqHEhyxCYobMxHVs2g0A9VbIZBSDLLYQgj2z3me32X/ts94GQNo234DGgYeCF9oWhTftD2VcU34mjxMj5s5oquIxFiUpImqZ4dWKxRdcE/Z//62MexfEmJIVCZ2J1qqOaa/VSNrsN3GWvFhJSWyvUHCu0Ws6Tpo@@5y9HhDxbT3d@1/MHs3W/Owbu3DaQvb3D0UafwfBkgyvWUbuVn7AZxbYzf/ACZscC18AYC7gk6oYggb4qgZ6WRHwJL8qroE@OUIUf0Eo4ieMrfFUFbcFfLQyBV0RO@v2GWD8cvgE "PHP โ€“ Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~43~~ ~~39~~ 38 bytes ``` [a@>3DC']": [`"g@-6|>s"`]("(g@v^s1)')] ``` [Try it online!](https://tio.run/##VY7NrsFAGIZv5TNdIMF3SvykC@k4tdCELnTXjFCqRpg2nSGpnIV74I7ciRsZReTEu36fJ0/KU62Dhd1vOb9lRiwI5iS2652/viRzViGV2D7OpFktV5nW2oDgp00H5pDVwIQwV5HWUOx2LSR@lgNXkIgdF1GJBf7Iq29bx24zlLKAP6QFG6VSaSHGXG0OYWOZ7JGuMr4Qq30k8H3T3/g/pHjSyA4CDWN8Gkx8xx3jGrHn@oinyTSeUuHmy7VDKZC3Ce7nCzzbRgq8Vxt5AA "Pip โ€“ Try It Online") Takes the lines as separate command-line arguments. An example invocation could look like: ``` > pip.py -f convert.pip "# [05AB1E], 1 byte" "" " ร”" "" "[Try it online!][TIO-j3v72bss]" "" "[05AB1E]: https://github.com/Adriandmen/05AB1E" "[TIO-j3v72bss]: https://tio.run/##MzBNTDJM/f//8JT//zNSgSAnJycfDAA \"05AB1E โ€“ Try It Online\"" ``` though actually this doesn't work for me because Windows `cmd` complains about the `ร”`... [inarticulate muttering] --At any rate, it works on TIO. Or, use the `-r` flag and take input from lines of stdin instead. Assumes that the language name will not contain `]` (which would break the markdown anyway). ### Explanation ``` g is list of cmdline args; a is 1st arg; s is space; v is -1 (implicit) [ ] Build a list with these elements: a@>3 1st line, sans first three characters, DC'] with the ] character deleted ": [`" This string g@-6 6th line from the end (the code) |>s with leading spaces stripped "`](" This string g@v Last line (containing the URL) ^s split on spaces ( 1) get element at index 1 ') This character By default, the list is concatenated and printed ``` ]
[Question] [ You're given a hexagonal grid of the characters `.` and `#`, like this: ``` . . . . . . . . . . . . # . . . . # . . . # . . . . . # . . . . . . . . . # . . . . . . . . . . ``` Your task is to fill the entire axis-aligned bounding box of the `#` with further `#`: ``` . . . . . . . . . . # # # # . . . # # # # # . . . . # # # # # . . . # # # # . . . . . . . . . . ``` The axis-aligned bounding box is the smallest convex hexagonal shape which contains all the `#`. Note that in the case of the hexagonal grid, there are *three* axes to consider (W/E, SW/NE, NW/SE): [![enter image description here](https://i.stack.imgur.com/gcBoY.png)](https://i.stack.imgur.com/gcBoY.png) Here is another example to show that in some cases, one or more sides will contain only one `#`: ``` . . . . . . . . . . . . . . . . . # . . . . . . . # # # # . . . . . . . . # . . . . # # # # . . . . # . . . . . . . # # # . . . . . . . . . . . . . . . . . . . ``` You can either view these as hexagons with degenerate sides, or you can draw the bounding box around them, like I have done above, in which case they are still hexagons: [![enter image description here](https://i.stack.imgur.com/yNMAq.png)](https://i.stack.imgur.com/yNMAq.png) **Too hard? [Try Part I!](https://codegolf.stackexchange.com/q/91065/8478)** ## Rules You may use any two *distinct* non-space printable ASCII characters (0x21 to 0x7E, inclusive), in place of `#` and `.`. I'll continue referring to them as `#` and `.` for the remainder of the specification though. Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent. You may assume that the input contains at least one `#` and all lines are the same length. Note that there are two different "kinds" of lines (starting with a space or a non-space) - you may *not* assume that the input always starts with the same type. You may assume that the bounding box always fits inside the grid you are given. You may write a [program or a function](http://meta.codegolf.stackexchange.com/q/2419) and use any of the our [standard methods](http://meta.codegolf.stackexchange.com/q/2447) of receiving input and providing output. You may use any [programming language](http://meta.codegolf.stackexchange.com/q/2028), but note that [these loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer โ€“ measured in *bytes* โ€“ wins. ## Test Cases Each test case has input and output next to each other. ``` # # . . . . # . # # # # . . . . . # . # . . . . # . # . # . # . # . . . . . # . . # . # # . # . # . . # # . . # # # . # # # # . . # # # . # # # . . # . # # . . # # # . . # # . # . . # # . . . # # . . # . # # . . . . . . . . . . . . . . . . . . # . # . . . . . # # # . . . . . . . . . . . . . . # # . . . . . . # . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . # . . . # . . . # # # # # . . . . . . . . . . . . # # # # . . . . # . . . . . . . # # # . . . . . . . . . . . . . . . . . . . # . . . . . . . # # # # . . . . . . . . # . . . . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . . . # # # # . . . . . . . . # . . . . # # # # . . . . # . . . . . . . # # # . . . . . . . # . . . . . # # # # . . . # . . . # . . . # # # # # . . . . . # . . . . . . # # # # # . . . . . . # . . . . # # # # . . ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~82~~ 71 bytes ``` ~~L,hbebMqH@S+GH1KhMyJs.e,Lkfq\#@bTUb.zA,ySm-FdJySsMJj.es.eXW&&gKkgG-kYgH+kYZ\.\#b.z~~ MqH@S[hGHeG)1j.es.eXW&&ghMJs.e,Lkfq\#@bTUb.zkgSm-FdJ-kYgSsMJ+kYZ\.\#b.z ``` [Try it online!](http://pyth.herokuapp.com/?code=MqH%40S%5BhGHeG%291j.es.eXW%26%26ghMJs.e%2CLkfq%5C%23%40bTUb.zkgSm-FdJ-kYgSsMJ%2BkYZ%5C.%5C%23b.z&input=+.+.+.+.+.+.+.+.%0A.+.+.+.+%23+.+.+.+%0A+.+%23+.+.+.+%23+.+.%0A.+.+.+%23+.+.+.+.+%0A+.+.+.+.+.+%23+.+.%0A.+.+.+.+.+.+.+.+&debug=0) ### Explanation * Let A be the point with the lowest y-coordinate and B the point with the highest y-coordinate. * Let C be the point with the lowest (x-value minus y-value) and D the point with the highest. * Let E be the point with the lowest (x-value plus y-value) and F the point with the highest. Then it is equivalent to finding the coordinates which the y-coordinate is between A and B, the x-value minus y-value is between C and D, and the x-value plus y-value is between E and F. [Answer] ## Haskell, ~~256 254~~ 243 bytes ``` import Data.List f=z(\l->(,).(,))[0..]l)[0..] q l=m(m(\e->min(snd e).(".#"!!).fromEnum.and.z($)(m(\x y->y>=minimum x&&y<=maximum x).transpose.m b.filter((==)'#'.snd).concat$l)$b e))l b=(m uncurry[const,(-),(+)]<*>).pure.fst z=zipWith m=map q.f ``` Thanks @Damien for golfing `f`! Input is taken as list of list of chars, output is provided the same way. Soo this was a beast to write. It's based on LeakyNun's idea using a maximum and minimum based filtering on the coordinates of the items. I'm really surprised by the fact that `m=map` actually saves bytes since it seems so costly. --- Explanation: Here's a slightly less butchered version (emphasis on *slightly*): ``` import Data.List f=zipWith(\y l->zipWith(\x e->((y,x),e))[0..]l)[0..] p=map(\x y->y>=minimum x&&y<=maximum x).transpose.map b.filter((==)'#'.snd).concat q l=map(map(\e->min(snd e).(".#"!!).fromEnum.and.zipWith($)(p$l)$b e))l b=(map uncurry[const,(-),(+)]<*>).pure.fst ``` * `f` is a function which assigns each char an index `(y-index, x-index)` while preserving the original structure of the list. * `b`: Given an item of the indexed list, `b` computes `[y-index, y - x, y + x]`. * `p`: Given the indexed field, return 3 functions `Int -> Bool`, the first of which is the check of the y-index, the second of the difference and the third of the sum. `min(snd e)` takes care of the spaces (a space is smaller than both). This function is inlined in the golfed code. * `q` given the indexed field, change all necessary `.` to `#` by checking if that specific field return `True` to every test function. The final solution is then the composition of `q` and `f`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~45~~ ~~3513~~ ~~42~~ 41 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แน€โ‚ฌยป\ แนšร‡แนšยซร‡แน" ล’Dแน™ZL$ร‡แน™Lโ€™$ล’แธŒยซร‡ แนšร‡แนšยซร‡ nโถaร‡oโถ ``` This is a list of links; the last one has to be called on the input to produce the output. I/O is in form of string arrays, where `.` indicates empty and `@` indicates filled. [Try it online!](http://jelly.tryitonline.net/#code=4bmA4oKswrtcCuG5msOH4bmawqvDh-G5gSIKxZJE4bmZWkwkw4fhuZlM4oCZJMWS4biMwqvDhwrhuZrDh-G5msKrw4cKbuKBtmHDh2_igbYK4bu0w4dZICAgICAgICAgICAgICDhuLcg4oCcU3BsaXQgYXQgbGluZWZlZWRzLCBjYWxsIHByZXZpb3VzIGxpbmssIGpvaW4gYXQgbGluZWZlZWRzLuKAnQ&input=&args=LiAuIEAKIC4gLiAKQCAuIC4) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmA4oKswrtcCuG5msOH4bmawqvDh-G5gSIKxZJE4bmZWkwkw4fhuZlM4oCZJMWS4biMwqvDhwrhuZrDh-G5msKrw4cKbuKBtmHDh2_igbYK4bu0w4dZCsWT4bmj4oCcwrbCtuKAncOH4oKsauKAnMK2wrbigJ0&input=&args=QAoKIC4gLiAKQCAuIEAKIC4gLiAKCiAuIEAgCi4gLiAuCiBAIC4gCgogQCAuIAouIC4gLgogLiBAIAoKIEAgLiAKQCAuIC4KIC4gQCAKCiBAIEAgCkAgQCBACiBAIEAgCgouIC4gLiAuIC4gLiAuIC4gCiAuIC4gQCAuIEAgLiAuIC4KLiAuIC4gLiAuIC4gLiAuIAogLiAuIC4gQCAuIC4gLiAuCgouIC4gLiAuIC4gLiAuIC4gCiAuIC4gQCAuIC4gLiBAIC4KLiAuIC4gLiAuIC4gLiAuIAogLiAuIC4gQCAuIC4gLiAuCgouIC4gLiAuIC4gLiAuIC4gCiAuIEAgLiAuIC4gLiAuIC4KLiAuIC4gLiAuIEAgLiAuIAogLiAuIC4gLiAuIC4gLiAuCgouIC4gLiAuIC4gLiAuIC4gCiAuIEAgLiAuIC4gLiAuIC4KLiAuIC4gLiAuIEAgLiAuIAogLiAuIEAgLiAuIC4gLiAuCgouIC4gQCAuIEAgLiAuIC4gCiAuIEAgLiAuIC4gQCAuIC4KLiAuIC4gQCAuIEAgQCAuIAogLiAuIEAgLiAuIEAgLiAu). ### Background Let's consider the following example. ``` . . . . . . . . . @ . . . . . . . . . . . @ . . . . @ . . . . . ``` By drawing a pair or parallel lines โ€“ the closest pair that encloses all filled positions โ€“ in each of the three directions, we can determine the hexagonal bounding box. In the implementation, we replace all characters between those two lines with `@`, and everything outside these lines with `.`, with the possible exception of diagonals that only contains spaces). For the horizontal axis, this gives ``` ................ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ``` for the falling diagonal axis, it gives ``` ..@@@@@@@...... ...@@@@@@@...... ....@@@@@@@..... ....@@@@@@@.... ``` and for the raising diagonal axis, it gives ``` ....@@@@@@@@@... ...@@@@@@@@@.... ..@@@@@@@@@.... .@@@@@@@@@.... . ``` By taking the character-wise minimum of all three, since `.` < `@`, we get ``` ............... ...@@@@@@@...... ....@@@@@@@.... ....@@@@@.... . ``` All that's left to do is restoring the spaces. ### How it works ``` nโถaร‡oโถ Main link. Argument: A (array of strings) nโถ Not-equal space; yield 0 for spaces, 1 otherwise. aร‡ Take the logical AND with the result the 4th helper link. This will replace 1's (corresponding to non-space characters) with the corresponding character that result from calling the link. oโถ Logical OR with space; replaces the 0's with spaces. ``` ``` แนšร‡แนšยซร‡ 4th helper link. Argument: A แนš Reverse the order of the strings in A. ร‡ Call the 3rd helper link. แนš Reverse the order of the strings in the resulting array. ร‡ Call the 3rd helper link with argument A (unmodified). ยซ Take the character-wise minimum of both results. ``` ``` ล’Dแน™ZL$ร‡แน™Lโ€™$ล’แธŒยซร‡ 3rd helper link. Argument: L (array of strings) ล’D Yield all falling diagonals of L. This is a reversible operation, so it begins with the main diagonal. ZL$ Yield the length of the transpose (number of columns). แน™ Shift the array of diagonals that many units to the left. This puts the diagonals in their natural order. ร‡ Call the helper link on the result. Lโ€™$ Yield the decremented length (number of columns) of L. แน™ Shift the result that many units to the left. This puts the changed diagonals in their original order. ล’แธŒ Undiagonal; reconstruct the string array. ร‡ Call the 2nd helper link with argument L (unmodified). ยซ Take the character-wise minimum of both results. ``` ``` แนšร‡แนšยซร‡แน" 2nd helper link. Argument: M (array) แนš Reverse the rows of M. ร‡ Call the 1st helper link on the result. แนš Reverse the rows of the result. ร‡ Call the 1nd helper link with argument M (unmodified). ยซ Take the minimum of both results. แน" Mold zipwith; repeat each character in the result to the left as many times as needed to fill the corresponding row of M. ``` ``` แน€โ‚ฌยป\ 1st helper link. Argument: N (array) แน€โ‚ฌ Take the maximum of each row of N. ยป\ Take the cumulative maxima of the resulting characters. ``` [Answer] # Python 3, ~~380~~ ~~378~~ ~~348~~ 346 bytes Note that the indentation is with tabs, not spaces. ### Golfed version: ``` def s(i): L=i.splitlines();E=enumerate;A=lambda x,y:(y,x+y,x-y);N=(2**64,)*3;X=(-2**64,)*3 for y,l in E(L): for x,c in E(l): if c=='#':p=A(x,y);X=tuple(map(max,X,p));N=tuple(map(min,N,p)) R='' for y,l in E(L): for x,c in E(l): if c!='.':R+=c else:p=A(x,y);f=all(N[j]<=p[j]<=X[j]for j in range(0,3));R+='.#'[f] R+='\n' return R ``` [Test it on Ideone](https://ideone.com/zSrjwB) ### Explanation (for ungolfed version below): All processing is done without any conversion, space characters are simply skipped. Function `axes_pos` calculates 3-tuple of imaginary "3D" coordinates, they are accumulated into (element wise) minimum and maximum 3-tuples (`bmin`, `bmax`) for all `#` characters. Coordinates are calculated in `def axes_pos(x, y): return y, x + y, lc - y + x`; where X counts from 0 to right, and Y counts from 0 to bottom (from first line to last). First imaginary coordinate is basically Y, because it's obvious why. Its axe is orthogonal to green bounds (in the OP's pictures) Second is orthogonal to red bounds, and third is orthogonal to blue bounds. In the second pass, replacement is done for all `.` characters which "3D" coordinates fall into `bmin`..`bmax` range, element wise โ€” this is checked in this expression `all(bmin[j] <= p[j] <= bmax[j] for j in range(0, 3))`. ### Ungolfed version with tests, [also on Ideone](https://ideone.com/zb0Gkk): ``` def solve(i): ls = i.splitlines() lc = len(ls) def axes_pos(x, y): return y, x + y, lc - y + x I = 2 ** 64 bmin = (I, I, I) bmax = (0, 0, 0) for y, line in enumerate(ls): for x, char in enumerate(line): if char != '#': continue p = axes_pos(x, y) bmax = tuple(map(max, bmax, p)) bmin = tuple(map(min, bmin, p)) result = '' for y, line in enumerate(ls): for x, char in enumerate(line): if char != '.': result += char else: p = axes_pos(x, y) f = all(bmin[j] <= p[j] <= bmax[j] for j in range(0, 3)) result += '#' if f else char result += '\n' return result def run_test(a, b): result = solve(a) if result != b: raise AssertionError('\n' + result + '\n\nshould be equal to\n\n' + b) def run_tests(): run_test( "#\n", "#\n") run_test( " . . \n" "# . #\n" " . . \n", " . . \n" "# # #\n" " . . \n") run_test( " . # \n" ". . .\n" " # . \n", " . # \n" ". # .\n" " # . \n") run_test( " # . \n" ". . .\n" " . # \n", " # . \n" ". # .\n" " . # \n") run_test( " # . \n" "# . .\n" " . # \n", " # . \n" "# # .\n" " # # \n") run_test( " . # \n" "# . .\n" " . # \n", " # # \n" "# # #\n" " # # \n") run_test( ". . . . . . . . \n" " . . # . # . . .\n" ". . . . . . . . \n" " . . . # . . . .\n", ". . . . . . . . \n" " . . # # # . . .\n" ". . . # # . . . \n" " . . . # . . . .\n") run_test( ". . . . . . . . \n" " . . # . . . # .\n" ". . . . . . . . \n" " . . . # . . . .\n", ". . . . . . . . \n" " . . # # # # # .\n" ". . . # # # # . \n" " . . . # # # . .\n") run_test( ". . . . . . . . \n" " . # . . . . . .\n" ". . . . . # . . \n" " . . . . . . . .\n", ". . . . . . . . \n" " . # # # # . . .\n" ". . # # # # . . \n" " . . . . . . . .\n") run_test( ". . . . . . . . \n" " . # . . . . . .\n" ". . . . . # . . \n" " . . # . . . . .\n", ". . . . . . . . \n" " . # # # # . . .\n" ". . # # # # . . \n" " . . # # # . . .\n") run_test( ". . . . # . . . \n" " . # . . . # . .\n" ". . . # . . . . \n" " . . . . . # . .\n", ". . # # # # . . \n" " . # # # # # . .\n" ". . # # # # # . \n" " . . # # # # . .\n") if __name__ == '__main__': run_tests() ``` Update 1: Removed unnecessary `-1` for third imaginary coordinate, because it doesn't change anything Update 2,3: Partially implemented improvements suggested by `Leaky Nun` + my own too. [Answer] # Python, ~~237~~ 230 bytes **7 bytes thanks to Dennis.** ``` def f(a):i=range(len(a[0]));j=range(len(a));b,c,d=map(sorted,zip(*[[x,x+y,x-y]for y in i for x in j if"?"<a[x][y]]));return[[[a[x][y],"#"][(a[x][y]>" ")*(b[0]<=x<=b[-1])*(c[0]<=x+y<=c[-1])*(d[0]<=x-y<=d[-1])]for y in i]for x in j] ``` Port of [my answer in Pyth](https://codegolf.stackexchange.com/a/91545/48934). Takes array of lines as input, outputs 2D array of characters. * Python 2: [Ideone it!](http://ideone.com/FMoB1y) * Python 3: [Ideone it!](http://ideone.com/fIlW3a) [Answer] # Perl, ~~128~~ 126 bytes Includes +6 for `-0F\n` Run with input on STDIN. Use `1` for filled, `0` for empty. Lines do not have to be padded with spaces at the end: ``` perl -M5.010 hexafill.pl 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 ^D ``` `hexafill.pl` ``` #!/usr/bin/perl -0F\n $-=map{s%$=%$=^!map{/$/;grep{pos=$`;$=?$_|="!"x$`.1:!/\b.*\G./}${--$@}}@F-$-+pos,$-+pos,$-%eeg;--$-;$=||say}@F while$=-- ``` Uses cube coordinates. Determine maximum and minimum during the `$= == 1` loop and fills coordinates between these bounds during the `$= == 0` loop. The first 58 loops are pointless and are only there to fill `$-` with the number of lines [Answer] # TSQL, 768 bytes I wrote a query to solve this - which I found quite difficult. It is not able to compete with all the excellent shorter answer. But wanted to post it anyway for those interested. Sorry about the length of the answer - hoping codegolf is also about different approachs. **Golfed:** ``` DECLARE @ varchar(max)= ' . . . . # . . . . # . . . # . . . . . # . . . . . . . . . # . . . . . . . . . . ' ;WITH c as(SELECT cast(0as varchar(max))a,x=0,y=1,z=0UNION ALL SELECT SUBSTRING(@,z,1),IIF(SUBSTRING(@,z,1)=CHAR(10),1,x+1),IIF(SUBSTRING(@,z,1)=CHAR(10),y+1,y),z+1FROM c WHERE LEN(@)>z)SELECT @=stuff(@,z-1,1,'#')FROM c b WHERE((exists(SELECT*FROM c WHERE b.y=y and'#'=a)or exists(SELECT*FROM c WHERE b.y<y and'#'=a)and exists(SELECT*FROM c WHERE b.y>y and'#'=a))and a='.')and(exists(SELECT*FROM c WHERE b.x<=x-ABS(y-b.y)and'#'=a)or exists(SELECT*FROM c WHERE b.x<=x+y-b.y and a='#'and b.y<y)and exists(SELECT*FROM c WHERE b.x<=x+b.y-y and a='#'and b.y>y))and(exists(SELECT*FROM c WHERE b.x>=x+ABS(y-b.y)and'#'=a)or exists(SELECT*FROM c WHERE b.x>=x-y+b.y and b.y<y and'#'=a)and exists(SELECT*FROM c WHERE b.x>=x-b.y+y and a='#'and b.y>y))OPTION(MAXRECURSION 0)PRINT @ ``` **Ungolfed:** ``` DECLARE @ varchar(max)= ' . . . . # . . . . # . . . # . . . . . # . . . . . . . . . # . . . . . . . . . . ' ;WITH c as ( SELECT cast(0as varchar(max))a,x=0,y=1,z=0 UNION ALL SELECT SUBSTRING(@,z,1),IIF(SUBSTRING(@,z,1)=CHAR(10),1,x+1), IIF(SUBSTRING(@,z,1)=CHAR(10),y+1,y), z+1 FROM c WHERE LEN(@)>z ) SELECT @=stuff(@,z-1,1,'#')FROM c b WHERE((exists(SELECT*FROM c WHERE b.y=y and'#'=a) or exists(SELECT*FROM c WHERE b.y<y and'#'=a) and exists(SELECT*FROM c WHERE b.y>y and'#'=a) )and a='.') and (exists(SELECT*FROM c WHERE b.x<=x-ABS(y-b.y)and'#'=a) or exists(SELECT*FROM c WHERE b.x<=x+y-b.y and a='#'and b.y<y) and exists(SELECT*FROM c WHERE b.x<=x+b.y-y and a='#'and b.y>y)) and(exists(SELECT*FROM c WHERE b.x>=x+ABS(y-b.y)and'#'=a) or exists(SELECT*FROM c WHERE b.x>=x-y+b.y and b.y<y and'#'=a) and exists(SELECT*FROM c WHERE b.x>=x-b.y+y and a='#'and b.y>y)) OPTION(MAXRECURSION 0) PRINT @ ``` **[Fiddle ungolfed](https://data.stackexchange.com/stackoverflow/query/530759/highlight-the-bounding-box-part-ii-hexagonal-grid)** [Answer] # GNU Octave, ~~212~~, 196 bytes Maybe not really a golfer's favourite choice language, but that's what makes the challenge, isn't it? Assuming m is taken as a char matrix: **178 bytes** stand alone and **196 if stuffed into a function**. golfed: ``` function k=f(m)[a,b]=size(m);[y,x]=ndgrid(1:a,1:b);t={y,y+x,x-y};k=m;s=x>0;for j=1:3l{j}=unique(sort(vec(t{j}.*(m==['#']))))([2,end]);s&=(l{j}(1)<=t{j})&(l{j}(2)>=t{j});endk(s&mod(x+y,2))=['#']end ``` ungolfed: ``` function k=f(m) [a,b]=size(m);[y,x]=ndgrid(1:a,1:b);t={y,y+x,x-y};k=m;s=x>0; for j=1:3 l{j}=unique(sort(vec(t{j}.*(m==['#']))))([2,end]); s&=(l{j}(1)<=t{j})&(l{j}(2)>=t{j}); end k(s&mod(x+y,2))=['#'] end ``` **Explanation** : we build a coordinate system, 3 axes - orthogonal to the hexagons sides, find max and min of each coordinate, then build a logical mask starting with 1 everywhere and logically and:ing each coordinate max and min constraint, finally re-setting each remaining "true" position to "#" char. If you want to test it, you can just create m matrix like this: ``` m = [' . . . . . . . .. . . . # . . . . # . . . # . .. . . # . . . . . . . . . # . .. . . . . . . . ']; m = reshape(m,[numel(m)/6,6])'; ``` and then call the f(m) and compare with m by building a matrix with both of them in: ``` [' before after ';m,ones(6,1)*'|',f(m)] ``` ]
[Question] [ It's very easy: Create a program without writing a single line of code. The code may only consist of existing Stack Overflow questions and answers. The program should create two random numbers and output the numbers * added to, * subtracted from, * multiplied with and * divided by each other. **Rules** You must include links to the questions/answers you used in your answer. You may not modify the code you find, with the following exceptions: 1. You may rename variables, functions, and methods. (This doesn't mean you can change a method invocation, by changing, say scanner.nextInt() to scanner.nextLine() and claiming that you're changing a method name. The change must be in the definition or reference to the same entity.). The solution should still work if variables, functions or methods would be renamed again. 2. You may adjust indentation appropriately. 3. You can assume that the proper modules are loaded for the code snippets to work. (e.g., import statements for Java and Python, using statements for C# and C++, and their equivalents in all languages) If the code snippet includes the imports for you, you can move them to the top of the code. 4. If the language requires the code to be in some kind of method body to execute (e.g., `public static void main(String[] args)` for Java, `static int Main(string[] args)` for C#, and so on), you can wrap your code in the appropriate method. But the contents of that main method must remain unmodified. 5. You must supply an explicit list of any variable/method/function/class renamings performed. 6. You can't take snippets of snippets (meaning if you take a code block from a post, you take the whole thing) Provide a brief description of what the code does for people who aren't intimate with the language you're using. You must use snippets posted before this challenge was started. **Popularity contest, so the most upvotes wins!** **Deadline** I will accept the the submission that has the most votes around the end of August, 6. [Answer] # J, 7 questions/answers, none about J ``` echo a%b[echo a*b[echo a-b[echo a+b[b=:?2147483647 [a=:?2147483647 ``` It's a pretty damn cheap way to do it, I'm not gonna lie. Here are the SO answers I used: * `echo` [This answer](https://stackoverflow.com/questions/8467424/echo-new-line-in-bash-prints-literal-n/8467449#8467449) * `+`, `-`, `*` and `%` [This question](https://stackoverflow.com/questions/11694546/divide-a-number-by-3-without-using-operators) * `?` [This answer](https://stackoverflow.com/questions/4554749/replace-a-question-mark-with/4554779#4554779) * `[` [This answer](https://stackoverflow.com/questions/27722201/php-explode-all-square-bracket/27722229#27722229) * `=` and `:` [This community wiki question](https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) * `2147483647` [This answer](https://stackoverflow.com/questions/94591/what-is-the-maximum-value-for-a-int32/17487532#17487532) * `foo` [This answer](https://stackoverflow.com/questions/7098348/query-search-letters-to-letters/7098439#7098439) I renamed variable `foo` as `a` and `b` in the code. [Answer] # Python 2, ~~7~~ 6 references Creating this solution wasn't as easy as it looked. Searching Stack Overflow for specific code is difficult, since symbols are not included in the search. I had found a way to do this with 2000-bit random numbers, using a different answer in place of Ref #1, ~~but I couldn't test it on the online environments I use since it involves `getrandbits`, which calls `os.urandom`, giving me a `NotImplementedError`, so I went this way instead.~~ This could actually be used now, with TIO. [**Try it online**](https://tio.run/nexus/python2#hZHNTsMwEITvfoqVuCQoP7VLRanEEY68QJXDxnYbq8naclxAvDfnYjcpBQmJS8bONzPrOKcb6EJw46aupVV6b/tdNQaUB/0uO6S9rqQdaqxXy4f1ql7e3fM1Y2Zw1gfwSMoOjBGHR9g2USt0TpPKJlIlMRQyXgBfLPI8WsVsFf9afWod0GXjcSjgw7iMIiQRmRcz6nFoFULYQNguGiij8AaKX2aGbZpJfGuaWxLxCTvrwYCh9AV7nfWaoj3PmzS0gB7HEBOex8oiScmbOPIKxATEGWD7DbA9gygJ0DVBU4KmBLuBFxvieNkflVbpHOooQxnQxV36CxU8xxO@am92RmIwliB0GM4M3qw/jBVzPl4XEJ@bY@kTKaAfxWz2eH5ZiHmB7XQpu95iyLDNoU4Vf727BE6nT7KlRNnpLw) ``` #assumed to be loaded import random n1 = [] n1.append(random.randint(1, 100)) n2 = [] n2.append(random.randint(1, 100)) r1 = map(sum, zip(n1, n2)) r2 = map(lambda t: t[0] - t[1] ,zip(n1, n2)) ab = [n1[i]*n2[i] for i in range(len(n1))] r1, last = r1[0], r1[-1] r2, last = r2[0], r2[-1] ab, last = ab[0], ab[-1] n2, last = n2[0], n2[-1] print r1 print r2 print ab ab = float(ab) / n2 ab = float(ab) / n2 print ab ``` ### References `import random` is assumed to be loaded, since the question says that's allowed. 1. `lst = []` and `lst.append(random.randint(1, 100))` - [Here](https://stackoverflow.com/a/30295181/2415524) 2. `map(sum, zip(r1, r2))`, `map(lambda t: t[0] - t[1] ,zip(r1, r2))`, `r1`, and `r2` - [Here](https://stackoverflow.com/questions/15916966/python-math-adding-numbers-from-two-list-index-by-index/15917073#15917073) 3. `result = float(a) / b` - [Here](https://stackoverflow.com/a/6315997/2415524) 4. `ab = [a[i]*b[i] for i in range(len(a))]` - [Here](https://stackoverflow.com/a/22242119/2415524) 5. `first, last = some_list[0], some_list[-1]` - [Here](https://stackoverflow.com/a/12218857/2415524) 6. `print x` - [Here](https://stackoverflow.com/a/22004184/2415524) ### Renamed 1. `lst` renamed to `n1` and `n2` (Ref #1: I used the entire code twice) 2. `r1` and `r2` renamed to `n1` and `n2` (Ref #2: I used the separate variables later though, to assign the maps and to divide in the last print, since the answer included them. ) 3. `result` and `a` renamed to `ab`, and `b` renamed to `n2` (Ref #3) 4. `a` and `b` renamed to `n1` and `n2` (Ref #4) 5. `first` and `some_list` both renamed to `r1`, `r2`, `ab`, or `n2`, depending on which line. (Ref #5: I used this four times. Note that only the first assignment is used, so I don't rename `last`) 6. `x` is renamed to `r1`, `r2`, or `ab`, depending on which line. (Ref #6) [Answer] # [Decimal](//git.io/Decimal), 2 references ``` 82D82D00D30001D30041D301212010D301200D30001D30042D301212010D301200D30001D30043D301212010D301200D30001D30044D30122 ``` Commands used: * `0` SET (default stack index) * `1` PUSH + `2` CHAR * `2` POP * `3` I/O + `00` duplicate stack + `01` from stack to STDOUT * `4` MATH + `1` ADD + `2` SUBTRACT + `3` MULTIPLY + `4` DIVIDE * `8` BUILTIN + `2` push random integer to stack Explained version: ``` 82D ; push random INT - stack contains {r1} 82D ; push random INT - stack contains {r1, r2} 00D300 ; duplicate stack[0] - stack contains {r1, r2, r1} 01D300 ; duplicate stack[1] - stack contains {r1, r2, r1, r2} 41D ; math + - stack contains {r1, r2, r1+r2} 301 ; print from stack to output 2 ; pop - stack contains {r1, r2} 12010D3012; print newline 00D300 ; duplicate stack[0] - stack contains {r1, r2, r1} 01D300 ; duplicate stack[1] - stack contains {r1, r2, r1, r2} 42D ; math - - stack contains {r1, r2, r1-r2} 301 ; print from stack to output 2 ; pop - stack contains {r1, r2} 12010D3012; print newline 00D300 ; duplicate stack[0] - stack contains {r1, r2, r1} 01D300 ; duplicate stack[1] - stack contains {r1, r2, r1, r2} 43D ; math * - stack contains {r1, r2, r1*r2} 301 ; print from stack to output 2 ; - stack contains {r1, r2} 12010D3012; print newline 00D300 ; duplicate stack[0] - stack contains {r1, r2, r1} 01D300 ; duplicate stack[1] - stack contains {r1, r2, r1, r2} 44D ; math / - stack contains {r1, r2, r1/r2} 301 ; print from stack to output ``` Sources: * <https://stackoverflow.com/a/473309/6850771> - `d` (capitalized) * <https://stackoverflow.com/q/15405966/6850771> - `0` through `9` [Try it online!](https://tio.run/##S0lNzsxNzPn/38LIBYgMDFyMDQwMDEGkCYg0NDI0MjA0ALNQJI3wSRrjkzQBCxn9//81L183OTE5IxUA) You'll need to disable the output cache if it's not automatically disabled. ]
[Question] [ ## The background My son Leonhard (4 years old) loves labyrinths. I don't know where he knows labyrinths from, but he paints them and knows quite well how they work: ![Labyrinth](https://i.stack.imgur.com/qhS4X.jpg) Recently, he started making a game from his paintings. These are his rules: * a black square denotes the starting point. * a hook denotes the exit of the labyrinth (that's where you get pulled out). * you can collect crowns. * you can collect gold nuggets (the round things). * you can go a way forth and back, but not more than that. * arrows may guide you to the exit. (If he paints a labyrinth for me to solve, they are often misleading). Annotated version: * blue: starting point * orange: crowns * yellow: area with gold nuggets * green: hook (exit) * pink: arrows (mostly misleading) ![Annotated labyrinth](https://i.stack.imgur.com/6I28o.jpg) ## The Task Maybe you know, at the age of 4, kids start telling porky-pies and sometimes he does not follow his own rules, especially if he finds out that he cannot reach the end of the maze any more. That's where you come into play: since I'm looking for [games for kids](https://softwarerecs.stackexchange.com/questions/16823/computer-games-for-4-year-old-children) anyway, you turn his idea into a game where cheating is not possible. Well, we need some more definitions I'd say: * the playing field is a `n`\*`m` rectangle of equally sized squares. * a square can have 0 to 4 walls, one on each side. * a crown is worth 50 points. * a gold nugget is worth 20 points. * walking on a square that has already been walked subtracts 1 point. * squares are marked in a way to identify how often the player walked on it (0, 1 or 2 times) * the player can walk in 4 directions, except if there is a wall. * Input device can be anything. Please consider keyboard support. * The labyrinth must be solvable. I.e. it must be possible to reach the hook from the starting point and it must be possible to collect all the valuables (even if that does not result in the highest possible score). * If the player gets stuck, the game ends. * The player must not die by falling off the board. You may put a wall around the complete maze or wrap around edges, whatever you like. * the program takes an word (0-65535) argument as input. This is the seed for the random number generator. Calling the program with the same seed again results in the same labyrinth. Bonus: * calculate the maximum points that can be collected. Consider that due to -1 points it might be better to not collect all items. * Show the best solution (shortest way to get maximum points) ## The Rules This is a popularity contest, since I want to be able to read and understand the code and perhaps adapt to new ideas of my son. Sorry, code golfers, maybe you want to create a copy of this question with rules more suitable for golfing, e.g. a console version with all the characters defined. The most popular game on 3rd of May will become the accepted answer. And, hey, why not publish it in an app store? [Answer] # JavaScript Work in progress. Unfortunately the maze is not always solvable - the limit on back-forward is the real hurdle. **Edit 1** Cosmetic **Edit 2** Better gameplay, but the big problem is still there ``` var rows, columns, rowOfs, maze, plPos, points, playing $('#BNEW').on('click', function() { NewMaze(); }); $('#BREP').on('click', function() { Start(); }); $(document).on('keydown', function(e) { var ok, move, pxy, mz, $td switch (e.which) { case 37: (move = -1, ok = maze[plPos+move] < 9 && maze[plPos+move*2] < 9); break; case 39: (move = 1, ok = maze[plPos+move] < 9 && maze[plPos+move*2] < 9); break; case 38: (move = -rowOfs, ok = maze[plPos+move] < 9 && maze[plPos+move*2] < 9); break; case 40: (move = rowOfs, ok = maze[plPos+move] < 9 && maze[plPos+move*2] < 9); break; } if (playing && ok) { pxy = getXY(plPos) mz = maze[plPos] < 8 ? 8 : 9; $td = $('#Field table tr').eq(pxy.y).find('td').eq(pxy.x) $td.addClass("m"+mz); maze[plPos] = mz; maze[plPos+move] = mz; plPos += move*2; mz = maze[plPos]; PTS.value = mz==7 ? points += 20 : mz==6 ? points += 50 : mz == 8 ? points -= 1 : points; pxy = getXY(plPos) $td = $('#Field table tr').eq(pxy.y).find('td').eq(pxy.x) $td.removeClass("m6 m7") $('#Player').finish().animate(playerCss(pxy.x,pxy.y)); CheckEndGame(); } return !move }); function CheckEndGame() { var msg = '' if (maze[plPos] == 5) { msg = "Maze completed!"; } else if (maze[plPos+1]==9 && maze[plPos-1]==9 && maze[plPos+rowOfs]==9 && maze[plPos-rowOfs]==9) { msg = "You are stuck, try again!"; } if (msg) { $("#Msg").text(msg).show(); playing=false } } function seed(s) { return function() { s = Math.sin(s) * 10000; return s - Math.floor(s); }; }; function Build() { var i var Fill = function(p) { var d=[rowOfs,-rowOfs,1,-1], i, s, l maze[p] = 1 while(d[0]) { i = random()*d.length|0 s = d[i] if (s != (l=d.pop())) d[i]=l if (maze[p+s+s]>8) { maze[p+s] = 1, Fill(p+s+s) } } } rowOfs = (columns + 1) * 2 maze = Array(rowOfs * (rows*2+1)) for (i=0; i < maze.length; i++) maze[i] = i % rowOfs? 9 : 0 Fill(rowOfs+2) } function NewMaze() { SEED.value = Math.random()*65536 | 0 Start() } function Start() { var sd = SEED.value || 1 columns = COLS.value |0 || 18 rows = ROWS.value | 0 || 12 COLS.value = columns ROWS.value = rows random = seed(sd) PTS.value = points = 0 $("#Msg").hide(); Build() plx = random()*columns|0; ply = random()*rows|0; setPlayer(plx,ply); plPos = getPos(plx,ply); BlockTriples(plPos); AddItems(plPos); Draw(); playing = true; } function AddItems(p) { var d=[rowOfs,-rowOfs,1,-1] var cells=[] // scan all reachable cells and calc distance from start var Go = function(p,l) { var i,t,mark,r ++l cells.push([p,l]) maze[p] = 8; for(i=0; d[i]; i++) { t = d[i] if (maze[p+t]<2 && maze[p+t+t]<2) { Go(p+t+t, l) } } maze[p] = 0; } Go(p,0) cells.sort(function(a,b){return a[1]-b[1]}) cells=cells.slice(10) // cut the shortest distances r = random()*10|0; //exit r = cells.length-r-1 maze[cells[r][0]] = 5; console.log(r) cells = cells.slice(0,r) var ncr = rows, nnu = columns for(i = ncr+nnu; i; i--) { r = random()*cells.length|0 maze[cells[r][0]] = (i > ncr ? 7 : 6); cells[r] = cells.pop(); } } function BlockTriples(p) { var d=[rowOfs,-rowOfs,1,-1] var Go = function(p) { var i,t,size=[0,0,0,0],s=1,nw=0,min,minp maze[p] = 8 for(i=0; d[i]; i++) { t = d[i] if (maze[p+t]<9 && maze[p+t+t]<8) { ++nw s += size[i] = Go(p+t+t) } } if (nw > 2) // triple way, block the smallest { for(i=0,min=1e6; d[i]; i++) size[i] && size[i] < min && (min = size[minp = i]) maze[p + d[minp]] = 5; } maze[p]=0 return s } Go(p) } function Draw() { var q=[], i, x, y; for(i = rowOfs+2, y = 0; y < rows; y++) { q.push('<tr>') for (x = 0; x < columns; i += 2, x++) { tcl = 'm'+(maze[i]|0) maze[i-1]>8 && (tcl += ' wl') maze[i+1]>8 && (tcl += ' wr') maze[i-rowOfs]>8 && (tcl += ' wu') maze[i+rowOfs]>8 && (tcl += ' wb') q.push('<td class="'+tcl+'"></td>') } q.push('</tr>') i += rowOfs+2 } $("#TOUT").html(q.join('')); $("#Field").show(); } function setPlayer(posx, posy) { $('#Player').css(playerCss(posx, posy)); } function getXY(pos) { return { x: (plPos % rowOfs)/2-1, y: plPos / rowOfs / 2 | 0} } function getPos(x, y) { return (x+y*rowOfs)*2 + rowOfs+2; } function playerCss(posx, posy) { return{ left: 6+posx*21, top: posy*21+2}; } ``` ``` input { width: 3em; margin-right:1em } table { border: 2px solid #000; border-collapse: collapse; font-size: 8px } #Field { margin: 10px; position: relative; display: none; } td { width: 19px; height: 19px; padding: 0; margin: 0; text-align: center; } td.wl { border-left: 2px solid #444; background: #fff } td.wr { border-right: 2px solid #444; background: #fff } td.wt { border-top: 2px solid #444;; background: #fff } td.wb { border-bottom: 2px solid #444; background: #fff } td.m7 { background: #ffd url(https://i.stack.imgur.com/QUInh.png) -21px 0} td.m6 { background: #efe url(https://i.stack.imgur.com/QUInh.png) -1px 0} td.m5 { background: #ddf url(https://i.stack.imgur.com/QUInh.png) -40px 0} td.m8 { background: #eed } td.m9 { background: #f55 } #Player { position: absolute; top:0; left:0; color: #007; background: #fcb; font-size:12px } #Msg { color: red; font-size:40px; display:none; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> ID:<input id=SEED> Rows:<input id=ROWS> Columns:<input id=COLS> <button id=BNEW>New</button> <button id=BREP>Replay</button> <div id=Msg></div> <div id=Field> <table id=TOUT border=0 cellspacing=0 cellpadding=0> </table> <span id=Player>โ€šรตร‘</span> </div> Score: <input readonly id=PTS> ``` [Answer] # Java I never complained about GolfScript or CJam, but here's a Java answer for you anyway. This was a really enjoyable challenge. ;) ``` import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.Ellipse2D; import java.util.*; import javax.swing.*; public class MazeMaker { int row, col, exitRow, exitCol, numCells, score, array[][]; final int SQWIDTH = 20; boolean gameOver = true; Ellipse2D.Double ellipse; JFrame frame; JPanel mazePanel; JLabel scoreLabel; public MazeMaker() { frame = new JFrame("Maze"); frame.setLayout(new BorderLayout()); JPanel topPanel = createTopPanel(); frame.add(topPanel,BorderLayout.NORTH); createMazePanel(); frame.add(new JScrollPane(mazePanel),BorderLayout.CENTER); setKeyActions(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } private void constructArray(int seed, int rows, int cols) { array = new int[rows*2-1][cols*2-1]; for (int[] a : array) Arrays.fill(a,-1); numCells = (array.length / 2 + 1) * (array[0].length / 2 + 1); Random rand = new Random(seed); int row = rand.nextInt(array.length / 2 + 1) * 2; int col = rand.nextInt(array[0].length / 2 + 1) * 2; array[row][col] = 0; boolean first = true, a = false, exitFound = false; while (true) { if (first) { int direction = rand.nextInt(4); if (direction == 0 && row != 0) { array[row-1][col] = 0; array[row-2][col] = 0; row -= 2; first = false; } else if (direction == 1 && col != array[0].length - 1) { array[row][col+1] = 0; array[row][col+2] = 0; col += 2; first = false; } else if (direction == 2 && row != array.length - 1) { array[row+1][col] = 0; array[row+2][col] = 0; row += 2; first = false; } else if (direction == 3 && col != 0) { array[row][col-1] = 0; array[row][col-2] = 0; col -= 2; first = false; } } else { int availableCells = 0; boolean up = false, down = false, left = false, right = false; if (row != 0 && array[row-2][col] == -1) { availableCells++; up = true; } if (col != array[0].length-1 && array[row][col+2] == -1) { availableCells++; right = true; } if (row != array.length-1 && array[row+2][col] == -1) { availableCells++; down = true; } if (col != 0 && array[row][col-2] == -1) { availableCells++; left = true; } if (availableCells != 0) { a = true; while (true) { boolean[] b = {up,right,down,left}; int i = rand.nextInt(4); if (b[i]) { if (i == 0) { array[row-1][col] = 0; array[row-2][col] = 0; row -= 2; } else if (i == 1) { array[row][col+1] = 0; array[row][col+2] = 0; col += 2; } else if (i == 2) { array[row+1][col] = 0; array[row+2][col] = 0; row += 2; } else if (i == 3) { array[row][col-1] = 0; array[row][col-2] = 0; col -= 2; } break; } } } else { array[row][col] = 1; if (!exitFound && a) { if (new Random().nextInt(5) == 0) { exitFound = true; exitRow = row; exitCol = col; } } a = false; if (row != 0 && array[row-1][col] == 0 && (array[row-2][col] == 0 || array[row-2][col] == 1)) { array[row-1][col] = 1; array[row-2][col] = 1; row -= 2; } else if (col != array[0].length-1 && array[row][col+1] == 0 && (array[row][col+2] == 0 || array[row][col+2] == 1)) { array[row][col+1] = 1; array[row][col+2] = 1; col += 2; } else if (row != array.length-1 && array[row+1][col] == 0 && (array[row+2][col] == 0 || array[row+2][col] == 1)) { array[row+1][col] = 1; array[row+2][col] = 1; row += 2; } else if (col != 0 && array[row][col-1] == 0 && (array[row][col-2] == 0 || array[row][col-2] == 1)) { array[row][col-1] = 1; array[row][col-2] = 1; col -= 2; } } if (checkDone()) { if (!exitFound) { exitRow = row; exitCol = col; } break; } } } } private boolean checkDone() { int count = 0; for (int k = 0; k < array.length; k+=2) { for (int l = 0; l < array[0].length; l+=2) { if (array[k][l] == 0 || array[k][l] == 1) count++; } } return count == numCells; } private JPanel createTopPanel() { GridBagLayout l = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; JPanel panel = new JPanel(l); JLabel inputLabel = new JLabel("ID:"); c.gridwidth = 1; l.setConstraints(inputLabel,c); panel.add(inputLabel); JTextField inputField = new JTextField(5); l.setConstraints(inputField,c); panel.add(inputField); JLabel rowLabel = new JLabel("Rows:"); l.setConstraints(rowLabel,c); panel.add(rowLabel); JTextField rowField = new JTextField(3); l.setConstraints(rowField,c); panel.add(rowField); JLabel colLabel = new JLabel("Columns:"); l.setConstraints(colLabel,c); panel.add(colLabel); JTextField colField = new JTextField(3); l.setConstraints(colField,c); panel.add(colField); JButton applyButton = new JButton("Apply"); applyButton.addActionListener(ev -> { try { int seed = Integer.parseInt(inputField.getText()), rows = Integer.parseInt(rowField.getText()), cols = Integer.parseInt(colField.getText()); if (seed >= 0 && rows >= 3 && cols >= 3) { gameOver = false; scoreLabel.setText("Score: " + (score = 0)); constructArray(seed,rows,cols); row = (int) (Math.random() * (array.length / 2 + 1)) * 2; col = (int) (Math.random() * (array[0].length / 2 + 1)) * 2; frame.setSize((1+SQWIDTH * array[0].length)/2 > 750 ? (1+SQWIDTH * array[0].length)/2 : 750, 75+(1+SQWIDTH * array.length)/2); mazePanel.setPreferredSize(new Dimension( (1+SQWIDTH * array[0].length)/2 > 750 ? (1+SQWIDTH * array[0].length)/2 - 15 : 750, 15+(1+SQWIDTH * array.length)/2)); ellipse = new Ellipse2D.Double(col*SQWIDTH/2+3,row*SQWIDTH/2+3,10,10); setItems(); mazePanel.repaint(); } } catch (NumberFormatException ignore) {} }); l.setConstraints(applyButton,c); panel.add(applyButton); scoreLabel = new JLabel("Score: "); c.gridwidth = GridBagConstraints.REMAINDER; l.setConstraints(scoreLabel,c); panel.add(scoreLabel); return panel; } private void createMazePanel() { mazePanel = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int x = 0, y = 0; if (!gameOver) { for (int k = 0; k < array.length; k+=2) { for (int l = 0; l < array[0].length; l+=2) { int n = array[k][l]; if (n == 0 || n == 1 || n == 4 || n == 5 || n == 6) g.setColor(Color.white); else if (n == 2) g.setColor(Color.green); else if (n == 3) g.setColor(Color.red); g.fillRect(x, y, SQWIDTH, SQWIDTH); if (n == 4) { g.setColor(new Color(245,209,34)); g.fillOval(x+3, y+3, 10, 10); } else if (n == 5) { g.setColor(new Color(255,223,55)); g.fillPolygon(new int[]{x,x+3,x+8,x+13,x+16,x+14,x+2},new int[]{y+2,y+6,y+2,y+6,y+2,y+16,y+16},7); g.setColor(new Color(12,234,44)); g.fillOval(x+7,y+6,4,7); } else if (n == 6) { Graphics2D g2 = (Graphics2D) g.create(); g2.setStroke(new BasicStroke(2,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND)); g2.setColor(new Color(108,225,119)); g2.drawOval(x+5, y+1, 8, 8); g2.drawLine(x+5, y+3, x+5, y+11); g2.drawArc(x+5, y+8, 7, 7, 180, 180); } g.setColor(Color.black); if (k != array.length-1 && array[k+1][l] == -1) g.fillRect(x-3, y+SQWIDTH-3, SQWIDTH+3, 3); if (l != array[0].length-1 && array[k][l+1] == -1) g.fillRect(x+SQWIDTH-3,y,3,SQWIDTH); x += SQWIDTH; } x = 0; y += SQWIDTH; } g.setColor(Color.red); ((Graphics2D) g).fill(ellipse); } } }; } private void setKeyActions() { InputMap im = mazePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); ActionMap am = mazePanel.getActionMap(); im.put(KeyStroke.getKeyStroke("pressed UP"), "up"); am.put("up", new AbstractAction() { @Override public void actionPerformed(ActionEvent ev) { if (row != 0 && array[row-1][col] != -1 && array[row-2][col] != 3 && !gameOver) { int n = array[row][col]; array[row][col] = n == 0 || n == 1 || n == 4 || n == 5 ? 2 : 3; row -= 2; n = array[row][col]; if (n == 4) scoreLabel.setText("Score: " + (score += 20)); else if (n == 5) scoreLabel.setText("Score: " + (score += 50)); else if (n == 2) scoreLabel.setText("Score: " + (score -= 1)); ellipse.y = row * SQWIDTH/2 + 3; mazePanel.repaint(); } if (!gameOver && array[row][col] == 6) { JOptionPane.showMessageDialog(frame, "Huzzah! You found the exit! ", "Finish", JOptionPane.PLAIN_MESSAGE); gameOver = true; } else if (!gameOver && checkGameOver()) { JOptionPane.showMessageDialog(frame, "You got trapped! Try again!", "Game over", JOptionPane.PLAIN_MESSAGE); gameOver = true; } } }); im.put(KeyStroke.getKeyStroke("pressed RIGHT"), "right"); am.put("right",new AbstractAction() { @Override public void actionPerformed(ActionEvent ev) { if (col != array[0].length-1 && array[row][col+1] != -1 && array[row][col+2] != 3 && !gameOver) { int n = array[row][col]; array[row][col] = n == 0 || n == 1 || n == 4 || n == 5 ? 2 : 3; col += 2; n = array[row][col]; if (n == 4) scoreLabel.setText("Score: " + (score += 20)); else if (n == 5) scoreLabel.setText("Score: " + (score += 50)); else if (n == 2) scoreLabel.setText("Score: " + (score -= 1)); ellipse.x = col * SQWIDTH/2 + 3; mazePanel.repaint(); } if (!gameOver && array[row][col] == 6) { JOptionPane.showMessageDialog(frame, "Huzzah! You found the exit! ", "Finish", JOptionPane.PLAIN_MESSAGE); gameOver = true; } else if (!gameOver && checkGameOver()) { JOptionPane.showMessageDialog(frame, "You got trapped! Try again!", "Game over", JOptionPane.PLAIN_MESSAGE); gameOver = true; } } }); im.put(KeyStroke.getKeyStroke("pressed DOWN"), "down"); am.put("down", new AbstractAction() { @Override public void actionPerformed(ActionEvent ev) { if (row != array.length-1 && array[row+1][col] != -1 && array[row+2][col] != 3 && !gameOver) { int n = array[row][col]; array[row][col] = n == 0 || n == 1 || n == 4 || n == 5 ? 2 : 3; row += 2; n = array[row][col]; if (n == 4) scoreLabel.setText("Score: " + (score += 20)); else if (n == 5) scoreLabel.setText("Score: " + (score += 50)); else if (n == 2) scoreLabel.setText("Score: " + (score -= 1)); ellipse.y = row * SQWIDTH/2 + 3; mazePanel.repaint(); } if (!gameOver && array[row][col] == 6) { JOptionPane.showMessageDialog(frame, "Huzzah! You found the exit! ", "Finish", JOptionPane.PLAIN_MESSAGE); gameOver = true; } else if (!gameOver && checkGameOver()) { JOptionPane.showMessageDialog(frame, "You got trapped! Try again!", "Game over", JOptionPane.PLAIN_MESSAGE); gameOver = true; } } }); im.put(KeyStroke.getKeyStroke("pressed LEFT"), "left"); am.put("left",new AbstractAction() { @Override public void actionPerformed(ActionEvent ev) { if (col != 0 && array[row][col-1] != -1 && array[row][col-2] != -1 && !gameOver) { int n = array[row][col]; array[row][col] = n == 0 || n == 1 || n == 4 || n == 5 ? 2 : 3; col -= 2; n = array[row][col]; if (n == 4) scoreLabel.setText("Score: " + (score += 20)); else if (n == 5) scoreLabel.setText("Score: " + (score += 50)); else if (n == 2) scoreLabel.setText("Score: " + (score -= 1)); ellipse.x = col * SQWIDTH/2 + 3; mazePanel.repaint(); } if (!gameOver && array[row][col] == 6) { JOptionPane.showMessageDialog(frame, "Huzzah! You found the exit! ", "Finish", JOptionPane.PLAIN_MESSAGE); gameOver = true; } else if (!gameOver && checkGameOver()) { JOptionPane.showMessageDialog(frame, "You got trapped! Try again!", "Game over", JOptionPane.PLAIN_MESSAGE); gameOver = true; } } }); } private void setItems() { array[exitRow][exitCol] = 6; Random r = new Random(); for (int k = 1; k < (array.length * array[0].length) / 20; k++) { int row = r.nextInt(array.length / 2 + 1) * 2, col = r.nextInt(array[0].length / 2 + 1) * 2; if ((row == this.row && col == this.col) || array[row][col] == 4 || array[row][col] == 5 || array[row][col] == 6) k--; else array[row][col] = r.nextInt(2) + 4; } } private boolean checkGameOver() { if (row == 0 && col == 0) return (array[row+2][col] == 3 && array[row][col+2] == 3) || (array[row+1][col] == -1 && array[row][col+2] == 3) || (array[row+2][col] == 3 && array[row][col+1] == -1); else if (row == 0 && col == array[0].length-1) return (array[row+2][col] == 3 && array[row][col-2] == 3) || (array[row+1][col] == -1 && array[row][col-2] == 3) || (array[row+2][col] == 3 && array[row][col-1] == -1); else if (row == array.length-1 && col == 0) return (array[row-2][col] == 3 && array[row][col+2] == 3) || (array[row-1][col] == -1 && array[row][col+2] == 3) || (array[row-2][col] == 3 && array[row][col+1] == -1); else if (row == array.length-1 && col == array[0].length-1) return (array[row-2][col] == 3 && array[row][col-2] == 3) || (array[row-1][col] == -1 && array[row][col-2] == 3) || (array[row-2][col] == 3 && array[row][col-1] == -1); else if (row == 0) return (array[row+2][col] == 3 && array[row][col-1] == -1 && array[row][col+1] == -1) || (array[row+1][col] == -1 && array[row][col-2] == 3 && array[row][col+1] == -1) || (array[row+1][col] == -1 && array[row][col-1] == -1 && array[row][col+2] == 3) || (array[row+1][col] == -1 && array[row][col-2] == 3 && array[row][col+2] == 3) || (array[row+2][col] == 3 && array[row][col-2] == 3 && array[row][col+1] == -1) || (array[row+2][col] == 3 && array[row][col-1] == -1 && array[row][col+2] == 3) || (array[row+2][col] == 3 && array[row][col-2] == 3 && array[row][col+2] == 3); else if (col == 0) return (array[row][col+2] == 3 && array[row-1][col] == -1 && array[row+1][col] == -1) || (array[row][col+1] == -1 && array[row-2][col] == 3 && array[row+1][col] == -1) || (array[row][col+1] == -1 && array[row-1][col] == -1 && array[row+2][col] == 3) || (array[row][col+1] == -1 && array[row-2][col] == 3 && array[row+2][col] == 3) || (array[row][col+2] == 3 && array[row-2][col] == 3 && array[row+1][col] == -1) || (array[row][col+2] == 3 && array[row-1][col] == -1 && array[row+2][col] == 3) || (array[row][col+2] == 3 && array[row-2][col] == 3 && array[row+2][col] == 3); else if (row == array.length-1) return (array[row-2][col] == 3 && array[row][col-1] == -1 && array[row][col+1] == -1) || (array[row-1][col] == -1 && array[row][col-2] == 3 && array[row][col+1] == -1) || (array[row-1][col] == -1 && array[row][col-1] == -1 && array[row][col+2] == 3) || (array[row-1][col] == -1 && array[row][col-2] == 3 && array[row][col+2] == 3) || (array[row-2][col] == 3 && array[row][col-2] == 3 && array[row][col+1] == -1) || (array[row-2][col] == 3 && array[row][col-1] == -1 && array[row][col+2] == 3) || (array[row-2][col] == 3 && array[row][col-2] == 3 && array[row][col+2] == 3); else if (col == array[0].length-1) return (array[row][col-2] == 3 && array[row-1][col] == -1 && array[row+1][col] == -1) || (array[row][col-1] == -1 && array[row-2][col] == 3 && array[row+1][col] == -1) || (array[row][col-1] == -1 && array[row-1][col] == -1 && array[row+2][col] == 3) || (array[row][col-1] == -1 && array[row-2][col] == 3 && array[row+2][col] == 3) || (array[row][col-2] == 3 && array[row-2][col] == 3 && array[row+1][col] == -1) || (array[row][col-2] == 3 && array[row-1][col] == -1 && array[row+2][col] == 3) || (array[row][col-2] == 3 && array[row-2][col] == 3 && array[row+2][col] == 3); else return (array[row-2][col] == 3 && array[row][col+1] == -1 && array[row+1][col] == -1 && array[row][col-1] == -1) || (array[row-1][col] == -1 && array[row][col+2] == 3 && array[row+1][col] == -1 && array[row][col-1] == -1) || (array[row-1][col] == -1 && array[row][col+1] == -1 && array[row+2][col] == 3 && array[row][col-1] == -1) || (array[row-1][col] == -1 && array[row][col+1] == -1 && array[row+1][col] == -1 && array[row][col-2] == 3) || (array[row-1][col] == -1 && array[row+1][col] == -1 && array[row][col-2] == 3 && array[row][col+2] == 3) || (array[row-2][col] == 3 && array[row+2][col] == 3 && array[row][col-1] == -1 && array[row][col+1] == -1) || (array[row-2][col] == 3 && array[row+1][col] == -1 && array[row][col-1] == -1 && array[row][col+2] == 3) || (array[row-1][col] == -1 && array[row+2][col] == 3 && array[row][col-2] == 3 && array[row][col+1] == -1) || (array[row-1][col] == -1 && array[row+2][col] == 3 && array[row][col-1] == -1 && array[row][col+2] == 3) || (array[row-2][col] == 3 && array[row+1][col] == -1 && array[row][col-2] == 3 && array[row][col+1] == -1) || (array[row-1][col] == -1 && array[row+2][col] == 3 && array[row][col-2] == 3 && array[row][col+2] == 3) || (array[row-2][col] == 3 && array[row+1][col] == -1 && array[row][col-2] == 3 && array[row][col+2] == 3) || (array[row-2][col] == 3 && array[row+2][col] == 3 && array[row][col-1] == -1 && array[row][col+2] == 3) || (array[row-2][col] == 3 && array[row+2][col] == 3 && array[row][col-2] == 3 && array[row][col+1] == -1) || (array[row-2][col] == 3 && array[row+2][col] == 3 && array[row][col-2] == 3 && array[row][col+2] == 3); } public static void main(String[] args) { SwingUtilities.invokeLater(MazeMaker::new); } } ``` The process of creating the actual maze uses the [depth-first search algorithm](http://en.wikipedia.org/wiki/Maze_generation_algorithm#Depth-first_search), but with an iterative approach. Here's how it works. We start with a 2D array of `int` values, each element being a -1. A random element with even indices is chosen, and its value becomes 0: ``` -1 -1 -1 -1 -1 -1 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 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ``` Then the program enters a loop, checking for available cells until it reaches a state where there are no available cells. This can happen several times, and is when it begins to backtrack. At this time all 0s that it comes across become 1s. Also during this time is when it determines whether an exit should be placed at that location. So at the end of it all, the array could look like this: ``` 0 0 0 0 0 0 1 1 1 0 -1 -1 -1 -1 -1 0 -1 1 0 0 0 0 0 -1 0 -1 1 -1 -1 -1 -1 -1 -1 0 -1 1 0 0 0 0 0 0 0 -1 1 0 -1 -1 -1 -1 -1 -1 -1 1 0 -1 1 1 1 1 1 -1 1 0 -1 1 -1 1 -1 -1 -1 1 0 -1 1 -1 1 1 1 1 1 ``` When there are a predetermined number of 1s or 0s at certain spots in the array, the loop exits. Then, using the array, the resulting maze is drawn: ![Resulting maze](https://i.stack.imgur.com/wj09T.png) It's easy to see that the -1s in the array represent walls, and the 0s and 1s are corridors. Items are randomly distributed throughout the maze. The red ellipse is the "player" that you control. The maze is wrapped in a scroll pane for convenience so that if the size exceeds the frame's maximum size you can scroll to see the rest of the maze. I'd say the only problem with this is how the end of game check is carried out. I thought about several ways to go about doing it, but I ended up resorting to hard-coding it all. I'm open to suggestions on how it can be done. [Answer] # Python I realize I'm late for the party, but here is my take on this challenge. I went text based as I haven't gotten around to learning pygame, yet. It is Python 3. Change input to raw\_input and it should work in python2 also. The Hook (exit) is represented by "J". "W" is crowns (50). "G" is Gold nuggets (20). The Player is "O". I experimented with using "P" for the player, but I found "O" easier to Identify. I used standard depth first maze generation, then add the gold, crowns, hook, and current player position. I did not implement the criteria that all treasure can be obtained. ![Screen shot of maze game](https://i.stack.imgur.com/bA2Fo.png) ``` import random direcs = {'n':[0,-1], 's':[0,1], 'w':[-1,0], 'e':[1,0]} dirs = ['n','s','e','w'] class maze_space(object): def __init__(self): self.n = 0 self.s = 0 self.e = 0 self.w = 0 self.visited = 0 self.contents = ' ' def mirror(self,drct,val): if drct == 'n' : self.s = val if drct == 's' : self.n = val if drct == 'e' : self.w = val if drct == 'w' : self.e = val class MazeGame(object): def __init__(self,horiz=12,vert=8): self.completed = 0 self.score = 0 self.grid = [[maze_space() for x in range(horiz)] for y in range(vert)] def walk(y,x): self.grid[y][x].visited = 1 drs = self.make_dir_list(y, x) random.shuffle(drs) for dr in drs: yy = y + direcs[dr][1] xx = x + direcs[dr][0] if not self.grid[yy][xx].visited: setattr(self.grid[y][x], dr, 1) self.grid[yy][xx].mirror(dr, 1) walk(yy, xx) y, x = self.pick_row_col() walk(y, x) self.maze_populate() self.printmaze() def main_loop(self): while not self.completed: move = get_move(self.grid, self.cury, self.curx) self.make_move(move) self.printmaze() def pick_row_col(self): '''pick a random cell in the grid''' row = random.randint(0, len(self.grid) - 1) col = random.randint(0, len(self.grid[0]) - 1) return row, col def make_dir_list(self, y, x): '''return list of available move directions''' drs = dirs[:] if x == 0 : drs.pop(drs.index('w')) if y == 0 : drs.pop(drs.index('n')) if x == len(self.grid[0]) - 1 : drs.pop(drs.index('e')) if y == len(self.grid) - 1 : drs.pop(drs.index('s')) return drs def maze_populate(self): # populate maze with crowns and gold nuggets for treasure in ['G', 'W']: for _ in range(random.randint(1, len(self.grid[0]))): yy, xx = self.pick_row_col() self.grid[yy][xx].contents = treasure self.cury, self.curx = self.pick_row_col() # start position exity, exitx = self.pick_row_col() # hook (exit) position #make sure start is not on top of exit while self.cury == exity and self.curx == exitx : exitx = random.randint(0, len(self.grid[0]) - 1) self.grid[self.cury][self.curx].contents = 'O' self.grid[exity][exitx].contents = 'J' def make_move(self,dr): self.grid[self.cury][self.curx].visited += 1 self.grid[self.cury][self.curx].contents = '.' # player has walked twice -> disable if self.grid[self.cury][self.curx].visited >= 3: self.grid[self.cury][self.curx].contents = 'X' drs = self.make_dir_list(self.cury, self.curx) for d in drs: yyy = self.cury + direcs[d][1] xxx = self.curx + direcs[d][0] self.grid[yyy][xxx].mirror(d,0) yy = self.cury + direcs[dr][1] xx = self.curx + direcs[dr][0] if self.grid[yy][xx].contents == 'J': self.completed = 1 if self.grid[yy][xx].contents == 'W': self.score += 50 if self.grid[yy][xx].contents == 'G': self.score += 20 if self.grid[yy][xx].contents == '.': self.score -= 1 self.grid[yy][xx].contents = 'O' self.cury, self.curx = yy, xx def printmaze(self): if self.completed: print('\nMaze complete. Good job!') print('Score: %d'%self.score) print('|'+''.join('---' for _ in self.grid[0])) for line in self.grid: print('|' + ''.join(' %s '%x.contents if x.e else ' %s|'% x.contents for x in line)) print('|' + ''.join(' -' if x.s else '---' for x in line)) def get_params(): hor = input('width (default=12): ') hor = int(hor) if hor else 12 ver = input('height (default=8): ') ver = int(ver) if ver else 8 rseed = input('seed : ') rseed = int(rseed) if rseed else random.randint(1,65535) print(rseed) random.seed(rseed) print("'J' = hook (exit)\n'O' = Player") print("'G' = gold nugget (20 points)\n'W' = Crown (50 points)") print('Player may only tread on a given tile twice') return hor,ver def get_move(grid, y, x): choice = input('where do you want to move %s q to quit: '%dirs) if choice == 'q' : exit() if choice in dirs and getattr(grid[y][x],choice): return choice return get_move(grid, y, x) def main(): hor,ver = get_params() maze = MazeGame(hor,ver) maze.main_loop() if __name__ == '__main__': main() ``` ]
[Question] [ Greetings, noble code golfers. Today you will resolve the most ancient and distinguished of debates - Emacs or Vim? Your challenge is to take two search terms as input, and output which of those terms has the most Google search results. (This is obviously completely fair. What do you mean, biased?) Here are some example inputs and outputs: Input: `emacs` and `vim` Output: `vim` (totally not creating any flamewars in the comments) Input: `google` and `microsoft` Output: `google` Input: `code golf stack exchange` and `code review stack exchange` Output: `code golf stack exchange` (yeah!) And here are some edge cases just for fun (and for testing your solutions): Input: `About 1,000,000 results` and `About 100,000 results` Output: `About 100,000 results` Input: `This will autocotrect` and `Another testcase` Output: `Another testcase` (if you don't consider autocorrecting, then the first one will win) For the following test cases, you must remove the `#` signs in the search terms first, since they rely on the term having a specific amount of results and posting the term here would ruin that. Input: `Thissear#chter#mhasno#results` and `Another testcase` Output: `Another testcase` (just a test for zero results) Input: `"These exact wo#rds do#n't exi#st# on the Internet"` and `Another testcase` Output: `Another testcase` (testing `"`s) Input: `Abo#ut 1,65#2,85#3,2#86 re#sults` and `Another testcase` Output: `Another testcase` (this one is tricky - the above search term has one result) Input: `"Abo#ut 4#8,234,8#75,14#7 res#ults"` and `Another testcase` Output: `Another testcase` (also tricky - no results, so it displays the search term) You don't need to handle the corner-case of `"quoted"` searches returning "No results, showing results without quotes instead" because that would just be too complicated. You don't need to handle inputs with the same number of results either. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win! [Answer] # Ruby, ~~203~~ 180 bytes ``` ->*s{s.map{|x|[(open("http://www.google.com/search?nord=1&q=#{URI.escape x}&nfpr=1").read.match(/s">(About )?([\d,]+) result/)||[?0])[-1].split(?,).join.to_i,x]}.max[1]} ``` +11 bytes for the `-ropen-uri` flag (plus space). Input is taken as two arguments. URL explanation: * `?nord=1`: prevent auto-redirect from HTTP to HTTPS * `&q=#{URI.escape x}`: escape the query so `"`s work * `&nfpr=1`: no autocorrect The whole `map` turns `['emacs','vim']` into `[[2150000, 'emacs'], [14900000, 'vim']]`. (You can see this by changing the `.max[1]` at the end to `.inspect`.) Then, the `max` is taken, which will grab the one with the most results, and `[1]` is used to get the search term. [Answer] Of the text editors mentioned in the problem, only one of them can solve this on its own... # Emacs: 137 keystrokes ``` <C-o><C-u><C-k>(if(<<C-y><C-y><M-<><C-n><F3><C-a>http://google.com/search?nfpr=1&q=<C-S-e><M-x>r-st<RET> <RET>+<RET><C-a><C-k><M-x>b-em<RET><C-y><RET><C-x><C-q><C-s><RET>ts"><RET><M-z><<C-x>0<C-y>0 r<C-a><C-M-s><RET>[0-9]<RET><C-b><M-z> <C-a><C-y><C-k><C-S-a><M-x><up><up><RET>,<RET><RET><F4><C-n><F4><C-e>)(next-line)())<C-x><C-e><C-n><C-a><C-k><C-x>h<DEL><C-y> ``` It expects the first search terms to be on the first line and the second search terms to be on the second line, with the cursor at the beginning of the buffer. For those unfamiliar with Emacs, * `C-s` means `Ctrl-S`. * `M-z` means `Alt-Z` (`Alt` is likely your meta key) * `M-<` means `Alt-<` or `Alt-Shift-,` * `C-S-e` means `Ctrl-Shift-e` For those familiar with Emacs, * Start emacs with `emacs -q`. That doesn't load your `.emacs` file, so any fancy packages won't intefere with this. ## Explanation 1. Write the beginning of the elisp statment shell * `<C-o><C-u><C-k>` Saves the arguments with a newline * `(if(<<C-y><C-y>` Write the start of the if statement and places 2 copies of the arguments * `<M-<><C-n>` Move to the second line 2. Define the HTTP macro. This converts the argument to a Google search URL and then returns the number of search results. * `<F3>` Start defining the keyboard macro * `<C-a>` Move to the start of the search term. * `http://google.com/search?nfpr=1&q=` Prepend the search URL * `<C-S-e><M-x>r-st<RET> <RET>+<RET>` Replace all the spaces with + signs. * `<C-a><C-k><M-x>b-em<RET><C-y><RET>` Emacs retrieve the raw HTML (`b-em` is short for `browse-url-emacs`) * `<C-x><C-q>` Make the file writable (required so the macro doesn't error ou t) * `<C-s><RET>ts"><RET>` Move to the number of results div (need to do a regular search because emacs macros rely on isearch to work) * `<M-z><`Cut the text of of the diff (this is why the was required) * `<C-x>0` Switch back to the original buffer * `<C-y>0 r`;; Put the results back on the line ('0 r' handles no results) * `<C-a><C-M-s><RET>[0-9]<RET><C-b><M-z> <C-a><C-y><C-k>`;; Extract the number from the string. * `<C-S-a><M-x><up><up><RET>,<RET><RET>` Strips commas out of the number * `<F4>` Finish the keyboard macro 3. Move down and execute the keyboard macro on the next line. * `<C-n>` Goes to the next line * `<F4>` Repeat the macro once. 4. Finish up the elisp statement and execute it * `<C-e>)(next-line)())` Finish up the elisp statement * `<C-x><C-e>` Evaluate the elisp command * `<C-n><C-a><C-k>` Kill the winning argument * `<C-x>h<DEL>` Delete everything else * `<C-y>` Paste the winning argument ## Running It Yourself Luckily you don't have to type all those keystrokes in perfectly! The meat and potatoes is all in a macro that you can just copy and paste. The macro can be copy and pasted into emacs! 1.Edit the keyboard macro `<C-x><C-k><C-e>` 2.Paste this into the whole buffer (paste should be `<C-y>`) ``` ;; Keyboard Macro Editor. Press C-c C-c to finish; press C-x k RET to cancel. ;; Original keys: C-a http://google.com/search?nfpr= 1&q= S-C-e M-x r-st RET SPC RET + RET C-a C-k M-x b-em RET C-y RET C-x C-q C-s RET ts"> RET M-z < C-x 0 C-y 0 SPC r C-a M-C-s [0-9] 5*DEL RET [0-9] RET C-b M-z SPC C-a C-y C-k S-C-a M-x 2*<up> RET , 2*RET Command: last-kbd-macro Key: none Macro: C-a ;; move-beginning-of-line http://google.com/search?nfpr= ;; self-insert-command * 30 1&q= ;; self-insert-command * 4 S-C-e M-x ;; execute-extended-command r-st ;; self-insert-command * 4 RET ;; newline SPC ;; self-insert-command RET ;; newline + ;; self-insert-command RET ;; newline C-a ;; move-beginning-of-line C-k ;; kill-line M-x ;; execute-extended-command b-em ;; self-insert-command * 4 RET ;; newline C-y ;; yank RET ;; newline C-x C-q ;; read-only-mode C-s ;; isearch-forward RET ;; newline ts"> ;; self-insert-command * 4 RET ;; newline M-z ;; zap-to-char < ;; self-insert-command C-x 0 ;; delete-window C-y ;; yank 0 ;; self-insert-command SPC ;; self-insert-command r ;; self-insert-command C-a ;; move-beginning-of-line M-C-s ;; isearch-forward-regexp RET ;; newline [0-9] ;; self-insert-command * 5 RET ;; newline C-b ;; backward-char M-z ;; zap-to-char SPC ;; self-insert-command C-a ;; move-beginning-of-line C-y ;; yank C-k ;; kill-line S-C-a M-x ;; execute-extended-command 2*<up> ;; previous-line RET ;; newline , ;; self-insert-command 2*RET ;; newline ``` 3. Type `<C-c><C-c>` to save the macro. 4. If following the explanation steps, replace step 2 with `<F4>` to run the macro (or just run it on its own to try) ## Caveats 1. You can't run the macro on the same search twice without killing the buffer the HTML gets loaded into. Kill the buffers * `<C-x><k> search<TAB>` * Choose one of the buffers in this list to kill. * Repeat for all the buffers beginning with "search" 2. If you run the macro too much, Google will think you are a robot and block access for atime * If the macro returns something like `<input type="submit" name="submit" value="Submit"...>`, then this likely occurred. * You can confirm it by looking at the raw HTML (`<C-x><C-b>` and choose the buffer with the search term in it). * If you see stuff about robots and captcha, Google's blocking you. It's not my fault. [Answer] # [Factor](http://factorcode.org), ~~305~~ ~~201~~ ~~196~~ ~~200~~ ~~201~~ ~~188~~ ~~184~~ ~~182~~ ~~179~~ ~~169~~ ~~178~~ ~~171~~ ~~165~~ ~~199~~ ~~171~~ ~~170~~ ~~165~~ 163 bytes A language nearly as verbose as Java, beating Ruby... and Powershell! :D Better regex, now. Thanks to [@fede s.](https://codegolf.stackexchange.com/users/39436/fede-s) for [5 bytes off!](https://codegolf.stackexchange.com/a/77477/46231) ``` [ dup [ url-encode "google.com/search?nfpr=1&q="prepend http-get R/ s">About [\d,]+/ first-match " "split second 10 >base ] map zip [ last ] sort-with last first ] ``` Or **~~159~~ 157** if the output can be like `{ "vim" 9782948234 }`: ``` [ dup [ url-encode "google.com/search?nfpr=1&q="prepend http-get R/ s">About [\d,]+/ first-match " "split second 10 >base ] map zip [ last ] sort-with last ] ``` --- On the other hand, if we want to be unkillable, for **~~199~~ ~~196~~ 193 bytes**: ``` [ dup [ url-encode "google.com/search?nfpr=1&q="prepend scrape-html nip dup "resultStats"find-by-id-between second text>> " "split second string>number ] map zip [ last ] sort-with last first ] ``` Unkillable because it parses HTML, so way more robust than the answers using regex. [Answer] # Java, ~~828~~ ~~800~~ ~~783~~ ~~744~~ ~~739~~ 687 bytes ``` import java.net.*;import java.util.*;import java.util.regex.*;interface G{static Scanner s(String a)throws Exception{URL u=new URL("http://google.com/search?q="+a);HttpURLConnection c=(HttpURLConnection)u.openConnection();c.addRequestProperty("User-Agent","Mozilla/4.0");return new Scanner(c.getInputStream());}static void main(String[]r)throws Exception{String a,b;String c=s(a=r[0]).useDelimiter("\\Z").next(),d=s(b=r[1]).useDelimiter("\\Z").next();Matcher m=Pattern.compile("ut ([0-9,]+) res").matcher(c);m.find();long i=new Scanner(m.group(1)).nextLong();m=Pattern.compile("ut ([0-9,]+) res").matcher(d);m.find();long j=new Scanner(m.group(1)).nextLong();System.out.print(i>j?a:b);}} ``` [Answer] # Python 3, ~~227~~ ~~226~~ ~~208~~ ~~213~~ ~~226~~ ~~220~~ ~~221~~ ~~206~~ ~~202~~ ~~200~~ 198 bytes ``` import re,requests as r,urllib.parse as u lambda*t:sorted(zip(map(lambda a:int(re.findall("s\">About ([\d,]+)",r.get("http://google.com/search?q="+u.quote(a)).text)[0].replace(",","")),t),t))[-1][1] ``` Assign the lambda to something to call it. Uses the [requests library](http://docs.python-requests.com). Ungolfed: ``` import re, requests as r, urllib.parse as u lambda*t: sorted( list( zip(map( lambda a: int(re.findall("About ([\d,]+)", r.get("http://google.com/search?q="+u.quote(a)).text)[0].replace(",","")), t ), t) ) )[-1][1] ``` [Answer] # Powershell, ~~175~~, 172 bytes ``` ($args|%{[pscustomobject]@{'a'=$_;'b'=[int]((iwr "google.com/search?nord=1&q=$_&nfpr=1").parsedhtml.getelementbyid('resultstats').innertext-split" ")[1]}}|sort -des b).a[0] ``` Showing the score as well as the name would cut 2 more bytes. This uses the same `unkillable` feature as the `196 Byte` **Factor** answer (Parsed HTML) and cuts down from the previous regex answer. [Answer] # Racket, ~~360~~ 337 bytes ``` #lang racket(require net/url net/uri-codec)(ฮป(t)(cddr(sort(map list t(map(lambda(a)(string->number(string-replace(list-ref(string-split(car(regexp-match#px"s\">About [\\d,]+ res"(call/input-url(string->url(string-append"http://google.com/search?nfpr=1&q="(uri-encode a)))(curry get-pure-port)port->string)))" ")1)",""")))))#:key cdr <))) ``` 0.o There's a reason they call it Lost In a Sea of Parentheses. Ungolfed: ``` #lang racket (require net/url) (require net/uri-codec) (define (open-url term) (call/input-url (string->url (string-append "http://" term)) (curry get-pure-port #:redirections 5) port->string)) (define (get-result term) (string->number (string-replace (list-ref (string-split (car (regexp-match #px"s\">About [\\d,]+ results" (open-url (string-append "google.com/search?nfpr=1&q=" (uri-encode term))))) " ") 1) "," ""))) (define (zip a b) (map list a b)) (define (google-fite terms) (cddr (sort (zip terms (map get-result terms))) #:key cdr <)) ``` ]
[Question] [ You've been hired by a bomb defusing company to perform some "controlled" demolition of un-exploded ordnance. You are given a list of bombs represented by non-negative integers. ``` [3,2,4,0,3,1,2] ``` Every step you can set up and explode a bomb. When a bomb \$n\$ explodes, it destroys all bombs within \$n\$ places replacing them with zeros ``` v [3,2,4,0,3,1,2] * * * * * * [3,0,0,0,0,0,0] ``` Once everything is zeros you are done "defusing". ## Task Given a starting non-empty list of bombs output the minimum steps required to clear it. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the length of your source code as measured in bytes. ## Test cases ``` [0,0,0,0,0] -> 0 [0,0,1,0] -> 1 [3,2,4,1,3,1,2] -> 1 [9,9,10,9] -> 1 [1,4,1,3,1,0,5] -> 1 [1,1,1,1,1] -> 2 [1,1,1,1,1,5,1,1,1,1,4,1,0,0,1] -> 2 [1,1,1,1,1,5,1,6,1,1,4,1,0,0,1] -> 2 ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 72 bytes *-3 bytes thanks to @loopy walt* Returns `False` instead of `0`. ``` f=lambda a,i=0:any(a)and-~min(f(a[:i][:-x])+f(a[x+(i:=i+1):])for x in a) ``` [Try it online!](https://tio.run/##dY3BboNADETvfIVvWQtT7UISlZXojyAOrhIUS7Cs6KYll/46XShJe2g1suR5npH9LVwGVzz7cZ7bquP@9cTAJJW27G6Kkd0p@@zFqVZxbaWpbTY1mC5uSpXYSlKDtsF2GGECccA4f1ykO4OxSfSeYLgGDxX07NX5nTta6DUofHrznQS1g@wFdogJ@FFciI/iHb9rONeaNjVLTicrMJs1SV1QTvsIijj5HZZUktFU3r15RDQdfuCmFeS/AB0e237t6P9Cx79CXw "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") The idea is to recursively split the array into left and right sections after an explosion. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~29~~ 26 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Quite inefficient depth-first search. ``` {(โ€šรขโ€ โ€šรฅรคยฌยฅ1+๏ฃฟรนรฏรคร€รฒ)๏ฃฟรนรฏยฉโ€šรคโˆโˆšรณร€รฒ๏ฃฟรนรฏยฉ/๏ฃฟรนรฏยฉ<|-โ€šรฅรบร€รบโ€šรœรฏโ€šรขโ€ ๏ฃฟรนรฏยฉ} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjiiaDijIrCtDEr8J2VisuYKfCdlaniirjDl8uY8J2VqS/wnZWpPHwt4oycy5zihpXiiaDwnZWpfQoKIyBjaGFuZ2UgdGhpcyB0byAxIHRvIGluY2x1ZGUgdGhlIGxhc3QgdHdvIGNhc2VzCiMgdGhpcyB3aWxsIGZyZWV6ZSB0aGUgcGFnZSBmb3Ig4oi+MSBtaW4KcnVuQWxsIOKGkCAwCgo+KOKLiOKfnEYpwqggKMKvMsOXwqxydW5BbGwpIOKGkyDin6gKMOKAvzDigL8w4oC/MOKAvzAKMOKAvzDigL8x4oC/MAoz4oC/MuKAvzTigL8x4oC/M+KAvzHigL8yCjnigL854oC/MTDigL85CjHigL804oC/MeKAvzPigL8x4oC/MOKAvzUKMeKAvzHigL8x4oC/MeKAvzEKMeKAvzHigL8x4oC/MeKAvzHigL814oC/MeKAvzHigL8x4oC/MeKAvzTigL8x4oC/MOKAvzDigL8xCjHigL8x4oC/MeKAvzHigL8x4oC/NeKAvzHigL824oC/MeKAvzHigL804oC/MeKAvzDigL8w4oC/MQrin6k=) or [click here](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjiiaDijIrCtDEr8J2VisuYKfCdlaniirjDl8uY8J2VqS/wnZWpPHwt4oycy5zihpXiiaDwnZWpfQoKYiDihpAgMeKAvzTigL8x4oC/M+KAvzHigL8w4oC/NQp74oCiU2hvd/CdlY9ifcKoIOKfqAoiVGhlIGlucHV0IgogICAgICAgICAgICB7ICAgICAgICAgICAgICDwnZWpfQoiSW5kaWNlcyBvZiB0aGUgaW5wdXQiCiAgICAgICAgICAgIHsgICAgICAgICAgICDihpXiiaDwnZWpfQoiVGFibGUgb2YgYWJzb2x1dGUgZGlmZmVyZW5jZXM7IGRpc3RhbmNlcyB0byB0aGUgZGlhZ29uYWwiCiAgICAgICAgICAgIHsgICAgICAgIHwt4oycy5zihpXiiaDwnZWpfQoiV2Ugd2lsbCBkbyBvbmUgZXhwbG9zaW9uIGluIGVhY2ggcm93IgoiV2hlcmUgaXMgdGhlIHRhYmxlIGxhcmdlciB0aGFuIHRoZSBib21iPyIK4o2J4oiY4omN4oi+4peLPCAgICAgIHsgICAgICDwnZWpPHwt4oycy5zihpXiiaDwnZWpfQoiUmVtb3ZlIHJvd3MgY29ycmVzcG9uZGluZyB0byBzaXplLTAgZXhwbG9zaW9ucyAoQWxzbyBkdXBsaWNhdGVzIG90aGVyIHJvd3MpIgrijYniiJjiiY3iiJgvy5ziiL7il4s8ICAgeyAgICDwnZWpL/Cdlak8fC3ijJzLnOKGleKJoPCdlal9CiJNdWx0aXBseSBlYWNoIHJvdyB3aXRoIHRoZSBpbnB1dCB2ZWN0b3IiCjLigL8x4qWK4oqi4oi+4peLPCAgICB78J2VqeKKuMOXy5jwnZWpL/Cdlak8fC3ijJzLnOKGleKJoPCdlal9CiJOb3cgZG8gYSByZWN1cnNpdmUgY2FsbCBvbiBlYWNoIHJvdywgYW5kIHJldHVybiB0aGUgbWluaW11bSByZXN1bHQgKyAxIgoiSWYgdGhlIG1hdHJpeCB3YXMgZW1wdHksIHJldHVybiBpdHMgbGVuZ3RoICgwKSIKICAgIyDiiaDijIrCtDEr8J2VisuYCuKfqQoKRiBi) for step-by-step results with comments. [Answer] # [Julia 1.0](http://julialang.org/), ~~65~~ 62 bytes ``` !l=sum(l)>(j=0)&&minimum(i->1+!l[1:(j+=1)-i]+!l[j+i:end],l.+1) ``` [Try it online!](https://tio.run/##dY7BioMwEIbvPkW8lATHktFasKBv0CcQD4FmYWRMRW3Zt3fTrM3upTMM5P/4JsnwYDL4vW0pN8tjlKxaOTRaHQ4jORo9obzFLOUOL3LIGlQ59a84ZHSx7tYDHzNU29d9FiTIidmaG5Ozi1SJ8GVEI5aJaZWkOuwjs0/D8mpXc5zMvFhp1K8/zeRWdtI7rUiNSvwjW6dh717krdBJALhHTLoSCjh5UPop3rCGGlBD/c4YFQ3VH9w7gOIfgCqeTmFHf5LOn6Twx3hTBZEEpfwB "Julia 1.0 โ€šร„รฌ Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~31~~ 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [DOโˆšรผ_#ยฌยบล’ยตฦ’ร…Dล’ยฅล’ยฑโ€šร„ฯ€โˆšโˆy*โˆšโˆyฦ’ร„โˆšรจ}โ€šร‡ยจ`}ยฌรฆ ``` -6 bytes and sped up substantially by porting [@ovs' BQN answer](https://codegolf.stackexchange.com/a/242908/52210). Input as a wrapped list. If this is not allowed, a leading `ยฌโˆ` can be added. [Try it online](https://tio.run/##yy9OTMpM/f8/2sX/8Px45UN7zm090uhybsu5jY8adh7eUakFxEcaDvfXPmpak1B7aB9QZbSRjgEQGoJwbCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeWiHi72SwqO2SQpK9v@jXfwPz49XPrTn3NYjjS7ntpzb@Khh5@EdlVpAfKThcH/to6Y1CbWH9v3X0Tu09X90tIEOFMbqgNmGYJaxjpGOCZBtDMRGQL6ljqWOoYGOJZBpCJcw0DEF86EQma1jCmeZgFUaYJE3wyIPdgBcv6kOXAQmC6SNdAzQRdFxbCwA). **Explanation:** ``` [ # Loop indefinitely: D # Duplicate the current list of lists # (which will be the implicitly input in the first iteration) Oโˆšรผ_ # Check if there is an inner list of only 0s: O # Sum each inner list in the duplicate โˆšรผ # Pop and push the minimum _ # Check if this is equal to 0 # If it's truthy: # # Stop the infinite loop ยฌยบ # Increase `ยฌรฆ` by 1 (0 by default) ล’ยต # Map over each inner list `y`: ฦ’ร…Dล’ยฅล’ยฑ # Create a matrix of the same length with 0 as main diagonal, and # with each adjacent diagonal 1 higher than the previous: ฦ’ร… # Push a list in the range [1,length] (without popping `y`) D # Duplicate it ล’ยฅ # Apply double-vectorized: ล’ยฑ # Absolute difference โ€šร„ฯ€ # Check for all values in a row if it's smaller than the value at the # same position in list `y` that's was still on the stack โˆšโˆy*โˆšโˆ # Multiply each column to the corresponding value in list `y`: โˆšโˆ # Zip/transpose; swapping rows/columns y* # Multiply each row by the same positioned value in list `y` โˆšโˆ # Zip/transpose the row/columns back yฦ’ร„โˆšรจ # Remove the rows for which the corresponding value in `y` is 0: y # Push list `y` again ฦ’ร„ # Check for each value if it's NOT 0 โˆšรจ # Only leave the rows at the truthy positions }โ€šร‡ยจ` # After the inner map: flatten one level down }ยฌรฆ # After the infinite loop: push the counter variable `ยฌรฆ` # (which is output implicitly as result) ``` [Answer] # Python3, 84 bytes: ``` f=lambda x:any(x)and-~min(f(x[:max(i-a,0)])+f(x[i+a+1:])for i,a in enumerate(x)if a) ``` [Try it online!](https://tio.run/##dZDBaoQwEIbP61MMXjbBcYm6lirYR@gLWCkjG2lAo2ha3Etf3cagbi/LkGHmm38G8g9389Xr5HUYl6UpWurqG8Gck76zmZO@hb@d0qxhc5l3NDMVEgpe8WAlKqAgyive9CMoJFAapP7u5EhG2m3VAPFFdUM/GqDJeFPh@34pcIsKwjcQngPR1kZemWCMVwsS@@IdZphhJDDb@@iQCEwfcAsH4n8A06O6uh3xTPTyTAQC4cipy0fxGDl9Yr/pOVNWSxrVGjmy915LhOkyDa0y7Pyhz5znJ@9EWEMBHQ3MWnSxM2tf@yl/qEVQu3q9avVWPU3Sutkw4kVRL38) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` J_r+โ€ฆรณโ€šร…โˆโ‰ˆรญPFยทโˆรผ@Lโ€ฆรณโˆšรปTยทโˆยขL ``` A monadic Link accepting a list of non-negative integers that yields a non-negative integer. **[Try it online!](https://tio.run/##y0rNyan8/98rvkj75PRHjTuOTgpwe7hjvoPPyemH54U83LHI5////9HGOgY6hiAYCwA "Jelly โ€šร„รฌ Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/98rvkj75PRHjTuOTgpwe7hjvoPPyemH54U83LHI5//h9kdNa/7/j4420IHCWC4dMMcQwjTWMdIxAXKMgdgIJGCpY6ljaKBjCWIbwqUMdEwhAlCIwtExhbNMwGoNsCkwQ1cQCwA "Jelly โ€šร„รฌ Try It Online"). ### How? I *think* brute force is tersest for this one, but maybe not... ``` J_r+โ€ฆรณโ€šร…โˆโ‰ˆรญPFยทโˆรผ@Lโ€ฆรณโˆšรปTยทโˆยขL - Link: bombs J - range of length of bombs -> I = [1,2,...] โ€ฆรณโ€šร…โˆ - last three links as a dyad - f(I, bombs) _ - I subtract bombs (vectorises) + - I add bombs (vectorises) r - inclusive range -> list of blast zones (includes out of bounds, but that's OK...) โ‰ˆรญP - powerset T - truthy indices of bombs -> T = indices we need to affect โˆšรป - sort the powerset by: โ€ฆรณ - last three links as a dyad - f(set, T) F - flatten the set ยทโˆรผ@ - filter those values out of T L - length ยทโˆยข - head L - length ``` [Answer] # [Python](https://www.python.org), 94 bytes ``` f=lambda a:any(a)and-~min(f([v<abs(i-t)and x for i,x in E(a)])for t,v in E(a)if v) E=enumerate ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY349JscxJzk1ISFRKtEvMqNRI1E_NSdOtyM_M00jSiy2wSk4o1MnVLQKIKFQpp-UUKmToVCpl5Cq5ApbGaIIESnTKYQGaaQpkml6ttal5pbmpRYkkq1JYnBUWZeSUa2kAjDXSgMFZTkwtV2BBd0FjHSMcEKGwMxEaoUpY6ljqGBjqWqKKGcOUGOqboUlCIQ1jHFM4yAes3wK_UDEMpxK-wkAUA) Simple depth-first search. --- ## [Whython](https://github.com/pxeger/whython), 87 bytes ``` f=lambda a:min(f([v<abs(i-t)and x for i,x in E(a)])for t,v in E(a)if v)+1?0 E=enumerate ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8GCpaUlaboWN8PTbHMSc5NSEhUSrXIz8zTSNKLLbBKTijUydUs0E_NSFCoU0vKLFDJ1KhQy8xRcNRI1YzVBAiU6ZTCBzDSFMk1tQ3sDLlfb1LzS3NSixJJUqPFPCooy80o0tIHGGuhAYaymJheqsCG6oLGOkY4JUNgYiI1QpSx1LHUMDXQsUUUN4coNdEzRpaAQh7COKZxlAtZvgF-pGYZSiF9hQQoA) Base-case is `ValueError: min() arg is an empty sequence`, which indicates the array is all `0`s. [Answer] # [Perl 5](https://www.perl.org/) `List::Util`, 109 bytes ``` sub f{my($b,$r,@i)=@_;@i[$b-min($r,$b)..$b+$r]=()if$r;!sum(@i)?0:1+min map $i[$_]?f($_,$i[$_],@i):inf,0..$#i} ``` [Try it online!](https://tio.run/##fZBPa8JAEMXv@RRTuyUbHGWjRjAhNfeWemlPNoSm3ZWlJqb5Qy3iZ4@TmAb04A4Lj9@892A3k/nWqatCwrMuStd9K/UWfn55olNIPvZQVInl1UUVgzokf5zFyHIMtOUHkRfoNYtH5OTEWGyNxywesjz0uaUVy707CnPyLoVrD8@FGTAKReFScRbhWTd1rk4VCiq418da7XJurGEtsJsQ/EcQEOI/tTtmd2yKE5wRndKdXGwWuEBb4OIC2r1ZoHO16aalk2uKTq9mbVrcdM5vOttn9J0O9qT1TRufdTCATvPxGpmkX2eR1yG28RVvegOmrTPMcp2WavAwmhcAcp/Jz1J@ucAk7Ta7ktSGlE6zijTF3tMB0tb3iS/B3H2b4IL5snqF1ZPpGUejPgE "Perl 5 โ€šร„รฌ Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~89~~ ~~79~~ 67 bytes -7 bytes from Arnauld ``` f=x=>0|Math.min(...x.map((v,i)=>v?1+f(x.map(w=>i*i-->v*v&&w)):1/0)) ``` [Try it online!](https://tio.run/##dZDBboMwDIbvfYqeSsKckECZyibobbeddqQ9RDR06SgwQlM27dnHUErpLrVlyf702/rlgzBCZ42qW1JWO9n3edzFCft5Fe07PaoSUUo7ehQ1QgYUjhOz5g85uqBznChXEZIY1ywWZ4yfuMcw7p@zqtRVIWlR7VEjP0@qkcjJtYNpI8XuRRXy7avMEAPn1OYri@tCZBJ5m5S6683W28NgI0fSiAJ1eIg@ZTDmdk6SOZtZwMeRz9IAfFgOIBjKv8IIIuAMouvMJwmD8AbHtMD/ByCcuqXdYfdEj/dE1uN0KYSJWEnwW9WtGt7VE92K7INo9S3j6BJ/ "JavaScript (Node.js) โ€šร„รฌ Try It Online") Using fact that `(Infinity | 0) == 0` DFS BFS answer deprecated [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 52 bytes ``` ^ !ยฌโˆ‚ \d+ *_-$%" ^/^[0,-]*$/m}+`\d*,?_(_*-),?\d* $1 ! ``` [Try it online!](https://tio.run/##K0otycxLNPyvqqHhnvA/jkvx0DaumBRtLq14XRVVJa44/bhoAx3dWC0V/dxa7YSYFC0d@3iNeC1dTR17IIdLxZBL8f9/Ax0o5AKRhkDaWMdIxwTIMgZiIy5LHUsdQwMdSy5DuKCBjimQB4UIlo4pnGUCVmWAIWuGIQu2Eq7XVAcuAgA "Retina โ€šร„รฌ Try It Online") ## Explanation ``` ^ !ยฌโˆ‚ ``` Prepend a new line with a single `!` to keep track of number of steps --- ``` \d+ *_-$%" ``` For each nonnegative integer, duplicate the whole line but with the number replaced by that many `_`s followed by a `-`. For example, `3,2,4,1,3,1,2` becomes ``` ___-,2,4,1,3,1,2 ,__-,4,1,3,1,2 3,,____-,1,3,1,2 3,2,,_-,3,1,2 3,2,4,,___-,1,2 3,2,4,1,,_-,2 3,2,4,1,3,,__- 3,2,4,1,3,1, ``` The `_`s represents a "blast wave" which destroys other bombs. Some of the numbers next to the "defused" bomb are also deleted along the way. This does not affect the result because * if the "defused" bomb is positive, that number would have been blown up anyway * if the "defused" bomb is 0, then it is not the optimal move anyway as long as there are still positive bombs (which is guaranteed by the looping condition) Also note that the original line (with the last number removed) is kept, effectively giving the option of actually defusing the last bomb (without blowing it up). But since that won't ever be better than just blowing it up, we can just leave it. --- ``` +`\d*,?_(_*-),?\d* $1 ``` Propagate the blast waves repeatedly until it no more propagation is possible To propagate a blast wave, 1. Delete the adjacent spaces. 2. Reduce the blast wave by 1 This compresses the entire "blast zone" to one space, but it is fine because there is no need to keep track of how large a blast zone was. A `-` is left behind in that space and it act as a barrier to prevent blast waves from later steps from propagating through an old blast zone. If a blast wave from a later step wants to cross an old blast zone, then either: * it doesn't have enough power to cross the whole blast zone anyway, so the barrier didn't prevent the new blast wave from destroying any bombs * it has enough power to cross the whole blast zone, which means the new blast wave covers the entire old blast zone, so "defusing" that new bomb first is a more optimal move anyway --- ``` ^/^[,0-]+$/m} ``` Loop all the above until there is a line with only `,`s, `0`s, and/or `-`s (i.e. a finished state) --- ``` ! ``` Count the number of `!`s marked. That is the number of steps taken to reach the finished state. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes ``` โ€šรครปล“ร–ร”ยบยฐโ€šรขรฎโ€šร…โˆžล’โˆ‚ร”ยบโˆ‘โ€šรฅรคร”ยบโ€ขล“ร–โ€šรฅร ล’โˆซยฌยดโ€šรขยถโ€šรครฏล’โˆ‚โ€šรขรฎล“ร–ล’โˆ‘โ€šรขรฎโ€šรผยถโ€šรผรŸล“ร–ร”ยบยถล’โˆ‘ร”ยบยถร”ยบโ€ขล’โˆซร”ยบโ€ขล’โˆซโ€šร รŸโ€šร„โˆซโ€šรœรฎโ€šร…ยชล’รฆล’ยบล’ยชล’ฮฉโ€šรครปล“ร–ล’ยชยฌยชร”ยบยฉล’โˆ‚ ``` [Try it online!](https://tio.run/##TU/LqgIxDF07X5FlChVGUDd3NbgQFwPuh1nUsfe22OlIHyqK317TqnATDsnJ45AMSrhhEialffQKI4edPceAjP1Ujff6z2LN4U7sqrSRgK22eowjtuKcp1txK/TEyOBRzaj@2dvZwclR2iCPb4XZp0Fr6h/teg4x89/JASoGJWb9U9YvobFH3DopgnTYHPxkYpD5lOjxxmFkjIMh2HLF9xNDos9q77QNuBE@4J2@SqnrFvzrK8K6ZEtCTb7o@zS/mBc "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. Explanation: ``` โ€šรครปล“ร–ร”ยบยฐ ``` Start with just the input list. ``` โ€šรขรฎโ€šร…โˆžล’โˆ‚ ``` Start with 0 explosions. ``` ร”ยบโˆ‘โ€šรฅรคร”ยบโ€ขล“ร–โ€šรฅร ล’โˆซยฌยด ``` Repeat until a fully cleared list is found. ``` โ€šรขยถโ€šรครฏล’โˆ‚ ``` Increment the number of explosions. ``` โ€šรขรฎล“ร–ล’โˆ‘โ€šรขรฎโ€šรผยถโ€šรผรŸล“ร– ``` Temporarily save the list of lists. ``` ร”ยบยถล’โˆ‘ร”ยบยถร”ยบโ€ขล’โˆซร”ยบโ€ขล’โˆซโ€šร รŸโ€šร„โˆซโ€šรœรฎโ€šร…ยชล’รฆล’ยบล’ยชล’ฮฉโ€šรครปล“ร–ล’ยช ``` Make a new list of lists of the results of exploding each entry in each list (including zero entries, which have no effect on the list). ``` ยฌยชร”ยบยฉล’โˆ‚ ``` Output the number of explosions needed. 23 bytes using the newer version of Charcoal on ATO: ``` โ€šรครปล“ร–ร”ยบยฐโ€šรขรฎโ€šร…โˆžล’โˆ‚ร”ยบโˆ‘โ€šรฅรคร”ยบโ€ขล“ร–โ€šรฅร ล’โˆซยฌยดโ€šรขยถโ€šรครฏล’โˆ‚โ€šรขรฎล’ยฃร”ยบโ€ขล“ร–ร”ยบโ€ขล’โˆซร”ยบโ€ขล’โˆซโ€šร รŸโ€šร„โˆซโ€šรœรฎโ€šร…ยชล“ร„ล’ฮฉล’ยบล’รฆล“ร–ยฌยชร”ยบยฉล’โˆ‚ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TU87CsJAEK3NKVarWdiAgopgFSwkRUCwDCnWuJrFZA37UVE8iY2FovfwFLmNo0Zxhsd833xO9zTjOl3z_Hy-OrvwB9Vj4kwGjpFQlc4CpUMvMEYuFbQZ2WO0zWQuCERSycIVEPHy1R3x3TtcURRy8BqYr3mhSrUohLJi_pnQqAvTf3oJq58J1BzGWnArNAQzs86dFa-FzkDJiKKUkQKxQzicd_QmWioLI24s7PHii5mlpn7oFrf8Td5KqmYcd9hXe4j-2-si2qidJPkQng "Charcoal โ€šร„รฌ Attempt This Online") Link is to verbose version of code. ]
[Question] [ In [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle) each number is the sum of the two numbers directly above it, treating empty spots as zero: [![Source: https://en.wikipedia.org/wiki/File:Pascal_triangle_small.png](https://i.stack.imgur.com/EhBwg.png)](https://i.stack.imgur.com/EhBwg.png) By rotating the triangle, we can cut out square matrices of varying sizes and rotations which I will call *Pascal's matrices*. Note that those matrices always need to contain the top \$1\$. Here are some examples: ``` 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20 6 3 1 3 2 1 1 1 1 1 5 15 35 70 1 4 10 20 35 1 3 6 10 15 1 2 3 4 5 1 1 1 1 1 1 1 1 2 1 ``` ## The Task Given a square matrix containing positive numbers in any reasonable format, decide if it is a *Pascal's matrix*. *Decide* means to either return truthy or falsy values depending on whether the input is a *Pascal's matrix*, or to fix two constant values and return one for the true inputs and the other for false inputs. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to use as few bytes as possible in the language of your choice. The shortest code in *each language* wins, thus I will not accept an answer. ### Test cases True ``` [[1, 1, 1, 1], [1, 2, 3, 4], [1, 3, 6, 10], [1, 4, 10, 20]] [[6, 3, 1], [3, 2, 1], [1, 1, 1]] [[1, 5, 15, 35, 70], [1, 4, 10, 20, 35], [1, 3, 6, 10, 15], [1, 2, 3, 4, 5], [1, 1, 1, 1, 1]] [[1]] [[1, 1], [2, 1]] ``` False ``` [[2]] [[1, 2], [2, 1]] [[1, 1], [3, 1]] [[1, 1, 1, 1], [1, 2, 3, 4], [1, 4, 6, 10], [1, 4, 10, 20]] [[6, 3, 1], [1, 1, 1], [3, 2, 1]] [[2, 2, 2, 2], [2, 4, 6, 8], [2, 6, 12, 20], [2, 8, 20, 40]] [[40, 20, 8, 2], [20, 12, 6, 2], [8, 6, 4, 2], [2, 2, 2, 2]] [[1, 5, 15, 34, 70], [1, 4, 10, 20, 34], [1, 3, 6, 10, 15], [1, 2, 3, 4, 5], [1, 1, 1, 1, 1]] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~28~~ ~~24~~ 23 bytes This feels quite long but here it is anyway * -4 bytes thanks to DLosc by compressing the optional flips * -1 bytes thanks to DLosc again by doing the partial sums in 1 go `{|โ†”}\โ†ฐโ‚{k{aโ‚€แถ +แต}แตโІ?h=โ‚}` ## Explanation ``` {|โ†”}\โ†ฐโ‚{k{aโ‚€แถ +แต}แตโІ?h=โ‚} # Tests if this is a pascal matrix: {|โ†”}\โ†ฐโ‚ # By trying to get a rows of 1's on top {|โ†”} # Through optionally mirroring vertically \ # Transposing โ†ฐโ‚ # Through optionally mirroring vertically {k{aโ‚€แถ +แต}แตโІ?h=โ‚} # and checking the following ?h=โ‚ # first row is a rows of 1's k{ }แต # and for each row except the last aโ‚€แถ +แต # calculate the partial sum by aโ‚€แถ  # take all prefixes of the input +แต # and sum each โІ? # => as a list is a subsequence of the rotated input ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7rmUduU2phHbRseNTVWZ1cnPmpqeLhtgfbDrRNqgfhRV5t9hi1Qqvb//@hoQx0FUx0FQyA2BmJzg1gdBZCYCVDMQEfByAAkDhUz1lEwgwgbwoSMwKJAxTABBIqNBQA "Brachylog โ€“ Try It Online") [Answer] # JavaScript (ES6), 114 bytes ``` m=>[m,m,m=m.map(r=>[...r].reverse()),m].some(m=>m.reverse(p=[1]).every(r=>p=!r.some((v,x)=>v-~~p[x]-~~r[x-1])&&r)) ``` [Try it online!](https://tio.run/##nVHLboMwELznK@glsSVjEeOmuTjHfEFulg8odfoQDsikiFzy63RtoIUGqBSBhcc7O7N4PpMyKY72I7@E5@xV1ydRG7GThsAjDDVJjixgSqlV1OpS20IjjIlRtMiMRkA2P@e5kGuFqUNX15aLJ9vQUEkqLHZleLvlslLwsbIKgbxcWozrY3YuslTTNHtDK3mwX5f3q1rhRf/8hKRck6B9FQkcYiSIScBbBNsN1KIWcrcHTqQUvtfaeL4Xir1Qp@nlxzqg8Aw1WDGslzsbd/5nEkcfjgoaPZ85t6kZ/Jysa1sM726fpMXo1bEpOTaQm/KL5wgzkfAHI@lpdumMdTBfY79/0fhtW@Ssmbdr8LaJiUf/5csn8uUP51t/Aw "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 17 bytes ``` 4:"Gas2YLG@X!X=va ``` [Try it online!](https://tio.run/##y00syfn/38RKyT2x2CjSx90hQjHCtizx//9oMx0FYx0FQ2sQaQRmGOqAUSwA "MATL โ€“ Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8N/ESsk9sdgo0sfdIUIxwrYs8X9shEtURcj/aEMdBSiyBpFGOgrGOgomYDaQYQYUNwBzTEAsoLxBLFe0GVgOqMEYrAGiE4SAckDKFMgCYmMgNkfTDBJFMRukFNlioG64aQgzIeYC7TGCCBhBBIzgAoYw58A4OLxkQtBLcJ1Qv4FsA7OMYPZBzLAAs0GGgSQMwDwLiBdNDGIVUALCBGtAmJAaEAA). Outputs `1` for Pascal matrices, `0` otherwise. ### Explanation ``` 4: % Push [1 2 3 4] " % For each G % Push input: Nร—N a % 1ร—N vector containing 1 for matrix columns that have at least a nonzero % entry, and 0 otherwise. So it gives a vector containing 1 in all entries s % Sum. Gives N 2YL % Pascal matrix of that size G % Push input @ % Push current iteration index X! % Rotate the matrix that many times in steps of 90 degress X= % Are they equal? v % Concatenate with previous accumulated result a % Gives 1 if at least one entry of the vector is nonzero % End (implicit). Display (implicit) ``` [Answer] # [R](https://www.r-project.org/), 104 bytes ``` function(m,R=row(m)-1,y=nrow(m):1,Z=choose(R+t(R),R))any(sapply(list(Z,Z[,y],Z[y,y],Z[y,]),identical,m)) ``` [Try it online!](https://tio.run/##jVHLaoNQEN3nK4Rs7tAJeF@2hLrool11ZdONJQuxkQo@glpav97OKNrEmhIOODPMOWe8M1WXOPcbp0s@i7hJy0LkGPhV@SVy2Ehs/WLItxJDP/4oy/oggptGBIABQFS0oo6Ox6wVWVo3IsTwDds9fdsx7AHT90PRpHGUYQ7QrZ1d8Pq4SkQeNVX6LWIhcYRCjYaiRg@lS4nhoFygxOAO4FTmEY2papQDFXrOkmhRWtQWb08Muf4dY6fRdvoVcrOEuRv0zT8zWE89ReDeau08PTy/nL1SXZCqc@nMVv/T67E1/auu3tcAPQxd2JfCEWx6R5GsFa9MceWiWXY3/VqZT0GyivkeESfHRd14HzO7j7n6Pt0P "R โ€“ Try It Online") Nasty... Creates a canonical Pascal's matrix `Z` with dimensions equal to that of `m`, then tests if the input matrix `m` is `identical` to `any` of the rotations of `Z`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` ๏ผฆโ€นยนโŒˆยงฮธโฐโ‰”โฎŒฮธฮธ๏ผฆโ€นยนโŒˆ๏ผฅฮธยงฮนโฐโ‰ฆโฎŒฮธโŒŠโญ†ฮธโญ†ฮนโผฮปโˆจยฌฮบฮฃโ€ฆยงฮธโŠ–ฮบโŠ•ฮผ ``` [Try it online!](https://tio.run/##bY4xb8IwEIV3fsWNZ8mVEqB0YEK0A1JTKhijDFa4glXHSWyD6K93L5AorcTpbrhP7z298qRcWSsT41ftAN/Je0wlZOqqq3OFq7CxB7piKyERPLDyXh8t7uhCzhO2QkIrlpOH5kw1nXHI0H2GYEHzP@ce8um0DZhpe3PvA7/HPmN8OOWtPSvj0UjYOvyoA35ziz1b1j@lofWpbv72fqXSUUU20IGFrNzYEVSin2WMeZ5z@WcJKd@M7yUpJHRsziyRME063rOZhMUdpwOa3iiLBzBuURTx6WJ@AQ "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผฆโ€นยนโŒˆยงฮธโฐ ``` If the maximum of its first row is greater than 1, ``` โ‰”โฎŒฮธฮธ ``` then flip the input array. ``` ๏ผฆโ€นยนโŒˆ๏ผฅฮธยงฮนโฐ ``` If the maximum of its first column is greater than 1, ``` โ‰ฆโฎŒฮธ ``` then mirror the input array. ``` โŒŠโญ†ฮธโญ†ฮน ``` Loop over the elements of the input array and print the minimum result (i.e. the logical And of all of the results), ``` โผฮปโˆจยฌฮบฮฃโ€ฆยงฮธโŠ–ฮบโŠ•ฮผ ``` comparing each value to 1 if it is on the first row otherwise the sum of the row above up to and including the cell above. [Answer] # [Python 2](https://docs.python.org/2/), 129 bytes ``` f=lambda M,i=4:i and(set(M[0])=={1}and all(a+b==c for x,y in zip(M,M[1:])for a,b,c in zip(x[1:],y,y[1:]))or f(zip(*M[::-1]),i-1)) ``` [Try it online!](https://tio.run/##nVBBboMwEDyXV@zRbjcSGDeNkPwE8wHLB5MU1RIQlHIIifp2ahsQoVGqqhKWdmZ3Zpdp@@7j2LBhKEVl6uJgQKIVPLNgmgP5fO@IVLGmQlyTL8eAqSpiXgoh9lAeT3DGHmwDF9sSiVIlmaaeNljgfm6cPY099qFNXbsknn@WKss2iaZoNwmlg5QgQEVPSiUI06cRPGIIKQKfkCu3rhdPkPvazcRao1dvw0SQpkE6uwTDccaVrw65l7r3dmfl@R/b/Pj6HOdx47z2X/aE7eEKHekoak@26UCVpKYhwdrHJKXr5Pn8/2xRs0W9MkzX1C9p8T@ndeMyBzfOsIDYcs3ouZuQt2fBcsS7MUEe34fNH4TN/xn2w0TzXEfDNw "Python 2 โ€“ Try It Online") Returns `True` if `M` is a Pascal's Matrix, else `0`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ยฌPโ‰ iR}DรธะฝPโ‰ iรญ}ยฌPฮ˜sรผ)ฮต`sฮทOQ}P* ``` [Try it online](https://tio.run/##yy9OTMpM/f//0JqAR50LMoNqXQ7vuLAXzD68thYoem5G8eE9mue2JhSf2@4fWBug9f9/dLSJgY6RgY6FjlGsTjSQYWikYwZmWwBpE4ioDhjGxgIA) or [verify all test cases](https://tio.run/##lU@xCsIwEP2V0k25oU3S2q2Lu9U1BFRw6ORQEBy6Cq5Ojn6AjqKDLnYvfkN/pF4uhrYoiGTIu3f33t1bZrN5uqhX69h1qs3OceN1/Tgm1faQTvJhcX3eCRenHNlynxW3XnmeZuVlNM6Tfg21lNIHegoQMeAgCHEIwfcICgTAPKXAkTLEjp7lOGs0WkstHwLwA@ABDDpCZFqWONKsgsBatGysm7ZnhsWaWZo1tJ3irfJLFvEji9WYTNRiQI9WaXlECG2YVmsc6WTC60YXH9HFP9EFaSKz19PLQsIR/uJ9jblLqRc). **Explanation:** ``` ยฌPโ‰ i } # If the product of the first row of the (implicit) input-matrix is NOT 1: R # Reverse the order of the rows D # Duplicate the resulting matrix รธะฝPโ‰ i } # If the product of the first column is NOT 1: รญ # Reverse each row individually ยฌPฮ˜ # Check if the product of the first row is exactly 1 * # AND P # And check if everything after the following map is truthy: sรผ)ฮต } # Map over each pair of rows: `sฮท # Get the prefixes of the first row O # Sum each prefix Q # And check if it's equal to the second row # (and output the result implicitly) ``` [Answer] # [Kotlin](https://kotlinlang.org), 269 bytes ``` {m:List<List<Int>>->val n=m.size var r=0 var c=0 fun f()=if(m[0][0]!=1)m[n-r-1][n-c-1] else if(m[n-1][0]!=1)m[r][n-c-1] else if(m[0][n-1]!=1)m[n-r-1][c] else m[r][c] var g=0<1 for(l in 0..n*2-2){r=l c=0 var v=1 do{if(r<n&&c<n)g=f()==v&&g v=v*(l-c)/++c}while(--r>=0)} g} ``` [Try it online!](https://tio.run/##vVltbxs3Ev6uX8EYd46UyGtJVpycYLlo2uTOQNMcLgHyIWcU9C5X4nmXVJdcy6rr357ODIe7K8dyjB7uiiRakjPD4bw8M2QvrS@0@XJ4KM7MqvYzYaxfarMQ3oraKeGXSmQql3XhhVfOi1Q65YStesBSwqxeFUqACJzMhTZeLVTlRCkvSQqwu19rWSmil77S10kPv3@olPQqE7mtgEo7kdpMiYUtcpEuZVEos1AzJFx6v3Kzw0Ncx@XEeZleqmugApIkteXhr4fjV@OX0wmSn7kg7p/SpbJ46sQ72vQ72vTMtPMwCwJAeSXTpTB1eaEqoV1QuS7xNPjp15YXnch0pVJfbIS8sFdKaD8EKXAMPKkqV34j3Mp6J6QTv6nKzmjPD7auUjVrzqFMstaXeqUyLRNbLQ5xdPhWF2oWdPslavaLK8EQycosSNDrjaisD7uRZkw2FGsFbjEirb2w8DcYPFg7DX65ktUG@Zz@DSakyViUNU6slxoMcCbWuihADvzT2CiKSMTP1mMwSIiCpXUd4bJYy40TRoEvIWZSa7zUJihoV2JMqv9DgT6ok7MlGPxalhA1LthnLOIfHk2EOBJiyiP4PBbjEY@m8CkmI2I8pkXiOiKucUdcFP1CjF@Ioxfi5R0JMLe9AdBt7w@82@o1Uhu18XcSpz/CiT9Kd0mDv@srZYTccsV1NA46YmWd9kDUxBbYTBrwsJLOGnkBcQmZAXxDSL9UQ2poyC6PASrv@IcT6sdAVioJPgVPKA0@qECgryvwR1X75QbyVuSycBsIiKIG72VqpUyGClkDgaCIBX2nEQ3u3W2IQkB@DgfC5IBDQUYaH0VScIVNrVGc3xitNUsNJDhnabuclYrLCZsTNmdYOMC8H0LwgJRNRCZIslytxcXGK8o4sKjTaDeOvgKSo5YLheG/gRwEWLEQsQk5yi1tFeAMUQc4CAQalrU2DnJ7WbuYFwCLQqapWsEPesqtVZWQng0oBrXhmPTx@fN4KPjP@VDgaDIUR0Mx5RF8HsPaiIdT/Aaa0fl5YD8mEuI9It4ohiSeN3u8gCH8PYK/L78ShvN39kPybYVARkf0nQ06O5ECk7CIk2/RaXzYSYdu0qHb4j26M/eAdaaPt05HTDQUE01oOGk1ClJf8Qg3mJDQMH4VLDZtNpmyDV9FCaPAcczjV/Q5beXH3c7FV@6Z7nDP9M@6B3d4h1Cb1yZFJMfEoJi@i/8w7xQCCLJAamzEUgLyQL7qjLO7rYacxSGJyqQH0kGSNn1ZLdxMfF9VcnPyAcjN4nQgbno9IUDqm@sVJDWW86gMl89ClheZFKvKXmnEmUAORbtUxgecul4VeAztE1jE7YAY1Hb9gDcz8ZN2/oT@OTP@9HQwE6@tLQDnwvYkEdCvwEPjnlzLQYPKrgPapLaoS4PHigxIGAENv4EUVjMFwwhPgSky0GISN8pASx2AkLYEu6sskjZGAMTSnmozWRwBxDnmKRMiB3tHhecRz7FK82JFis3FqBkHrWgq7ve2EwER71H/uqpUBGZ2SGThinSxARxf1BVVgNoT24X13pawT2XIil2L1Yb6Bjg@C0Bbyew/tWvaEtA3cuxHZcF2MRIXyrOrg7NzWOsPxJwmBFY59vvn0Tn8EU/mYjzgRcG7fg4GO4CtDsbncRT2ggmmVlRSWnlMNt4tFuQ9WtrovBX4GCWDvK60e3ePZG1cc@@NllWOPi0V00S8hfgLdQva78gQ29aYz9Sz5Rpyba2xs@8GfuThhIOlytaLZeBBoUkTdQtrM4w5cQLtDvkONu8jDULFKEnCaZ9NDiaDmJYk@wP4u17FyBhyRLRJluvK@ZacY5VLOKogPi01nSP2kAGhWpbYYSD1sHOWmGGCU6ixkujmUJjAI4at53w@ITLbHoQ2OssbpGgiGxXaYdiYNgjJ2kP/FDaQC0A7FzwKyJvWhYzQEV0IRkXz1KtMetVxfdJQYSCiHicRO/YbjeJUG48iei/m2pxVASZc2TrkR0Kz64ga2IE1SooL6HMy0K/LkIcoCLsPcJfuxMF48KxLTWvPx5xeg8PwmwCi@@Vd0I1QBeAiLjDOUuyOQYEYO2gB6I7D7JbNLcSBWqFzYnR0ztSNroYrep9@n5GajZLPn29pdYtXJgjJ/gEmtziFMArGvuVwpAEDMRmYlzg2uWZ2SxaXyahscwOmwq24uAa2K7gtINbTHRT1xwqyIgDF68jx30JL/OWmnN0pnAenVGzmZSgwVFzmI/pN4ZfQuD@Y67xfBvB9Mh8Pys/mgEDTHKSIhoyDfZwft0TVPQQIkTCzJSVlAuKAAWHLfHQy7sHZ@0UEE8KRm2pe9FLW8Go@7mX2BgRXJ2Z/Pz0xg8Uc1Z1f7e8velfzK3DaQUrOuiX/oHtO56PBbW9x@@WrOplpB33HpgusDJ3spaZZidHGFW/dUKgsdiwsbGfHAkCCIQEtg/GF6e/928Rnini9is8UYu95E5J7f7lZscjB7d6ghd3Qq7BCUTivNRUXs6PFANq6v/fXo2wvCRdLphxEmqjcV6FMn3xCDt2PFd1U6eIo8TZWCbeC@2eutzqDIfacxOBqan3yumgROnQBeKO7ubfcsRxsEeltJfoBgxdmIwu@tMQiAb4JjRY3twREnWepXhcfSIshwryzbaEDyJXYidUeL@How/d5x5VsHqQkPWIJYUTAwrxd//4FZmoBKFyrSa0LMOBl7Ls6zRlxFdauEKfgco5rOQoH70LzRH0WNJTBJl0Mw@QO8ufknJ9gDdD@u1nYqtNgEVWi3RuU0R@0URIIWzV@sAbgxndeBLjigwElfDsf@0Nukfn1r5/K2kVFr/HWrMP7guG3qqd@0LKhY5vXDbypU0/A9ZyLIE43bXH0YURxR0vRDujBRGYZHxPiVkPki71BUsqVuMG48xacCba5HXSsEvzZgDn@xy5GiYBmATZbDd5jT7LWTg1DLsfHQ5VadFslsGhW3b4DM8HiZkSPC0@D7sib6TxX1LDnFfTfW/HQtQh2aestyyZ3e1QS@YQVJ3vgDOAv/bbnC6LOoNYsZPF9tajxVvYmiu13OghAo0@V5RdEvlo92etgBSVAk8fcKsWjYY4Krm2c1jBrrI/04cpKL5mQj/jYspXHW89ovdaSu0yx5U7x@@@ia5AtGzzeAnvvuoqzSmiCqM8nfL729@uMym7jnmiKBunkLWIM5mIAzPedM2HTXIZLMj2u1abTqSvuCiRcR2vXfaOPUdTpJuLLa0KwnkoPl4e@qipbzaDxA0sg5n1VrV4DgvHLXchq/h8C7km3KIU@1xAqvM9by/GYf9onjMFwK7zadX722LkeX0p2EjTPK4MOybYa/Hx0vwh@Rdopn7TfKfruk9y31UTKb54WRX7LZLDzg0p/U/UHT7XDIJMHRU4eFDn5MyLHDznuG3z/ZehN/9eh96CCMS53G7t5gdxpV34B3bnevInupGheSXfr0X033SGn85J6P0X7trpTk3jWx6Ti9NGpOP2/pmLTfMVqgDA6iF03NMe92/Bcp82XPwA "Kotlin โ€“ Try It Online") [Answer] # [Julia 0.7](http://julialang.org/), 78 bytes ``` m->any(i->(n=rotr90(m,i))[1]<2&&all(cumsum(n)'[1:end-1,:]-n[2:end,:].==0),0:3) ``` [Try it online!](https://tio.run/##dVDLboMwELz3K/aU2BJUfkEohPwI4oDaRiICt6Lh0K8nu0uSWkC1lr2sZmaHuYxd2xymczn18anxv6KNT8KXw9d1eFOij1opK10fzW7XdJ14H/ufsRde7iudf/qPWEd5HfvK0Ae2r2WpZKRyK6fvofXXzouzqDTA/RR4GQAL4KjFNwWtqHX4glG1lC8BM2WMLizTmE5ngcJRAjoBm8AhFMNBsAURwXqkFH@@NjTr/XKJLswKZtYwswHT/A8bUyr0YdATJeIeefwXh2X4LLfhBrjQAAll@KIcDhR2GQXi1MrCnJybk3sGR2ZsEBsb5MjutdBxTMtot6KVKXYZ3o7dcCFjugE "Julia 0.7 โ€“ Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 234 bytes ``` m->{int l=m.length,L=l-1,p=1,s=0,S=0,e=l,E=l,d=1,D=1,i,j;if(m[0][0]>1|m[0][L]>1){s=L;e=d=-1;}if(m[0][0]>1|m[L][0]>1){S=L;E=D=-1;}for(i=s;i!=e;i+=d)for(j=S;j!=E;j+=D)p=(i==s|j==S?m[i][j]<2:m[i][j]==m[i-d][j]+m[i][j-D])?p:0;return p>0;} ``` [Try it online!](https://tio.run/##nVNNj5swEL3nV8zeQmMQEJpG8U72ktyyUiWOiAMNJDXlS9hZtWL57elgyCbLppVaiYGZ8fOb4XmcRi@RmcY/ziKvylpBSrF1UiKzDqdir0RZWJ/4ZJ9FUsJzJApoJgDV6Vsm9iBVpOjzUooYclqb@qoWxTEIIaqP0tBQgK91Eot9pJJHUaggDMI1VJHcR9lzRPCfgOfcXDe0BhnmVpYUR/Wd7TAzHVahwyTazCdLMGNbsphyGzLBUi4O0zywQ3rWzqv2duQZjcQdTzBG0@HtCLPrPaPxCbPFjcYcynoqUHLxgAkXM4yNLpOiz9MH3PJ0hhujQoKgfE0R/ac8EGGQho/uavAQyTHjzp31KXMTGk/VyuZ1ok51AdXa5u2Za0kGIUgolUglAQepAJrGYTA8LYMuchnMGXhDRO6C1uwh9DqfMHbbsjeKhYbp/XO9/0KlWW@AFH@mFNmc7MsH0i4/qtvB3zdGHDf0d4qMKupm3BHIHYHceyDn@lMf8n@RzPs3yW6oLurdNqpT7rXDnn05RF0hV5P38bKX0XtXzBvEXV5Y7H7XYoiX2vWuNS4V7x@d94ej8/7z6HSNtp9UfTP6adWzuuon1ngbWP@XVElulSdlVXT5VVZMb2@31cGn3cswesaOvp20598 "Java (JDK) โ€“ Try It Online") ## Credits * -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` ลปโ‚ฌIแนซ2โผแน–aFแธข=1ฦฒ ,แนš;U$ร‡โ‚ฌแบธ ``` [Try it online!](https://tio.run/##y0rNyan8///o7kdNazwf7lxt9Khxz8Od0xLdHu5YZGt4bBOXzsOds6xDVQ63AxU83LXj/9FJD3fO0HnUMEfX7lHDXJ3D7Vxgqcj//6OjDXUUoChWRwHEM9JRMNZRMIHygEwzoJwBlGsCYgPVGMTG6kRHm4HlwRqNwRphZoCNA6kAMkyBbCA2BmJzDGNA4mg2gZSjOgVoBpK5yKbD7ADbawQTNoIJG6EIGyKcihDA43UTIr2OZAYsFMCuALONEK6AmGcB5YGMNgIbB@FbQILDBGK8CTR0LGDaDSDKzaB8CzDTBGE4zKpYBdRQN8ER6iZkhjoA "Jelly โ€“ Try It Online") ### Explanation Helper link, checks whether this rotation of matrix valid ``` ลปโ‚ฌ | prepend each row with zero I | find differences within rows แนซ2 | drop the first row โผแน– | compare to the original matrix | with the last row removed a | logical and Fแธข=1ฦฒ | top left cell is 1 ``` Main link ``` ,แนš | copy the matrix and reverse the rows ;U$ | append a copy of both of these | with the columns reversed ร‡โ‚ฌ | run each version of the matrix | through the helper link แบธ | check if any are valid ``` ]
[Question] [ Two lists `A` and `B` are congruent if they have the same length, and elements that compare equal in `A` compare equal in `B`. In other words, given any two valid indices `x` and `y`: * If `A[x] = A[y]`, then `B[x] = B[y]`. * If `A[x] != A[y]`, then `B[x] != B[y]`. For example, the lists `[1, 2, 1, 4, 5]` and `[0, 1, 0, 2, 3]` are congruent. ## The Task Given a nonempty list of *nonnegative* integers `A`, return a new list of *nonnegative* integers `B` such that is congruent to `A`, while minimizing the sum of the integers in `B`. There are potentially many possible valid outputs. For example, in the list `[12, 700, 3]`, any permutation of `[0, 1, 2]` would be considered valid output. ## Test Cases ``` Format: input -> one possible valid output [1 2 1 4 5] -> [0 1 0 2 3] (this is the example given above) [3 2 2 1 5 7 2] -> [1 0 0 2 3 4 0] [8 8 8 8 8] -> [0 0 0 0 0] [2] -> [0] [8 6 8 4 6 8 2 4 6 8 0 2 4 6 8] -> [0 1 0 2 1 0 3 2 1 0 4 3 2 1 0] [14 1] -> [1 0] [19 6 4 9 14 17 10 9 6 14 8 14 6 15] -> [8 0 3 2 1 7 5 2 0 1 4 1 0 6] [15] -> [0] [1 18 4 8 6 19 12 17 6 13 7 6 8 1 6] -> [1 8 3 2 0 9 5 7 0 6 4 0 2 1 0] [9 10 11 9 7 11 16 17 11 8 7] -> [2 4 0 2 1 0 5 6 0 3 1] [1 3 16 19 14] -> [0 1 3 4 2] [18 8] -> [1 0] [13 4 9 6] -> [3 0 2 1] [16 16 18 6 12 10 4 6] -> [1 1 5 0 4 3 2 0] [11 18] -> [0 1] [14 18 18 11 9 8 13 3 3 4] -> [7 1 1 5 4 3 6 0 0 2] [20 19 1 1 13] -> [3 2 0 0 1] [12] -> [0] [1 14 20 4 18 15 19] -> [0 2 6 1 4 3 5] [13 18 20] -> [0 1 2] [9 1 12 2] -> [2 0 3 1] [15 11 2 9 10 19 17 10 19 11 16 5 13 2] -> [7 2 0 5 1 3 9 1 3 2 8 4 6 0] [5 4 2 2 19 14 18 11 3 12 20 14 2 19 7] -> [5 4 0 0 2 1 9 7 3 8 10 1 0 2 6] [9 11 13 13 13 12 17 8 4] -> [3 4 0 0 0 5 6 2 1] [10 14 16 17 7 4 3] -> [3 4 5 6 2 1 0] [2 4 8 7 8 19 16 11 10 19 4 7 8] -> [4 1 0 2 0 3 7 6 5 3 1 2 0] [15 17 20 18 20 13 6 10 4 19 9 15 18 17 5] -> [0 1 3 2 3 9 6 8 4 10 7 0 2 1 5] [15 14 4 5 5 5 3 3 19 12 4] -> [5 4 2 0 0 0 1 1 6 3 2] [7 12] -> [0 1] [18 5 18 2 5 20 8 8] -> [2 0 2 3 0 4 1 1] [4 6 10 7 3 1] -> [2 3 5 4 1 0] [5] -> [0] [6 12 14 18] -> [0 1 2 3] [7 15 13 3 4 7 20] -> [0 4 3 1 2 0 5] [10 15 19 14] -> [0 2 3 1] [14] -> [0] [19 10 20 12 17 3 6 16] -> [6 2 7 3 5 0 1 4] [9 4 7 18 18 15 3] -> [4 2 3 0 0 5 1] [7 4 13 7] -> [0 1 2 0] [19 1 10 3 1] -> [3 0 2 1 0] [8 14 20 4] -> [1 2 3 0] [17 20 18 11 1 15 7 2] -> [5 7 6 3 0 4 2 1] [11 4 3 17] -> [2 1 0 3] [1 9 15 1 20 8 6] -> [0 3 4 0 5 2 1] [16 13 10] -> [2 1 0] [17 20 20 12 19 10 19 7 8 5 12 19] -> [7 2 2 1 0 6 0 4 5 3 1 0] [18 11] -> [1 0] [2 16 7 12 10 18 4 14 14 7 15 4 8 3 14] -> [3 9 2 7 6 10 1 0 0 2 8 1 5 4 0] [5 7 2 2 16 14 7 7 18 19 16] -> [3 0 1 1 2 4 0 0 5 6 2] [8 6 17 5 10 2 14] -> [3 2 6 1 4 0 5] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submission (counted in bytes) wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~62~~ 54 bytes ``` lambda L:map(sorted(set(L),key=L.count)[::-1].index,L) ``` [Try it online!](https://tio.run/##VVNBbuMwDDxvXpFbEoAtTFmy7ADtsSf/oO0hu3HQYjdOkLpA@/qUQ1FyFjYsmSJnOCR1/p7eTqO7Hh5erv92x9/73bLfHnfn9cfpMg379ccwrfsN/R2@H/r7P6fPcdo8b7d3/Hr/Pu6HL@o31/1wWD6J03bx63x5H6fl6mVcUU@ru0dsDnK0WDytn5kcMXkKrxv81vILQ6BILplasif9FmsjNq9fZ2uVd8mFPbHtOrF66gimSFwRDPLT4iM7Yy8rMbDBIaHsECTbmqLyMDXJrwMUs6BFLNwoOotLzEC1WsFsliJE4JCSQcGrAW2jfBWE2AmymRW1@oKzRUZ4DNpVSoSnNn9X9HhywERsELeSghhcVdSAO8cEsDhKGjurGzYqNIDcXIMAa9tSgTW9WqEqJcZBLBxIL79a2TYLYHVPVYyCaSqctgJ@IGgUQTPxMM7ZRuVr9Vujjiq4g4KgWUUKs7fH0OmDEqY2Wx6i1JVuaaiTRWBL73yCj4i0GqQldc@XjkXl1iZhoqtZaPhvKnwZVDmDAK2MqiizBgRrf8i1QZkwl3M4AEpWbW68necSsU7JzSVj3EEJK3ObipZE34youFS3WJZqHhI0KSRLKSBzbqMARJtuvV@sr5YIHa5LOTQx0gB1SLq7Ugu9JRFMuPKIuv4A "Python 2 โ€“ Try It Online") Edit: saved 8 bytes via map thanx to Maltysen [Answer] # Pyth - ~~12~~ ~~11~~ 10 bytes ``` XQ_o/QN{QU ``` [Test Suite](http://pyth.herokuapp.com/?code=XQ_o%2FQNK%7BQUK&test_suite=1&test_suite_input=%5B1%2C+2%2C+1%2C+4%2C+5%5D%0A%5B8%2C+6%2C+8%2C+4%2C+6%2C+8%2C+2%2C+4%2C+6%2C+8%2C+0%2C+2%2C+4%2C+6%2C+8%5D&debug=0). [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 bytes ``` ยฃรข รฑ@รจยฆXรƒbX ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=o+Ig8UDopljDYlg=&input=WzE5IDYgNCA5IDE0IDE3IDEwIDkgNiAxNCA4IDE0IDYgMTVd) ### Explanation ``` ยฃ รข รฑ@ รจยฆ Xรƒ bX UmX{Uรข รฑX{Uรจ!=X} bX} Ungolfed Implicit: U = input array UmX{ } Map each item X in the input to: Uรข Take the unique items of U. รฑX{ } Sort each item X in this by Uรจ!=X how many items in U are not equal to X. This sorts the items that occur most to the front of the list. bX Return the index of X in this list. Implicit: output result of last expression ``` [Answer] # [J](http://jsoftware.com/), 11 bytes ``` i.~~.\:#/.~ ``` [Try it online!](https://tio.run/##y/r/P03B1kohU6@uTi/GSllfr46LKzU5I18hTcFQwQiITRRM//8HAA "J โ€“ Try It Online") ## Explanation ``` i.~~.\:#/.~ Input: array A #/.~ Frequency of each unique character, sorted by first appearance ~. Unique, sorted by first appearance \: Sort down the uniques using their frequencies i.~ First index in that for each element of A ``` [Answer] # [Rรถda](https://github.com/fergusq/roda), 55 bytes ``` {|l|l|indexOf _,[sort(l)|count|[[-_2,_1]]|sort|_|[_2]]} ``` [Try it online!](https://tio.run/##bVVda9tAEHyOfsWSJwcS0J3uJDmQQl8KoYX8ANWYkCjF4NhBtqEQ57enN7N7kgJFRlJ0@zE7O7sZ9s@Pn@/FxYvc3snvz/fzNl2b3XP/9@FF1tfdYT8cF9ur89P@tDueu@5m7a/XbrU64@C8Pndrv1p9fH4UxevjZieItB9ks3s7Ha9lfzryuZbnfXFxMfSH0/aIRC@L7vC23RwXNOzc7U1YXclZ3h6HQ3@/O/Z/@mGxvuK3w@l1cZW8n/bD0D/RXX01Opzd/5xnrm/DZneUy4efl7J5kU4MyJ3kmCvpt4deLtXwx/f7X5fFxfN@1xcfn10lPl1OojTiV3LzreiclOnyUkmQclUUXSt26XkpduHMfMyuTlaBd2/PMr9lX8dPuFf2DPkNMVwQN8Lgh2XyDrIUnDTiSsGH9EeLW3qLat6OEZtUjBdkCoxfM0ycAXXigBN4U3jnETi9VtIQs0suBqFlTOQEQSWhlBPaJfA4l44bPFxNiHBrNIKf7FOEmhidQqhojromakC55/HIdqahIgkGrNKgPKgZh7V4wAkTerQ186tRUPmYLvPd8ocqWpCAyzClYhgEIWqVBZteEjiuKgPyPNaY/ivXqSagQJKYHHN@D8gMHa3CZOHLiQ1vFKMwn/mcGIzA7EV7sDRx4IWNiCjF5zI8@QfBS969CZUQUR@nQEVGLiomLQkeB9bPyH5qR9H0CpRlUdeGF7TkH7XVZj4rc1cx5A4yi2qnAR@TrVnZqFGyiAagNfOw4ICP6hQMCliCmCMKGbsfkQJFtbyjpxRMirFkb1oYxLkePSnTuU62jdUec7xAlJGJKpumMHHlrVxopUY4@KVG@a8ibIXJPSa3nDaNtz1EjGoaFHNDFZhRRYUaS/M515EIc80jnmGIKnawN6kuZMKsxFI1O5tSPwowzGVOGYJVdpzU2hyihQ1BciepSJDVBi/mjgcrllJVkIFbaY5@zIZ8IwnVfCu1eeTyHmBY@uX2Ow7vbOlHykWpzrrU4XTjKuPS1plWuWiz6gxP1R3nmym5lzP3CYMxlYcXqo76ZRpZzVgTkwq5NLW4r/8jPMahsf3H1e74Y5MDl7gbJ3DJdtR5bEvuAl1ytg0sd60htE/LsZ2VydnbLHNG878/jA@FMEuY95xK6h8 "Rรถda โ€“ Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~93~~ ~~91~~ 85 bytes ``` import Data.List f a=[i|x<-a,(i,y:_)<-zip[0..]$sortOn((0-).length)$group$sort a,x==y] ``` [Try it online!](https://tio.run/##Hcq9CsIwFEDh3ae4Q4YEbkIVXaTZHAUfIAS5Q38utmlIIrTiu8ficpbvjJRf3TTVynNcUoEbFTJ3zuXQA1nH37XVhJJxuz5Vqz8cXWOMF3mfH0HKRiszdWEooxJDWt7xL0C4Wrv5OhMHsBAThwICenBHhBPC3jPCxdcf "Haskell โ€“ Try It Online") EDIT: Thanks to @Laikoni for taking off 6 bytes! Not very short but I can't think of anything else. The idea is to iterate over the array (`x<-a`) and perform a lookup in a tuple list (`(i,y:_)<-`...`,x==y`) that assigns a nonnegative integer to each unique element in the input based on how common it is. That tuple list is generated by first `sort`ing the input, `group`ing it into sublists of equal elements, sorting that list by the length of the sublists (`sortOn((0-).length)`; length is negated to sort into "descending" order), then finally zipping it with an infinite list incrementing from 0. We use pattern matching to extract the actual element fromm the sublist into `y`. [Answer] # Mathematica, 94 bytes ``` (s=First/@Reverse@SortBy[Tally[j=#],Last];For[i=1,i<=Length@s,j=j//.s[[i]]->i+5!;i++];j-5!-1)& ``` [Try it online!](https://tio.run/##RcixCsIwEADQ3a@wCKL0akk1ONRIcOjUQdQtZAiS2gu1hVwQivTbo06@8T1NaPFOsRFxRaJCTyGXF/uynqy8Dj6cRnUzXTcqJxYaakNBl9XgFQoGeBC17R@hlQROuDzfkFKodXbElCclpqkuXcaTjK2X8eyxD3PZqDeDAhjsgE969t/td3/PYQ/FpOMH "Mathics โ€“ Try It Online") [Answer] # CJam, ~~17~~ 14 bytes -3 bytes thanks to Peter Taylor This is a golfed version of the program I used to generate the testcases. ``` {_$e`$W%1f=f#} ``` This is an anonymous block that expects input as an array on top of the stack and outputs an array on top of the stack. Explanation: ``` {_$e`$W%1f=f#} Stack: [1 2 1 4 5] _ Duplicate: [1 2 1 4 5] [1 2 1 4 5] $ Sort: [1 2 1 4 5] [1 1 2 4 5] e` Run-length encode: [1 2 1 4 5] [[2 1] [1 2] [1 4] [1 5]] $ Sort lexicographically: [1 2 1 4 5] [[1 2] [1 4] [1 5] [2 1]] W% Reverse: [1 2 1 4 5] [[2 1] [1 5] [1 4] [1 2]] 1f= Second element of each: [1 2 1 4 5] [1 5 4 2] f# Vectorized indexing: [0 3 0 2 1] ``` [Answer] # TI-BASIC, 66 bytes ``` Ans+max(Ans+1)seq(sum(Ans=Ans(I)),I,1,dim(Ansโ†’A cumSum(Ansโ†’B SortD(โˆŸA,โˆŸB cumSum(0โ‰ ฮ”List(augment({0},โˆŸAโ†’A SortA(โˆŸB,โˆŸA โˆŸA-1 ``` # Explanation ``` seq(sum(Ans=Ans(I)),I,1,dim(Ans Calculates the frequency of each element of Ans. Comparing a value to a list returns a list of booleans, so taking the sum will produce the number of matches. Ans+max(Ans+1) Multiplies each frequency by one more than the max element, then adds each original value. This ensures that identical values with the same frequency will be grouped together when sorting. Additionally, all resulting values will be positive. โ†’A Stores to โˆŸA. cumSum(Ansโ†’B Stores the prefix sum of the result into โˆŸB. Since โˆŸA has only positive values, โˆŸB is guaranteed to be strictly increasing. SortD(โˆŸA,โˆŸB Sort โˆŸA in descending order (by frequency), grouping identical values together. Also, dependently sort โˆŸB so the original ordering can be restored. 0โ‰ ฮ”List(augment({0},โˆŸA Prepends a 0 to โˆŸA and compares each consecutive difference to 0. This places a 1 at each element that is different from the previous element, and 0 everywhere else. The first element is never 0, so it is considered different. cumSum( โ†’A Takes the prefix sum of this list and stores to โˆŸA. Since there is a 1 at each element with a new value, the running sum will increase by 1 at each value change. As a result, we've created a unique mapping. SortA(โˆŸB,โˆŸA Sorts โˆŸB in ascending order with โˆŸA as a dependent, restoring the original element ordering. โˆŸA-1 Since we started counting up at 1 instead of 0, subtract 1 from each element in โˆŸA and return it. ``` [Answer] # [Perl 5](https://www.perl.org/), 77 + 1 (-a) = 78 bytes ``` $c{$_}++for@F;%r=map{$_=>$i++.$"}sort{$c{$b}<=>$c{$a}}keys%c;print$r{$_}for@F ``` [Try it online!](https://tio.run/##HYzBCsIwEER/ZZH0FFq6amuktnjy5jdILBVCtQmbXErJr7smnubxmBk30bthFuMmHlHKl6XrrSuo/2iXTD8II2UldtFbCltuPeMl2QQ6xnlafTF2jswSBOWH/54ZARUcQUELeAbcA54yHiCHAoT2a10wdvFc3puqxppL/QM "Perl 5 โ€“ Try It Online") [Answer] # JavaScript (ES6), 91 bytes Using a list of unique values, sorted by frequency. ``` x=>x.map(x=>Object.keys(C).sort((a,b)=>C[b]-C[a]).indexOf(x+''),C={},x.map(v=>C[v]=-~C[v])) ``` **Test** ``` var F= x=>x.map(x=>Object.keys(C).sort((a,b)=>C[b]-C[a]).indexOf(x+''),C={},x.map(v=>C[v]=-~C[v])) Test=`[1 2 1 4 5] -> [0 1 0 2 3] [3 2 2 1 5 7 2] -> [1 0 0 2 3 4 0] [8 8 8 8 8] -> [0 0 0 0 0] [2] -> [0] [8 6 8 4 6 8 2 4 6 8 0 2 4 6 8] -> [0 1 0 2 1 0 3 2 1 0 4 3 2 1 0] [14 1] -> [1 0] [19 6 4 9 14 17 10 9 6 14 8 14 6 15] -> [8 0 3 2 1 7 5 2 0 1 4 1 0 6] [15] -> [0] [1 18 4 8 6 19 12 17 6 13 7 6 8 1 6] -> [1 8 3 2 0 9 5 7 0 6 4 0 2 1 0] [9 10 11 9 7 11 16 17 11 8 7] -> [2 4 0 2 1 0 5 6 0 3 1] [1 3 16 19 14] -> [0 1 3 4 2] [18 8] -> [1 0] [13 4 9 6] -> [3 0 2 1] [16 16 18 6 12 10 4 6] -> [1 1 5 0 4 3 2 0] [11 18] -> [0 1] [14 18 18 11 9 8 13 3 3 4] -> [7 1 1 5 4 3 6 0 0 2] [20 19 1 1 13] -> [3 2 0 0 1] [12] -> [0] [1 14 20 4 18 15 19] -> [0 2 6 1 4 3 5] [13 18 20] -> [0 1 2] [9 1 12 2] -> [2 0 3 1] [15 11 2 9 10 19 17 10 19 11 16 5 13 2] -> [7 2 0 5 1 3 9 1 3 2 8 4 6 0] [5 4 2 2 19 14 18 11 3 12 20 14 2 19 7] -> [5 4 0 0 2 1 9 7 3 8 10 1 0 2 6] [9 11 13 13 13 12 17 8 4] -> [3 4 0 0 0 5 6 2 1] [10 14 16 17 7 4 3] -> [3 4 5 6 2 1 0] [2 4 8 7 8 19 16 11 10 19 4 7 8] -> [4 1 0 2 0 3 7 6 5 3 1 2 0] [15 17 20 18 20 13 6 10 4 19 9 15 18 17 5] -> [0 1 3 2 3 9 6 8 4 10 7 0 2 1 5] [15 14 4 5 5 5 3 3 19 12 4] -> [5 4 2 0 0 0 1 1 6 3 2] [7 12] -> [0 1] [18 5 18 2 5 20 8 8] -> [2 0 2 3 0 4 1 1] [4 6 10 7 3 1] -> [2 3 5 4 1 0] [5] -> [0] [6 12 14 18] -> [0 1 2 3] [7 15 13 3 4 7 20] -> [0 4 3 1 2 0 5] [10 15 19 14] -> [0 2 3 1] [14] -> [0] [19 10 20 12 17 3 6 16] -> [6 2 7 3 5 0 1 4] [9 4 7 18 18 15 3] -> [4 2 3 0 0 5 1] [7 4 13 7] -> [0 1 2 0] [19 1 10 3 1] -> [3 0 2 1 0] [8 14 20 4] -> [1 2 3 0] [17 20 18 11 1 15 7 2] -> [5 7 6 3 0 4 2 1] [11 4 3 17] -> [2 1 0 3] [1 9 15 1 20 8 6] -> [0 3 4 0 5 2 1] [16 13 10] -> [2 1 0] [17 20 20 12 19 10 19 7 8 5 12 19] -> [7 2 2 1 0 6 0 4 5 3 1 0] [18 11] -> [1 0] [2 16 7 12 10 18 4 14 14 7 15 4 8 3 14] -> [3 9 2 7 6 10 1 0 0 2 8 1 5 4 0] [5 7 2 2 16 14 7 7 18 19 16] -> [3 0 1 1 2 4 0 0 5 6 2] [8 6 17 5 10 2 14] -> [3 2 6 1 4 0 5]` Test.split(`\n`).forEach(row => { row=row.match(/\d+/g) var nv = row.length/2 var tc = row.slice(0,nv) var exp = row.slice(nv) var xsum = eval(exp.join`+`) var result = F(tc) var rsum = eval(result.join`+`) var ok = xsum == rsum console.log('Test ' + (ok ? 'OK':'KO') + '\nInput [' + tc + ']\nExpected (sum ' + xsum + ') ['+ exp + ']\nResult (sum ' + rsum + ') [' + result + ']') }) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` Qฤ‹@รžโธUiโฑฎยตโ€™ ``` [Try it online!](https://tio.run/##y0rNyan8/z/wSLfD4XmPGneEZj7auO7Q1kcNM////x9tqKNgpKMAJE10FExjAQ "Jelly โ€“ Try It Online") I'm certain there's a way to remove at least one byte, but I've spend an hour not finding it so... ## How it works ``` Qฤ‹@รžโธUiโฑฎยตโ€™ - Main link. Takes A on the left Q - Remove duplicates in A รž - Sort by the following function: ฤ‹ - Number of times... @ โธ - ...in A U - Reverse. Call this l โฑฎ - Over each element in A... i - Find its index in l ยตโ€™ - Decrement to account for Jelly's 1-indexing ``` [Answer] # [PHP](https://php.net/), 92 bytes ``` $b=array_unique($a);print_r(array_map(function($v)use($b){return array_search($v,$b);},$a)); ``` [Try it online!](https://tio.run/##JYzNCsIwEIRfpYccEtiDgfpTYvFBRMq2RJKDcd0mQik@e9zSyzAz3zAUqF5vFKhR2N9tBydooQPbgj2DPcBWSLhsIu74cFWNPTLjMpQUP8VrhcYRx5QH1jt4IelnSVOO76TV15RZVqNZ2efCqdlHs0eegmAQ5H4gN8bV@gc "PHP โ€“ Try It Online") [Answer] # [R](https://www.r-project.org/), 58 bytes ``` x=scan();cat(match(x,names(z<-table(x))[rev(order(z))])-1) ``` [Try it online!](https://tio.run/##HYhbCoAgEACvsp@7kND2huok0cdmQh9ZYBLi5U2CgWHGpRTmR8uFNGrxaMXrA0NxiTUPxkl52U6DgWhx5sXb7cZhJFpJMaUKuIMeOLsEHqAB/smrzTFAnSt9 "R โ€“ Try It Online") Port of [Chas Brown's Python answer](https://codegolf.stackexchange.com/a/138759/67312). `table` computes the counts of each element in `x` (storing the values as the `names` attribute), `order` returns a permutation of the indices in `z`, and `match` returns the index of the first match of `x` in `names(z)`. Then it subtracts `1` because R indices are 1-based. ]
[Question] [ > > Disclaimer: The story told within this question is entirely fictional, and invented solely for the purpose of providing an intro. > > > My boss has gotten a new toy robot, and he wants me to help program it. He wants to be able to enter simple arrow instructions to get it to move. These instructions are: ^ (for move forward) < (for turn left), and > (for turn right). However, now that I've programmed the robot, he wants additional functionality. He wants me to transform any sequence of arrows he inputs, so that rather than having the robot take the path indicated, it moves to the desired location, indicated by the place it would end up if it had taken the inputted path, as efficiently as possible. I appeal to you, the members of PP&CG, to help me with this task. ## Your Task: Write a program or function to convert a string made up of arrows into a string that will get to the location indicated by the input as quickly as possible. Turning takes exactly as long as moving backwards or forwards. ## Input: A string of arrows, as indicated above. If you wish, different characters may be substituted for the arrows, but be sure to include the fact that you do so in your answer. All test cases use the arrows normally. ## Output: A string of arrows (or your equivalent characters), that take the robot to the desired destination as efficiently as possible. ## Test Cases: Note that the solutions offered are only possibilities, and that other solutions may be valid. ``` >^<<^^>^^ -> ^^<^ ^^^^>^^^^ -> ^^^^>^^^^ >>>^^^^^^ -> <^^^^^^ >^>^>^>^ -> (empty string) ^<^^<^^<^^^^ -> >^^>^ ``` ## Scoring: The robot's memory is limited, so your program must have the lowest byte count possible. [Answer] # [Retina](https://github.com/m-ender/retina), ~~103~~ ~~74~~ 71 bytes ``` < >>> +`(>(\^*>){3})\^ ^$1 +`\^(>\^*>)\^ $1 >>(\^*)>(\^+) <$2<$1 <?>*$ ``` [Try it online!](https://tio.run/##JYw7DoAwDEP3nKNI/UzAGpmRS1RWGRhYGBAb4uwltErkWE92rv0@zq0Ofi1VBYCk4uEzI8IzvyFT6EaDmR6NGjGAlgm/piDqJjWoC6KTWkFVErQu2zVnr8nu2Edoob7kBw "Retina โ€“ Try It Online") Link includes test cases. Explanation: ``` < >>> ``` Turn left turns into triple right turns. ``` +`(>(\^*>){3})\^ ^$1 ``` Reduce all turns modulo 4. ``` +`\^(>\^*>)\^ $1 ``` Cancel out movements in opposite directions. ``` >>(\^*)>(\^+) <$2<$1 ``` Turn a triple right turn back into a left turn. This also handles the case of `>>^>^` which needs to become `<^<^`. ``` <?>*$ ``` Delete unnecessary trailing turns. [Answer] # Mathematica, 135 bytes ``` {a="^"~Table~Ramp@#&;a@#,s=If[#2>0,">","<"],a@Abs@#2,If[#<0,s,""],a@-#}<>""&@@ReIm[j=0;i=1;Switch[#,">",i*=I,"<",i/=I,"^",j+=i]&/@#;j]& ``` Takes a `List` of strings as input. ### Explanation ``` j=0;i=1 ``` Set `j` to 0, and set `i` to 1. ``` /@# ``` For each character in input... ``` Switch[#,">",i*=I,"<",i/=I,"^",j+=i] ``` If the character is `>`, multiply `i` by the imaginary unit. If the character is `>`, divide `i` by the imaginary unit. If the character is `^`, add `i` to `j`. ``` ReIm[ ... ;j] ``` Take the real and imaginary parts of `j`. This gives the Cartesian coordinate of the robot. ``` ... &@@ ``` Apply the following to this result: --- ``` a="^"~Table~Ramp@#&; ``` Set `a` to a function that generates a string with `(input)` or `0` character `^`s, whichever is larger. ``` { ... } ``` A `List` consisting of... ``` a@# ``` `a` applied to the first input (real part of `j`) ``` s=If[#2>0,">","<"] ``` If the second input (imaginary part of `j`) is larger than `0`, `>`. Otherwise, `<`. Set `s` to the resulting character. ``` a@Abs@#2 ``` `a` applied to the absolute value of the second input. ``` If[#<0,s,""] ``` If the first input is less than 0, `s`. Otherwise, empty string. ``` a@-# ``` Apply `a` to the input times negative one. ``` ... <>"" ``` Join the strings. [Answer] ## Mathematica 119 Bytes JungHwan's final position to path code was shorter than mine, so using that. I think there is probably an even shorter way to do this... I use the built-in `AnglePath` function to decide the final position. I also define the symbols L, F, and R for "<", "^" and ">", to save a few quote characters. ``` L={0,Pi/2};R=-L;F={1,0};{a="F"~Table~Ramp@#&;a@#,s=If[#2>0,"L","R"],a@Abs@#2,If[#<0,s,""],a@-#}<>""&@@Last@AnglePath@#& ``` Usage: ``` %@{R,F,L,L,F,F,R,F,F} ``` Output: ``` FFLF ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 130 bytes ``` ->s{w,d=0,1;s.bytes{|b|b>93?w+=d:d*=1i*(b<=>61)};r,c=w.rect;[w=(d=">><"[c<=>0])+?^*c.abs,?^*r.abs+w,w+d+?^*r.abs][r<=>0].chomp ?>} ``` ### How it works ``` ->s{ # We start from (0,0i), direction is +1 w,d=0,1 s.bytes{|b| # If it's ASCII 94, go one step forward, # else multiply direction by +i or -i b>93?w+=d:d*=1i*(b<=>61) } # Get the rectangular representation of the result r,c=w.rect # Now, create 2 strings of "^" (call them x and y) for horizontal and vertical moves # And a single ">" or "<" (call it d) for the direction change # If x>0, output x+d+y # If x==0, output d+y # If x>0, output d+y+d+x [w=(d=">><"[c<=>0])+?^*c.abs,?^*r.abs+w,w+d+?^*r.abs][r<=>0] #If y==0 we get an extra ">" sometimes .chomp ?> } ``` [Try it online!](https://tio.run/##NYrRCoMgGEZfJbyqdFIMBpv@fw8iCVOL7SIWWkhUz@7a2OBcnMP3@dksqYd0wrBG5qBitQjcLFMX1s1sBq/nJlJwN1dC/SxzIwEvdbELzyxE7js7CRUhd0AQJVH22Ku2oI0uLb@bwA7xH6GRReroP1vlv09uH69hzBrc0zhPIesV0VL/0Jq06Q0 "Ruby โ€“ Try It Online") [Answer] # J, 90 bytes ## solution ``` t=.{&' ><'@* g=.'^'#~| (t,g@{.,t@-@(*/),g@{:`g@{:,t@{.,g@|@{.@.(0<:{:))@+.@(+/)@(=&1*j.**/\) ``` ## explanation there's a neat trick using complex numbers (multiplying by *i* is a 90 degree left rotation, and *-i* gives you a right one). so we take our input as complex numbers: a 1 represents "walk forward" and *i* / *-i* represent left and right turns. the final position is calculated effortlessly with this representation. Note this is the first (rightmost) part of my final expression above: ``` (+/)@(=&1*j.**/\) ``` That short line above is what solves the problem. Everything else is just figuring out how to format the answer, and could surely be golfed down significantly more. To understand the short line above, note that `*/\` (the scan of partial products) gives you list of *the positions you are facing* at each index in the input: *i* is north, 1 and -1 are east and west, and *-i* is south. But since we start facing north, we have to multiply all of those by *i* which, in J, is represented by `j.` (chew on that sentence for a moment). We only actually "move" when the original input is 1, so we then multiply that result elementwise by the boolean array which is 1 where the original input is 1 and 0 otherwise: `=&1*`. The result of *that* multiplication is an array of "directional steps". Our final position is simply the sum of those steps: `+/` ## testing Unfortunately I can't get this working in TIO for some reason, but pasting the following into J console will verify that it works: ``` t=.{&' ><'@* g=.'^'#~| f=.(t,g@{.,t@-@(*/),g@{:`g@{:,t@{.,g@|@{.@.(0<:{:))@+.@(+/)@(=&1*j.**/\) NB. test cases NB. format input as complex numbers convert=. {&0j1 0j_1 1@:('<>^'&i.) s=. '^<^^<^^<^^^^' NB. >^^>^ echo f convert s s=. '>^<<^^>^^' NB. ^^<^ echo f convert s s=. '^^^^>^^^^' NB. ^^^^>^^^^ echo f convert s s=. '>>>^^^^^^' NB. <^^^^^^ echo f convert s s=. '>^>^>^>^' NB. empty string echo f convert s ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 349 bytes ``` n=>{int a=0,b=0,x=0,y=1,t=0,j=0,k=0,w,e,r;var p="";foreach(var c in n){if(c==62){t=x;x=y;y=-t;}if(c<61){t=x;x=-y;y=t;}if(c>63){a+=x;b+=y;}}while(a!=j|b!=k){w=0;e=a-j;r=b-k;if(r>=e&r>=-e){w=b-k;k+=w;}else if(r<=e&r<=-e){p+=">>";w=k-b;k-=w;}else if(r>=e&r<=-e){p+="<";w=j-a;j-=w;}else if(r<=e&r>=-e){p+=">";w=a-j;j+=w;}p+=new string('^',w);}return p;} ``` [Try it online!](https://tio.run/##jZDPS8MwFMfv@yuyHlzLmrEp7JK@XAQvKogePIiBtEu3tDUbSbau1P7tM9kPZAq6JC8Pvt9PXh4vMzhbarHLKm4Meuq1PWO5lRnaLOUMPXKpQmO1VPO3d8T13ESOeGmMFR@ju7XKkoMZo0OmKEewU0BbqSziMI5TF1sXDUxi63LhonRRxyLWZMM1WkEQkNz1wLNF6IUMSYVU1Mo8zACm11FrYUu20JAGsCWd15Pp5CRjrx9lOr2JWj50ejp0fNfVC1mJkPeh@Ez7UEZtDWMigOOCaEhxSdwrTUFcuQsLb3uxHEJNOlEZgbyfeD/Z@6shBJQGpIYSp6TEZxw95xKPFZiTAv8uR7/Lecw3VOx/dZIS9XGe4YAN4joinRZ2rRVakW5HTvO/XSqzrMToVUsrHqQSYR4GlCUJY5SxIIr@JhnbcxeQlO65S0h22P9/7po8nGNVdFw/Hj0LPrsXTeiIrtftvgA "C# (.NET Core) โ€“ Try It Online") Takes a string as an input and outputs the shortest path that the input would take. --- **Ungolfed & Commented** ``` n => { // First, calculate the route that the robot is going to take, represented by xy int a = 0, b = 0; // The current coordinates (a=x, b=y) int x = 0, y = 1; // The movement vector int t = 0; // A temp variable var p = ""; // The path we are going to return // Calculate the path the robot is going to take by input foreach (var c in n) { if (c == '>') { t = x; x = y; y = -t; } // Turn movement vector right if (c == '<') { t = x; x = -y; y = t; } // left if (c == '^') { a += x; b += y; } // Move forward } int j = 0, k = 0; // The new movement coordinates (j=x,k=y) // While the target position is not reached, move the robot while (a != j | b != k) { int w = 0; // The forward variable, counting how many times we have to go forward int e = a - j, r = b - k; // The target position minus the current position (e=x,r=y) if (r >= e & r >= -e) { w = b - k; k += w; } // Up else if (r <= e & r <= -e) { p += ">>"; w = k - b; k -= w; } // Down else if (r >= e & r <= -e) { p += "<"; w = j - a; j -= w; } // Left else if (r <= e & r >= -e) { p += ">"; w = a - j; j += w; } // Right p += new string('^', w); } // Return the final path return p; } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 187 bytes ``` s=>{x=y=t=0;r=x=>"^".repeat(x<0?-x:x);for(c of s){t-=b=c<">"||-(c<"^");if(!b)[z=>++y,z=>++x,z=>--y,z=>--x][t&3]()}t=x<0?"<":">";return (y>0?r(y):"")+(x?t+r(x):"")+(y<0?(x?t:t+t)+r(y):"")} ``` [Try it online!](https://tio.run/##bY7dbsMgDIXv9xSZLyYQpYq0uwSTB6lqKc2SqVMVKkIr6M@zZyRtsrWbQLKPOZ85X@Wx7Cq73TvZmo@6b7DvUJ89BnSY5hY9aiBY2npfl455lRbSZ57njbGsSkyTdPzsJG6wUqDhcpEsNgQ83zbsdcNXJ9RChMVY/FCkDLfi1yv39r5m/Opw2AsKsrgit7U72DZhQaeFZYFnAFwwXzhhmb@rEP3DKHPCcTG5rn1l2s7s6uXOfLKGgSaliDTFPItHiQhEKjYvTwjR6JiQX3JEZvXMaT0@zF/9yMipqf9D0e1M@SaFEfonm6L7neM9TCKkaeT7bw "JavaScript (Node.js) โ€“ Try It Online") [Golfed version with whitespace](https://tio.run/##bY7dbsMgDIXv@xQZFxOIUkXaXYbJg1S1lGbJ1KkKFWETbO2zZ0B@tmYzCPtgPnzeqo@qr83pYkWnX5qhhaEH9bXJQjjwYCF/TsKAA0WQ7ExzaSpLncxL4QrHxnarDa0z3WY9G@EYVsARakkUuV4FDQWS6XmMU0sfjmz/CYpzv03JxSSEH5M77O3j04GyhNzSaSEOJpIU4dfJWWPfTZdRr/LSUM8KQtgyhFNXWm6oW1/78E3sFZZbxhfuNtS66/W52Z31K20pUSglosJgfXsvAQiiDMVmhSCmFzPySyZkUWtOqdRYRv3IwMm5/kPhuGZ/s4IA/eNN4rQXe3c3AVKY@OEb) **-14 bytes** by @Neil --- ### Ungolfed: ``` s=>{ // convert turns to up/down/left/right movements to final destination let directions = [ z=>++y, // up z=>++x, // right z=>--y, // down z=>--x // left ]; let x = y = direction = 0; for(c of s){ let relativeDirection = "<^>".indexOf(c)-1; // relative turn offset: -1 = left, 1 = right direction += relativeDirection; if(direction<0){direction+=4} // make sure direction%4 > 0 if(c==="^"){directions[direction%4]()} // do the movement if going forwards } // convert destination back to turns // the most efficient output has up before left/right before down let absoluteRepeat = num => "^".repeat(Math.abs(num)); let turn = x<0 ? "<" : ">"; let outp = ""; if (y>0) { outp += absoluteRepeat(y) } // handle up before left/right if (x) { outp+=turn+absoluteRepeat(x) } // handle left/right if (y<0) { outp += (outp?turn:turn+turn)+absoluteRepeat(y)) } // handle down (including w/o left/right) return outp; } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~174~~ ~~169~~ 165 bytes Edit 1: -5 bytes by allowing the direction to be outside the range 0-3, and removing whitespace. Edit 2: -4 bytes by changing input to (1, 2, 3) instead of (<, ^, >) since the OP allowed it, as well as changing my coordinate system to allow me to reduce my distance calculation. ``` n,d=[0,0],0 for c in input():exec'd-=1 n[d%2]+=(-1)**(d/2%2) d+=1'.split()[ord(c)-49] print'2'*n[0]+'13'[n[1]>0]*any(n)+'2'*abs(n[1])+'13'[n[1]>0]*(n[0]<0)+'2'*-n[0] ``` [Try it online!](https://tio.run/##VZDdasQgEIXvfQqxhNH8bHXsTZfNvohYSKNlhWBCktLu06eatLDFuTh@c8Y5ON3X2xhxe/q6hcFTdZ7mEFcKrFgYFDzE6XPl4jT7aeh6z@ECNSh4AG8J4CO4JqBBCEL60fmWMbbF2rVG1tLWknyMM@1piPT36bP/9j24plU0GlegrVreKFGW3D1jgYK6qlVwWqYhJLcZZ8d70by8WrInTbvLaKStQGkw0Sh7lbbs4p1HUeVm977wjMV/B89DF3l4mnzZUlLy9ws5FM35N6ZRKUSNyAhD3NWutd7VofE42ZLMR6XODw "Python 2 โ€“ Try It Online") Determines final coordinates via the dictionary's values being executed, then just prints the direct path to the end goal. [Answer] # [Perl 5](https://www.perl.org/), 185 + 1 (-p) = 186 bytes ``` /</?$d--:/>/?$d++:/\^/?$m[$d%4]++:0for/./g;$y=$m[0]-$m[2];$x=$m[1]-$m[3];$q='^'x abs$x;$_=A.$q.B.('^'x-$y);$x<0?y/AB/</:$x?y/AB/>/:0;$_=('^'x$y).($x<0?'<':$x>0?'>':'').$q if$y>0;y/AB//d ``` [Try it online!](https://tio.run/##LY3NDoIwEIRfhcOaQki7ReVSoATuPoFSo0EMicqfB/ry1gVNNpuZyTe7/W18xM5hijnUnCvUiwhDhSdD6nmEerOvyMumG1HgPQGbUSwrTntbJTAvNlrtjuyQMcNm73KdYE7gnBUCBlEKf0k52IAKqcwtFiX9VDD/pEYlF3rFiBL@irGUEaJJaKYYC@iW1zZgtUzWGtbOmdT8x5hP17/b7jU5foiFjKTj/Rc "Perl 5 โ€“ Try It Online") [Answer] **JavaScript (document.getElementById() kind), 343 chars** ``` function b(s){s=s.split('');c=[0,0];r=0;p='';w='<';e='>';n='^';for(i in s){r+=s[i]==e?.5:s[i]==w?-.5:0;r=r>1?-.5:r<-.5?1:r;c[1-Math.ceil(Math.abs(r%1))]+=s[i]==n?r>0?1:-1:0;}x=c[0];y=c[1];j=x<0?-x:x;k=y<0?-y:y;f=function(a){p+=a==j?x<0?w:x>0?e:'':j>k?y<0?w:y>0?e:'':y>0?e+e:'';for(i=0;i<a;i++){p+=n}};if(j>k){f(j);f(k)}else{f(k);f(j)}alert(p)} ``` expanded: ``` function b(s){ s = s.split(''); c = [0, 0]; r = 0; p = ''; w = '<'; e = '>'; n = '^'; for(i in s){ r += s[i] == e ? .5 : s[i] == w ? -.5 : 0; r = r > 1 ? -.5 : r < -.5 ? 1 : r; c[1 - Math.ceil( Math.abs( r%1 ) )] += s[i] == n ? r > 0 ? 1 : -1 : 0; } x = c[0]; y = c[1]; j = x < 0 ? -x : x; k = y < 0 ? -y : y; f = function(a){ p += a == j ? x < 0 ? w : x > 0 ? e : '' : j > k ? y < 0 ? w : y > 0 ? e : '' : y > 0 ? e+e : ''; for( i = 0; i < a; i++){ p += n } }; if( j>k ){ f(j); f(k) } else { f(k); f(j) } alert(p) ``` } Usage: ``` b('^<^^<^^<^^^^') ``` alerts: `>^^>^` A robot with reverse would have been useful. ]
[Question] [ My parents have an home theater device. The remote is broken making it incredibly difficult to navigate rightwards in a menu. Most the time it doesn't work but when it does it moves rightwards incredibly quickly. This is obviously frustrating but it is most frustrating when you want to enter a movie title which requires navigating a keyboard that looks like this: ``` 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 1 2 3 4 5 6 7 8 9 0 ``` Your task is to take as input a movie title and calculate how "frustrating" it is to type that movie title. The frustration number of a particular string is the number of letters that require moving right from the letter before them. We don't care how far right they are, since if we start moving right we pretty much instantly go to the end of the line, and we don't care about up, down or leftwards movement because they are easy. For example if we wanted to type in ``` keyboard ``` * We start at `k` for free. * `e` is just above `k` so we don't need to move right. * `y` is all the way left so no need to move right. * `b` however is on the next column rightwards so we need to move right to get to it. * `o` is on the next column over so we have to move rightwards to get to it. * `a` is back in the first column so we move left to get to it. * `r` is all the way on the right so we move right to it. * `d` is two columns to the left of `r`'s column. The characters that need to move to the right are `bor` meaning that this is frustration 3. ## Additional rules This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge so your answers will be scored in bytes with fewer bytes being better. The input will always consist of alphanumeric characters, you can support either capital or lowercase letters and you only need to support one. The input will never be empty. ## Testcases ``` keyboard -> 3 2001aspaceodyssey -> 6 sorrytobotheryou -> 8 thinblueline -> 5 blast2 -> 3 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~61~~ ~~55~~ 54 bytes *Saved 1 byte thanks to @nwellnhof* Takes input as an array of characters. ``` s=>s.map(p=c=>r+=p>(p=(+c?~c:1-Buffer(c)[0])%6),r=0)|r ``` [Try it online!](https://tio.run/##bc5BCsIwEIXhvacQQUhQY1UUEVLBa4iLNJ3aauyEmVQIiFevRVEQOqtZfA/@i7kbtlT5MKsxh7bQLeuU1c144bXVKU20T7tXTOz@aXeL2aEpCiBh5TE5yfFGTkkn8kGtxZrRgXJ4FoU4KqVGV4gZGspHJymH35vPh6tBD14myYK9sYB5ZIb4HnV404cZiWLADEMJFLH54m0fDmVVZ64BV9XwS@nwug9nznBY/hV/mtsX "JavaScript (Node.js) โ€“ Try It Online") ### How? For all characters but digits greater than \$0\$, the 0-indexed column \$x\$ is given by: $$x=(c-1)\bmod 6$$ where \$c\$ is the ASCII code of the character. For positive digits \$n\$, we need to do instead: $$x=(n+1)\bmod 6$$ *Examples:* ``` "a" --> (97 - 1) mod 6 = 96 mod 6 = 0 "b" --> (98 - 1) mod 6 = 97 mod 6 = 1 "0" --> (48 - 1) mod 6 = 47 mod 6 = 5 "3" --> ( 3 + 1) mod 6 = 4 mod 6 = 4 ``` ### Commented ``` s => // s = input string (as array) s.map(p = // initialize p to a non-numeric value c => // for each character c in s: r += // update the result r: p > ( // compare p with p = ( // the new value of p defined as: +c ? // if c is a positive digit: ~c // -(int(c) + 1) : // else: 1-Buffer(c)[0] // -(ord(c) - 1) ) % 6 // apply modulo 6 ), // yields 1 if the previous value is greater than the new one r = 0 // start with r = 0 ) | r // end of map(); return r ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` โพ04yOโ€˜%6<ฦS ``` A monadic Link accepting a list of (uppercase) characters. **[Try it online!](https://tio.run/##y0rNyan8//9R4z4Dk0r/Rw0zVM1sjs0N/v//v5GBgaFjcICjs6u/S2RwsGskAA "Jelly โ€“ Try It Online")** ### How? First replaces any `'0'`s with `'4'`s (so the rest of the code treats them as being in the rightmost column). Then casts to ordinals, adds one and modulo's by `6` to get 0-based column indices. Then compares neighbours with is-less-than and sums the result. ``` โพ04yOโ€˜%6<ฦS - Link: list of characters e.g. "BLAST20" โพ04 - list of characters = ['0', '4'] y - translate "BLAST24" O - ordinals [66,76,65,83,84,50,52] โ€˜ - increment [67,77,66,84,85,51,53] 6 - literal six % - modulo [ 1, 5, 0, 0, 1, 3, 5] ฦ - neighbourly: < - less than? [ 1, 0, 0, 1, 1, 1 ] S - sum 4 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~45~~ 39 bytes ``` {sum .[1..*]Z<$_}o{(2 X-.ords)X%46 X%6} ``` [Try it online!](https://tio.run/##BcFRCoMwDADQq@RjDh2sqAy/dOeQjTFajSirRpL2I4hn797bkX2TVoXrBF06JK5g3pUxt8@rvXxPOvIa@rshHqXos0cDfdacSazClJs4FDARQ/tDdWR5hLosKyu7HZBGFUEFIWYN5CjMyEoRwrxszkf0y4bgvJVQP9Mf "Perl 6 โ€“ Try It Online") Works with uppercase letters. `(2-ord(c))%46%6` computes the reversed x coordinate. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 85 bytes ``` import StdEnv (\s=sum[1\\a<-s&b<-tl s|b>a])o map(\e=(toInt e+if(e-'1'>'/')1 -1)rem 6) ``` [Try it online!](https://tio.run/##rZI/b9swEMVn61PcVEmpVFkpGrSAlakdAnQokNHycJTONVH@UcljEwH97FVJOU6QPdu9e@C7H48cFKFZtB2DItAoTdZcQdOA1JN17GFAkzPgNBE6kMbLkQAN0OPkyHtpDfAJGYInHysChVqMCMdgBo5ulQGkOG9Xd7DxuLCPIGOy1ZoM0wg2MIiwhoxwtA7YMioQM6cTwfCH5YwD9zx@M3@yovedD3rf9j3uav9O7GpW4P@KWzyUNl5jKnrqCrZ3hoHey2NBdd7mt3mTly3UbelIw025XDWJLYEJUvbhmTrhxYsalgOqamUzqCNcYSyDo99BuqgeTmTO0NIoaajMXmM@x3XwRsRZds8YB3TxDUbYv/CaKTJ2XVplqvoeirVXPXVK2NXA5NkfsojtKNusKibts82m2Oe/aBYW3ZgfKvhYVufm9Xbbop9wIDvO3tOc3JuL661zM1th4wbdbEMyP19MPkkjVKC0mGR8uhhCoefrV2O@bJNsy6gOy7/hqPCnX@q778vXOe5dDmfxQyHH36H/Aw "Clean โ€“ Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 56 bytes ``` ->s{w=9;s.count{|c|w<w=[*?a..?z,*?1..?9,?0].index(c)%6}} ``` [Try it online!](https://tio.run/##VcnRCoIwFIDh@54ihKDEhnoRiNkeRLzY5hEl2ZGdDVvqs68IuvDqh/8zTvrQVeH6oGWuipKYQqftsqp1vs9VHXPBGH8nMc@@LRKeNmzQLbzO6nK6bVuYjl0dPcFLFKaNmOqFoebwu3maZjQJBdh6IvB7JTTGW5RoezAe3V5tP2g5OhgHDXuRoyCb/1/4AA "Ruby โ€“ Try It Online") Preliminary naive version, will be golfed. [Answer] # [Japt](https://github.com/ETHproductions/japt) `-x`, 14 bytes ``` ยฎrT4 c ร„ u6รƒรค< ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=rnJUNCBjIMQgdTbD5Dw=&input=WyJCIiwiTCIsIkEiLCJTIiwiVCIsIjIiXQoteA==) Port of [this](https://codegolf.stackexchange.com/a/176498/71434) Jelly answer. Takes input as an array of characters, with letters uppercase. Explanation: ``` ยฎrT4 c ร„ u6รƒรค< : ยฎ รƒ :Map each character through: rT4 : Replace 0 with 4 c : Get the char-code ร„ : Increment it u6 : Modulo 6 รค< :Replace with 1 if you had to move right, 0 otherwise :Implicitly sum and output ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 73 bytes Not a bad solution for Java! That zero being on the right-hand side cost me several bytes. ``` t->{int a=9,c=0;for(int d:t)c+=a<(a=(--d+(d/48==1?2:0))%6)?1:0;return c;} ``` [Try it online!](https://tio.run/##bVHBbgIhFDzrVxCTJhDZLZqmqbulpum5XjwaDyygoits4K0JMX77ltVNenEOvPBmHszAUVxE5hptj@rUNW1VG4lkLUJAv8JYdB2PUcJABBCQirGg/U5IjVZJgAYMmkQii@VB@M0WSVLe@dt4dK/DAStkEUcdZF/XXi74gkrOyp3zuN@rAoiccvGJBcdZpqZYvb59cD5bzgtGyMs7Wc4KVnoNrbdIlreufGbz4oxC55QCr8Ebu09@hN8HkjyP@qse3b6HijuzYds8NLUBPKETQv6j9VjHAPqcuxbyJs1BbbHNLU5zObifFPfbexExIUPkR@zHeuu6k46VE17ROWMzEZr0ek7FEHSkwXkfwVUODtpH11I4GFvVra6N1bRKnwFzumB/ "Java (OpenJDK 8) โ€“ Try It Online") **Explained** ``` t -> { // Lambda taking a char array as input int a=9, // Initialise last column value c=0; // Initialise frustration count for(int d:t) // Loop through all chars in title c+= // increment the frustration count if... a< // The last column is smaller than the current column (a= // Set last column to current column (--d+ // Decrement ascii value of char (d/48==1 // If ascii decremented ascii value is between 48 and 95 ?2:0) // increment by 2 (1 total) or 0 (-1 total) )%6) // Mod 6 to retrieve column index ?1:0; // Increment if to right hand side return c; // return calculated frustration count } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes -1 byte thanks to @Kevin Cruijssen ``` ยพ4:ร‡>6%ยฅ1@O ``` Another port of Jonathan Allan's Jelly answer. Takes input in uppercase. Explanation: ``` ยพ4:ร‡>6%ยฅ1@O //full program ยพ4: //replace all '0's with '4's ร‡ //get ASCII code points > //increment 6% //modulo 6 ยฅ //get deltas 1@ //is >= 1 O //sum ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0D4Tq8Ptdmaqh5YaOvj//@/k4xgcYgQA "05AB1E โ€“ Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~32 31~~ 28 bytes ``` +/>':6!(,/"a10"+!'26 9 1)?0+ ``` [Try it online!](https://tio.run/##HYzRCoIwFEDf@wq7BCoWTiOpXagPEcEtZ4pji22CI@rXF/p4zoEzndRLhdDTLL/HtNonxxxYQSDbx2UV3aIifZAsOPo51P5naB8t2OoJk7Zno8QFPZq0@e5cDZPwXDPTAZ6blUtCCmbf7Cl0560VHrDagtXGeKe5doMwXs@A1827YVRczkKOSgBeNscls65cl@EP "K (ngn/k) โ€“ Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 46 bytes ``` T`l1-90`1-61-61-61-61-61-6 . ;$&$* &`;(1+);1\1 ``` [Try it online!](https://tio.run/##XcIxDsIwDADA3e8oVQEVxR2QUB7ABxgZklBLjYjiynEHvz7snE5Ic439ND1Df4WC88MFnO9/4QZ@GIcLjMFPeD17fGPvX7LEUVZYnMPY9vghXq01MmgsYsqJdSMxPkC3XFM5qORKkEpsuvwA "Retina 0.8.2 โ€“ Try It Online") Link includes test cases. Explanation: ``` T`l1-90`1-61-61-61-61-61-6 ``` List the alphabet and digits in the order on the OSK and map each one to a (1-indexed) column number. ``` . ;$&$* ``` Convert each column number to unary. ``` &`;(1+);1\1 ``` Count the number of columns that are followed by a larger (i.e. rightwards) column. The `&`` allows the matches to overlap. [Answer] # [Python 2](https://docs.python.org/2/), 84 bytes ``` def f(s,k=6):j=(ord(s[0])+('0'<s[0]<':')*2-1)%6;return(j>k)+(~-len(s)and f(s[1:],j)) ``` [Try it online!](https://tio.run/##FY69bsMwEIPn9im0BCc1MiB7CBA3yYsYHuTqDP9BZ9zJgzr01d1oIcgPBME9p4lic54BRzVqsevzZtrlqYmDls715qrBwaPYB7RgvpqqNpfbN2M6OOrltb4bf9WGUYvxMZSRrm57uxhzjsRK1BxVByvmgTwHsAoa52ovu/9BClkEc4FCzDnRQGlCznQUlqY5DtuB2xyx5GHzkpri7q5o/q2hbz8/dp5jUmKheoF9HzDnPw "Python 2 โ€“ Try It Online") [Answer] # Mathematica, 102 bytes ``` Differences[Last@@Join[Alphabet[],ToString/@Range@9,{"0"}]~Partition~6~Position~#&/@#]~Count~_?(#>0&)& ``` Pure function. Takes a list of characters as input and returns a number as output. This is a pretty naive solution, golfing suggestions welcome. [Answer] # PHP, ~~74 81~~ 77 bytes ``` for(;$o=ord($argn[$i]);$i++&&$f+=$p<$x,$p=$x)$x=(--$o/48^1?$o:$o+2)%6;echo$f; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/b886a69f5aefe0e55bef6fad8102dcfa9d195b4c). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~82ย 79~~ ย 77 bytes ``` o;c(i){i+=i<60&i>48?1:5;i%=6;}f(char*s){for(o=0;*++s;o+=c(*s)>c(s[-1]));o=o;} ``` [Try it online!](https://tio.run/##bY/BaoQwFEX3fkUQLHEcIQ7tUCaNw/xB920XMcYa6uQN78WFiN9u08WUQn3Le8698Ez5acy6gjTc5bMrlHs5igdXPz6fq9OTdJk6yqXjpte4o3zuADkoIXdFQRIKZXhMa8Ppraw@8lyCArmsOPqLb1/R@XBvsjlh8W4/WcfTjFhZs6x99@me9h2n2E2WJImUXbXz/F74O5V@2akBjW0a5X/wIESl6aaNhXYispsSAeIUoIHQW5xg3JRC73wzjHZwfnulGTSFwy@yYUTPRHxg/QY "C (gcc) โ€“ Try It Online") This function will only support lowercase inputs --- # Ungolfed and commented: ``` o; //Used for output c(i){ //Calculates the column of given character i+= //Correct i to get the correct column i<60 //If i is a digit... & i>48 //... but not '0' ?1 //Then move it one column on the right :5; //Else move it five columns on the right i%=6; //Get the column number } f(char*s){ // The actual "frustrating" function for( //Loop for each character o=0; //reinitialize output *++s; //move to next character / while this is not '\0' o+=c(*s)>c(s[-1]) //Increment if current character is on the right of the previous one ); o=o; // Outputs result } ``` --- If my function is allowed to accept wide character strings, it can be reduced to **76 bytes** with: ``` o;c(i){i+=i<60&i>48?1:5;i%=6;}f(int*s){for(o=0;*++s;o+=c(*s)>c(s[-1]));o=o;} ``` [Try it online!](https://tio.run/##dY9BS8QwEIXv/RWhUEm3W0gXXWRjKt73IHhUD2ma7g7WzJJJkVL622sEFcHdOb73fQ/GlAdjlgWl4ZBPUCi424orqK9v76vdjYRMbeXccXBhRfnUoeeohFwVBUkslOExrQ2n57J6zXOJCuW8@ME9uPbRR@lbZFPC4n2cvrKO79PsiZU1y9oXl65p3XGKcjInSazZuwbHf5S/W/v0zY4Nat@mkf7fboSoNJ20sdiORPY8Rej9GLDBcLR@xOE8FY7gmn6wPbgLO02vKWx@OxsG75iIXyyf "C (gcc) โ€“ Try It Online") This version just accept input as `int*` instead of `char*` --- # Edits: * Golfed 3 bytes in the calculation of the column (function `c`) * Golfed 2 bytes thanks to ceilingcat ]
[Question] [ ## Background Alice and Bob are creating a golfing language to win every single PPCG challenge. Alice wants to make a two-dimensional language, like ><>, but Bob prefers a prefix-infix syntax like in J. As a compromise, they decide to create a two-dimensional prefix-infix language. The parser is a pain to write, and they need your help! ## Syntax specification In Alice's and Bob's language, there are *variables*, which are represented by lowercase ASCII letters `a-z`, and *functions*, which are represented by uppercase ASCII letters `A-Z`. A function can be invoked with one or two arguments. A *program* is a rectangular grid of letters `a-zA-Z` and spaces, and the top left corner must not contain a space. This is an example of a valid program: ``` F Gy H R x ``` When the program is parsed, it's transformed into an expression of a C-style language (C, Java, Python...) containing single-letter variables and function calls in the format `<func>(<arg>)` or `<func>(<arg1>,<arg2>)`. For example, the above program results in this expression: ``` F(H(R(x)),G(x,y)) ``` The details of the parsing process are as follows: * The spaces are just filler, so they are not parsed. * Every variable `a-z` is always parsed as itself. * Every function `A-Z` is parsed as a function call. Its arguments are the closest expressions below it and to its right in the grid, in this order. If only one of these is present, it's given as the sole argument. You can assume that all functions have at least one argument in the grid. In the above example, the variables `x` and `y` are parsed as themselves. The function `R` has nothing below it and `x` to its right, so it's parsed as the one-argument invocation `R(x)`. Similarly, `H` is parsed as `H(R(x))`, since it has `R` below it. The function `G` has `x` below it and `y` to its right, so it's parsed as `G(x,y)`, and similarly for `F`. The expression parsed at the top left corner is the result of the parsing process. ## Input and output Your input is a non-empty rectangular array of characters. It will always be a valid program in Alice's and Bob's language, but it may contain expressions that are not used in the output. Your output shall be the parsed expression resulting from the above process. ## Rules and scoring You can write a full program of a function. The lowest byte count wins, and standard loopholes are disallowed. ## Test cases These are given in the format `grid <newline> expression`, with hyphens `---` between the cases. The SE format leaves some lines blank, but they should be filled with spaces. ``` x x --- x y z x --- Fx F(x) --- Fx y F(y,x) --- ABu A(B(u)) --- G H k G(H(k)) --- ABCA x xs DFk A(x,B(D(F(k)),C(x,A(s)))) --- A B C D x A(C(D(x)),B(D(x))) --- RT Hq I xR k R(I(x),T(H(R(k),q))) --- A A A a S A b B C Dx d X u f A(B(d,C(D(f,x))),A(X(u),A(u,a))) ``` [Answer] ## CJam, ~~67~~ ~~62~~ ~~60~~ ~~58~~ ~~57~~ 54 bytes *Thanks to Dennis for saving 4 bytes.* ``` {:Gsc_32&{"()"[GGz2{1m<_{S#}#>W<\}*z]{},{J}%',**+}|}:J ``` This defines a named block (function) `J` and leaves it on the stack. The function itself expects an array of strings on the stack, which represents the input grid, and leaves the desired string in its stead. [Test it here.](http://cjam.aditsu.net/#code=%7B%3AGsc_32%26%7B%22()%22%5BGGz2%7B1m%3C_%7BS%23%7D%23%3EW%3C%5C%7D*z%5D%7B%7D%2C%7BJ%7D%25'%2C**%2B%7D%7C%7D%3AJ%3B%0A%0AqN%2Fed%0A%0AJ%0A%0Aed%5D%3B&input=A%20A%20%20A%20a%20%0A%20S%20A%20%20b%20%20%0AB%20%20C%20%20%20Dx%0Ad%20X%20%20u%20f%20) I've been meaning to tackle this one since it was posted, but apparently I needed a bounty and an overly long Pyth solution to motivate myself sufficiently. ### Explanation The solution is of course recursive and gradually builds up the string. ``` { :G e# Store the current grid in G. sc e# Convert the grid to a string, flattening it, then to a character, which e# discards everything but the first character. This is a golfed 0=0=. e# This character will either be an upper-case letter (function) or a lower- e# case letter (variable). _32& e# Make a copy of the character and take bitwise AND with 32. This gives a e# NULL character for functions and a space for variables. { e# If the result is falsy... (i.e. NULL, i.e. we have a function) "()" e# Push parentheses for later use. [ e# Remember the current stack depth. GGz e# Push an array which contains the grid and its transpose. 2{ e# Run this block twice... (it will be applied once to each grid) 1m< e# Rotate the rows. This has two effects: a) It removes the first row e# from the front such that we can go looking for the next non-space e# character down the first column from the start. b) It places a row e# at the end which we know doesn't start with a space, which acts as e# a guard in case there are no further letters below the current one. _ e# Duplicate this grid. { e# Find the first index where this block yields something truthy... S# e# Find the index of the first space in the current row. If the row e# starts with a space, this is 0, i.e. falsy and the search continues. e# If there is a space in any later position, that will be positive and e# truthy, so this index gets returned. If there is no space at all, e# the result is -1 which is also truthy and ends the search. }# > e# Discard all lines up to (but not including) the found index. W< e# Discard the guard row at the end. \ e# Swap the grids so that the next pass processes the other grid. }* z e# Transpose the second grid back to its original orientation. ] e# Wrap both processed grids in an array. {}, e# Remove a grid if it's empty. {J}/ e# For each remaining grid, call J recursively. ',* e# Join the grids with commas if there are still two of them. * e# Wrap this string in the parentheses below on the stack. + e# Prepend the function name. }| }:J ``` [Answer] # Python 2, ~~227~~ ~~223~~ ~~192~~ ~~182~~ ~~179~~ 177 bytes ``` def r(i,y=0,x=0): c=i[y][x];z=[] for t in"pq": p=q=0 try: while" "==i[y+p][x+q]or 1>p+q:exec t+"+=1" z+=[r(i,y+p,x+q)] except:1 return c+"(%s)"%",".join(z)*c.isupper() ``` (The four spaces are in fact tabs) Takes a 2d list of characters as the first argument to r. [Answer] # Pyth, 97 bytes ``` D:TkdI}p@@QTkGR)=Z0p\(V2JK0W|q\ @@Q=b+TJ=H+kK!+JK=J+NJ=K+!NK)I!|gblQgHl@Q0p*Z\,:bH+=Z1d))p\);:000 ``` My god that took a long time to make (about 5/6 hours?). Pyth really wasn't designed for this... Try it [here](http://pyth.herokuapp.com/?code=D%3ATkdI%7Dp%40%40QTkGR%29%3DZ0p%5C%28V2JK0W|q+%40%40Q%3Db%2BTJ%3DH%2BkK!%2BJK%3DJ%2BNJ%3DK%2B!NK%29I!|gblQgHl%40Q0p*Z%5C%2C%3AbH%2B%3DZ1d%29%29p%5C%29%3B%3A000&input=[[%22F%22%2C%22+%22%2C%22G%22%2C%22y%22]%2C[%22H%22%2C%22+%22%2C%22+%22%2C%22+%22]%2C[%22R%22%2C%22+%22%2C%22x%22%2C%22+%22]]%0A&debug=0). Attempt at explanation as well as python equivalent ``` Q = literal_eval(input()) def at_slice(T,k,d): if Pprint(Q[T][k]) in "abcdefghijklmnopqrstuvwxyz": return Z = 0 Pprint("(") for N in range(2): J=K=0 while " "==Q[assign('b',T+J)][assign('H',k+K)] or not J+K: J+=N K+=not N if not (b>=len(Q) or H>=len(Q[0])): Pprint(Z*",") at_slice(b,H,assign('Z',1)+d) Pprint(")") at_slice(0,0,0) ``` Where the functions `Pprint` and `assign` return what they're given. [Answer] ## Haskell, ~~124~~ ~~122~~ ~~120~~ 119 bytes ``` r@((c:_):_)#g|c>'_'=[c]|c<'!'=g%r|1<2=c:'(':(tail%r)!(map tail%r)++")" _#_="" g%r=g r#g a!b=a++[','|a>"",b>""]++b (#id) ``` Usage example: `(#id) ["RT Hq ","I xR k"]` -> `"R(I(x),T(H(R(k),q)))"`. How it works: besides the input grid `r`, the function `#` takes another function `g` as an argument that is applied on `r` whenever the top left character is a space. If it's a lowercase char instead, return it. Otherwise it must be an uppercase character and `#` is called recursively, once with `tail` to go down and once with `map tail` to go right. `!` joins the results from the recursive calls with a `,`, if needed. All starts with the input grid and the identity function. [Answer] # Python 3, 187 bytes Still looking for ways to golf this down, but I'm just pleased I managed to turn it into a one-liner. ``` lambda g,r=0,c=0:g[r][c]+'(%s)'%','.join([p(g,R,c)for R in range(r+1,len(g))if c<len(g[R])and' '!=g[R][c]][:1]+[p(g,r,C)for C in range(c+1,len(g[r]))if' '!=g[r][C]][:1])*g[r][c].isupper() ``` ]
[Question] [ Write a program that outputs the exact string: ``` jan ale o, toki! ``` *("Hello, world" but in toki pona to prevent builtins.)* with an optional trailing newline. Additionally when all copies of any one byte present in your program are removed the program must fail to produce a correct output no matter what byte is selected. To fail it just has to produce a wrong result, it doesn't matter whether it errors or not. Wrong doesn't necessarily mean different, just wrong. So using a different output format or dropping the optional trailing newline are not failure. You are not allowed to read your own source code. ## Scoring Answers will be scored on two properties, the first is the number of distinct bytes, used (max being 256) in the program, with higher score being better. Since it shouldn't be too hard to achieve the maximum for your choice of language in the first category the second category is good old [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Answers are scored then in total number of bytes with lower being better. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 256 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), score 256 Crushed my other answer :) ``` โ€šร…รฆjยฌยฐยฌยชโ€šร„รบbยฌยขยฌยฃยฌโ€ขยฌยถยฌยฉยฌยจยฌร†ยฌยตยฌฮฉยฌรธโˆšรœโˆšรกโˆšรชโˆšรซaโˆšรณโˆšรฒโ‰ˆรญโˆšรปโˆšรผโˆšยถโˆšรŸโˆšโˆžฦ’ยฑยปโˆ‘โˆšยฑโˆšโˆ‘โˆšโˆโ‰ˆรฌnโˆšรฆ"#$&'()*-.078 :;<=>?@ABCEFGHยทโˆโ€ขIJKLMNPQRSTUVWlXYZ[\]^_`cdfghempqruvwxyz{|}~โˆ†รนยฌโˆ‚ยฌโˆžยฌฯ€ยฌโ‰คยฌโ‰ฅโ€šร…ยฅโ€šร…ยตโ€šร…โˆ‚โ€šร…โˆ‘โ€šร…โˆโ€šร…ฯ€โ€šร…โˆซโ€šร…ยชโ€šร…ยบoโˆ†ร…โˆ†รกโˆ†รคโˆ†รซโˆ†รฌโˆ†รฒโ€šยฑร†โˆ†ยงโˆ†ยจโˆ†โ‰คยปยงโ€ฆรฌโˆ†ร โ€ฆรณ,โˆ†รญโ€ฆโ€ โ€ฆยถโˆ†รดโ€ฆยฑโ€ฆโ‰คโˆ†โ€ขย โ€ โ€ฆยบย ร‡โˆ†โ‰ ย รฃยปโ€ขยทโˆซโ€ ยทฯ€ยฃยทโˆร‘ยทโˆรฅยทโˆซโˆยทโˆยงยทยชรคยทโˆโ‰คยทโˆโˆ‚ยทฯ€ร‡ยทฯ€รœยทฯ€รถยทฯ€ยขยทฯ€ยจยทยชยงยทฯ€รฆtยทโˆซร ยทยชยฅยทโˆซรญยปยถยทโˆร‡ฦ’รคฦ’รฑยทโˆรปฦ’โ€ ฦ’โˆžฦ’รธยทฯ€ร„ยทฯ€ร‘ยปร†ยทโˆโ‰ฅยทฯ€รฒยทฯ€โ€ ยทฯ€โ„ขยทโˆซรœยทโˆซรคยทโˆซรฉโ‰ˆยชยทโˆซยฐยทโˆร–ยทโˆรงยทโˆซฯ€ยทยชรฃยทโˆโˆ‘ยทฯ€ร‰kยทฯ€รกยทยชรงยทฯ€รตยทฯ€โ‰ ยฌรŸยทโˆซรขยทยชยตยทโˆซรฌยปรŸยทโˆร‰ฦ’รฃยทโˆรฃฦ’รณยทโˆรผiฦ’ยฐยทโˆยฃโ‰ˆร„ยทฯ€ร…ยทฯ€ร–ยปร˜ยทฯ€รณยทฯ€รดยทฯ€ยฐยทฯ€ยดยทโˆซรกยทโˆซรฃยทโˆซรจโ‰ˆยบ!โ€šร„รนs9123456Dยทโˆรคยทฯ€รฑ+/ยฌยงยทโˆยขโ€šร‡ยจOโ€šร„รดโ€šร„รฒ%โ€šร…ฮฉยฌยดโˆšร‘ยทยชรฅ ``` **[Try it online!](https://tio.run/##DcznUlpBHIfhW0nvvffee@89McWQXk0bFlEMaBJhRiCJClKcRCSAAvvfozize9g5h7v47Y0Qvr/v097m8XQ0m4bV2mVSWsb7@44ckSmZkVn5R@ZkXpbltJxR3Sqgfqj@2yqqYvWwGlLDKqtGVcEuOlVVVFXF65GnqjZn7rwFCxctXrJ8xaqNm2Zt2bpt@46du3bv2bv/wMFD4JnDR44eO37i1OkzZ8@dv3DRc@nylavXrt@4eevuvfsPHrY9ef7i5Zu37953fPj46fMXPSgrsiBJluSEYZOGlQ2rGFY1jBtGhgnDLMOmnmmmAzqo@3VEx0wxr9M6p0tO2o3oHje6TIfdhJvVcbfolnSmkXCnGj493gg5GYgEKAXuB@@F4OBpWEHwEngF5AN1g36CRkA5WGlQ7TVED6xJiLCTBffZQXsAfMhO2AV7BuQF@Z08@AQoBmrJfyG6IYIQ3@oWRBK8C7wPgmCFwKugzsegAKw@0C/QuByF@AqrDBFxRsE77VYUsqPgw4/s1puqt3wG6nL@gaKgOCgJGoMIQIQgvtenZhvv4KvNq9esXbd@wz7wIGhg6UqZBh8xvtxJ440bb2y@YdNyTPlh9Tab/wE "Jelly โ€šร„รฌ Try It Online")** Or [try to remove any byte](https://tio.run/##DZHnUlpBAEZfJb0X00xM770X03tMMaRX04ZFBAOaRJgRSKLSmUQkgAK7exFndi879/IW374Iuf/Pd358p7fH5eprt0VehUUWdKKju93u7Gpr0ugVCWFo9@87IilSIiOy4o/Ii4KoiFkxJ33SL3/IkdsyIqPNkByXEzIrc7JolqyaLMmapM3wU9lYsHDRkqXLlq9YvaZj85Z5W7dt37Fz1@49e/cdOHjoMGjmyNFjx0@cPH3m7LnzF7ovui5dvnL12vUbN2/dvXf/wcOeJ89fvHzz9t37vg8fP33@osZEVRQFE2UxrcmMJhVNqprUNKGaME24JoYm9WeKKL8KqBEVVlFdKqi0yquylbbDatCOrFIhO25nVcwu2WWVacXtesujplpBKwMeB0uBekGHwCloGkYAtAxaBfOA@cB@giXB8jDSYI3X4IMwZsBDlnOcxwyYo6DjZtwsmnNgbjCvVQCdBouCOea/4D7wAPi3pgGeAB0AHQZnMIKgNbD@x2B@GMNgv8CmRA78K4wKeNjKgfabDhQ0I06gR6azTTUdPwEbsP6BRcBiYAmwSXA/eBD8e7M@X7vHXnWtW79h46bO/aABsNGVa0UaNKk9@VPaHdPu6GJNZsWk9MIY@g8 "Jelly โ€šร„รฌ Try It Online") - this will remove the byte at the nth position and evaluate the result as a niladic link. Some notable byte positions... * removing any of \$217\$ to \$231\$ (`ฦ’ยฐยทโˆยฃโ‰ˆร„ยทฯ€ร…ยทฯ€ร–ยปร˜ยทฯ€รณยทฯ€รดยทฯ€ยฐยทฯ€ยดยทโˆซรกยทโˆซรฃยทโˆซรจโ‰ˆยบ!`) will print `jan ale o, toki` without the final `!` * removing \$1\$ (`โ€šร…รฆ`) will, when run as a full-program, hang waiting for input, and, if an input is given, it will then error comparing an integer to a string (on TIO it will give an EOF error with no pre-prepared input). * removing \$241\$ (`D`) will take about 12 seconds but will print `j` * removing \$256\$ (`ยทยชรฅ`) will print a list of integers, the ordinal values of `jan ale o, toki!`. #### The base program A large portion of the code is: ``` โ€šร„รบbยฌยขยฌยฃยฌโ€ขยฌยถยฌยฉยฌยจยฌร†ยฌยตยฌฮฉยฌรธโˆšรœโˆšรกโˆšรชโˆšรซaโˆšรณโˆšรฒโ‰ˆรญโˆšรปโˆšรผโˆšยถโˆšรŸโˆšโˆžฦ’ยฑยปโˆ‘โˆšยฑโˆšโˆ‘โˆšโˆโ‰ˆรฌnโˆšรฆ"#$&'()*-.078 :;<=>?@ABCEFGHยทโˆโ€ขIJKLMNPQRSTUVWlXYZ[\]^_`cdfghempqruvwxyz{|}~โˆ†รนยฌโˆ‚ยฌโˆžยฌฯ€ยฌโ‰คยฌโ‰ฅโ€šร…ยฅโ€šร…ยตโ€šร…โˆ‚โ€šร…โˆ‘โ€šร…โˆโ€šร…ฯ€โ€šร…โˆซโ€šร…ยชโ€šร…ยบoโˆ†ร…โˆ†รกโˆ†รคโˆ†รซโˆ†รฌโˆ†รฒโ€šยฑร†โˆ†ยงโˆ†ยจโˆ†โ‰คยปยงโ€ฆรฌโˆ†ร โ€ฆรณ,โˆ†รญโ€ฆโ€ โ€ฆยถโˆ†รดโ€ฆยฑโ€ฆโ‰คโˆ†โ€ขย โ€ โ€ฆยบย ร‡โˆ†โ‰ ย รฃยปโ€ขยทโˆซโ€ ยทฯ€ยฃยทโˆร‘ยทโˆรฅยทโˆซโˆยทโˆยงยทยชรคยทโˆโ‰คยทโˆโˆ‚ยทฯ€ร‡ยทฯ€รœยทฯ€รถยทฯ€ยขยทฯ€ยจยทยชยงยทฯ€รฆtยทโˆซร ยทยชยฅยทโˆซรญยปยถยทโˆร‡ฦ’รคฦ’รฑยทโˆรปฦ’โ€ ฦ’โˆžฦ’รธยทฯ€ร„ยทฯ€ร‘ยปร†ยทโˆโ‰ฅยทฯ€รฒยทฯ€โ€ ยทฯ€โ„ขยทโˆซรœยทโˆซรคยทโˆซรฉโ‰ˆยชยทโˆซยฐยทโˆร–ยทโˆรงยทโˆซฯ€ยทยชรฃยทโˆโˆ‘ยทฯ€ร‰kยทฯ€รกยทยชรงยทฯ€รตยทฯ€โ‰ ยฌรŸยทโˆซรขยทยชยตยทโˆซรฌยปรŸยทโˆร‰ฦ’รฃยทโˆรฃฦ’รณยทโˆรผiฦ’ยฐยทโˆยฃโ‰ˆร„ยทฯ€ร…ยทฯ€ร–ยปร˜ยทฯ€รณยทฯ€รดยทฯ€ยฐยทฯ€ยดยทโˆซรกยทโˆซรฃยทโˆซรจโ‰ˆยบ!โ€šร„รน ``` Which is a string with runs of \$15\$ bytes: ``` โ€šร„รบb..a..n.. ..ยทโˆโ€ข..l..e..โˆ†รน..o..,..ยทฯ€ยฃ..t..ยทโˆโ‰ฅ..k..i..!โ€šร„รน ``` Here each of the \$15\$ occurrences of `..` represents \$14\$ filler bytes that are simply placed arbitrarily (it isn't guaranteed that any placement of the remaining \$210\$ bytes would do but most will). Replacing that for brevity with `โ€šร„รบdataโ€šร„รน` the code is: ``` โ€šร…รฆjยฌยฐยฌยชโ€šร„รบdataโ€šร„รนs9123456Dยทโˆรคยทฯ€รฑ+/ยฌยงยทโˆยขโ€šร‡ยจOโ€šร„รดโ€šร„รฒ%โ€šร…ฮฉยฌยดโˆšร‘ยทยชรฅ - Link: no arguments โ€šร…รฆjยฌยฐ - list of characters = "jยฌยฐ" โ€šร„รบdataโ€šร„รน - list of characters = the data described above ยฌยช - maximum (vectorises) -> replaces the first character with 'j' call this newData ยฌยง - nilad followed by link(s) as a nilad: 9123456 - 9,123,456 D - to decimal digits -> [9,1,2,3,4,5,6] ยทโˆรค - dequeue -> [1,2,3,4,5,6] ยทฯ€รฑ - pop -> [1,2,3,4,5] / - reduce with: + - addition -> 1+2+3+4+5=15 s - split (newData) into slices of length (15) ยทโˆยขโ€šร‡ยจ - head of each -> "jan ยทโˆโ€ขleโˆ†รนo,ยทฯ€ยฃtยทโˆโ‰ฅki!" O - ordinals โ€šร„รด - decrement -> ordials - 1 โ€šร„รฒ - increment -> ordinals -> [106,97,110,32,7717,108,101,413,111,44,7779,116,7731,107,105,33] โ€šร…ฮฉยฌยดโˆšร‘ - 127 % - (ordinals) modulo (127) -> [106,97,110,32,97,108,101,32,111,44,32,116,111,107,105,33] ยทยชรฅ - cast to characters -> "jan ale o, toki!" ``` [Answer] # [Julia 1.0](http://julialang.org/), score ~~126~~ 242, (~~269~~ 259 bytes) ``` lowercase("   #\$&'./;<=?%6890+-gh@BCDFGHJKM๏ฃฟรธยชฮฉร’ยฎรนรปรšร โˆ‘ยฅร›รŸยตโˆซโ€กรธรฃยทยฃยงโ€šยขรฅโ€žร˜รดโ€ฐยฐรถร‚โˆ‚ร‰รŠโˆžยบรรฎยจร‹รผยถรˆรงร‡รรฏรกรŽรจโ‰ครโˆรตรŒรœยฉร“ร‘รคร”รชรณโ€™โˆšยฑฦ’รขโ‰ˆยดโˆ†ฯ€ยซโ„ขยปร„โ€ฆโ€ ย รซร€รฉรƒรธร•โ€ขล’รฆล“ร–โ€“รฑโ€”รฌโ€œร…โ€โ‰ โ€˜รบโ€™ร†รทรฒโ—Šโ‰ฅรฟร†ลธรฌโ„รฆโ‚ฌรŸโ€นรปโ€บยฉ๏ฌรช๏ฌ‚ยตPQRSUVWXYZ^_`bdfmquvxyz{}~jAN aLE O, TokI!"[213:4*57])|>print ``` [Try it online!](https://tio.run/##AQ4B8f5qdWxpYTF4//9sb3dlcmNhc2UoIgAKAQIDBAUGBwgJCgsMDg8QERITFBUWFxgZGhscHR4fI1wkJicuLzs8PT8lNjg5MCstZ2hAQkNERkdISktN8L@7vfGonZ7yiLe086e1uuC/i@GjpOKijOOvmeShmuW2g@awvOeUrOifpumNguqVh@uPsuy4m@2Gqe6Eiu@Ql8KSw7HEicWrxrnHqsiAyaDKkcuOzL/Npc6@z4XQltGT0oHTrdSc1a7WmNez2K7Zk9q@26fcnt2p3pDftVBRUlNVVldYWVpeX2BiZGZtcXV2eHl6e31@f2pBTiBhTEUgTywgVG9rSSEiWzIxMzo0KjU3XSl8PnByaW50//8 "Julia 1.0 โ€šร„รฌ Try It Online") (the first 2 characters of the long string are `\r\0`) [Check the score](https://tio.run/##yyrNyUw0rPj/P9G2KDUxRaO4JCUzT5OroCgzryQnTyMnNS@9JEMjuATIT9eITrSO1dTUUVBSSM5ILCpWwlCXCJZMqixJxSJZmpdZWJoKVANWBOFhqFXKzSwuBtoFkbBSUNJRKE4FuiktTcPAysjUVEcBqP///5z88tSi5MTiVA0lBi5GJmYWVjZ2Dk4ubh4@fgFBIWERUTFxCUkpaRlZOXnlGBU1dT19axtbe1UzC0sDbd30DAcnZxc3dw8vb98P@3fv/bhi7rxPHdu3fF6@ddeD/d0PFy95tKjn8fqZTxbOerqt@dmGPc@nrHkxf9nL3qZXU9tf9296s2P227aV71q63k@YfmjS4Y1HOo@uPrbz@KoTDScXnJp4uu/M/rNLz@0733ph2sXJlxovr70y5@q6azOub76x7ubkW/tuL78z7@7KexPubw0IDAoODQuPiIyKi09ISknLLSwtq6isqq6tq89y9FNI9HFV8NdRCMnP9lRUijYyNLYy0TI1j9WssQMHFgA "Julia 1.0 โ€šร„รฌ Try It Online") (+1 because TIO turns `\r` into `\n`) -10 bytes with [Jakque's idea](https://codegolf.stackexchange.com/a/233698/98541) ### hexdump ``` 00000000 6c 6f 77 65 72 63 61 73 65 28 22 0d 00 01 02 03 |lowercase(".....| 00000010 04 05 06 07 08 09 0a 0b 0c 0e 0f 10 11 12 13 14 |................| 00000020 15 16 17 18 19 1a 1b 1c 1d 1e 1f 23 5c 24 26 27 |...........#\$&'| 00000030 2e 2f 3b 3c 3d 3f 25 36 38 39 30 2b 2d 67 68 40 |./;<=?%6890+-gh@| 00000040 42 43 44 46 47 48 4a 4b 4d f0 bf bb bd f1 a8 9d |BCDFGHJKM.......| 00000050 9e f2 88 b7 b4 f3 a7 b5 ba e0 bf 8b e1 a3 a4 e2 |................| 00000060 a2 8c e3 af 99 e4 a1 9a e5 b6 83 e6 b0 bc e7 94 |................| 00000070 ac e8 9f a6 e9 8d 82 ea 95 87 eb 8f b2 ec b8 9b |................| 00000080 ed 86 a9 ee 84 8a ef 90 97 c2 92 c3 b1 c4 89 c5 |................| 00000090 ab c6 b9 c7 aa c8 80 c9 a0 ca 91 cb 8e cc bf cd |................| 000000a0 a5 ce be cf 85 d0 96 d1 93 d2 81 d3 ad d4 9c d5 |................| 000000b0 ae d6 98 d7 b3 d8 ae d9 93 da be db a7 dc 9e dd |................| 000000c0 a9 de 90 df b5 50 51 52 53 55 56 57 58 59 5a 5e |.....PQRSUVWXYZ^| 000000d0 5f 60 62 64 66 6d 71 75 76 78 79 7a 7b 7d 7e 7f |_`bdfmquvxyz{}~.| 000000e0 6a 41 4e 20 61 4c 45 20 4f 2c 20 54 6f 6b 49 21 |jAN aLE O, TokI!| 000000f0 22 5b 32 31 33 3a 34 2a 35 37 5d 29 7c 3e 70 72 |"[213:4*57])|>pr| 00000100 69 6e 74 |int| ``` ### Explanation ``` lowercase("long string...jAN aLE O, TokI!"[213:4*57])|>print ``` * if a byte is missing in the long string, 4\*57 will be greater than the length of the string and will error, alternatively, it will produce an incorrect unicode sequence and error as well * a byte missing in the numbers (213 and 4\*57) will give an other substring or error * a byte missing elsewhere will be a syntax error or an undefined function * `lowercase` allows to mix the case in the Hello world and thus reduce the length of the string * `213:4*57` was found by brute-force I believe this is all I can get with valid UTF-8 sequences this is getting close to optimal, with only 17 repeated bytes [Answer] # [Husk](https://github.com/barbuz/Husk), ~~256~~ 256 bytes *Edit: removed '`\`' character from the filler string, which was otherwise interpreted as an escape signal and not counted towards its length (and so would be deletable).* ``` โ€šรœรฌโ€šร‡ร…-237+6L"ยฌยงยฌฮฉโ€šรœรฏโ€šรœรซโ€šรœรฎโ€šรœรชโ€šรœรญโ€šร รผยฌยฐยฌรธโ€šร„ยบโ€šร„ยถโ€šร„โˆžโ€šร„ยฐโ€šร รถโ€šรขยงโ€šรขโ€ขยฌยฑโ€šร ร‡โ€šร ยดโ€šร รปโ€šรขร โ€šรขโ€ โ€šรขยฐโ€šรฅรชโˆšโˆ‘โˆšรณ #$%&`'()*./014589:;=>?@ABCDEFGHIJKMNOPQRSTUVWXYZ[]^_bcdefghiklmnopqrstuvwxyz{|}~ยฌโˆ‘โ€šร‡ร‡โ€šร‡ร‰โ€šร‡ร‘โ€šร‡ร–โ€šร‡รœโ€šร‡รกโ€šร‡ร โ€šร‡รขโ€šรฅร โ€šรฅรขโ€šรฅรคโ€šรฅรฃล’รฌล’รฎล’รฒล’รตล’รปล’โ€ ล’ยฃล’ยถล’ยฎล’ยฉล’ยฑล’โ‰คล’โ‰ฅล’ยฅล’ยตล’โˆ‚ล’โˆ‘ล’โˆล’ยชล’ยบล’รฆล“ร„ล“ร…ล“ร‡ล“ร‰ล“ร‘ล“รœล“รกล“ร ล“รขโ€šร…โˆžยฌฯ€ยฌโ‰คยฌโ‰ฅโ€šร…ยฅโ€šร…ยตโ€šร…โˆ‚โ€šร…โˆ‘โ€šร…โˆโ€šร…ฯ€ยฌยขยฌยฃโ€šร‡ยจยฌโ€ขโˆ†รญยฌยฅโ€šรฑโ‰คโ€šรฑยบโ€šรฑโˆซโ€šรณร‘ยฌรŸยทโˆร‡ฦ’รคยทโˆรคฦ’รฑฦ’โ€ ยทโˆยขฦ’โˆžฦ’รธยทฯ€ร„ยทฯ€ร‘ยปร†ยทฯ€รฑยทฯ€รฒยทฯ€โ€ ยทฯ€โ„ขยทโˆซรœยทโˆซรคยทโˆซรฉโ‰ˆยชยปรŸยทโˆร‰ฦ’รฃยทโˆรฃฦ’รณยทโˆรผฦ’ยฐยทโˆยฃฦ’ยฑยปโˆ‘โ‰ˆร„ยทฯ€ร…ยทฯ€ร–ยปร˜ยทฯ€รณยทฯ€รดยทฯ€ยฐยทฯ€ยดยทโˆซรกยทโˆซรฃยทโˆซรจโ‰ˆยบโˆšร‘โˆšรฃโˆšรจโˆšรฑโˆšรบโ‰ˆโˆโˆšรฒโˆšยงโˆšยดโˆšร˜โˆšโˆ‚โˆšยบโˆšรธโˆšโˆโ€šรณรคโ€šรฑยฐยฌโˆ‚ยฌยดยฌยช ยฌยฎ\jaยฌยจยปยถยฌยถโ€šร‡ร„,โ€šร„โ€ ยทโˆรป<! ``` [Try it online!](https://tio.run/##Dc5XcxJRHIbxez@Fvffee@@9G7tGY4@x6@weyLILjIlJXLAMgUAwSsYAIbBnQZk5Z3G4OvsZ/u8XQW6eu9/M09nT3dVqwRgE05esXLVu0drDM0VG/IHxGcYnGEMw@mEMwBwWKVGHVoOWhZaHloL5FVYG1qgowGQwczATsExYSVgpRPtlRcamz5o9Z@61efMXLFy6bPmK1WvWb9i4acvWbdt37Ny1e8/effsPHDx05Oix4ydOnjp95uy58xcuXrrScfXGzVu379ztvNf14OGjx0@ePut@3vPi5avXb96@e/9BVMAYWAAsCNYLZoCFwEwwC1ET0XbDiEbUoBpScfVNJVRSpVVWjamfqqCKalKV1JQqq4pyVFXV1F9f83Wf@QE/6Bt@yDd9C3pecFEUk9BL0Kegl6FXoDvQuRgRabBxMfpvQJRgF2HXYLuIBcUPcpgXJifs2V6SnBEv79WJa8SDzd/EbeJx4kniv8g1yA2T@7FRbbZNwIuQE/Fi5Ax7KXLSXqFZabSVTry3OUE8RvwL8RTxHLkhciPk9jVqMigjsk/a8nvDkXGZkTk5IcuyJuvSQSwMOyXKIieq08TY5fvXxXgzK7Jg2mJo7bPE5hmt1n8 "Husk โ€šร„รฌ Try It Online") First attempt using a long compressed string was quickly debunked, so here's one without compression of the filler string... ``` โ€šรœรฌโ€šร‡ร… # drop X characters from the compressed string on next line # which is ยฌยฎ\jaยฌยจยปยถยฌยถโ€šร‡ร„,โ€šร„โ€ ยทโˆรป<!ยฌยฎ encoding "\jan ale o, toki!" # Calculate X as: L" # Length of this non-compressed filler string # (containing all the other Husk codepoints), +6 # plus 5, -237 # minus 257: # X should equal 1 (to remove the leading '`' character; # deletion of any character from the filler string yields X=0, # so the '\' is printed. ``` [Answer] # [Zsh](https://www.zsh.org/), score 256 (269 total bytes) ``` grep -Eax .{240}<<X|cut -f1 jan ale o, toki! "#$%&'()*+/356789:;=>?@ABCDFGHIJKLMNOPQRSTUVWYZ[]^_\`bdhmqsvwyxz~............................................................................................................................................................... ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwfrUioL8ohIFH-d4Rx8fW-elpSVpuha3GHnTi1ILFHRdEysU9KqNTAxqbWwiapJLSxR00wy5shLzFBJzUhXydRRK8rMzFTmVlFVU1dQ1NLW09Y1NzcwtLK2sbe3sHRydnF3c3D08vbx9fP38AwKDgkNCw8Ijo6Jj4-JjEpJSMnILi8vKKyuq6vQGN4CEygIoBaUB) Those `.`s are all unprintables, so here's a hexdump: ``` 00000000: 6772 6570 202d 4561 7820 2e7b 3234 307d grep -Eax .{240} 00000010: 3c3c 587c 6375 7420 2d66 310a 6a61 6e20 <<X|cut -f1.jan 00000020: 616c 6520 6f2c 2074 6f6b 6921 0922 2324 ale o, toki!."#$ 00000030: 2526 2728 292a 2b2f 3335 3637 3839 3a3b %&'()*+/356789:; 00000040: 3d3e 3f40 4142 4344 4647 4849 4a4b 4c4d =>?@ABCDFGHIJKLM 00000050: 4e4f 5051 5253 5455 5657 595a 5b5d 5e5f NOPQRSTUVWYZ[]^_ 00000060: 5c60 6264 686d 7173 7677 7978 7a7e 0001 \`bdhmqsvwyxz~.. 00000070: 0203 0405 0607 080b 0c0d 0e0f 1011 1213 ................ 00000080: 1415 1617 1819 1a1b 1c1d 1e1f 7f80 8182 ................ 00000090: 8384 8586 8788 898a 8b8c 8d8e 8f90 9192 ................ 000000a0: 9394 9596 9798 999a 9b9c 9d9e 9fa0 a1a2 ................ 000000b0: a3a4 a5a6 a7a8 a9aa abac adae afb0 b1b2 ................ 000000c0: b3b4 b5b6 b7b8 b9ba bbbc bdbe bfc0 c1c2 ................ 000000d0: c3c4 c5c6 c7c8 c9ca cbcc cdce cfd0 d1d2 ................ 000000e0: d3d4 d5d6 d7d8 d9da dbdc ddde dfe0 e1e2 ................ 000000f0: e3e4 e5e6 e7e8 e9ea ebec edee eff0 f1f2 ................ 00000100: f3f4 f5f6 f7f8 f9fa fbfc fdfe ff ............. ``` Needs to be run with `LC_ALL=C`, because otherwise `grep`/`cut`/`Zsh` get confused by broken Unicode. ## Explanation `<<X` takes the rest of the file and passes it to `grep`, which searches for a line containing 241 characters. `-E` is necessary to activate the `{}` quantifier, `-a` forces processing of the input even though it is "binary" not "text", and `-x` ensures the whole line has to match, not just a substring. If it matches (i.e. no characters on the second line have been removed), this is passed to `cut`, which outputs only the `1`st `f`ield (tab-separated). If any character on the first line (including the newline) is removed, the search command will break or the pattern won't be matched. `\` escapes the ```, because even in a heredoc (`<<X`), some expansions (importantly ````) are still processed, and otherwise it would be unmatched. `x` is duplicated in the second line even though it's already used in the first line, because if it's removed from the `grep` command then the pattern still matches, but we need it to disallow any of the digits `240` from being removed (otherwise there is always a 20-character substring of that line, or whatever) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 141 bytes, score 97 ``` โ€šรงรฒโ€šรงรฒ!ltoojjjtnn!!iiea,teoikneleaa ยฌยถ !,aeijklnotยฌยถ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R7wwgUswpyc/PysoqyctTVMzMTE3UKUnNz8zOS81JTUxUOLRMQVEnMTUzKzsnL78ExFNSVlFVU9fQ1NLW0dXTNzA0MjYxNTO3sLSytrG1s3dwdHJ2cXVz9/D08vbx9fMPCAwKDgkNC4@IjIqOiY2LT0hMSk5JTUvPAJmYm5dfUFhUXFJaVl5RWVVdU1v3/z8A "Charcoal โ€šร„รฌ Try It Online") Explanation: The string `!ltoojjjtnn!!iiea,teoikneleaa` is interpreted in the custom base `!,aeijklnot` and then converted to the custom base of printable ASCII. Removing any of the characters in the custom base will obviously prevent them from being output, but also removing any of the other printable ASCII will scramble the result, while removing the either of the two non-ASCII characters will break the Charcoal program as a whole. [Answer] # [><>](https://esolangs.org/wiki/Fish), 297 bytes, score 256 ``` '!ikot ,o ela naj'!;v "#$%&()*+-./01234567o; 89:<=>?@ABCDEFGHIJKL ; MNOPQRSTUVWXYZ[\]^_` ; bcdfghmpqrsuwxyz{|}~ ; .................... ; .................... ; .................... ; .................... ; .................... ; .................... ; .................... ; .................... ; ``` [Try it online!](https://tio.run/##S8sszvj/X10xMzu/REEnXyE1J1EhLzFLXdG6jEtJWUVVTUNTS1tXT9/A0MjYxNTMPN@ay8LSysbWzt7B0cnZxdXN3cPTy9tHwZrL188/IDAoOCQ0LDwiMio6JjYuPgEonJSckpaekVtQWFRcWl5RWVVdU1sHFNbDAoaA8P//AA "><> โ€šร„รฌ Try It Online") (replace the dots with all the unprintable ascii) The main idea is fairly simple, removing any byte will block the "print corridor" with the termination character `;` Some notable exceptions: * Removing the letters in the original phrase will crash the instruction pointer into `J`, `K` or `L` * Removing a single quote will crash the instruction pointer at `k` * Removing `;` will crash the instruction pointer at `L` * Removing newlines or `v` will cause no output to be written. [Answer] # [Python 3](https://docs.python.org/3/), 243 unique bytes, ~~265~~ 261 bytes ``` B=0 input("   #$%&'*+-/25789;<>?@CDFGHMPQRSUVWXYZ^_`bcdghjkmqsvyz{|}~ลธโˆšรบฦ’รบโ‰ˆรบโˆ†รบยซรบยปรบโ€ฆรบย รบร€รบรƒรบร•รบล’รบล“รบโ€“โ€ โ€”ยฐโ€œยขโ€ยฃโ€˜ยงโ€™โ€ขรทยถโ—ŠรŸรฟยฎลธยฉโ„โ„ขโ‚ฌยดโ€นยจโ€บโ‰ ๏ฌร†๏ฌ‚ร˜โ€กโˆžร„ยทยฑร…โ€šโ‰คร‡โ€žโ‰ฅร‰โ€ฐยฅร‘ร‚ยตร–รŠโˆ‚รœรโˆ‘รกร‹โˆร รˆฯ€รขรโˆซรครŽยชรฃรยบรฅรŒรงฮฉร“รฆรฉร”รธรจ๏ฃฟรชรซรญร’รฌรฎรฏรšรฑรณรฒร›รดรถรต_JaN ALE \x4f, TOKI!".lower()[136:]) ``` [Try it online!](https://tio.run/##AUsBtP5weXRob24z/yMgdG8gaGF2ZSB0aGUgcmlnaHQgY29kZSwgcmVwbGFjZSB0aGUgbGFzdCAiXyIgYnkgY2hyKDEwNTA0NjIp/0I9MAppbnB1dCgiAAoBAgMEBQYHCAkLDA4PEBESExQVFhcYGRobHB0eHyMkJSYnKistLzI1Nzg5Ozw@P0BDREZHSE1QUVJTVVZXWFlaXl9gYmNkZ2hqa21xc3Z5ent8fX5/wp/DnMScxZzGnMecyJzJnMqcy5zMnM2czpzPnNCg0aHSotOj1KTVpdam16fYqNmp2qrbq9ys3a3ert@v4LCA4bGB4rKC47OD5LSE5bWF5raG57eH6LiI6bmJ6rqK67uL7LyM7Y297r6O77@P8JCRkvGTlJXylpeY85mam19KYU4gQUxFIFx4NGYsIFRPS0khIi5sb3dlcigpWzEzNjpdKf// "Python 3 โ€šร„รฌ Try It Online") [Score !](https://tio.run/##yyrNyUw0rPj/P9G2KDUxRaO4JCUzT5OroCgzryQnTyMnNS@9JEMjuATIT9eITrSO1dTUUVBSSM5ILCpWwlCXCJZMqixJxSJZmpdZWJoKVANWBOFhqFXKzSwuBtoFkbBSUNJRKE4FuiktTcPAysjUVEcBqP@/skJJvkJGYlmqQklGqkJRZnpGiUJyfkqqjkJRakFOYjJEPCexuERBKR7kIKCDizQMDUwNTMyMNP872RpwZeYVlJZoKDFwMTIxs7CysXNwcvPw8QsICgmLiIqJS0hKScvIyskrq6iqqWtp6@obmZpbWFrb2Nk7OLu4uXv4BgQGBYeGhUdERsXFJyQlp6RnZGXnFhaXVVZV19TW1R@af3jOkTlH5xybc3zOiTkn55yac3rOmTln55ybc37OhQUXF15adHnxlSVXl15bdn35jRU3V95adXv1nTV3195bd3/9gw0NDzc2PtrU9Hhz85MtLU@3tj7b1vZ8e/uLHR0vd3a@2tX1enf3mz09b3v3vtvX935//4cJEyd9nDxl6qdp02d8njlr9peGufO8Ev0UHH1cFWIqTNJ0FEL8vT0VlfRy8stTizQ0ow2NzaxiNQE "Julia 1.0 โ€šร„รฌ Try It Online") (the score shows 242 because tio interprets `\n` and `\r` the same way) ## Note : as MarcMush pointed, TIO link doesn't like unicodes `\U10xxxx`. To make my link works, I changed `ร›รดรถรต` by `_` in the code. ## Explanation: the code is equivalent to : ``` B=0 input("""<bunch of useless stuff>JaN ALE \x4f, TOKI!""".lower()[<index>:]) ``` * store the wanted string upper case and lower it allows to reduce the number of bytes as they would have been stored in the code anyways. I also used `\x4f` instead of `O` to save 1 byte * if ant byte is removed from the first line, the program will crash due to a syntax error or a Name error. * if any byte is removed from the string, or the slice, the portion written would not be the correct one. * if any other byte is removed, the code will crash [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 256 ``` โ€šร„รบยฌยฐยฌยขยฌยฃยฌยงยฌโ€ขยฌยถยฌยฉยฌยจยฌร†ยฌยตยฌฮฉยฌรธโ€šร‡ยจโˆšรœโˆšรกโˆšรชโˆšรซโˆšรณโˆšรฒโ‰ˆรญโˆšรปโˆšรผโˆšยถโˆšรŸโˆšโˆžฦ’ยฑยปโˆ‘โˆšยฑโˆšโˆ‘โˆšโˆโ‰ˆรฌโˆšรฆ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghiโ€šร„รบjklmnopqrstuvwxyz{|}~ยฌโˆ‚ยฌโˆžยฌฯ€ยฌโ‰คยฌโ‰ฅโ€šร…ยฅโ€šร…ยตโ€šร…โˆ‚โ€šร…โˆ‘โ€šร…โˆโ€šร…ฯ€โ€šร…โˆซโ€šร…ยชโ€šร…ยบโ€šร…ฮฉโ€šร…รฆโˆ†ร…โˆ†รกโˆ†รคโˆ†รซโˆ†รฌโˆ†รฒโ€šยฑร†โˆ†รนโˆ†ยงโˆ†ยจโˆ†โ‰คยปยงโ€ฆรฌโˆ†ร โ€ฆรณโˆ†รญโ€ฆโ€ โ€ฆยถโˆ†รดโ€ฆยฑโ€ฆโ‰คโˆ†โ€ขย โ€ โ€ฆยบย ร‡โˆ†โ‰ ย รฃยปโ€ขยทโˆซโ€ ยทโˆร‘ยทโˆรฅยทโˆซโˆยทโˆยงยทยชรคยทโˆโ‰คยทโˆโˆ‚ยทฯ€ร‡ยทฯ€รœยทยชรฅยทฯ€รถยทฯ€ยขยทฯ€ยจยทยชยงยทฯ€รฆยทโˆซร ยทยชยฅยทโˆซรญยปยถยทโˆร‡ฦ’รคยทโˆรคฦ’รฑยทโˆรปฦ’โ€ ยทโˆยขฦ’โˆžฦ’รธยทฯ€ร„ยทฯ€ร‘ยปร†โ€šร„รบยทฯ€รฑยทฯ€รฒยทฯ€โ€ ยทฯ€โ„ขยทโˆซรœยทโˆซรคยทโˆซรฉโ‰ˆยชยทโˆซยฐยทโˆร–ยทโˆรงยทโˆซฯ€ยทโˆโ€ขยทยชรฃยทโˆโ‰ฅยทโˆโˆ‘ยทฯ€ร‰ยทฯ€รกยทยชรงยทฯ€รตยทฯ€ยฃยทฯ€โ‰ ยฌรŸโˆšร‘ยทโˆซรขยทยชยตยทโˆซรฌยปรŸยทโˆร‰ฦ’รฃยทโˆรฃฦ’รณยทโˆรผฦ’ยฐยทโˆยฃโ‰ˆร„ยทฯ€ร…ยทฯ€ร–ยปร˜ยทฯ€รณยทฯ€รดยทฯ€ยฐยทฯ€ยดยทโˆซรกยทโˆซรฃยทโˆซรจโ‰ˆยบยฌยฐยฌยขยฌยฃยฌยงยฌโ€ขยฌยถยฌยฉยฌยจยฌร†ยฌยตยฌฮฉยฌรธโ€šร‡ยจโˆšรœโˆšรกโˆšรชโˆšรซโˆšรณโˆšรฒโ‰ˆรญโˆšรปโˆšรผโˆšยถโˆšรŸโˆšโˆžฦ’ยฑยปโˆ‘โˆšยฑโˆšโˆ‘โˆšโˆโ‰ˆรฌโˆšรฆ !"#$%&'()*+,-./0123456789:;<=>โ€šร„รบ?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^โ€šร„รบ_`abcdefghijklmnopqrstuvwxyz{|}~ยฌโˆ‚ยฌโˆžยฌฯ€ยฌโ‰คยฌโ‰ฅโ€šร…ยฅโ€šร…ยตโ€šร…โˆ‚โ€šร…โˆ‘โ€šร…โˆโ€šร…ฯ€โ€šร…โˆซโ€šร…ยชโ€šร…ยบโ€šร…ฮฉโ€šร…รฆโˆ†ร…โˆ†รกโˆ†รคโˆ†รซโˆ†รฌโˆ†รฒโ€šยฑร†โˆ†รนโˆ†ยงโˆ†ยจโˆ†โ‰คยปยงโ€ฆรฌโˆ†ร โ€ฆรณโˆ†รญโ€ฆโ€ โ€ฆยถโˆ†รดโ€ฆยฑโ€ฆโ‰คโˆ†โ€ขย โ€ โ€ฆยบย ร‡โˆ†โ‰ ย รฃยปโ€ขยทโˆซโ€ ยทโˆร‘ยทโˆรฅยทโˆซโˆยทโˆยงยทยชรคยทโˆโ‰คยทโˆโˆ‚ยทฯ€ร‡ยทฯ€รœยทยชรฅยทฯ€รถยทฯ€ยขยทฯ€ยจยทยชยงยทฯ€รฆยทโˆซร ยทยชยฅยทโˆซรญยปยถยทโˆร‡โ€šร„รบฦ’รคยทโˆรคฦ’รฑยทโˆรปฦ’โ€ ยทโˆยขฦ’โˆžฦ’รธยทฯ€ร„ยทฯ€ร‘ยปร†ยทฯ€รฑยทฯ€รฒยทฯ€โ€ ยทฯ€โ„ขยทโˆซรœยทโˆซรคยทโˆซรฉโ‰ˆยชยทโˆซยฐยทโˆร–ยทโˆรงยทโˆซฯ€ยทโˆโ€ขยทยชรฃยทโˆโ‰ฅยทโˆโˆ‘ยทฯ€ร‰ยทฯ€รกยทยชรงยทฯ€รตยทฯ€ยฃยทฯ€โ‰ ยฌรŸโˆšร‘ยทโˆซรขยทยชยตยทโˆซรฌยปรŸยทโˆร‰ฦ’รฃยทโˆรฃฦ’รณยทโˆรผฦ’ยฐยทโˆยฃโ‰ˆร„ยทฯ€ร…ยทฯ€ร–ยปร˜ยทฯ€รณยทฯ€รดยทฯ€ยฐยทฯ€ยดยทโˆซรกยทโˆซรฃยทโˆซรจโ‰ˆยบยฌยฐยฌยขยฌยฃยฌยงยฌโ€ขยฌยถยฌยฉยฌยจยฌร†ยฌยตยฌฮฉยฌรธโ€šร‡ยจโˆšรœโˆšรกโˆšรชโˆšรซโˆšรณโˆšรฒโ‰ˆรญโˆšรปโˆšรผโˆšยถโˆšรŸโˆšโˆžฦ’ยฑยปโˆ‘โˆšยฑโˆšโˆ‘โˆšโˆโ‰ˆรฌโˆšรฆ !"#$%&'()*+,-./01โ€šร„รบ23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ยฌโˆ‚ยฌโˆžยฌฯ€ยฌโ‰คยฌโ‰ฅโ€šร…ยฅโ€šร…ยตโ€šร…โˆ‚โ€šร…โˆ‘โ€šร…โˆโ€šร…ฯ€โ€šร…โˆซโ€šร…ยชโ€šร…ยบโ€šร…ฮฉโ€šร…รฆโˆ†ร…โˆ†รกโˆ†รคโˆ†รซโˆ†รฌโˆ†รฒโ€šยฑร†โˆ†รนโ€šร„รบโˆ†ยงโˆ†ยจโˆ†โ‰คยปยงโ€ฆรฌโˆ†ร โ€ฆรณโˆ†รญโ€ฆโ€ โ€ฆยถโˆ†รดโ€ฆยฑโ€ฆโ‰คโˆ†โ€ขย โ€ โ€ฆยบย ร‡โˆ†โ‰ ย รฃยปโ€ขยทโˆซโ€ ยทโˆร‘ยทโˆรฅยทโˆซโˆยทโˆยงยทยชรคยทโˆโ‰คยทโˆโˆ‚ยทฯ€ร‡ยทฯ€รœยทยชรฅยทฯ€รถโ€šร„รบยทฯ€ยขยทฯ€ยจยทยชยงยทฯ€รฆยทโˆซร ยทยชยฅยทโˆซรญยปยถยทโˆร‡ฦ’รคยทโˆรคฦ’รฑยทโˆรปฦ’โ€ ยทโˆยขฦ’โˆžฦ’รธยทฯ€ร„ยทฯ€ร‘ยปร†ยทฯ€รฑยทฯ€รฒยทฯ€โ€ ยทฯ€โ„ขยทโˆซรœยทโˆซรคยทโˆซรฉโ‰ˆยชยทโˆซยฐยทโˆร–ยทโˆรงยทโˆซฯ€ยทโˆโ€ขยทยชรฃยทโˆโ‰ฅยทโˆโˆ‘ยทฯ€ร‰ยทฯ€รกยทยชรงยทฯ€รตยทฯ€ยฃยทฯ€โ‰ ยฌรŸโˆšร‘ยทโˆซรขยทยชยตยทโˆซรฌยปรŸยทโˆร‰ฦ’รฃยทโˆรฃฦ’รณยทโˆรผฦ’ยฐยทโˆยฃโ‰ˆร„ยทฯ€ร…ยทฯ€ร–ยปร˜ยทฯ€รณยทฯ€รดยทฯ€ยฐยทฯ€ยดยทโˆซรกยทโˆซรฃยทโˆซรจโ‰ˆยบยฌยฐยฌยขยฌยฃยฌยงยฌโ€ขยฌยถยฌยฉยฌยจยฌร†ยฌยตยฌฮฉยฌรธโ€šร‡ยจโˆšรœโˆšรกโˆšรชโˆšรซโˆšรณโˆšรฒโ‰ˆรญโˆšรปโˆšรผโˆšยถโˆšรŸโˆšโˆžฦ’ยฑยปโˆ‘โˆšยฑโˆšโˆ‘โˆšโˆโ‰ˆรฌโˆšรฆ !"#$%&'()*+โ€šร„รบ,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWโ€šร„รบXYZ[\]^_`abcdefghijklmnopqrstuvwโ€šร„รบxyz{|}~ยฌโˆ‚ยฌโˆžยฌฯ€ยฌโ‰คยฌโ‰ฅโ€šร…ยฅโ€šร…ยตโ€šร…โˆ‚โ€šร…โˆ‘โ€šร…โˆโ€šร…ฯ€โ€šร…โˆซโ€šร…ยชโ€šร…ยบโ€šร…ฮฉโ€šร…รฆโˆ†ร…โˆ†รกโˆ†รคโˆ†รซโˆ†รฌโˆ†รฒโ€šยฑร†โˆ†รนโˆ†ยงโˆ†ยจโˆ†โ‰คยปยงโ€ฆรฌโˆ†ร โ€ฆรณโˆ†รญโ€ฆโ€ โ€ฆยถโˆ†รดโ€ฆยฑโ€ฆโ‰คโˆ†โ€ขย โ€ โ€ฆยบย ร‡โˆ†โ‰ ย รฃยปโ€ขยทโˆซโ€ ยทโˆร‘ยทโˆรฅยทโˆซโˆยทโˆยงยทยชรคยทโˆโ‰คยทโˆโˆ‚ยทฯ€ร‡ยทฯ€รœยทยชรฅยทฯ€รถยทฯ€ยขยทฯ€ยจยทยชยงยทฯ€รฆยทโˆซร ยทยชยฅยทโˆซรญยปยถยทโˆร‡ฦ’รคยทโˆรคฦ’รฑยทโˆรปฦ’โ€ ยทโˆยขฦ’โˆžฦ’รธยทฯ€ร„ยทฯ€ร‘ยปร†ยทฯ€รฑยทฯ€รฒยทฯ€โ€ ยทฯ€โ„ขยทโˆซรœยทโˆซรคยทโˆซรฉโ‰ˆยชยทโˆซยฐยทโˆร–ยทโˆรงยทโˆซฯ€ยทโˆโ€ขยทยชรฃยทโˆโ‰ฅยทโˆโˆ‘ยทฯ€ร‰ยทฯ€รกยทยชรงยทฯ€รตยทฯ€ยฃยทฯ€โ‰ ยฌรŸโˆšร‘ยทโˆซรขยทยชยตยทโˆซรฌยปรŸยทโˆร‰ฦ’รฃยทโˆรฃฦ’รณยทโˆรผโ€šร„รบฦ’ยฐยทโˆยฃโ‰ˆร„ยทฯ€ร…ยทฯ€ร–ยปร˜ยทฯ€รณยทฯ€รดยทฯ€ยฐยทฯ€ยดยทโˆซรกยทโˆซรฃยทโˆซรจโ‰ˆยบยฌยฐยฌยขยฌยฃยฌยงยฌโ€ขยฌยถยฌยฉยฌยจยฌร†ยฌยตยฌฮฉยฌรธโ€šร‡ยจโˆšรœโˆšรกโˆšรชโˆšรซโˆšรณโˆšรฒโ‰ˆรญโˆšรปโˆšรผโˆšยถโˆšรŸโˆšโˆžฦ’ยฑยปโˆ‘โˆšยฑโˆšโˆ‘โˆšโˆโ‰ˆรฌโˆšรฆ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`โ€šร„รบabcdefghijklmnopqrstuvwxyz{|}~ยฌโˆ‚ยฌโˆžยฌฯ€ยฌโ‰คยฌโ‰ฅโ€šร…ยฅโ€šร…ยตโ€šร…โˆ‚โ€šร…โˆ‘โ€šร…โˆโ€šร…ฯ€โ€šร…โˆซโ€šร…ยชโ€šร…ยบโ€šร…ฮฉโ€šร…รฆโˆ†ร…โˆ†รกโˆ†รคโˆ†รซโˆ†รฌโˆ†รฒโ€šยฑร†โˆ†รนโˆ†ยงโˆ†ยจโˆ†โ‰คยปยงโ€ฆรฌโˆ†ร โ€ฆรณโˆ†รญโ€ฆโ€ โ€ฆยถโˆ†รดโ€ฆยฑโ€ฆโ‰คโˆ†โ€ขย โ€ โ€ฆยบย ร‡โˆ†โ‰ ย รฃยปโ€ขยทโˆซโ€ ยทโˆร‘ยทโˆรฅยทโˆซโˆยทโˆยงยทยชรคยทโˆโ‰คยทโˆโˆ‚ยทฯ€ร‡ยทฯ€รœยทยชรฅยทฯ€รถยทฯ€ยขยทฯ€ยจยทยชยงยทฯ€รฆยทโˆซร ยทยชยฅยทโˆซรญยปยถยทโˆร‡ฦ’รคยทโˆรคฦ’รฑยทโˆรปฦ’โ€ ยทโˆยขฦ’โˆžฦ’รธยทฯ€ร„ยทฯ€ร‘ยปร†ยทฯ€รฑโ€šร„รบยทฯ€รฒยทฯ€โ€ ยทฯ€โ„ขยทโˆซรœยทโˆซรคยทโˆซรฉโ‰ˆยชยทโˆซยฐยทโˆร–ยทโˆรงยทโˆซฯ€ยทโˆโ€ขยทยชรฃยทโˆโ‰ฅยทโˆโˆ‘ยทฯ€ร‰ยทฯ€รกยทยชรงยทฯ€รตยทฯ€ยฃยทฯ€โ‰ ยฌรŸโˆšร‘ยทโˆซรขยทยชยตยทโˆซรฌยปรŸยทโˆร‰ฦ’รฃยทโˆรฃฦ’รณยทโˆรผฦ’ยฐยทโˆยฃโ‰ˆร„ยทฯ€ร…ยทฯ€ร–ยปร˜ยทฯ€รณยทฯ€รดยทฯ€ยฐยทฯ€ยดยทโˆซรกยทโˆซรฃยทโˆซรจโ‰ˆยบยฌยฐยฌยขยฌยฃยฌยงยฌโ€ขยฌยถยฌยฉยฌยจยฌร†ยฌยตยฌฮฉยฌรธโ€šร‡ยจโˆšรœโˆšรกโˆšรชโˆšรซโˆšรณโˆšรฒโ‰ˆรญโˆšรปโˆšรผโˆšยถโˆšรŸโˆšโˆžฦ’ยฑยปโˆ‘โˆšยฑโˆšโˆ‘โˆšโˆโ‰ˆรฌโˆšรฆ !"#$%&'()*+,-./0123456789:โ€šร„รบ;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[โ€šร„รนยทโˆซร โ€šร„รฒโ€šร„รดยทยชรฅยฌยดโ€šร„รบโ‰ˆร„Wยฌยช ``` A full program using all 256 bytes in Jelly's [code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page). I am very confident that **this can be beaten** since it is a naive attempt using a run-length encoding of the ordinals, which stands at 1368 bytes! For 251 of the bytes the program will run successfully as a monadic Link - see them all [here](https://tio.run/##3ZZXU1NBFMff@RT22HvHgl3BXkAsWLEg9optckMJJqJCZkhQgRCSMEpAEiDZ3RtgZvfenXv5Fme/SDzgi@MDGRmYIXm4O/twdu@e/2/Pf09VZXV1TSajtFHQPwJrLMSZcn5XzvZC/HhvgQgUA@nkoQIcVbyfh0qVK2ami3ioBCflmUzG4XDgCt7FQ7ybh3mER/kPHuP9fJiP8DEMEg3CLb6IZuEXAbNFdIhOERU9YsCIWykRFylBTJ8YnTd/wcJFi5c4li5bvmLlqtVr1q5bv2Hjps1btm7bXrhj567dRXv27tt/4OChw0eKS44eO37i5KnTZ86eKy07X37h4qXLFVeuXrt@42blrdt37uJpqu5V33/w8NHjJ0@fPX/x8lXN6zdv373nST7AKU/wQaUNKW1YaUmlpZRGlEaVxpSmKy2ttBGUQGrSLT2yWfpkALOW7TIsYzJhhW2fbLT9ssUO2lHZZsfthIyMB@30uEv2jXutCLAgkDogqCUBEgbdAyQBJAnUBbRhQmP6FWgIaAz0MNBRlBz0IWAtVhSIy8Boj9EKpMPAbULGgDEG1Am0zurHpIC2Ag0ADQL9CawBmAfYJ1MH1gWkHkgTMAokAroXyCCQFNBaoG7Qm4B@A9oNtI/3iDpgH0AfBuazeoDUGhjrNfzI1sBNuk38lwa03voF1A@0DWgX0F5gbmBeYJ/N9GxTxiyzgcaQv1jnKGhMYgrW@Qkac55uRc84ZTzLTIKeLM5pFHW@gUYd/se6MTwbawzJB/eeVdATZjIn3Dt7ReNRc926p6Y86QT5@0ZjellBY9@IiilnQDnbUEzei4tMZxnXsVHMzKE2ca7ev38uX848JPof5L8B "Jelly โ€šร„รฌ Try It Online"). For the other five see these full programs: [removing `ยทยชรฅ` fails](https://tio.run/##3ZVnT1sxGIX/Svfee@@9N92bDkr3pEtxGKFJaQuRSGgLBDJQS6BJgMT2ZUj2jXUv/@L4j6Qun/qJqAikwvdj@z3vo3NcVlpeXlEoaM930SbaRVTERFwkxA@RFN2iTwyIIe1Nyhrpk19kvQzJcL5BtshWmZAdMmWnnZxMy5yk@aAcnDZ9xsxZs@fMnTd/wcJFi5csXbZ8xcpVq9esXbd@w8ZNm7ds3bZ9x85du/fs3bf/wMFDh48cPXb8xMlTp8@UnD13/sLFS5evXL12/cbN0lu379w105TdK7//4OGjx0@ePnv@4uWritdv3r57L7IiJZjIiB5NejXp0ySrSU4TqgnThGtiadKvyYAmg4oon/KrehVUYZ3uVs0qppIq48TcoKp1Q6rBjbgJ1eSm3YyKD0fc/mGv6hoOOHHwCGgV6EdwChqD5QfNgGbBvGA1YF/B2sGSsGJgg@C1sHrBG5wEqNc2Ur/dCNpimzva7ZQ9BOYBq3K6jSOwRrAwWATsJ3gNuB/8U94CbwOtBq0DZ6BxWAHQHtAcWCWYD1Yd2DewKFiX6JBV4B9g9YEHnQ7QSttoA3YItNU2l0Tz5i0CVu38AguBNYG1gXWC@8AD4J/z/RON2LgsRtlI/gI9GSkbB6OAnpqUjeexZnncEZtZxo3ySCzHEOepRtns4V8a28iLgTaSSV/aE0r5T438F6VdPMtm1End2KMjHumAqfsvG3tFKWtPs9mY9oS1p0l0mhN5T4mwCoXf "Jelly โ€šร„รฌ Try It Online"), [removing `ยทโˆซร ` fails](https://tio.run/##3ZVnT1sxGIX/Svfee@@9N9100UHpnnQpDiNtAm0hEgkdELJQS6AkQGL7MiT7xrqXf3H8R1KXT/1ERAVS4fux/Z730TkuL6uoqCwUtOebaBNRERNxkRBJ8UOkRJfoEwNiSHtTslb65GfZIEMynG@ULbJVJmW77LbTTk6mZU7SfFAOTps@Y@as2XPmzpu/YOGixUuWLlu@YuWq1WvWrlu/YeOmzVu2btu@Y@eu3Xv27tt/4OChw0eOHjt@4uSp02dKzp47f@HipculV65eu36j7Oat23fMNOV3K@7df/Dw0eMnT589f/Gy8tXrN2/fiazoFkxkRI8mvZr0aZLVJKcJ1YRpwjWxNOnXZECTQUWUT/lVgwqqsE53qe8qrlIq48TdoHrvhlSjG3GTqtlNuxmVGI64/cNe1TkccBLgEdBq0DpwChqH5QfNgGbBvGC1sOrAvoBFwVKw4mCDsHrBG50kqNc2Ur/dBNpimzuidrc9BOYBq3a6jCOwJrAwWATsJ3gtuB/8Y94CbwOtAa0HZ6AJWAHQHtAcWBWYD1Y92FewGFinaJfV4B9g9YEHnXbQKttoA3YItNU2l8Ty5i0CVuP8AguBNYO1gXWA@8AD4J/y/RON2LgsRtlI/gI9GSkbB6OAnpqUjed/zfK4IzazjCflkWSONc5TjbJZwlga28iLgTaSSV/aE0r5T438F6VdPMtm1End2KMjHimAqfsvG3tFKWuPadWw9jSbNYoOcyLvKRFWofAb "Jelly โ€šร„รฌ Try It Online"), [removing `โ€šร„รบ` fails](https://tio.run/##7dH3UlpBGAXwV0nvvffeezfdNFOM6dW0YVHBgCZRZgSSUUEBJxGNYGG/vagzu5ede3mLsy9C7nvk/n/mnJnza2xoamqu1WRaDshBmZFZmZO/ZV6Oykk5LWdNMK9CKqx@qC4VV4lKt@pT/SqnhtSYXXBKqqBKildiambO3HnzFyxctHjJ0mXLV6xctXrN2nXrN2zctHnL1m3bd@zctXvP3n37Dxw8dPjI0WPHT5w8dfrM2XPnL1y8VHf5ytVr12/crL91@87dew33Hzx81Pi46cnTZ89fvHz1@s3bd@@bP3z89PmLnJJjkmRRjhs2YdikYVOGlQzjhpFhwjDLsLJh04bNaKbDOqK7dEwnTGFU9@qMzuuik3Fjut2N62435eZ00i24RZ2tptxyNahHqlEnC5ECbwXvgODgGVgR8CL4FCgICsHqAP0EDYDysDKgGYh2WBMQ3U4OPGh76YjdA95nezUD9pg9CwqAWp1RUA8oAUqB/kCEICIQ3yoWRBq8DbwTgsCzsKLg4@AlUAsoDKsT9As0CBqRQ6oV4iusSYiYMwTeYnvZqB0H77e9ksGKN8RAbc5fUByUBKVBwxBhiCjE90rZ9/V9fV/f1/f1fX3f/8zXBHq9r0wgYQJJ70Y5XAnUSatW@wc "Jelly โ€šร„รฌ Try It Online"), [removing `โ€šร„รน` fails](https://tio.run/##3ZVnT1sxGIX/Svfee@@9N92bDkr3pEtxCIQm0BYikdABAZKglkBJGLF9A0j2jXUv/@L4j6Qun/qJqAikku/H9nveR@e4rLS8vCKf155volW0iXYRE3GRED9EUnSLfjEohrU3KaulX36W9TIsI7kG2SxbZEJ2yB475WRkSmYkzYXk0LTpM2bOmj1n7rz5CxYuWrxk6bLlK1auWr1m7br1GzZu2rxl67btO3bu2r1n7779Bw4eOnzk6LHjJ06eOn2m5Oy58xcuXrp85eq16zdult66feeumabsXvn9Bw8fPX7y9NnzFy9fVbx@8/bdezEgegQTadGrSZ8m/ZoMaJLRhGrCNOGaWJpkNRnUZEgR5VcBVa9CKqJT3eq7iqmkSjsxN6Rq3LBqcKNuQjW5KTet4iNRNzviVV0jQScOHgX1gdaCU9AYrABoGnQAzAtWDasW7AtYG1gSVgxsCLwGVh94g5MA9dpGHbAbQZttc02b3WMPg3nAfE63MQXWCBYBi4L9BK8GD4B/zFngraBVoHXgDDQOKwjaC5oBqwTzw6oD@wrWDtYlOqQP/AOsfvCQ0wFaaRtt0A6DttjmkvaceYuAVTm/wMJgTWCtYJ3gfvAg@KdcdrIpG5eFQBvJX6ynKGhjYgzWxQnaeB5voiecspllIkGPhnMcoS420GYP/1LdRl6ItZEUQ3tPKug/ZfJftHfhRJtRp3p1j015tAmK94829gqCNuvSnoj2NJlNik5zIucpEVY@/xs "Jelly โ€šร„รฌ Try It Online"), and [removing `ยฌยด` produces text, but must be run as a full-program](https://tio.run/##3ZVnT1sxGIX/Svfee@@9N92bDkr3pEtxGKEJtIVIJLQFAiRBbQMlgSS2L0Oyb6x7@RfHfyR1@dRPREUglXw/tt/zPjrHZaXl5RX5vPZ8E@2iQ3SKqIiJuPguEqJHpMWgGNbehKyRPvlZNsiQDOcaZatsk3HZJXvtpJOVSZmVNBeUQ9Omz5g5a/acufPmL1i4aPGSpcuWr1i5avWatevWb9i4afOWrdu279i5a/eevfv2Hzh46PCRo8eOnzh56vSZkrPnzl@4eOnylavXrt@4WXrr9p27Zpqye@X3Hzx89PjJ02fPX7x8VfH6zdt370VG9AomUqJPk35N0ppkNMlqQjVhmnBNLE0GNBnUZEgR5VN@1aCCKqyTPapFRVVCpZyoG1S1bkg1uhE3rprdpJtSsZGIOzDiVd0jAScGHgGtAq0Dp6BRWH7QFGgGzAtWA6sO7AtYB1gCVhRsCLwWVj94oxMH9dpG7bebQFttc02H3WsPg3nAqpweYwqsCSwMFgH7AV4D7gf/mLPA20GrQevBGWgMVgC0DzQLVgnmg1UP9hWsE6xbdMkq8A@w0uBBpwu00jbagB0CbbPNJZ058xYBq3Z@gYXAmsHawX6C@8AD4J9yA5NN2bgsBNpI/mI9RUEbE2OwLk7QxvN4Ez3hlM0sEwl6NJzjCHWxgTZ7@JfqNvJCrI2kGNp7UkH/KZP/or0LJ9qMOtWre2zKo01QvH@0sVcQtPa0mI1pT1h7ms0yzZGcp0RY@fxv "Jelly โ€šร„รฌ Try It Online") [Answer] # x86 .COM , 256/256 byte, ``` 00000000: bff2 01b8 9190 2905 6681 4506 9594 9392 ......).f.E..... 00000010: b409 575a 83ea 03fe 8d2a ffcd 22c3 ???? ..WZ.....*.."... 000000e0: ???? ???? ???? ???? ???? ???? ???? ??6a ...............j 000000f0: 616e b1f1 6c65 206f 978b e0dc 6b69 2124 an..le o....ki!$ ``` asm: ``` org 100h mov di, 0x1F2 mov ax, 0x9091 sub [di], ax add [di+6], dword 0x92939495 mov ah, 9 push di pop dx sub dx, 3 dec byte [di-0x1F2+k+1] k: int 0x22 ret db 0x1EF-$ dup ? db 'j' dw 'an' dw ' a'+0x9091-0x10000 dd 'le o' dd ', to'-0x92939495 dd 'ki!$' ``` Fill the `db 0x1EF-$ dup ?` with all left bytes Maybe it's possible to make one with MZ head ]
[Question] [ [Starry](http://esolangs.org/wiki/Starry) is a funny esoteric programming language in which code consists only of `+*.,`'` where the actual command represented by each of those characters is determined by the number of spaces in front of it. That makes it tricky even to golf fixed-output challenges, because different commands can account for vastly different numbers of bytes. In particular, number literals have a unary representation which makes it necessary to build up larger numbers by operating on smaller ones. Therefore, this challenge is about writing a program which can golf such Starry programs. ## How does Starry work? *(A few details are left unspecified on esolangs, so I'm going with the behaviour of the [Ruby interpreter](https://github.com/yhara/esolang-book-sources/blob/master/starry/starry.rb).)* Starry is a stack-based language, with a single stack of arbitrary-precision integer values (which is initially empty). The only meaningful characters are: ``` +*.,`' ``` and spaces. All other characters are ignored. Each sequence of spaces followed by one of those non-space characters represents a single instruction. The type of instruction depends on the non-space character and the *number* of spaces. The instructions are: ``` Spaces Symbol Meaning 0 + Invalid opcode. 1 + Duplicate top of stack. 2 + Swap top 2 stack elements. 3 + Rotate top 3 stack elements. That is, send the top stack element two positions down. [... 1 2 3] becomes [... 3 1 2]. 4 + Pop and discard top of stack. n โ‰ฅ 5 + Push n โˆ’ 5 to stack. 0 mod 5 * Pop y, pop x, push x + y. 1 mod 5 * Pop y, pop x, push x โˆ’ y. 2 mod 5 * Pop y, pop x, push x * y. 3 mod 5 * Pop y, pop x, push x / y, rounded towards -โˆž. 4 mod 5 * Pop y, pop x, push x % y. The sign of the result matches the sign of y. 0 mod 2 . Pop a value and print it as a decimal number. 1 mod 2 . Pop a value and print it as an ASCII character. This throws an error if the value is not in the range [0, 255]. n ` Mark label n. n ' Pop a value; if non-zero, jump to label n. ``` Note that the interpreter scans the source code for the labels before execution begins, so it's possible to jump forwards as well as backwards. Of course, Starry also has input commands (using `,` analogously to `.`), but those are irrelevant for this challenge. ## The Challenge Given a string, generate a Starry program which takes no input and prints that string exactly to STDOUT. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. You may assume that the string is not longer than 128 characters and that it will consist only of printable ASCII characters (code points 0x20 to 0x7E). Your solution should process any such input in less than 5 minutes on a reasonable desktop machine (there's some leeway to this; if it takes a few minutes more on my laptop I don't mind, but if it takes 15, I'll disqualify it). Your solution will be tested on a number of different strings listed below. **Your score is the total byte count of the corresponding Starry programs.** In the case of a tie, the shortest metagolfer wins. That is, don't bother golfing your own code unless there is a tie (which I think will only happen in the case that an optimal solution is possible). You must not optimise your code towards the specific test cases listed below. Specifically, you shouldn't hardcode hand-crafted solutions for them. Optimising towards classes of strings whose structure is similar to that of the given strings is fine. If I suspect anyone of hardcoding solutions, I reserve the right to replace some or all of the test cases (with strings of comparable structures). ## Test Cases Each line is a separate test case: ``` Hello, World! pneumonoultramicroscopicsilicovolcanoconiosis .oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo. Hickory, dickory, dock. The mouse ran up the clock. The clock struck 1. The mouse ran down. Hickory, dickory, dock. 36912059868043514648560046917066768694455682545071266675083273015450033938555319356951628735735013250100789433961153496780296165 bVZ48121347GLtpYnt76CZSxTpMDs6791EJE808077eySXldY162424ddTB90707UupwlWGb63618542VhA252989453TXrWgqGm85899uHOAY2oAKE198GOVUttvW63 7MYxoWBNt180CDHS5xBGvU70HHVB17bh8jYzIIiU6n6g98Rose1nOe8Svcg56nax20q30kT3Ttb2jHl5q2Iuf1vPbjPxm9cyKXwxc0OUK8pr13b2n7U9Y7RwQTc26A1I n9}unwxVa}[rj+5em6K#-H@= p^X/:DS]b*Jv/_x4.a5vT/So2R`yKy=in7-15B=g _BD`Bw=Z`Br;UwwF[{q]cS|&i;Gn4)q=`!G]8"eFP`Mn:zt-#mfCV2AL2^fL"A ``` Credits for the second test case go to [Dennis](https://codegolf.stackexchange.com/q/52152/8478). Credits for the fourth test case go to Sp3000. ## Reference Solution Here is a really basic reference solution in CJam: ``` q{S5*\iS*'+S'.}% ``` [You can run it against the entire test suite here.](http://goo.gl/dG0thu) The scores are: ``` 1233 5240 4223 11110 7735 10497 11524 11392 Total: 62954 ``` It's the simplest possible approach: push each character's code point as a literal, and then print it. It makes no use of small differences between consecutive characters, integer printing, repetitive parts of the string etc. I'll leave those things to you. I believe there is a lot of room for improvement. For reference, the [shortest handcrafted "Hello, World!"](https://codegolf.stackexchange.com/a/55526/8478) is only 169 bytes long. [Answer] ## Python 3, ~~17071~~ 11845 ``` from functools import lru_cache import heapq import time cases = r""" Hello, World! pneumonoultramicroscopicsilicovolcanoconiosis .oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo. Hickory, dickory, dock. The mouse ran up the clock. The clock struck 1. The mouse ran down. Hickory, dickory, dock. 36912059868043514648560046917066768694455682545071266675083273015450033938555319356951628735735013250100789433961153496780296165 bVZ48121347GLtpYnt76CZSxTpMDs6791EJE808077eySXldY162424ddTB90707UupwlWGb63618542VhA252989453TXrWgqGm85899uHOAY2oAKE198GOVUttvW63 7MYxoWBNt180CDHS5xBGvU70HHVB17bh8jYzIIiU6n6g98Rose1nOe8Svcg56nax20q30kT3Ttb2jHl5q2Iuf1vPbjPxm9cyKXwxc0OUK8pr13b2n7U9Y7RwQTc26A1I n9}unwxVa}[rj+5em6K#-H@= p^X/:DS]b*Jv/_x4.a5vT/So2R`yKy=in7-15B=g _BD`Bw=Z`Br;UwwF[{q]cS|&i;Gn4)q=`!G]8"eFP`Mn:zt-#mfCV2AL2^fL"A """.strip().splitlines() @lru_cache(maxsize=128) def shortest_m_to_n(m, n): if m is None: L = [] else: L = [m] to_search = [[0, "", L]] seen = set() while True: length, code, stack = heapq.heappop(to_search) if len(stack) == 1 and stack[-1] == n: return code seen.add(tuple(stack)) options = [] for i in range(1, 11): new_stack = stack[:] + [i] new_code = code + ' '*(i+5) + '+' options.append([len(new_code), new_code, new_stack]) if stack: new_stack = stack[:] + [stack[-1]] new_code = code + " +" options.append([len(new_code), new_code, new_stack]) if len(stack) >= 2: x, y = stack[-2:] for i, op in enumerate(['+', '-', '*', '//', '%']): try: new_elem = eval("{}{}{}".format(x, op, y)) new_stack = stack[:-2] + [new_elem] new_code = code + ' '*i + '*' options.append([len(new_code), new_code, new_stack]) except ZeroDivisionError: pass for op in options: if tuple(op[2]) in seen or len(op[2]) > 4 or op[2][-1] > 200: continue heapq.heappush(to_search, op) def lcs(s1, s2): dp_row = [""]*(len(s2)+1) for i, c1 in enumerate(s1): new_dp_row = [""] for j, c2 in enumerate(s2): if c1 == c2 and not c1.isdigit(): new_dp_row.append(dp_row[j] + c1) else: new_dp_row.append(max(dp_row[j+1], new_dp_row[-1], key=len)) dp_row = new_dp_row return dp_row[-1] def metagolf(s): keep = "" split_index = 0 for i in range(1, len(s)): l = lcs(s[:i], s[i:][::-1]) if len(l) > len(keep): keep = l split_index = i code = [] stack = [] keep_ptr = 0 i = 0 while i < len(s): c = s[i] n = ord(c) if c in "0123456789": code += [" "*(int(c)+5) + "+."] i += 1 continue if stack: if stack[-1] == n: code += [" +", " ."] elif len(stack) >= 2 and stack[-2] == n: for j in range(len(code)): if code[~j] == " +": code[~j] = "" break code += [" +", " ."] stack.pop() else: code += [shortest_m_to_n(stack[-1], n), " +", " ."] stack[-1] = n else: code += [shortest_m_to_n(None, n), " +", " ."] stack.append(n) while i < split_index and keep[keep_ptr:][:1] == c: code += [" +"] keep_ptr += 1 stack.append(n) i += 1 code = "".join(code) if code[-4:] == " + .": code = code[:-4] + " ." return code total = 0 for case in cases: start_time = time.time() s = metagolf(case) print(len(s), time.time() - start_time) total += len(s) print(s) print('='*50) print(total) ``` The relevant function is the aptly named `metagolf`. The results are: ``` 210 676 684 2007 1463 2071 2204 2530 Total: 11845 ``` You can find the full output [here](http://pastebin.com/WZugWrkk). ### Brief explanation I'm going to keep the explanation brief since there's many things still to be improved. The basic algorithm just looks at pairs of chars, and finds the optimal way to transition from one char to another via BFS. Digits are currently pushed and printed immediately, although this will be changed later. There's also a little longest-common-subsequence going on, to leave a few elements on the stack for reuse later. It's not as good as repetition, but provides decent savings. [Answer] # Ruby, ~~13461~~ 10997 ``` $s = {}; def shortest a,b=nil return $s[[a,b]] if $s[[a,b]] l = [] if b if a == b return $s[[a,b]] = "" elsif a > b l.push shortest(a-b)+" *" l.push " + *"+shortest(1,b) if a > 1 l.push " + *"+shortest(0,b) if a > 0 l.push " +"+shortest(b) elsif a < b l.push " + *"+shortest(a*a,b) if a*a>a && a*a<=b l.push " +*"+shortest(a+a,b) if a+a<=b && a+a>a l.push shortest(b-a)+"*" l.push " +"+shortest(a,b/a)+" *" if a>2 && b%a == 0 l.push " +"+shortest(a,b-a)+"*" if a>1 && b>a*2 end else l.push ' '*(a+5)+'+' #if a < 6 (1..a/2).each {|n| l.push shortest(n)+shortest(n,a) } end return $s[[a,b]] = l.min_by{|x|x.length} end def starry(str) arr = str.bytes.map{|b| if b>47 && b<58 b-48# change digets to numbers else b end } startNum = (1..128).min_by{|x|arr.inject{|s,y|s + [shortest(x,y).length+2,shortest(y).length].min}+shortest(x).length} #one number to be put on the stack at the start. code = shortest(startNum) code += [ shortest(arr[0]), " +"+shortest(startNum, arr[0]) ].min_by{|x|x.length} arr.each_cons(2) do |a| pr = a[0]<10?'.':' .' code += [ pr+shortest(a[1]), " +"+pr+shortest(a[0], a[1]), pr+" +"+shortest(startNum, a[1]) ].min_by{|x|x.length} end code += arr[-1]<10?'.':' .' end a = ["Hello, World!", "pneumonoultramicroscopicsilicovolcanoconiosis", ".oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.", "Hickory, dickory, dock. The mouse ran up the clock. The clock struck 1. The mouse ran down. Hickory, dickory, dock.", "36912059868043514648560046917066768694455682545071266675083273015450033938555319356951628735735013250100789433961153496780296165", "bVZ48121347GLtpYnt76CZSxTpMDs6791EJE808077eySXldY162424ddTB90707UupwlWGb63618542VhA252989453TXrWgqGm85899uHOAY2oAKE198GOVUttvW63", "7MYxoWBNt180CDHS5xBGvU70HHVB17bh8jYzIIiU6n6g98Rose1nOe8Svcg56nax20q30kT3Ttb2jHl5q2Iuf1vPbjPxm9cyKXwxc0OUK8pr13b2n7U9Y7RwQTc26A1I", "n9}unwxVa}[rj+5em6K#-H@= p^X/:DS]b*Jv/_x4.a5vT/So2R`yKy=in7-15B=g _BD`Bw=Z`Br;UwwF[{q]cS|&i;Gn4)q=`!G]8\"eFP`Mn:zt-#mfCV2AL2^fL\"A"] c = a.map{ |s| starry(s).length } p c.inject(0){|a,b|a+b} ``` The method `starry` answers the given question. Results: ``` 230 639 682 1974 1024 1897 2115 2436 Total: 10997 ``` ### How it works `shortest` is the main algorithm. It takes one number and finds the shortest way to place it on the stack, or it takes two numbers, and returns code to put the second on the stack assuming the first one is already on. `$s` is a Hash to hold the results of these operations for further use. `starry` takes a string and splits it into an array of character codes (or numbers for digests). It starts the code with one number on the bottom of the stack. Next it calculates the shortest way it can generate each successive number, possibly copying the last one or using the number put on the stack at the beginning. [Answer] # JavaScript, ~~25158~~ 23778 Now ES5-compatible! ``` String.prototype.repeat = String.prototype.repeat || function (n) { return Array(n+1).join(this); } function starrify(x) { function c(x){return x.charCodeAt()} var char = x[0], result = ' '.repeat(c(char)+5)+'+ + .'; x=x.slice(1); for(var i in x) { if (char < x[i]) { result += ' '.repeat(c(x[i])-c(char)+5)+'+* + .'; } else if (char > x[i]) { if(c(char)-c(x[i]) < c(x[i])) { result += ' '.repeat(c(char)-c(x[i])+5)+'+ * + .'; } else { result += ' '.repeat(c(x[i])+5)+'+ + .'; } } else { result += ' + .'; } char = x[i]; } return result; } ``` Results: ``` 432 949 2465 3996 1805 3551 5205 5375 Total: 23778 ``` A good start in my opinion, but obviously not finished. Instead of creating each char separately, it adds or subtracts from the previous char code. I'll add an full explanation when I'm done meta-golfing. [Answer] # C++, score: 9708 Uses an A\*-like search algorithm (i.e. what used to be A\* but was tweaked a lot so that it doesn't run out of RAM and searches fast enough, at the cost of finding non-optimal solutions), where the possible actions from a state are: * Print a character (if it's the next character needed) * Execute a precomputed sequence of commands to push the next character needed onto the stack * Execute a precomputed sequence of commands to change the top of the stack number to the next character needed * Duplicate the top of the stack, as long as that won't increase its size beyond 5 * Swap the top 2 items on the stack * Rotate the top 3 items on the stack Uses an algorithm extremely similar to the one used in MegaTom's Ruby answer to compute the sequences of commands mentioned (however it's slightly better, as it uses more possible transitions). Doesn't handle digits as special, easier-to-print characters; the score would be even lower if it would. The complete source code: ``` #include <x86intrin.h> #include <iostream> #include <streambuf> #include <bitset> #include <cstdio> #include <vector> #include <algorithm> #include <cmath> #include <climits> #include <random> #include <set> #include <list> #include <map> #include <unordered_map> #include <deque> #include <stack> #include <queue> #include <string> #include <iomanip> #include <unordered_set> #include <thread> //std::string shortestpath(int from, int to); //std::string shortestpath(int to); std::string shortestpath(int to, bool grown = false); std::string shortestpath(int from, int to, bool grown = false); std::map<std::pair<int,int>, std::pair<std::string, bool>> cache2; std::map<int, std::pair<std::string, bool>> cache1; std::string shortestpath(int to, bool grown) { if(cache1.count(to) && (grown || cache1[to].second == false)) return cache1[to].first; std::vector<std::string> paths; paths.push_back(std::string(to + 6, ' ')); paths[0].back() = '+'; for(int i = 1; i < to - 1; i++) paths.push_back(shortestpath(i, grown) + shortestpath(i, to, grown)); cache1[to] = {*std::min_element(paths.begin(), paths.end(), [](auto a, auto b){return a.size() < b.size();}), false}; return cache1[to].first; } std::string shortestpath(int from, int to, bool grown) { if(to > 512 || from > 512) return "qwertyuiopqwertyuiopqwertyuiopqwertyuioqwertyuiopqweryuiopqwertyuiopqwertyuiopqwertyuioqwertyuiopqwertyuiopqwertyuiopqwertyuiopqwertyuiop"; //printf("from=%d, to=%d\n", from, to); if(cache2.count({from, to}) && (grown || cache2[{from, to}].second == false)) return cache2[{from, to}].first; std::vector<std::string> paths; if(from == to) paths.push_back(""); if(from > to) paths.push_back(shortestpath(from - to, grown) + " *"); if(from > to && from > 0) paths.push_back(" + *" + shortestpath(0, to, grown)); if(from > to && from > 1) paths.push_back(" + *" + shortestpath(1, to, grown)); //if(from > to) paths.push_back(" +" + shortestpath(to, grown)); if(from > to) for(int i = to + 1; i < from; i++) { if(from % i == to) paths.push_back(shortestpath(i, grown) + " *"); if(from / i == to) paths.push_back(shortestpath(i, grown) + " *"); } if(from < to && from > 1 && (from*from <= to || !grown)) { bool ng = from*from > to; paths.push_back(" + *" + shortestpath(from*from, to, grown | ng)); } if(from < to && from > 0 && (from+from <= to || !grown)) { bool ng = from+from > to; paths.push_back(" +*" + shortestpath(from+from, to, grown | ng)); } if(from < to && from > 1 && to >= 2 * from) paths.push_back(" +"+shortestpath(from,to/from, grown)+" *" + shortestpath(to/from*from, to, grown)); if(from < to && from > 1 && to >= 2 * from && !grown) { bool ng = (to/from+1) * from > to; paths.push_back(" +" + shortestpath(from, to/from + 1, grown + ng) + " *" + shortestpath((to/from+1)*from, to, ng)); } if(from < to && from > 0 && to >= 2*from) paths.push_back(" +"+shortestpath(from,to-from, grown)+"*"); if(from < to) paths.push_back(shortestpath(to-from, grown)+"*"); cache2[{from, to}] = {*std::min_element(paths.begin(), paths.end(), [](auto a, auto b){return a.size() < b.size();}), grown}; return cache2[{from, to}].first; } std::string target; struct astate { std::vector<int> stack; int i = 0; int heur() const { return 3 * (target.size() - i); } bool operator < (const astate& rhs) const { if(i != rhs.i) return i > rhs.i; return stack < rhs.stack; } }; struct sstate { astate as; int f; bool operator < (const sstate& rhs) const { if(f != rhs.f) return f < rhs.f; if(as.heur() != rhs.as.heur()) return as.heur() < rhs.as.heur(); return as < rhs.as; } }; int metagolf(std::string target) { std::map<int, int> icounts; int hw = 2; ::target = target; sstate start = {{{}, 0}, 0}; std::map<astate, std::pair<astate, std::string>> prev; std::map<astate, int> dists; dists[start.as] = 0; std::set<sstate> openset; openset.insert(start); bool done = false; //int itsleft = 100; astate beststate = start.as; while(!openset.empty()) { auto it = openset.begin(); auto[cs, cf] = *it; openset.erase(it); icounts[cs.i]++; if(icounts[cs.i + 3] > 250) continue; //{ printf("continuing: i=%d\n", cs.i); continue; } int cd = dists[cs]; if(cs.i == target.size()) { done = true; beststate = cs; break; }; //print if(!cs.stack.empty() && cs.stack.back() == target[cs.i]) { auto next = cs; int dist = cd + 2; next.i++; next.stack.pop_back(); if(dists.count(next) == 0 || dist < dists[next]) { dists[next] = dist; openset.insert({next, dist + hw*next.heur()}); prev[next] = {cs, " ."}; } } //shortestpath from if(!cs.stack.empty()) { auto next = cs; std::string path = shortestpath(cs.stack.back(), target[cs.i]); int dist = cd + path.size(); next.stack.back() = target[cs.i]; if(dists.count(next) == 0 || dist < dists[next]) { dists[next] = dist; openset.insert({next, dist + hw*next.heur()}); prev[next] = {cs, path}; } } //shortestpath to { auto next = cs; std::string path = shortestpath(target[cs.i]); int dist = cd + path.size(); next.stack.push_back(target[cs.i]); if(dists.count(next) == 0 || dist < dists[next]) { dists[next] = dist; openset.insert({next, dist + hw*next.heur()}); prev[next] = {cs, path}; } } //dup if size below 5 if(!cs.stack.empty() && cs.stack.size() < 5) { auto next = cs; int dist = cd + 2; next.stack.push_back(next.stack.back()); if(dists.count(next) == 0 || dist < dists[next]) { dists[next] = dist; openset.insert({next, dist + hw*next.heur()}); prev[next] = {cs, " +"}; } } //swap if(cs.stack.size() >= 2) { auto next = cs; int dist = cd + 3; std::swap(next.stack.back(), next.stack[next.stack.size() - 2]); if(dists.count(next) == 0 || dist < dists[next]) { dists[next] = dist; openset.insert({next, dist + hw*next.heur()}); prev[next] = {cs, " +"}; } } //rot if(cs.stack.size() >= 3) { auto next = cs; int dist = cd + 4; std::swap(next.stack.back(), next.stack[next.stack.size() - 2]); std::swap(next.stack[next.stack.size() - 3], next.stack[next.stack.size() - 2]); if(dists.count(next) == 0 || dist < dists[next]) { dists[next] = dist; openset.insert({next, dist + hw*next.heur()}); prev[next] = {cs, " +"}; } } } astate cur = beststate; std::vector<std::string> code; while(cur < start.as || start.as < cur) { auto[pr, path] = prev[cur]; code.push_back(path); cur = pr; } std::reverse(code.begin(), code.end()); std::string ans; for(auto s : code) ans += s; printf("%s\n", ans.data()); return ans.size(); } int main()//int64_t argc, char*argv[]) { int ans = 0; for(int from = 0; from < 256; from++) for(int to = 0; to < 256; to++) { auto p = shortestpath(from, to); int len = p.size(); ans += len; //if(len < 35) continue; //printf("%d->%d: %d\n", from, to, p.size()); //printf("%s\n", p.data()); } printf("total length of all transitions within [0, 256): %d\n", ans); std::vector<std::string> targets { "Hello, World!", "pneumonoultramicroscopicsilicovolcanoconiosis", ".oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.", "Hickory, dickory, dock. The mouse ran up the clock. The clock struck 1. The mouse ran down. Hickory, dickory, dock.", "36912059868043514648560046917066768694455682545071266675083273015450033938555319356951628735735013250100789433961153496780296165", "bVZ48121347GLtpYnt76CZSxTpMDs6791EJE808077eySXldY162424ddTB90707UupwlWGb63618542VhA252989453TXrWgqGm85899uHOAY2oAKE198GOVUttvW63", "7MYxoWBNt180CDHS5xBGvU70HHVB17bh8jYzIIiU6n6g98Rose1nOe8Svcg56nax20q30kT3Ttb2jHl5q2Iuf1vPbjPxm9cyKXwxc0OUK8pr13b2n7U9Y7RwQTc26A1I", R"T(n9}unwxVa}[rj+5em6K#-H@= p^X/:DS]b*Jv/_x4.a5vT/So2R`yKy=in7-15B=g _BD`Bw=Z`Br;UwwF[{q]cS|&i;Gn4)q=`!G]8"eFP`Mn:zt-#mfCV2AL2^fL"A)T" }; int res = 0; for(std::string target : targets) { int len = metagolf(target); res += len; printf("%d\n", len); } printf("total length of all programs: %d\n", res); } ``` Output: ``` total length of all transitions within [0, 256): 1425541 + +* + * +* . + + +* + ** + . + +* + . + . + +* + . + +* +* + . + + * +* . +* + * . + . +* . . + * . + + +** . 208 + + + ** +* + . + * + . + + + * * . + +* + . + + + * . + +* + . + . + . + . + + * . + +* . + + +* + . + + + +* * + . + + * + . + * . +* + . + . + . + +* + . + + + . + + . +* . + +* + . + + . + . + . + +* + . + . + . + + +* + . + +* . + . + . + . + + * . + + + * + . + + . + . + . + + . + * + . + + . +* + . + . . 517 + + +* + +* + +* +**** + . + + + + +* + * ** + . + + + * +* * + . + + . + . + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + + . + . . . 386 + +* + * +* . + + +* + ** + . + + + * + . + +* + . +* + . +* + . +* . + +* +* + . + + * +* . + + +* . + + . + + . + +* + . +* + . + +* + . +* . + . + + * +* + . + + +* . + + . + + . + + +** . + + + +** . + . + + + + +** * . + +* . +* + . + + . + + + * . + . +* + . + + * . + + . + + . + + + * . + + + * . + + + ** . + + . + + . + + * . + + . + + * . + +* + . + . + . + + + + * + . + +* + . +* . + . + + +* . + + + +** . + . + + + +* +* * . + . + * . + . + + . + + + ** + . + +* . + + . + + * + . + + . + + + +** + . + +* . + + * . +* . + . . + . + + * + . + * . + . + + + + + * + ** + . + +* +** + . + * + . + . + + +** + . +* + . +* + . + * + . + + . + . + * . + + * . + + + ** + . + + + . + + * + . + + +* + . + + +** . + . + + +** . + . + +* + +** . + + + * + . + + * . +* . + . +* + . +* . + + +* +** + . + + . + + . + +* + . + + * . +* + . + +* + . +* + . +* . + + . + . + + + * + . + +* . + * . . +* . 1588 + + +* +* +* +** + . + + +* + . +* + . + + + * + . + +* . + * + . + +* . + . + * + . + + * . . + . + + +* + . + . + +* . + + * . + . + + +* + . + . + +* . + + * . + . + + + . + . + . + . + +* + . + + + * . + +* . + . + . + . + +* . + . + +* . + . + . + + + * + . + . +* + . + . + + . +* . + + + * + . + + . + + * . . + + * . + +* . + + * . . + + . + . . + + + +* + . + + . + * . + +* . + + * + . + + * . + . + . + * + . + +* . + + . + + * . . + . . + + + * + . + . + +* . + . + + + +* . . + . . + . + + * + . + + +* . . + . + +* + . + +* . + + . + . + . + + * . + +* . +* . + + + + * + . + + . +* . + . + . + + * + . + +* . + + . + + * . + . + . + +* . + . . + + +* + . +* + . +* + . + + +* . + . . + . + + +* + . + + + * + . . + +* . + . +* . + + . + + . + +* + . +* . + + * + . +* . + . + . + + * . + . + * . 1261 + + * +* + . + +* +* * + . +* + . + + + + * + +*** + . + +* . + + * + . + +* . . + + * . + . +* + . + + + ** + . +* . + +* +* + . + + * . + + + * . + +* . + . + . + + * + . + + + +* +** + . + + + . + * + . + +* + + + *** . +* . +* +* + . + + + +** . +* + . + +* . + . + +* + . +* . + + * . + +* + . + +* . . + +* + . + + +* * + . + . . + +* + . . + + +* + * + . + + +* +** . + + + * +* * + . +* + . + + +* . + * . +* . + + * + . + . + +* + . + + +* + . + . . + +* + . + . + + * * . + + ** . + + +** . + + * + . + +* + . + . . + + +* + ** + . + + + * +** + . + + * + . + +* . + * . +* + . + + * * . + +* . + +* + . + + * . + . + . +* + . + + * + . + + * + . + + * + . + + +* + ** . + +* . + + +* +** . + + . + . . + + +* + . + . + . + + * + . + +* . + * + . + + + + * + ** + . +* + . + +* . + * . +* +* . + +* +* . + + + + + +*** + . + + +* + * . + . + + * . + . +* + . + . +* +* . + +* . + + +** . + + * + . + + + + * +** . + + + * . +* + * . . + +* . + + * . + + + * . + +* + . + . + . + +** + . +* + . + + * . + + +* +* + . + . +* . + +* . + * + . + * . 1763 + + + * +** + . + + + +** + . + + +* +** . + + +* + +** + . + +* +* . + + +** . + + * + . + +* . + + * . + + * + . + +* . + * . + + +* + . + +* . + +* . + + ** . + + + * . + + . + + . + +* . + + * . + + + + *** . + . + + * . + + +* + . + . + +** . . + + + + * + . + . +* + . +* + . + +* . + +* . + + + + +** * + . + + + * +** . + + + * * + . . + +* . + * . + + + * + . + +* + . + + . + +* + * . +* + . + + * . + + ** + . + + +* + . +* . + + + * * + . + + * . + . + + * . + + . + + +* . + + +* . + +* + ** + . + + + * + . + +* . + + * + . +* . +* . + * . + +* . + + + * +* + . + * + . + + * . + +* + . + . + +* +* . + + + * + ** + . + + . + . + + * . + + +* + * . + + * . + +* +* + . + +* + * +* + . + +* . + +* + . +* +* . + + * . + + +* . + + + * . + + +* . + * + . + . + + + + + ** * + . + +* + . + +** + . + . + + +** + . + +* . + + +** . + +* +* . + + +* . + + +* + . + + + ** . + + * . . + + +* +* . + + * . + + +* + . +* + . + . + +* + . + +* + . +* . + + . + +* . + +* . + +* . + + +* + * . + * + . + + . + + +* + . + + + +* . + . + * + . + +* +* . + + * . +* . + +* +* . + +* + . +* . + + + ** + . + . + +** . 1938 + +* + + ** + . + + + + * +* ** + . + + + + +*** + . + + +* + . + . +* + . +* + . + + + + +* + ** * + . + +* . + . +* . + +* + . + +* * . + + +* * + . + + +** + . + +* + * . + +* +* . +* . + + + * +** + . + + + +* * . +* + . + + * + . + + +* . + +* . + + * +* . + +* + * . + + +* +* . + +* + * . +* + . + +* + . + + +** . + + ** . + +* + * + . +* . + + * . + +* . + + * + . + + + . + +* +* . + . + + +* + . + + + * . +* +* . +* + . + + . + + +* + +* * + . + . + * + . + + + +* + ** . + +* . + + * . +* +* + . + + + ** + . + + * + +** . . + + + +** + . + + +* + * + . +* . + +* . + + +* * + . +* . . + +* + . + + . + + +* . + + * +* . + + * . + + . + +* . + + . + . + +* + * + . + + . + + + * + . + . + +* . + +* + +* * . + * + . + + + * . + + . + . + + + +* +* * . +* + . + + +* + . + + * . +* + . + +* . + + +* * . + +* . + + + + +** * + . + + +* + ** . + . + +* + * . + + +* + ** + . + + + +** . +* . + +* . + +* + . + + +* . + + +** + . + +* +* . + . + + * . + +* + . + + +* + ** . + +* +* + . + +** + . + + + ** . + * . + . + + * + . + +* . +* . + + +* + . + + +* + . + +* +** . + + +** + . + +* + * + . + + +* + * . +* + . + + + * . + + ** + . + . + + +* * . . . + . +* + * . 2047 total length of all programs: 9708 ``` ]
[Question] [ Given a level from a simple platform game, your task is to make a program or function to determine if a level is winnable. Platform game levels are 4 characters tall and any number of characters wide. There is exactly one platform for each horizontal space in a level: ``` ======= = == = = === ===== = ==== === ``` The game consists of jumps. Jumps start from the space above the platform which is being jumped from, and end in the space above the platform which is being jumped to (these can be above the 4 platform height levels). To complete a jump, it must be possible to move from the start point to the end point in four or less (including the start/end points) up, down, left, and right moves which do not pass through a platform. Here are some examples (marked with A for start platform and B for end platform): ``` >>> ^ B =A = ``` ``` >>>> =A B= ``` ``` >> ^B A ``` Horizontal moves along a platform are just jumps which only move in one direction: ``` >> ==AB=== ``` The player would start on the leftmost platform, and wins by standing on the rightmost one (marked with `v`s): ``` v === v === == ``` ## Test cases Winnable: ``` === == = ===== = ``` ``` == = == === ==== ``` ``` ==== = === = === ``` ``` == == = = = == == = ``` Unwinnable: ``` ====== ====== ``` ``` ======= = = = = = ``` ``` = = = = == == ==== ``` ## Rules Your program should output one distinct value if a level is winnable, and a different one if it isn't. It can take input in any reasonable form, such as an ASCII art with any two distinct characters, a matrix, or a 2d array. Code golf, so shortest answer per language wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 22 bytes ``` ล’แนชแบกรพ`ยง<4NA1ยฆAยป/T$ยฆรLแนชแน€ ``` [Try it online!](https://tio.run/##VZCxCsIwEIb3e4ogjooIbnqCuzi56OTiUsTdrbq4iq46iFBBnEQCVXC4oO/RvEhMkzQkoaR3yX/f/blkvlislPrui/xWvM7iM6NrrzMatCkb0Ls1rlMmdsPyMk@VXH9qtUTs5Oae6LhBvCvTI3HW7DPiMj11xXZSh@@hyC/6njjx4v2cLuWai@3v4crKY6VYsIAhog0RAe3fHIGJK5nNsCoKCehDTbA4RwBHMxjwjQICxjgtAfBhmcVeo7bOp7OHPsfQUQgPCOjeZM3GuvhNZkRe6O1ZCgQjqorQz9V@ejOdnNwJseKyPw "Jelly โ€“ Try It Online") New version, which now efficiently handles moves backwards. Takes input as a boolean matrix (row major). Returns 1 for winnable and 0 for not. Thanks to @AZTECCO for first suggesting using the indices of platforms, and @tsh for a test case that made me rethink my approach. ## Explanation ``` ล’แนช | Multidimensional truthy indices of each แบกรพ` | Outer table using absolute difference and with the same argument on both sides: ยง | Sum innermost lists <4 | - Less than 4 N | Negate A1ยฆ | Absolute top row รL | Apply the following until no changes: A $ยฆ | Absolute the rows indicated by the following: ยป/ | - Max of each column T | - Truthy indices (i.e. where thereโ€™s a 1 in the column) แนช | Finally take the last row แน€ | Max ``` ## Step b step (each matrix shown collapsed as a grid, with - = -1): ### 1. Input ``` 0010 0001 1000 0010 0001 1000 ``` ### 2.`ล’แนช` Multidimensional indices. ``` [[1, 3], [2, 4], [3, 1], [4, 3], [5, 4], [6, 1]] ``` ### 3. `แบกรพ`ยง<4N` Convert to initial outer table with -1 for possible moves between columns and 0 where no move possible. ``` --0-00 --0--0 00--0- -----0 0-0--0 00-00- ``` ### 4. `A1ยฆAยป/T$ยฆรL` Absolute first row, then iteratively take each column with at least one 1 in it, and absolute the rows at those indices; results after each iteration shown. ``` Absolute row 1 -> 110100 --0--0 00--0- -----0 0-0--0 00-00- -> Absolute rows 1, 2, 4 -> 110100 110110 00--0- 111110 0-0--0 00-00- -> Absolute rows 1, 2, 3, 4, 5 -> 110100 110110 001101 111110 010110 00-00- -> Absolute rows 1, 2, 3, 4, 5, 6 -> 110100 110110 001101 111110 010110 001001 ``` ### 5. `แนชแน€` Finally, take the max of the last row ``` 1 ``` My [previous 61 byte version](https://tio.run/##VZCxasMwEIb3ewoTPNbUhmYyl6VToU@QrUMWE9q5mewuHroEOjiBZipkabqUIuoaMuhIoY8hvYh7sWQhGSP9J/369OuKxXL52Pe63KZyr9ptJg/UTKmZZTFwScecx7@GNglbdPWt2g/ZXbK4o/ohhntdiVO3Sm@oSa7k@@9nJvfXtEmLWFc/@umwSqmm9e08Ud3zdNHr6jiZFLTmnYL1hRS5Ll@liJJZJIUudznVcHpR7RvvSiGF6r7YS7U9cF7q@8j7IEJEIxEBzTwswaBHm6lwPOQT0EkmGJwlgKUNGHAXeQQMcWwBcPJchVmDa21OGw9djX4iH@4R0L7JhA194ZuGFjmji2co4LVoPISur@bn4R8 "Jelly โ€“ Try It Online") has explanation in the [edit history](https://codegolf.stackexchange.com/posts/196602/revisions "Edit history"); thanks to @JonathanAllan for golfing 3 bytes off that one! [Answer] # JavaScript (ES6), ~~129~~ 126 bytes Takes input as a binary matrix. Returns either \$0\$ or \$1\$. ``` f=(a,x=0,m,d=4,g=d=>k=a.findIndex(r=>r[x+d]))=>!~g(1)|[...'1350531'].some(v=>~g(--d)&&m^(M=m|1<<x+d)&&(k-=g``)*k<v&f(a,x+d,M)) ``` [Try it online!](https://tio.run/##nZM9b4MwEIZ3fgVdwG4M4pRmw@wdMlYdKFVIDIgCpoKIUCnqX6eUJMUQvlRZQtiv7/yc7/WHW7j5IQs/jxpPmVdVPkUuKalBEsLoEwkoo1ZEXd0POXvmzCtRRq3MLlfMwZhaD98BAny2dV1XYb0xNmtQHT1PEw8V1KpFTWNYUZJ3tKXJGUyzDqznKNJosNvhx8gsFP/3xBUjW4yrQ8rzNPb0OA2Qar@GnLv72HNULImKj2xJlm2DDA6HXERohijV84sI4lK78RZ5k7pppbriKYzead1kg4wwIP0xigWIjNMY7U7ontS/i1FGmCugyTWJIWJfU/7zNjrtvE99xehwqG/cfuGn5dZpLQALKGdK6PhpgXWA3MfAlDsm2jLKCAsd3IsSk8F8z2D4CYrf5m@kZ7fHLu@/5CQtQh7IsecfT27G8tEuCs@jpZ1ysIgtXkv1Aw "JavaScript (Node.js) โ€“ Try It Online") ### How? Given the current column \$x\$ and a horizontal jump distance \$dx\$, the helper function \$g\$ returns the 0-indexed row of the platform at column \$x+dx\$, or \$-1\$ if \$x+dx\$ is outside the playfield. ``` g = d => // d = dx k = // save the result in k a.findIndex(r => // for each row r in a[]: r[x + d] // test whether r[x + dx] is truthy ) // end of findIndex() ``` Starting with \$x=0\$, the recursive function \$f\$ attempts to find a way to the last column by trying all valid jumps and keeping track of visited columns. ``` f = ( // f is a recursive function taking: a, // a[] = input matrix x = 0, // x = current column m, // m = bit-mask of visited columns d = 4, // d = dx g = โ€ฆ // g = helper function (see above) ) => // !~g(1) | // success if g(1) is equal to -1 [...'1350531'] // list of exclusive upper bounds for dyยฒ // corresponding to dx = +3, +2, +1, 0, -1, -2, -3 .some(v => // for each upper bound v: ~g(--d) && // decrement d; success if g(d) is not equal to -1 m ^ ( // AND m is different from M = m | // the new bit-mask M 1 << x + d // where the bit corresponding to x + d is set ) && // AND (k -= g``) * k // dyยฒ = (g(d) - g(0))ยฒ < v & // is less than v f(a, x + d, M) // AND a recursive call at the new position is also true ) // end of some() ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 42 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ร•cรฐ รญ o v ร  cรก ยฎpV uWรƒd_รครˆcY รณ x_raรƒ<4 รƒr* ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1WPwIO0Kbwp2CuAgY%2bEgrnBWIHVXw2Rf5MhjWSDzIHhfcmHDPDQgw3Iq&input=WwoKW1swLDAsMSwwLDAsMV0sCiBbMCwwLDAsMCwwLDBdLAogWzEsMCwwLDEsMCwwXSwKIFswLDEsMCwwLDEsMF1dCgpdCi1t) [Test 1](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1WPwIO0Kbwp2CuEgY%2bAgrnBWIHVXw2Rf5MhjWSDzIHhfcmHDPDQgw3Iq&input=W1swLDAsMCwxLDBdLAogWzEsMSwxLDAsMF0sCiBbMCwwLDAsMCwwXSwKIFswLDAsMCwwLDFdXQ) [Test 2](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1WPwIO0Kbwp2CuEgY%2bAgrnBWIHVXw2Rf5MhjWSDzIHhfcmHDPDQgw3Iq&input=W1swLDAsMCwwLDFdLAogWzEsMSwwLDAsMF0sCiBbMCwwLDEsMCwwXSwKIFswLDAsMCwxLDBdXQ) [Test 3](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1WPwIO0Kbwp2CuEgY%2bAgrnBWIHVXw2Rf5MhjWSDzIHhfcmHDPDQgw3Iq&input=W1swLDAsMSwxLDAsMCwxLDBdLAogWzAsMCwwLDAsMCwwLDAsMF0sCiBbMSwwLDAsMCwwLDAsMCwwXSwKIFswLDEsMCwwLDEsMSwwLDFdXQ) Temporarily fixed by using permutations to allow backwards jumps (really inefficient) , going to try @Nick Kennedy solution soon. ``` z cรฐ รญ // get each column height and pair with column index o // save end position and remove from array v // same for start pos ร  cรก // combinations of permutations ยฎpV uWรƒ // restore end and start d // return true if any returns true to.. _ ... รƒr* // reduce result รค // pass each consecutive x,y รˆcY รณ // 'reshape~transpose' => [ platform pair, index pair] x_raรƒ // sum of absolute difference of each pair <4 // return if less for each pair ``` Saved 2 thanks to @Embodiment of Ignorance # [Japt](https://github.com/ETHproductions/japt) [`-Q`](https://codegolf.meta.stackexchange.com/a/14339/), 76 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ร•cรฐ รญ รฏรˆcY รณ x_raรƒ<4รƒยฎ*JรƒรฒUรŽl g0_ma @T=Uc x UgUy_x_>0}รƒรฐ _maรƒTยฅUc x}a o x >0 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=1WPwIO0g78hjWSDzIHhfcmHDPDTDripKw/JVzmwKZzBfbWEKQFQ9VWMgeCBVZ1V5X3hfPjB9w/AgX21hw1SlVWMgeH1hCm8geCA%2bMA&input=WwpbWzAsMCwxLDAsMCwxXSwKIFswLDAsMCwwLDAsMF0sCiBbMSwwLDAsMSwwLDBdLAogWzAsMSwwLDAsMSwwXQpdLApbWzAsMCwwLDEsMF0sCiBbMSwxLDEsMCwwXSwKIFswLDAsMCwwLDBdLAogWzAsMCwwLDAsMV0KXSwKW1swLDAsMCwwLDFdLAogWzEsMSwwLDAsMF0sCiBbMCwwLDEsMCwwXSwKIFswLDAsMCwxLDBdCl0sCltbMCwxLDEsMSwwLDAsMCwwLDAsMCwxLDFdLAogWzEsMCwwLDAsMCwxLDEsMSwxLDEsMCwwXSwKIFswLDAsMCwwLDEsMCwwLDAsMCwwLDAsMF0KXSwKW1swLDAsMSwxLDAsMCwxLDEsMCwwLDEsMF0sCiBbMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDBdLAogWzEsMCwwLDAsMCwwLDAsMCwwLDAsMCwwXSwKIFswLDEsMCwwLDEsMSwwLDAsMSwxLDAsMV0KXSwKW1swLDAsMCwxLDEsMSwxLDAsMSwwLDAsMF0sCiBbMSwxLDEsMCwwLDAsMCwwLDAsMCwwLDBdLAogWzAsMCwwLDAsMCwwLDAsMSwwLDAsMCwwXSwKIFswLDAsMCwwLDAsMCwwLDAsMCwxLDEsMV0KXSwKW1swLDEsMSwxLDEsMSwxLDEsMCwwLDAsMV0sCiBbMSwwLDAsMCwwLDAsMCwwLDAsMCwxLDBdLAogWzAsMCwwLDAsMCwwLDAsMCwwLDEsMCwwXSwKIFswLDAsMCwwLDAsMCwwLDAsMSwwLDAsMF0KXQpbWzAsMCwwLDAsMCwwLDAsMCwwLDAsMCwxXSwKIFswLDAsMCwxLDAsMCwwLDAsMCwwLDAsMF0sCiBbMSwwLDAsMCwwLDAsMSwwLDAsMCwwLDBdLAogWzAsMSwxLDAsMSwxLDAsMSwxLDEsMSwwXV0sCl0KLW0) Translation of [Jelly answer](https://codegolf.stackexchange.com/a/196602/84844) of @Nick Kennedy , a lot more efficient but longer , I think it can be shortened. ## Explanation / translation Jelly => Japt (taken from Nick answer) ``` ล’แนช => ร•cรฐ รญ M ultidimensional truthy indices of each แบกรพ` => รฏรˆcY รฒUรŽl O uter table using absolute difference and with the same argument on both sides: ยง => รณ x_ra Sum innermost lists <4 => รƒ<4รƒ Less than 4 N => ยฎ*Jรƒ Negate A1ยฆ => g0_ma Absolute top row รL => @T=Uc x...TยฅUc x}a Apply the following until no changes: On my side I used T to store the total of the whole matrix to check if it changed because g() modify the original matrix. A $ยฆ => Ug..._maรƒ Absolute the rows indicated by the following: ยป/ => Uy_x_>0} Max of each column : on my side I rotated the table and reduced to get the positive rows T => รƒรฐ Truthy indices (i.e. where thereโ€™s a 1 in the column) แนช => o Finally take the last row แน€ => x >0 Max : on my side >0 ``` [Answer] # [R](https://www.r-project.org/), ~~137~~ 136 bytes ``` function(a,e=abs(outer(b<-which(a,T),b,`-`)),g=-(e[,1,,1]+e[,2,,2]<4),h=1){while(any(g<{g[h,]=abs(g[h,]);g}))h=colSums(g>0)>0;rev(g)[1]} ``` [Try it online!](https://tio.run/##lVTLboMwELz3KyyfvOpSZaPeEvIT7S1FiiEGLBFAQFpFUb6dujTpA5tHJB@cZbw7M7vZqo3Z2mvjYx41usiFROXLsBbFsVGVCNfeR6qj1IRfAUPceTsATHxPqC0SIgWP5rJEXAbrZ8DUJzibB5kSMj@JZH1OtikGXcLuBqvkApD6UZG9HA8muFnAZrGq1LtIYEvBpY2LSmimc5bpuhEPjFWhzvciEgtkEweQdTC6HRvzFe9gZMd7D2/Z/mJcRQEHSLo5WGlHtNAo5keLLdnS4ibZg5FVfcjGSS10j@RroWEnnT2ie5ycb7hjEkbbTa7zy3leH@dYNKmFRmfSHo/51efPZO9vOFJ6st19df9J0p0kaXRX2JfrzwEnnZScBGjYE5P8AYCdTYFINkKWZXYS2mzVUtaNQrMiM1nWyuccsFalz99yDgZcN0UlE/V0KPZKaDDbm/GsSHQkM37NxZm3YRxZbL4j@354aT8B "R โ€“ Try It Online") Essentially an R translation of [my Jelly answer](https://codegolf.stackexchange.com/a/196602/42248), but with some R golfs to take advantage of the way `outer` works on arrays. A function that takes as its argument a logical matrix with the rows corresponding to the rows of the original question. Returns 1 for winnable and -1 for non-winnable. [Answer] # [Python 3](https://docs.python.org/3/), 198 bytes A messy solution with NumPy, takes a list of strings as input: ``` w=lambda l:t(g(array(where((array(list(map(list,l)))=='=').T)).T)) from numpy import* g=lambda p:abs(p[:,None]-p).sum(2)<4 t=lambda m,x=0:x+1==len(m)or max([t(m,p)for p in where(m[x])[0]if p>x]+[0]) ``` [Try it online!](https://tio.run/##hVJNb4MwDL37V@RGsrGq@ziheT9hp90Qh1SjLVISopQK@utZGiCYlmoIotjYz/bzs5fmWJv3vm9RSb37lUxlDT9w6Zy88PZYupKPhqpODdfShkuqhBCICSZi8yPCB3tXa2bO2l5YpW3tmic4TKg2k7sTt3mWftemLF6s2JzOmr@Jzw9opiCddrjNuudXRFUarkXtmJYdz33d1Iq9Ny2rDBva0nlXiHxbVHtmv7ri2V9F31bGyJ0qGbIcWJ4w8iQp@IMh4mD79oMHByP4x5irY8oq0gloSpyDltAY7Ql6KDZCR6Bg45yGeNvjiLJSzAdHoAH7Gvd/R/P4Mc8DQQFwNuukBUbwEfJKrZFCShpGJ95RdDfZLTQu2Z@8MQjXZsXlqofXH2FW6yrT8LzlSrCrmlRQ0zh9Idb/z/x4ffV0bqBaAiojoAoCoOKBBQKVDFC1hKQoFKAaASoPoMoAoKtbVlqWJbsCoGuiHVFwgoDjTLP8Hs0UKJr1BjQutIc3SRh5jYv7Aw "Python 3 โ€“ Try It Online") This assumes that no levels exist for which the bolded part here is of importance: > > To complete a jump, it must be possible to move from the start point to the end point in four or less (including the start/end points) up, down, left, and right moves **which do not pass through a platform**. > > > I have been unable to imagine such a level and none are given as a test case. ~~Likewise I can't imagine a level that requires a leftwards move so an appropriate test case there would be welcome also, if I'm mistaken.~~ Thanks to Nitrodon for pointing me in the right direciton. # [Python 3](https://docs.python.org/3/), 214 bytes ``` lambda l:t(g(array(where((array(list(map(list,l)))=='=').T)).T),[]) from numpy import* g=lambda p:abs(p[:,None]-p).sum(2)<4 t=lambda m,v,x=0:x+1==len(m)or max([t(m,v+[x],p)for p in where(m[x])[0]if x not in v]+[0]) ``` [Try it online!](https://tio.run/##hVNNb4MwDL37V/hGsmZV93FC81/YaTfGgWq0QyIhorSlv74LAYJpqValqH7Yz/bLq700v5V5u57p@1pmevuTYRk3Yi@yus4u4vyb17kYgrI4NEJn1v9QpZSSKKJIrr9k91VJKmFXVxrNUdsLFtpWdfMEexqIbZxtD8ImsfqsTJ4@W7k@HLV4lR/v0IxJWp1US5u4Xb0QlbkRWlY16qwViWuuTqukTZWVOwdaLAz2E2qHymSTFjts0VRN9@aUrhwir@fCmGxb5kiYACYRsk@kwD2QiPrYLeQR6gOPDzkdMFalaiQaC6ekOTWFeKTumw3UgcjHNJUR3c44sCw0c8mBqOfu8v6faFo/1DEidzhFKKZZGUaAKaQAR7OssxeRHg2zMN6gOteZAkh3qt6JcUtN8wsb0ZBES/LQ3B39cY8wEY7nbo8HAAUaR9IJZuvCNCI5i1Ji5@bSu3nQ0P2TFt9PKjtjX7l6wE0M3L/ArQvAXQszBu5V4Db1RcGhwM0J3JfALQnADTDvNG/LbhyAXzafiJMzBhp2mnz/aCcv0WR04Hl@PLopoqBruP4/ "Python 3 โ€“ Try It Online") A solution that incorporates leftwards movement, with tsh's test cases included. This cost quite a few bytes, I'll have to sleep on it to golf it more. ]
[Question] [ A venerated pass time of pedants is to point out that pictures of "Rubik's Cubes" (on t-shirts, posters etc.) are not actually solvable. The first thing that should be checked is that the cube is made up of the right pieces. To be solvable a cube needs six colors each with nine squares. The cube also needs each edge and corner unit (these are the smaller cubes that make up the cube) to be unique. Not only must they be unique but if two center pieces are opposite each other no edge or corner piece can contain both of those colors. Once you have a cube that is made up of all the right pieces you still need to verify it can be solvable. There are a couple of rules here, so I'll defer to an expert to explain them, the spoiler below explains how we can do this. If you are interested in solving the problem on your own you don't need to visit the site to understand or participate in this challenge. > > [Linked explanation](https://www.ryanheise.com/cube/cube_laws.html) > > > Your task is to take a pattern as input and determine if it is in fact a solvable Rubik's cube. To be solvable there must be a way to perform valid moves on a cube so that the cube has only one color on each face (and the different faces have different colors). Most Rubik's cubes have a standard coloring (White is opposite Yellow, etc.) you may not assume that the solve state follows this particular coloring. A valid move is either the clockwise or anti-clockwise rotation of a single face of the cube. With the rotation of the face of the cube any squares bordering the face are rotated as well, staying connected to the face they were previously touching. # IO You may take the cube in any reasonable manner. If your language has some builtin "cube-face" type, good for you, that is fine as input, other wise you can take a 2D array of the net, of the cube, 1 3 by 3 lists for each face. Just be reasonable. If you want to know if a specific format is acceptable comment or ping me in chat and I will add to the challenge to state its validity. Your input format need only support up to 9 possible colors. For output this is a decision problem so you should output one constant value for "Yes, this is a valid Rubik's cube" and one different constant value for "No, this is not a valid Rubiks cube". --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better. # Test Cases Here are test cases. They are formatted as the net of a cube with each square as a single letter. Different letters represent different colors. Any more testcases can be added upon request. ## Solvable ``` RRR RRR RRR GGGWWWBBBOOO GGGWWWBBBOOO GGGWWWBBBOOO YYY YYY YYY GRR GRR ORW WWRBWYBOOGGY GGRBWGYBBOOO OOGRWGYWWRBB WYO YYB YYB ``` ## Unsolvable ``` RRR RRR RRR GGGWWWBBBOOO GGGWWWBBBOOO GGGWYWBBBOOO YWY YYY YYY RRR RRR RRR GGGWWWBBBOOO GGGWWWBBBOOO GGGWWWBBBOOO YWY YYY YYY RRR RRR GGG GGYWYWRBBOBO GGYWWWROBOOO GGYWWWRBBOOO BBB YWY YYY RRW RRW GGG GGYWWYEOBROO GGYWWYEBBROO GGOWWYWBBROO BBB YYW YYO ``` [Answer] # [Cubically](//git.io/Cubically), ~~1664~~ ~~1631~~ 1089 [bytes](https://github.com/aaronryank/Cubically/wiki/Code-page) ``` โ‡’FD2F'R'D2RUR'D2RFD2F'U' โ‡’Ff1F' โ‡’LFf1F'L' โ‡’F'f1F โ‡’F2f1F2 โ‡’L'F2f1F2L โ‡’D'F'f1FD โ‡’LR'FLR'DLR'B2L'RDL'RFL'RU2 โ‡’LFf8F'L' โ‡’R'F'f8FR โ‡’Ff8F' โ‡’F'f8F โ‡’ULU'f8UL'U' โ‡’U'R'Uf8U'RU โ‡’F2f8F2 โ‡’Df15D' โ‡’D'f15D โ‡’D2f15D2 โ‡’UF2UF2D'L2B2U'B2DL2F2D2B2D2F2 โ‡’U'DL2UD'B2 โ‡’UF2UF2D'L2B2D'R2UR2F2D2B2U2B2 โ‡’BL'BU2D2F'RF'U2D2 โ‡’LD'F2U'B2U'RU2R'F2R2F2D'R2DF2D โ‡’B2URB2D2B2RB2U'D'L2D'B2 โ‡’B2LF'U'B2UFL'R2B2U'D2L2D'B2U โ‡’B2RB2D2B2RB2U'L2UD'F2U'F2B2 โ‡’D2R'FUB2U'F'RU2B2D'F2R2UF2UF2 โ‡’B2R2U'L'D2B2U2R'U2R2F2L2R2UR2 โ‡’D2L'B2U2F2RUL2U'F2R2U'R2U2F2DL2D' โ‡’UB2U'L2DL2B2DB2D'B2 โ‡’BR'BL2B'RBL2B2 โ‡’UF2B2U'F2B2U'F2L2R2B2R2 โ‡’R2U'F2DR2UF2D'R2DF2R2D'F2 โ‡’U'F2DF2UL2F2DL2DF2L2D2F2 โ‡’U2D'L2U'F2L2U'B2L2R2U'L2B2 โ‡’F2D'R2U2L2B2UF2L2U2F2L2UF2R2 โ‡’[f1]3 โ‡’[f2f37]3 โ‡’[f3f38]3 โ‡’[f4f39]3 โ‡’[f5f40]3 โ‡’[f6f41]3 โ‡’[f7f42]3 โ‡’[f8f43]2 โ‡’[f9f44]2 โ‡’[f10f45]2 โ‡’[f11f46]2 โ‡’[f12f47]2 โ‡’[f13f48]2 โ‡’[f14f49]2 โ‡’[f15f50]2 โ‡’[f16f51]2 โ‡’[f17f52]2 โ‡’[f18f53]2 โ‡’[f19f54]2 โ‡’[f20f55]3 โ‡’[f21f56]4 โ‡’[f22f57]5 โ‡’[f23f58]6 โ‡’[f24f59]7 โ‡’[f25f60]8 โ‡’[f26f61]9 โ‡’[f27f62]9[f27f62]2 โ‡’[f28f63]9[f28f63]3 โ‡’[f29f64]9[f29f64]4 โ‡’[f30f65]2 โ‡’[f31f66]3 โ‡’[f32f67]4 โ‡’[f33f68]5 โ‡’[f34f69]6 โ‡’[f35f70]7 rs[f36f71]8 ``` **Output if solvable: `Solved!`** **Output if unsolvable: (empty, no output)** Input should be formatted as a [Cubically cube-dump](https://tio.run/##Sy5NykxOzMmp/A8EAA) (see the `Debug` section). This was [explicitly allowed by the OP.](https://codegolf.stackexchange.com/questions/151476/is-it-a-rubiks-cube/152948#comment370294_151476) # Explanation This program takes the approach of using a [Devil's Algorithm](https://math.stackexchange.com/a/184762/383797) to iterate over every possible state of the cube in the same group as the solved cube. If the cube is solvable, it will be solved at some point before the algorithm has finished (assuming the [algorithm I used](https://web.archive.org/web/20130512024842/http://www.sam.math.ethz.ch/~efonn/stuff/docs/devalg.txt) works properly). Every line beginning with `โ‡’` (0x84 in Cubically's codepage) is a function definition; these functions build off of each other to make up the actual Devil's Algorithm. The first line to be executed is the last one: ``` rs[f36f71]8 ``` `r` reads a cube from stdin and sets the memory cube to it. `s` puts the interpreter into "solvemode", which means that it exits and prints `Solved!` if the cube becomes solved (after being unsolved) at any point. The rest of the commands (which simply repeat `f36f71` 8 times) correspond to the final algorithm at the bottom of the linked page: ``` (D) = (CP) = (CPT8) = [(CPC8)(CPT7)]8 (3,847,762,288,469,010,006,992 moves) (D) is the Devil's Algorithm. If you apply it to the cube, it will be solved at some point before you have done the algorithm once. As you can see, it is terribly long, nearly a thousand times more moves than there are possible positions. ``` # How can I run it? You can [try it online](https://tio.run/##XVE5rh0hEMzfKV5GCk3DMOkIEREhEVkT2F9qydKPbDnwCZz7iL7Ic3ezeJFmqeqtiubt26fPbx/f37@/Xr9@/CwZimkmQ@v6Vd7NQ1LkioKqqI6gYawAGICmzcBVSDZakTXRTOE383tBNS3zW/jtMKemNbVJVyptyKaypJJK9doZ9jp9dfbbmfOgaSQNI5lcyGa4EKgIBGm6F@AnmwoXdHaUKzBlwkceBWwVeubU/@XZNOhtlncYBVc1VwfdH68MhkjlBeh0sQd8LtA27s/80zaedOmgJlUisCR5S7J8Dsua1GaGke4j/3enehWxMg1l0euSKiIutkV@HGT2S58Zp@AtqrkKergxoYoWB1uvOlkamkayGNHFDPGsi7n@mOdb5pBp8l0bvKY9@YqOONAL10huY8W6nKZ2xz0UCfQ6VaV135HeyBgnm6rjSFNxDOugV6wler5epuwHcrcfAMgfC3vyaWEkfy4cCO3CkXD3HoSwcCL09xx@EuLCzhKGTRxh3AQIj008YdoECc9NAgW7SaTgNjkowCaJwjbgTgrbAVgKYR/XUYg3TgIUjjtM4imkO06CFM77mCRQtHeaJFJ09znJQRHuc4ElmCh6jSpYyidF1KiCacFbins93lGM@zKA4rHLPMW0nHqkeC6nPtBh2emXr4wjHe5Or9fz@bTWPuTnxo@Zcw4AvPeI@HDWCQSPAf/NcHUIQX8YJvsN), but that link doesn't work. TIO will almost definitely time out before this algorithm finishes (the maximum runtime for an interpreter is 60 seconds). If the cube is not solvable, this algorithm will take up to 11 million years for Cubically to finish (at ~15.2 million moves per second, which is what my [Cloud9 IDE](https://c9.io) gets). ~~Additionally, you need a *lot* of memory to perform 3 sextillion moves. Cubically can perform about 4 million moves per second, but the process will most likely be killed due to [overcommitted memory](https://stackoverflow.com/q/726690/6850771). It dies after 15 seconds on my VM with 512MB of memory.~~ Why should performing moves on an already-allocated flat array cost memory? Found a [memory leak](https://github.com/aaronryank/Cubically/blob/ca9e687ee89ed878109c0859d80bd74cf051aacb/src/rubiks.c#L178) (or twenty) and [fixed it](https://github.com/aaronryank/Cubically/commit/5c2181694214cc5e60fe7101e156cbc4ef6be762). [Here](https://tio.run/##tVY7bttAFOx5iu3YmkuJolqCYMWKwB4gMUAggKsEKXKC9DliLqLMvDePEo0I/iQGDA/5/m92Ofbj989fHj89Pf24XL6mb9XapPT75680pTGnqU5LzYclle0pPKWu1hzBSJvw3vr7HJY0w3hQUG22aj3qPdt7rtZOWfVmS3O1ntw61pGZxmrtowGmmRxGhyGzwMLX2qY0KCh/vhmqj6GaBzMuXh3mtMDYxDq9rdPkbfKekzetvRfUKmYr7EIimoN7jLBiLmsPz3Hbtrdtm873SnSNzD3FomaBoXdDdgNzzmqMMvYLwXPmzsU2H/lGs9l4PkjKDzGTuQuTBtqbe8XwsNC23BQr2ZOcioELDzTqethNyDZkbsXzaAfpkzkN2YjOUdjajPaINKdusMYaf8j@yNltuBj9GLGzX0FP88MOPpAfGTyA3EXOX6oHLz7vpF1Pwb/dsqLYSas4Ub7NRiKy@q2Pl66vDC5Gkm8/5yAZOefoNNcKnfxrm2MgL7aEb/Td8KnpdK@LjHGKmpCrtI2OjV@I@bmEP9Gdr1dhuFKgB5/UFkKon@4SznFb/@Y4F1GD8O2DmOQrcUd9Vq@vq9r6uZa4i1t/P@F541Rjd/FNjUGNvoZIC6aLT4UUP1PoiP3A4McFCaNvB3D6uUDPGLcD6JkzD11j3A7gdMIhcozbAZxONwSPcTuA0wmG7jFuB3A6nZAQxjnA6rStbH8QwNppVTRGhBD2oAA9ESOEXUxA7RgjhF0kQPUYI4R@a39oHmOEsGt1aBZjhLBrawgfY4Swa2HoH2OEsGtXyCBjhLBrW4ghY4Swa99Moo/PEX7tDd1j7B1EXNwIzHI8vYSIFz/QPea@EvHnTvxB@FjjjYh88QwxZK13IuroXCCQrPmPiHo6T8gna/9nRH3dCwgte30Qoo/uGcSZPT8Y0U/3F4rO3kLYdW9bakT3HOHXfYWIM/YOIi7EDDt2/UuIf7x0PyHhzH0lIk/3EmLOGm9EU3XWeCdeLn8A) is a much more readable version that behaves the same way. ### But I really want to see that it works! The first actual move that is executed in this devil's algorithm is `F2`, so the quickest cube to solve would be one scrambled with `F2`: ``` 000 000 555 113222133444 113222133444 113222133444 000 555 555 ``` This indeed executes in 0.007 seconds [on TIO](https://tio.run/##rZNLjhMxEIb3c4rsDGLTLj@6m2XL8sorSz4AjFQS0qxALDgBe47IRUJV/R06MMooaFDSX9e7yuXk8evHT48fnp6@nc8/v/@oharrrlAfRtOHe1AX@2pCM6nB6EQ2gUQgczvITZXiLKKYo7sqT5Fno@Z6kafKM2ivulyqds1aakfbpV5aLdZqtCHiaPtcQ@YdokuhfZAFgxT2qThMoaJJpJK5RyX5FtdooyETlUaiiiJHRoCMSqOI6@/w4jqNvocPQsDW3DbI9icrIzRpsgCrruORnIssTfKLvCxNKm1WqGuUNri0lC3p8sWsa7IxC8E94L/OtFm1Wd0HKtpvqKtqcx1b2@Mge77mOZxCtmjDNbLDoULTXmLso1llTehmKTqILQbNiy1mO4aXWxaT68rLBrd9PKX20Qnsws1SOlZsy@k2Lu6hqmG0vaum/r4juxGU0001HGnviGKD7IotxM436t6WvX5MIg7zATMFDssBM0UO6wEzJY7TATNljv6AmWaOdMBMC8dgME0qRgPmmjgmELrnmEHoxHEGoQeOCwg9clxB6InTBELPnDwIfeZEIPSFUwChr5wiiG3JadM1YfWc8nPCR5zmW0RE4LS8TMRFTus9RHTiPN1P5GTO/l@JzJkzvYaosnAOrydqrZzj/yL@FhPnBEKXn3m@JqzEeX5O@ALn5RYRETmvLxNxiefpHj58/vLev5vfcMg8i/A2n8@n02mapofjleR37H0gIh9ClL/ibeXPJLx@AQ). # How can this be improved? There are certainly more devil's algorithms; I've found one that uses less than a thirtieth of the moves this one does. However, that would come at the cost of several thousand bytes (around 100MB more) and several dozen hours of converting a complex Hamiltonian circuit to Cubically code. It's also possible to remove some of the functions and put them straight in the loop at the bottom. However, I'm going to sacrifice some bytes for some readability. Additionally, I'm considering a modification of Cubically's looping behavior so that I can more easily repeat algorithms 7 or 8 times (instead of just hard-coding them with the function calls repeated 7 or 8 times in the source). Or I'll work some magic out with the notepad, and golf this using more loops. Note that I will continue to optimize anything possible in the interpreter, so this may work on an average PC sometime in the future! --- # Cubically, 2 bytes ``` rโ–ฆ ``` I like the above answer better so I'm adding this as an alternate solution. This runs in under a second, as opposed to a few million years. ``` r read cube from standard in โ–ฆ and solve it ``` **Output if the cube is solvable:** (nothing) **Output if the cube is unsolvable:** `Error: The cube has reached an unsolvable state.` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~190~~ 174 bytes ``` {โˆง/~โˆŠ(ร—1 2 3|+.-โŒฟโ†‘โŠƒโˆ˜โ‹ยจยจยจa)({2|โ‰ขโˆช{โตโŒŠโต[โต]}โฃโ‰กโต,0}ยจโณโŒฟโ†‘โŒฝb)((โˆชโ‰ขโˆฉ)ยจ/bโ†(โŠƒโˆ˜โ‹โŒฝโŠข)ยจยจยจa),6โ‰ขโ‰ขโˆชโŠƒโŠƒaโ†{cโ†4โดโŠ‚โฌโ‹„c[+/1โ‰ i],โ†(โ‰ /ร—iโ†โ†‘โณ3โด3){โŠ‚โŒฝโฃโบโŠขโต~' '}ยจ,โŒฟ(3|โˆ˜.+โจโณ3)โ‰โคยฏ1โ†‘1 0 1\โตโ‹„1โ†“c}ยจโต(3 3โˆ˜โดยจ1 1โˆ˜โŒทยจโต)} ``` [Try it online!](https://tio.run/##pZLPaxNREMfv@SvebXdJ0uxmJaDHB2UPgg/28njUHtJIJRCoUC@SpIe2lOwmWxTRepIaBaMIHtogCEVI/5P5R@J3XnZrLKlYJcn82J35zHeGNJ90qo@eNTs7j6utTnN3t92a0/Gr9g4dPffn27BdGnys7dEgdS9PAlEXYa@8VqXRDzp6QekBDd5QNpxN@NP03G69R8mYBp@7lE1plMJu4LfZp@w9Je8QVvz@bELZWU4YXWx5rosG2/bJm01qWxjqXqFRQenYKyZUGlxoR3BJetBkiS2YO5SdU7pP2RcaHrY2yrWAktP2ZsXSktPa5UkbIc/MzkLUhl6Xy4GHtOw7hkDdniMc6KtAnRv2oGCtTBnLDT3KEso@zL4GQATCF8FDXnF4iPxly@40dUMRWtXns0kgAg5H3@wbrz9/am@JlmS8LUJRR5UDJgYyeXTBgbUcpK85QPkxpFUc5rLwKYvjKR7MXTY@m4bn@vysAQM1mJjuF8vyfm9v@t5zdKweRE4bezjqvgOVIigJIeI4vuaiKNJaSymVUn9IUG2MueZKOTVa4HKnYl3SOpbaoDOKDEBIIrMA4VGMhAskV2uTw2XhQPX/RatZ1qpXaPX/@wJ/SUUfelHNSyqpbIKNVU61yRVVLg6xBP9F1UuuoGqzrmRcgMy6zBOl7Qni36lGL5y66QJy5QXi2/4HbkVVxZtoNfUn "APL (Dyalog Classic) โ€“ Try It Online") The argument is a 3x2 matrix (row0: front back, row1: left right, row2: up down) of 3x3 character matrices. Returns 1 for a solvable Rubik's cube, 0 otherwise. In the TIO link, function `t`, which is not included in the character count, reads 9 lines of input, converts them from the default input format (a net) to the required 3x2 x 3x3 matrix, calls the solution and prints OK if the result is as expected. The algorithm splits the given cube into 26 cubies - strings of length 3 (corners), 2 (edges), and 1 (centres). It also generates the 26 cubies of a solved cube with the same 6 central cubies. All of the following criteria must be met: * there are no duplicates among the 6 centres * the sets of given/solved cubies match, up to rotation - e.g. consider `'WBR'` and `'BRW'` the same cubie, but not `'BWR'` * the parities of both the corner permutation and the edge permutation are even * the modulo-3 sum of corner rotation indices (e.g. taking the "smallest" letter `B` as a reference point we have: `'BRW'โ†’0`, `'WBR'โ†’1`, `'RWB'โ†’2`) match between the given and solved cubes; same for the corners modulo 2 ]
[Question] [ > > [Brain-flak](https://github.com/DJMcMayhem/Brain-Flak) turns one year old tomorrow! In honor of it's birthday, we're having a PPCG style birthday party, where several users post brain-flak related questions! [Help us celebrate!](https://hackmd.io/KwRgnARiAcCGAsBaaEBMAGR8DG8Cmis0AZsVhPLOtsWAOzQAmIQA?view) :) > > > --- Brain-flak is an esoteric language I wrote where all of the commands are brackets and all of the brackets must be fully matched. To borrow [my own definition](https://codegolf.stackexchange.com/q/77138/31716): * For the purpose of this challenge, a "bracket" is any of these characters: `()[]{}<>`. * A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as ``` () []{} ``` Or if every subelement inside of it is also matched. ``` [()()()()] {<[]>} (()()) ``` Subelements can also be nested several layers deep. ``` [(){<><>[()]}<>()] <[{((()))}]> ``` * A string is considered "Fully matched" if and only if: 1. Every single character is a bracket, 2. Each pair of brackets has the correct opening and closing bracket and in the right order In celebration of brain-flak's first birthday, today's challenge is about taking an unbalanced set of brackets, and determining what types of operations are needed to make it valid brain-flak. * For example, `((` is not valid brain-flak code, but if we append `))` to it, it becomes `(())`, which is fully balanced, and therefore valid brain-flak. That makes this input *appendable*. * Similarly, `>}` is not valid, but we can prepend `{<` to it to make `{<>}`, which is valid. That makes this input *prependable*. * Some inputs are slightly more complicated. For example, `)][({` cannot be made valid purely by appending or prepending. But it *can* be made valid by prepending `[(` and appending `})]`. Therefore, this input is both *prependable* and *appendable*. * Lastly, some inputs can never be made valid brain-flak code by any combination of appending or prepending. For example, `(>` can never be made valid. (Prepending `<` creates `<(>`, and appending `)` creates `(>)`, neither of which are valid) Therefore, this input is neither appendable or prependable. For today's challenge, you must write a program or function that takes a string of brackets and determines if the string is ``` appendable prependable both neither ``` You may pick what values you use to represent for each case. For example, outputting `1, 2, 3, 4`, or `'a', 'p', 'b', 'n'`, or `1, 'foo', 3.1415, -17`, or whatever is fine. As long as each output is *distinct* and *consistent*, that's fine. You *must* however, clearly specify which output corresponds to which case. You may return this value in whichever format is most convenient (for example, returning from a function, printing to STDOUT, modifying arguments, writing to a file, etc.). You can assume that the input will never be valid brain-flak or empty. # Examples The following inputs are all *prependable*: ``` )) (((()()())))} )>}] ()[]{}<>) ``` These are all *appendable*: ``` (({}{}) (((( ([]()())( {<<{ ``` These are all *both*: ``` ))(( >()[(()){ >{ ``` And these are all *neither*: ``` )(} {(((()()()))> [} ((((((((((> ((((((((((<>()] ``` As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard loopholes apply, and the shortest answer in bytes wins! --- This challenge is particularly difficult in brain-flak, so maximum [brownie points](https://en.wikipedia.org/wiki/Brownie_points) to any and every answer written in brain-flak. :) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~33 32 37 35~~ 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *bug found, horrible fix +5 bytes, better fix - 2 bytes, using a trick of Adnan's I saw [here](https://codegolf.stackexchange.com/questions/117996/find-the-first-bracket-match#comment289022_118011) for -1 more.* ``` โ€œ({[<โ€œ)}]>โ€Z;@Wล“แนฃFยฅ/ยตรLOโ€˜&2ยตIแน€>0ศฏQ ``` Return values: ``` prepends [2] appends [0] both [2,0] neither 1 ``` (Invalid input returns spurious results, although valid Brain-flack, returns `[]`.) **[Try it online!](https://tio.run/nexus/jelly#@/@oYY5GdbQNkNKsjbV71DA3ytoh/OjkhzsXux1aqn9o6@EJPv6PGmaoGR3a6vlwZ4OdwYn1gf@BynRTTyx/1LjjxPrD7VwPd2853P6oaU3k//@6ugoFRakFqXkpxVyamlwaQKAJgkBQy6VpVxvLpaEZHVtda2OnyQVUm1gAUaqhUV1bXQtRz6URHQvWosFVbWNTDVKWlF@SATQOKGcH1A40UrOay65aA2xEXmpmSUZqEZemRi1XNZJ9dlzRtWDzIMAOiW0DNAXokNhoTa5Ym9hqDQA)** - a test suite (prints mushed representations, so `20` for `[2,0]`, and ignores lines containing any `-`). [Answer] # [Retina](https://github.com/m-ender/retina), ~~41~~ ~~40~~ 41 bytes *1 byte saved thanks to @MartinEnder* ``` +`\(\)|\[]|{}|<> []})>]+ 1 \W+ 0 ...+ 01 ``` [Try it online!](https://tio.run/nexus/retina#TYxBCgMxCEX3/x4FJRA6@@C2R@jCCHMP49nT35nNfBFFH@8ln3O3c8rUNT1W1hoGeJRaNByY34Y3eu8cx96qEEb/xRTUKiDqkTVMwW9W1k1BPC5QkGMkwE1gpGnQhPEk4QpNYnSx86E3eF2iO/bYBy3xAw "Retina โ€“ TIO Nexus") * Prependable is `1` * Appendable is `0` * Both is `10` * None is `01` ### Edits * Gained 1 byte to fix bug noticed by @Neil [Answer] ## Batch, 337 bytes ``` @echo off set/ps= :g set "t=%s:<>=% set "t=%t:()=% set "t=%t:[]=% set "t=%t:{}=% if not "%t%"=="%s%" set "s=%t%"&goto g set "s=%s:<=[% set s=%s:>=]% set s=%s:(=[% set s=%s:)=]% set s=%s:{=[% set s=%s:}=]% :l if %s:~,2%==]] set s=%s:~1%&goto l :r if %s:~-2%==[[ set s=%s:~,-1%&goto l if not _%s:~2%==_ set s=[] echo %s% ``` Outputs `]` for prepend, `[` for append, `][` for both, `[]` for neither. [Answer] # [Haskell](https://www.haskell.org/), ~~115~~ 108 bytes EDIT: * -7 bytes: Use more guards. ``` (""#) s#""=[s>"",1>0] s#(c:d)|Just a<-lookup c$zip"([{<"")]}>"=(a:s)#d|(a:b)<-s=[1|a==c]>>b#d|0<1=take 1$s#d ``` [Try it online!](https://tio.run/nexus/haskell#TUxBjoMwDLz7FchwsKUtKtcq8QP2C1EOKaVa1BZQA1ppQ97OuvTS8cEz4xk/Qj/Yfpi7Z2jnahnu/dDF@hEmij/jb33lene2qyXEkiGWiNZFQfxq5OhVU3u68Pq9xLkI5nAfx9syFW31109ILhlE9lnQUjhFLi@r7jObQ7SuWYO1rRc5q300jZ3DrSuaKpaXbWMGUvBrFBlYsgdi51M28jqmnPI7BOT8niNIxiRQQiCa1T4nEHUoQ/r4J@DyXn1DPrjRood/ "Haskell โ€“ TIO Nexus") Use like `(""#) "))"`. Results are given as: ``` [False,True]: needs nothing [False]: prependable [True,True]: appendable [True]: both []: neither ``` # How it works * The output encoding is chosen such that a need to prepend is signaled by dropping the second element of the result for the remainder, if any, while a complete mismatch is signaled by dropping all of them. * `s#d` parses a remaining string `d`, given a string/stack `s` of expected closing brackets. + The `s#""` line checks if all closing brackets have been found by the end of the string, otherwise appending is needed. + The first branch of `s#(c:d)` checks if the next character `c` is an opening bracket, and if so leaves the corresponding closing bracket on the stack for the recursion. + Otherwise, if the stack contains closing brackets, the second branch checks if the top one matches the next character, and if not, returns an empty list instead of recursing. + Lastly, in the last branch the stack is empty, and we have an unmatched closing bracket that may be fixed by prepending, before recursing. [Answer] # [Japt](https://github.com/ETHproductions/japt), 44 bytes ``` =Ue"%(%)|%[]|\{}|<>" ยฎc -1&2|1})f31 |UfD |Ug ``` Outputs `1` for prependable, `3` for appendable, `13` for both, and `31` for neither. [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=PVVlIiUoJSl8JVtdfFx7fXw8PiIgrmMgLTEmMnwxfSlmMzEgfFVmRCB8VWc=&input=IigoKCgoKCgoKCg8PigpXSI=) or [Verify all test cases at once.](http://ethproductions.github.io/japt/?v=1.4.4&code=PVVlIiUoJSl8JVtdfFx7fXw8PiIgrmMgLTEmMnwxfSlmMzEgfFVmRCB8VWc=&input=WwogICIpKSIKICAiKCgoKCkoKSgpKSkpfSIKICAiKT59IgogICIoKVtde308PikiCgogICIoKHt9e30pIgogICIoKCgoIgogICIoW10oKSgpKSgiCiAgIns8PHsiCgogICIpKSgoIgogICI+KClbKCgpKXsiCiAgIj5deyIKCiAgIikofSIKICAieygoKCgpKCkoKSkpPiIKICAiW30iCiAgIigoKCgoKCgoKCg+IgogICIoKCgoKCgoKCgoPD4oKV0iCl0gLW0=) ### How it works ``` =Ue"%(%)|%[]|\{}|<>" ยฎ c -1&2|1})f31 |UfD |Ug U=Ue"%(%)|%[]|\{}|<>" mZ{Zc -1&2|1})f31 |UfD |Ug // "(((()()())))}" "([({}{})" ">()[(()){" "((((<>()]" Ue"%(%)|%[]|\{}|<>" // Recursively remove all instances of "()", "[]", "{}", and "<>" from U. // "}" "([" ">[{" "((((]" mZ{Zc -1&2|1} // Replace each char Z with (Z.charCodeAt() - 1) & 2 | 1. // "1" "33" "133" "33331" U= // Save the result in U. f31 |UfD |Ug // Match all instances of "31" and "13" (D = 13) and bitwise-OR the results with the first char. // null|null|1 null|null|3 null|13|1 31|null|3 // 1 3 13 31 // Implicit: output result of last expression ``` [Answer] # PHP, 137 Bytes ``` for($c=1;$c;)$a=preg_replace("#<>|\(\)|\[\]|\{\}#","",$a=&$argn,-1,$c);echo($a=preg_replace(["#[]})>]+#","#[[{(<]+#"],[1,2],$a))<13?$a:0; ``` 1 =>appendable, 2 =>prependable, 12=>both, 0 =>neither [Testcases](http://sandbox.onlinephpfunctions.com/code/dd0cd30cf376d398620fc72d3f4259e2a15db5df) ]
[Question] [ ## Background [Incident](http://esolangs.org/wiki/Incident) is a fairly unusual programming language, in that its list of tokens is not predetermined, but rather inferred from the input. As such, tokenising an Incident program can be fairly difficult, especially if you want to do so efficiently. This task is about doing that yourself. ## The task Your program will be given a string as input. Here's the algorithm that Incident uses to tokenise it: 1. Identify all strings that occur as a substring of the input in exactly three ways (i.e. there are exactly three occurrences of that string within the input). 2. Discard any of these strings that are a substring of another such string (e.g. for input `ababab`, the only remaining string would be `ab`, not `a` or `b`, because `a` and `b` are both substrings of `ab`). 3. Discard any strings that overlap within the input. (For example, `aaaa` contains exactly three copies of `aa`, but these copies overlap at the second and third characters, so would be discarded. Likewise, in `abababa`, there are three copies of `ab` and three copies of `ba`, but the second to sixth characters are each at the overlap of an `ab` and a `ba`, so both `ab` and `ba` would be discarded). 4. Any strings that remain at this point are the tokens used by the program. Tokenise the original input into a sequence of these tokens (due to the discarding in the previous step, there will only be one way to do it). Any characters in the input that aren't part of any token are treated as comments and discarded. Your program has to take a string as input, and return the corresponding tokenisation of the string (a list of tokens, each of which are expressed as strings) as output. Additionally, this has to be done at least moderately efficiently; specifically, the program has to run in **quadratic time** ("O(nยฒ)") or better. (Incidentally, it's almost certainly possible to go faster than quadratic, but this is not [fastest-algorithm](/questions/tagged/fastest-algorithm "show questions tagged 'fastest-algorithm'"), so feel free to use the tersest algorithm you can find that fits within the complexity bounds.) ## Clarifications * Although Incident programs can in theory contain any of the 256 octets, it's acceptable for the purpose of this challenge for your program to handle only inputs formed out of printable ASCII (including space), plus newline and tab. (All known Incident programs restrict themselves to this subset). Note that space/newline/tab aren't special and can appear in the middle of tokens; Incident treats all 256 octets as opaque. * The definition of "quadratic time" is "if the size of the input is doubled, the program will run slower by no more than a constant plus a factor of 4", i.e. if *t*(*x*) is the maximum time your program takes to process an input of size *x*, then there must be some constant *k* such that *t*(2โ€‰*x*) < 4โ€‰*t*(*x*) + *k* for all *x*. Bear in mind that comparing strings takes time proportional to the length of the strings. * Your program should theoretically be able to handle input programs of any length if run in a (possibly hypothetical) variant of your language that has unlimited memory and uses unbounded integers (it's OK if the program fails to achieve this goal when run in practice due to the language's integers or memory actually being finitely large). You may assume (for the purpose of calculating the complexity) that integers that are no greater than the length of the input can be compared in constant time (although bear in mind that if you use larger values, e.g. due to converting the input into a single integer, they will take a length of time to compare proportional to the number of digits they have). * You can use any algorithm that fits within the complexity bounds, even if it doesn't follow the same steps as the algorithm posted above, so long as it produces the same results. * This puzzle is about tokenising the input, not really about formatting the output. If the most natural way to output a list in your language involves an ambiguous format (e.g. newline-separated when the strings contain literal newlines, or without delimiters between the strings), don't worry about the fact that the output ends up ambiguous (so long as the list is actually constructed). You may want to make a second version of your submission that produces unambiguous output, to aid in testing, but the original version is the version that counts for the scoring. ## Test case For the following input string: ``` aaabcbcbcdefdfefedghijghighjkllkklmmmmonono-nonppqpq-pqprsrsrstststuvuvu ``` your program should produce the following output list: ``` a a a bc bc bc d e f d f e f e d gh gh gh k l l k k l pq pq pq u u u ``` ## Victory condition This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid (i.e. correct input/output behaviour and sufficiently fast to execute) program, measured in bytes, wins. [Answer] # C (gcc), 324 bytes The function `f` takes a null-terminated string and prints the tokens to stdout. All newlines can be removed from the code below. ``` f(char*s){ int n=strlen(s),b=0,z[n-~n],F[n+1],u,a,x=0,l,m,*t=z+n; int K(i){~m&&s[i]^s[a+m]?m=t[m],K(i):++m;} for(;b<2*n;){ for(a=b++%n,m=l=-1;a+l<n;K(a+l))t[++l]=m; for(l=0;l<n;++F[m])K(l++),F[l]=z[a]*=b>n?m^z[a]||~(m=t[z[l-m]]):0; for(printf("%.*s",z[a],s+a);n/b*l&&a+l>x;l--)F[l]^3?F[t[l]]+=F[l]:(a<x?z[u]=0:(z[u=a]=l),x=a+l); } } ``` This older 376-byte version is a little easier to read; the explanation below applies to it. ``` *t,m; char*p; K(c){for(;~m&&c^p[m];)m=t[m];++m;} k(i){for(*t=m=-1;p[i];t[++i]=m)K(p[i]);m=0;} f(char*s){ int n=strlen(s),z[n-~n],F[n+1],u,*Z=z,a=0,x=0,l; for(t=z+n;a<n;a++){ p=s+a; for(k(l=z[a]=0);l<n;++F[m])K(s[l++]),F[l]=0; for(;l&&a+l>x;l--)F[l]^3?F[t[l]]+=F[l]:(a<x?z[u]=0:(z[u=a]=l),x=a+l); } for(p=s;*p;printf("%.*s",*Z++,p++)) for(k(x=0);x<n;m==*Z?*Z*=!!z[x-m],m=t[m]:0) K(s[x++]); } ``` `k(0)` generates the table `t` for pattern `p` for the Knuthโ€“Morrisโ€“Pratt algorithm. `K(c)` process the next character `c` of the search string and updates `m`, the length of the largest prefix of `p` which can be found ending at the most recently processed character. In the first `for` loop, for each index `a` in the string, we count the number of times each possible value of `m` occurs when searching in the entire string for the substring beginning at `a`. Then we look for the largest `l` such that the length-`l` substring starting at `a` occurred exactly 3 times. If it's short enough to be entirely contained by a string found for a previous `a`, we ignore it. If it overlaps, we delete the previous string from `z`, the array recording which tokens will be kept. Otherwise, its length is stored in `z`. Then, we use KMP again to search the string for the tokens recorded in `z`. If one of them is found at a location with a 0 entry in `z`, we know that this token was deleted due to overlap. If the token was not deleted, it is printed. [Answer] ## JavaScript, ~~878~~ ~~867~~ ~~842~~ ~~825~~ ~~775~~ ~~752~~ ~~717~~ ~~712~~ ~~704~~ ~~673~~ ~~664~~ ~~650~~ 641 bytes Thanks to @Kritixi Lithos for helping golf the code Thanks to @User2428118 for golfing off 14 bytes (Will not work in IE7) (Newlines should be entered as "`\n`" and tab as "`\t`" in the input string, any unicode characters should be entered as `\u####`) ``` w=>{for(a=[],b=[],c=[],d=[],f=[],e=[],k=0;k<(g=w.length);a[k++]=h)for(b[R='push']([]),h=[d[k]=f[k]=j=i=0];i++<g-k;){while(j&&w[k+i]!=w[k+j])j=h[j-1];w[k+i]==w[k+j]&&j++,h[R](j)}for(k=0;k<g;k++)for(j=i=0;i<g;i++)if(w[i]!=w[k+j]){while(j&&w[i]!=w[k+j])j=a[k][j-1];w[i]==w[k+j]?i--:b[k][R](j)}else b[k][R](++j);for(k=0;k<g;c[k++]=l){for(h=f.map(Q=>i=l=0);i<g;)h[b[k][i++]]++;for(;i;)h[i]==3?(l=i,i=0):a[k][--i]?h[a[k][i]]+=h[i+1]:0}for(k=0;g>k++;)for(i=0;(S=c[k])&&i<g;)b[k][i++]==S?d[i-S]=S:0;for(k=0;k<g;k++)for(e[R](w.slice(k,(S=d[k])+k)),i=1;i<S;)f[k+i]=1,f[k]|=S<d[k+i]+i++;f.map((X,i)=>(P=e[i],X?e=e.map(Y=>P==Y?"":Y):0));return e.join``} ``` [Try it Online](https://tio.run/nexus/javascript-node#bVP/d5s2EP99fwUxWSwZAxJOnMYgnGzz@rbXt5fV615bRGxsBAgTcGLc0ObLv56dsNtme@PQ6b6g@9ydjhv2fMf8@6S6RRELwv5CsaVisWKJYkKxFSPuykMpu7MKUaZ1ht0oWBlGyDKsTi@Ct6y73m6yboiCEPczFsTBKmSJYjmTjISuNAwvNVcuvr/LZCFQfnR0BzFkeMDUnoc4Z1mQmzR0d3a2tx8d5YbRz4K3Icrxo4LbpZO6kEEL3yK4EiwAgmWC7oIXYV/i/QsNSgi/An6HG0vTHC2Uawcoio3QvuqGkWP3ZQrLXRsK3HYxY4l1Ha3Rn8yXrGAEt0nhLGjPQ3JhaBjteVcqs0IdjFHBZB8qwKM2I9OU4TgLWlnCAeiKNGg4It9qT30AddvSVeFoyiCNEB8dtWjfsBibjuNAmtOQTUfE/b/OCVXUnbUp5FKgVR8iqXvDxgpjyIhC@lPA2V0H7avrfGBTL24NhlS1tPWi932JmY8umYCU@@/HgonW8YH5l4x9GHc6ow94RDB2b0W9vS01YeWVLOfzx@dlVW6qQlhFlaIb1ImiaLFUFIskTkQi4jSTOaw0y1dFsVoV1/BUJZAJbL2@Wd@YwG43impF209AHYx/@E9oXdMo79Ah72iObX/iHJ3rtlsegw0WL3W7Nx9o0TaKPno@Hdq84/HO0F5YN@e8g5Hj4CmE4PWONDjw@TOv3cHw4Bxk5Sh1xmsftgBc8JKCXDeErugKJNmQvCEZyWhMKb0k4h1ZNGRBKhoDF0CkAVGSpCEpKUlJaUMqEJYNWYKQAE@VK4EgOZAkRMVWENekoO1DCLqaYchg7s15/cDL9a0sa4TEp6hAUCjnjZM4UE5Uxkg70zAMAR1oGJuIgEk7xlfU89DwBPs@GjoY/F3E@b1aj7jlAcIhflTS14W7@vEQvTLO9sQOsE4fmM2o7Ryzhp0F3qFxbpjn8DDf8PbbWPcNyzSt0OblbPbLxV8Xsxmjug2qbnFuQbqQaU/1Fa6npdbJFiKVJa/bD@Ht2W3rYWBkKXj9RdO0jfwiqqS77Jp0zDuDV7wzgu20vWVZLottLLxNHcvKynx1GHqkXUeyRFjT7J6Ki/Bcn3Pe7dn36229QV@w@2j3uvM5Lw@76tPuPgFzUB1X@uHhIS89f/CH5fl7R9Mo9uPT05PBa@OpV9d1z2r2Diag2ZrW1rMvbV@dTkJdLLNKc6AV0PDg14uf@9QzdacVpu9@0pV28l11QB0o9c3k9eTtZPK@Ty/fTC6mk9e//T15d7mTobBoDdFnT@XvD3p1ApMA@AqOb2GMFnGaSmcnqsGhD8ND2@52nRNN831f951TaxN91jWm7yaKnmL9anY1O30zAbWMtxsEg3Dg@UYIDbTtj47jnJ2d2QP4OTrOEH7H538A) ## Explanation of how it works and ungolfed code First, the program generates Knuth Morris Pratt arrays for every possible substring; ``` for(index=0;index<word.length;index++){ kmpArray=[0]; j=0; for(i=1;i<word.length-index;i++){ while(j&&word.charAt(index+i)!=word.charAt(index+j)){ j=kmpArray[j-1]; } if(word.charAt(index+i)==word.charAt(index+j)){ j++; } kmpArray.push(j); } kmpArrays.push(kmpArray); } ``` Next, the program finds the maximum matching lengths at every single index in the word with each substring. (this is O(n^2) time) ``` for(index=0;index<word.length;index++){ j=0; matchLength=[]; for(i=0;i<word.length;i++){ if(word.charAt(i)!=word.charAt(index+j)){ while(j&&word.charAt(i)!=word.charAt(index+j)){ j=kmpArrays[index][j-1]; } if(word.charAt(i)==word.charAt(index+j)){ i--; }else{ matchLength.push(j); } }else{ j++; matchLength.push(j); if(j==kmpArrays[index].length){ j=kmpArrays[index][j-1]; } } } matchLengths.push(matchLength); } ``` The program uses this data to find the longest substrings that appear three times for each starting character in the string. ``` for(index=0;index<word.length;index++){ counts=[] max=0; for(i=0;i<=word.length;i++){ counts.push(0); } for(i=0;i<word.length;i++){ counts[matchLengths[index][i]]++; } for(i=word.length-1;i>0;i--){ if(counts[i]==3){ max=i; break; } if(kmpArrays[index][i-1]){ //if this value has a smaller value it could be as well counts[kmpArrays[index][i]]+=counts[i-1]; } } maxLengths.push(max); } ``` The program uses this data to eliminate all substrings that do not appear exactly three times and all substrings of the longest valid substrings. ``` for(index=0;index<word.length;index++){ if(!maxLengths[index]) continue; for(i=0;i<word.length;i++){ if(matchLengths[index][i]==maxLengths[index]){ tokens[i-maxLengths[index]+1]=maxLengths[index]; } } } ``` Next, the program sets all overlapping or partial substrings as to be removed. ``` for(index=0;index<word.length;index++){ sStrs.push(word.substring(index,tokens[index]+index)); for(i=1;i<tokens[index];i++){ toRemove[index+i]=1; if(tokens[index]<tokens[index+i]+i){ toRemove[index]=1; } } } ``` For each of the to be removed values, all equivalent substrings are removed as well. ``` for(index=0;index<word.length;index++){ if(toRemove[index]){ removal=sStrs[index]; for(i=0;i<3;i++){ indxOf=sStrs.indexOf(removal); sStrs[indxOf]=""; toRemove[indxOf]=0; } } } ``` Finally, the program joins the array of substrings together and outputs it. ]
[Question] [ Write a program or function that given two integers *a, b* outputs a string containing a decimal number representing the fraction *a/b* **exactly**. If *a/b* is integer, simply output the value, without a decimal dot or leading zeroes: ``` 123562375921304812375087183597 / 2777 -> 44494913907563850333124661 81 / 3 -> 27 -6 / 2 -> -3 ``` If *a/b* is not integer but has a finite representation in base 10, output the value without leading or trailing zeroes (except a single zero before the dot): ``` 1 / 2 -> 0.5 3289323463 / -250000000 -> -13.157293852 ``` Finally, if **and only if** (so no `0.999...`) *a/b* is not integer and does not have a finite representation, output the finite part followed by the repeating part in parenthesis. The repeating part must be as small as possible, and start as early as possible. ``` -1 / 3 -> -0.(3) 235 / 14 -> 16.7(857142) 123 / 321 -> 0.(38317757009345794392523364485981308411214953271028037) 355 / 113 -> 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168) ``` --- Your program must work for all above examples in under 10 seconds on a modern desktop PC. Smallest program in bytes wins. [Answer] ## Python 2, 174 bytes ``` x,y=input() a=abs(x) b=abs(y) r=a%b*10 L=[] M='' while~-(r in L):L+=r,;M+=str(r/b);r=r%b*10 i=L.index(r) t=M[:i]+"(%s)"%M[i:]*(M[i:]>'0') print"-%d."[x*y>=0:(t>'')+3]%(a/b)+t ``` I'm not quite convinced about the validity of this answer, but it's worked for the test cases above and other test cases I've thrown at it. It looks like a right mess though, so I'm sure there's plenty of room for golfing. The initial setup takes absolute values of both arguments to ensure that we're dealing with nonnegative numbers (saving the sign calculation for later), and delegates the quotient part of the result to Python's arbitrary precision arithmetic. The fractional part is done with the grade-school division algorithm until we get a repeat in the remainder. We then look up when we last saw this repeat in order to get the period, and construct the string accordingly. Note that the algorithm's actually quite slow due to the O(n) `in` operation, but it's fast enough for the examples. [Answer] ## Batch, ~~349~~ 344 bytes ``` @echo off set/ad=%2,i=%1/d,r=%1%%d if not %r%==0 set i=%i%.&if %r% leq 0 set/ar=-r&if %i%==0 set i=-0. set d=%d:-=% set/ae=d :g if %r%==0 echo %i%&exit/b set/ag=-~!(e%%2)*(!(e%%5)*4+1) if not %g%==1 set/ae/=g&call:d&goto g set/as=r set i=%i%( :r call:d if %r%==%s% echo %i%)&exit/b goto r :d set/ar*=10,n=r/d,r%%=d set i=%i%%n% ``` Edit: Saved 5 bytes by removing unnecessary characters. "Ungolfed": ``` @echo off set /a d = %2 set /a i = %1 / d set /a r = %1 % d if not %r%==0 ( set i=%i%. Decimal point is required if %r% leq 0 ( set /a r = -r Get absolute value of remainder if %i%==0 set i=-0. Fix edge case (-1/3 = 0 remainder -1) ) ) set d = %d:-=% Get absolute value of divisor set /a e = d :g if %r%==0 echo %i% & exit /b Finished if there's no remainder set /a g = gcd(e, 10) Loop through nonrecurring decimals if not %g%==1 ( set /a e /= g call :d goto g ) set /a s = r Save remainder to know when loop ends set i=%i%( :r call :d if %r%==%s% echo %i%)&exit/b goto r :d Add the next decimal place set /a r *= 10 set /a n = r / d set /a r %= d set i=%i%%n% ``` [Answer] # [Perlย 6](http://perl6.org), ~~63 58~~ 50 bytes ``` {->$a,$b {$a~"($b)"x?$b}(|($^a.FatRat/$^b).base-repeating(10))} ``` ``` {->\a,$b {a~"($b)"x?$b}(|($^a.FatRat/$^b).base-repeating)} ``` ``` {$/=($^a.FatRat/$^b).base-repeating;$0~"($1)"x?$1} ``` [Test it](https://tio.run/nexus/perl6#xVLLbtswELzzK4hAaChUkrkPcskYTnPqBxQ9p1ActTDqOoYtBwnS9NfTVWQ7vrSHXqrTcjQ7s0vObtvZ@9jMp2an1edu20@N@fFo383vbjs7e3kqJjNXXLfNx7b/1PaT4vqmbG7abVdvunXX9ovVt2nhf525Asqzhw8FPL9o91WvQls7s85Y6wApRCQJGYE8JxhqnwQShSwVikhpZ5f2nJkzZ6DsJURKwRMRIMcI59UglKCikYkyInWscERqGhE4AL4JI0KYMiFxpKrG4Mdv3wTUQBDMaoZ7xaNH7RtH5YjqBhXwiENsxKUgwLj/qwtVhHDwdZQIRIJ4n4mDZKaMAYkicwo56SUkBkDgHAgFPCZPsteioE6wH4EaBwx6bxk9BcoJyfuUtC9IQFRfXS35QD6LOoGqsdqg@qeQ2IuXHDl6kJgzQPDMyCJJIvgImWP2GAOnKBhiJIGYhjFKzcB62a7s@/Eh9fj1bnN41frSFl@ssxffu0d3tVitd31Z2Yv7drnrXNE9rLt5392WtrRPutBia4couZ9H5pFyUjbrbrM0zy9/j4qd2CEswwR/jopJoDwaSCimjkPTcKjJGDgcNBzmLReKviXjlXuaC2Pqo@KYCaNTKgI8QKdxMDrvQEUYTf4xCUZDMOjDq@f/CMFv "Perl 6 โ€“ TIO Nexus") If you don't care that it will only work with denominators that fit into a 64 bit integer it can be shortened to just 43 bytes: ``` {$/=($^a/$^b).base-repeating;$0~"($1)"x?$1} ``` ### Expanded: ``` { # store in match variable so that we can # use ๏ฝข$0๏ฝฃ and ๏ฝข$1๏ฝฃ $/ = ( # turn the first value into a FatRat so that # it will continue to work for all Int inputs $^a.FatRat / $^b ).base-repeating; # ๏ฝข$0๏ฝฃ is short for ๏ฝข$/[0]๏ฝฃ which is the non-repeating part $0 # string concatenated with ~ # string repeat once if $1 is truthy (the repeating part) # otherwise it will be an empty Str "($1)" x ?$1 } ``` [Answer] # Java, 625 605 Golfed code: ``` import static java.math.BigInteger.*; String f(BigInteger a, BigInteger b){BigInteger[]r=a.divideAndRemainder(b);String s=r[0].toString();if(r[1].signum()<0)s="-"+s;if(!ZERO.equals(r[1])){s+='.';List<BigInteger>x=new ArrayList();List<BigInteger>y=new ArrayList();for(BigInteger d=TEN.multiply(r[1].abs());;){BigInteger[]z=d.divideAndRemainder(b.abs());int i=y.indexOf(z[1]);if(i>-1&&i==x.indexOf(z[0])){for(int j=0;j<i;++j)s+=x.get(j);s+='(';for(int j=i;j<x.size();++j)s+=x.get(j);s+=')';break;}x.add(z[0]);y.add(z[1]);if(ZERO.equals(z[1])){for(BigInteger j:x)s+=j;break;}d=TEN.multiply(z[1]);}}return s;} ``` Note: I count the static import as part of the function for golfing purposes. This function starts out by getting the division result. It adds the integral portion and sign, if necessary. Then if there is a remainder, it performs base 10 long division. At each step, perform the division. Store the calculated digit and the remainder in two lists. If we encounter the same digit and remainder again, there is a repeated portion and we know what index it starts at. The code either adds the digits (no repeat) or the pre-repeat digits, then the repeated digits enclosed in parentheses. This is a bit big mostly because of `BigInteger`. If the inputs did not overflow even a `long` then it could be a bit shorter. Still, I expect there are ways to improve this entry. Ungolfed code with main method for testing: ``` import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import static java.math.BigInteger.*; public class FractionToExactDecimal { public static void main(String[] args) { // @formatter:off String[][] testData = new String[][] { { "123562375921304812375087183597", "2777", "44494913907563850333124661" }, { "81", "3", "27" }, { "-6", "2", "-3" }, { "1", "2", "0.5" }, { "3289323463", "-250000000", "-13.157293852" }, { "-1", "3", "-0.(3)" }, { "235", "14", "16.7(857142)" }, { "123", "321", "0.(38317757009345794392523364485981308411214953271028037)" }, { "355", "113", "3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)" } }; // @formatter:on for (String[] data : testData) { System.out.println(data[0] + " / " + data[1]); System.out.println(" Expected -> " + data[2]); System.out.print(" Actual -> "); System.out.println(new FractionToExactDecimal().f(new BigInteger(data[0]), new BigInteger(data[1]))); System.out.println(); } } // Begin golf String f(BigInteger a, BigInteger b) { BigInteger[] r = a.divideAndRemainder(b); String s = r[0].toString(); if (r[1].signum() < 0) s = "-" + s; if (!ZERO.equals(r[1])) { s += '.'; List<BigInteger> x = new ArrayList(); List<BigInteger> y = new ArrayList(); for (BigInteger d = TEN.multiply(r[1].abs());;) { BigInteger[] z = d.divideAndRemainder(b.abs()); int i = y.indexOf(z[1]); if (i > -1 && i == x.indexOf(z[0])) { for (int j = 0; j < i; ++j) s += x.get(j); s += '('; for (int j = i; j < x.size(); ++j) s += x.get(j); s += ')'; break; } x.add(z[0]); y.add(z[1]); if (ZERO.equals(z[1])) { for (BigInteger j : x) s += j; break; } d = TEN.multiply(z[1]); } } return s; } // End golf } ``` Program output: ``` 123562375921304812375087183597 / 2777 Expected -> 44494913907563850333124661 Actual -> 44494913907563850333124661 81 / 3 Expected -> 27 Actual -> 27 -6 / 2 Expected -> -3 Actual -> -3 1 / 2 Expected -> 0.5 Actual -> 0.5 3289323463 / -250000000 Expected -> -13.157293852 Actual -> -13.157293852 -1 / 3 Expected -> -0.(3) Actual -> -0.(3) 235 / 14 Expected -> 16.7(857142) Actual -> 16.7(857142) 123 / 321 Expected -> 0.(38317757009345794392523364485981308411214953271028037) Actual -> 0.(38317757009345794392523364485981308411214953271028037) 355 / 113 Expected -> 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168) Actual -> 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168) ``` [Answer] # PHP, 277 Bytes ``` list(,$n,$d)=$argv;$a[]=$n;$n-=$d*$r[]=$n/$d^0;!$n?:$r[]=".";while($n&&!$t){$n*=10;$n-=$d*$r[]=$n/$d^0;$t=in_array($n%=$d,$a);$a[]=$n;}if($t){$l=count($a)-($p=array_search(end($a),$a));echo join(array_slice($r,0,2+$p))."(".join(array_slice($r,2+$p,$l)).")";}else echo join($r); ``` [Answer] # Mathematica 198 bytes ``` i=Integer;t=ToString;a_~h~b_:=f[a/b];f@q_i:= t@q; f@q_:=""<>{t@IntegerPart[q],".",RealDigits[FractionalPart[q]][[1]]//.{{x___,{k__i}}:> {x,"("<>(t/@{k})<>")"},{x__i,j___String}:>""<> {""<>t/@{x},j}}} ``` --- ## UnGolfed ``` (* hand over quotient of a, b to function f *) h[a_, b_] := f[a/b]; (* if the quotient is an integer, return it as a string *) f[q_Integer] := ToString@q; (* otherwise, return the integer part, followed by a decimal point ...*) f[q_] := "" <> {ToString@IntegerPart[q], ".", (* replacing the repeating part (if it exists) between parentheses *) RealDigits[FractionalPart[q]][[1]] //. {{x___, {i__Integer}} :> {x, "(" <>(ToString /@ {i}) <> ")"}, (* and the non-repeating part (if it exists) without parentheses *) {x__Integer, i___String} :> "" <> {"" <> ToString /@ {x}, i}}} ``` --- ]
[Question] [ This challenge is about gradually shifting hues in an image to make pretty pictures like this: [![big Starry Night](https://i.stack.imgur.com/hDcQr.jpg)](https://i.stack.imgur.com/hDcQr.jpg) ([original](https://i.stack.imgur.com/XFKAg.jpg)) # Challenge Write a program or function that takes in two non-negative integers and an image in any common image file format of your choosing (you can take a path to the image or the raw image data). We'll call the first integer the **cycles** and the second integer the **offset**. We'll also define floating-point **step** as 360 times **cycles** divided by the area of the image, or `step = 360 * cycles / (image width * image height)`. For each pixel **P** in the image, moving one row at a time, left-to-right, top-to-bottom (i.e. in reading order if the pixels were letters), do the following: 1. Increase the [hue](https://en.wikipedia.org/wiki/Hue) of **P** by **offset** degrees (looping around from 360 to 0 if necessary). 2. Then increase **offset** by **step**. Save, display, or output raw the resulting image in any common image file format. This procedure incrementally increases the hue of all the pixels in the image, making **cycles** full loops around the [hue rainbow](https://en.wikipedia.org/wiki/Hue#/media/File:HueScale.svg), starting by initially offsetting the hue by **offset**. When **cycles** is 1 and **offset** is 0, as in the Starry Night image above, the top and bottom rows of pixels have practically no hue shift but in between there's a full color cycle. # Details * **Cycles** can be any non-negative integer but you may assume that **offset** is from 0 to 359 inclusive. * When **cycles** is 0, every pixel in the image will have its hue shifted by exactly **offset** since **step** must be 0 too. (In this case if **offset** is 0 then the image doesn't change at all.) * You may assume **cycles** and **offset** are input as floats if desired (i.e. `1.0` instead of `1`). (I realize they needn't be integers at all, it just makes the challenge simpler.) * "Hue" refers to the RGB color space version, common in [HSL/HSV color models](https://en.wikipedia.org/wiki/HSL_and_HSV). # Examples Original: [![river](https://i.stack.imgur.com/8sEvg.png)](https://i.stack.imgur.com/8sEvg.png) Cycles = 1, offset = 0: [![river output 1](https://i.stack.imgur.com/83Fky.png)](https://i.stack.imgur.com/83Fky.png) Cycles = 1, offset = 180: [![river output 2](https://i.stack.imgur.com/W4GZA.png)](https://i.stack.imgur.com/W4GZA.png) Original: [![spheres](https://i.stack.imgur.com/BgfFX.png)](https://i.stack.imgur.com/BgfFX.png) Cycles = 2, offset = 60: [![spheres output](https://i.stack.imgur.com/XffYB.png)](https://i.stack.imgur.com/XffYB.png) Original: [![sunset](https://i.stack.imgur.com/Ulokx.png)](https://i.stack.imgur.com/Ulokx.png) (Thanks [ArtOfCode](https://hardwarerecs.stackexchange.com/users/8/artofcode).) Cycles = 1, offset = 120: [![sunset output](https://i.stack.imgur.com/rjKNP.png)](https://i.stack.imgur.com/rjKNP.png) Original: [![doorknob](https://i.stack.imgur.com/shFHM.png)](https://i.stack.imgur.com/shFHM.png) (Thanks [Doorknob](https://codegolf.stackexchange.com/users/3808/doorknob).) Cycles = 1, offset = 0: [![doorknob output 1](https://i.stack.imgur.com/hjji7.png)](https://i.stack.imgur.com/hjji7.png) Cycles = 4, offset = 0: [![doorknob output 2](https://i.stack.imgur.com/Jok8J.png)](https://i.stack.imgur.com/Jok8J.png) Cycles = 200, offset = 0: [![doorknob output 3](https://i.stack.imgur.com/LILtv.png)](https://i.stack.imgur.com/LILtv.png) Cycles = 30000, offset = 0: [![doorknob output 4](https://i.stack.imgur.com/GrMEY.png)](https://i.stack.imgur.com/GrMEY.png) (These images may not be pixel perfect due to imgur compressing them.) # Scoring The shortest code in bytes wins. Tiebreaker is higher voted answer. Answers that post their own cool looking test images will get more brownie points from me. [Answer] # Pyth, 86 bytes, full program ``` =N.tE7=Z*6*.n0cEl.n'zMmhtS[0255ss*VG.>+Lc-1.tH1 3[.tH1Kc.tH0@3 2_K)d)3.wmmgk~-NZd'z ``` Pyth doesn't have built-in color space conversions - this is the real deal. Takes input in the following format on stdin: ``` input_filename.png offset cycles ``` The output image is written to `o.png`. --- This works by rotating the color cube around its diagonal, and then clamping any values outside of the range. If `a` is the angle to rotate by, and `r, g, b` is the input color, we calculate the new color `r', g', b'` by: ``` o = cos(a), i = sin(a) / sqrt(3) n = (1 - o) / 3 m = [n + o, n - i, n + i] clamp(c) = max(0, min(255, c)) r' = clamp(r*m[0] + g*m[1] + b*m[2]) g' = clamp(r*m[2] + g*m[0] + b*m[1]) b' = clamp(r*m[1] + g*m[2] + b*m[0]) ``` [Answer] # Python, 379 bytes ``` from PIL.Image import* from colorsys import* def f(H,c,I): i=open(I);x,y=i.size;S=1.*c/(x*y);r,g,b=i.split();R=[];G=[];B=[] for x,y,z in zip(r.getdata(),g.getdata(),b.getdata()): e=255.;h,s,v=rgb_to_hsv(x/e,y/e,z/e);t=hsv_to_rgb(h+H,s,v);H=H+S%1.;x,y,z=[int(x*e)for x in t];R.append(x);G.append(y);B.append(z) p=Image.putdata;p(r,R);p(g,G);p(b,B);return merge('RGB',(r,g,b)) ``` This takes a path to a `.jpg` as input. It will not work with png, although you can change `r,g,b=i.split();` to `r,g,b=i.split()[:3];` to load a png image. Here are some images: Original: [![enter image description here](https://i.stack.imgur.com/McvcF.jpg)](https://i.stack.imgur.com/McvcF.jpg) Offset: 0, Cycles: 4 [![enter image description here](https://i.stack.imgur.com/Mj2iB.jpg)](https://i.stack.imgur.com/Mj2iB.jpg) Original: [![enter image description here](https://i.stack.imgur.com/oHQyc.jpg)](https://i.stack.imgur.com/oHQyc.jpg) Offset 0, 1 cycle: [![enter image description here](https://i.stack.imgur.com/40vyj.jpg)](https://i.stack.imgur.com/40vyj.jpg) Original: [![enter image description here](https://i.stack.imgur.com/qrxVX.jpg)](https://i.stack.imgur.com/qrxVX.jpg) Offset 0, 2.5 cycles: [![enter image description here](https://i.stack.imgur.com/85Ph7.jpg)](https://i.stack.imgur.com/85Ph7.jpg) [Answer] # Java (Full program), 491 488 bytes (Thanks @Geobits) ``` import java.awt.*;import java.io.*;import static javax.imageio.ImageIO.*;class Q{public static void main(String[]v)throws Exception{File f=new File(v[2]);java.awt.image.BufferedImage b=read(f);for(int i=0,j,h=b.getHeight(),w=b.getWidth();i<h;i++)for(j=0;j<w;){Color c=new Color(b.getRGB(j,i));float[]a=new float[3];c.RGBtoHSB(c.getRed(),c.getGreen(),c.getBlue(),a);b.setRGB(j++,i,c.HSBtoRGB((a[0]+Float.valueOf(v[1])/360+(i*w+j)*Float.valueOf(v[0])/w/h)%1,a[1],a[2]));}write(b,"png",f);}} ``` ### Ungolfed ``` import java.awt.*; import java.io.*; import static javax.imageio.ImageIO.*; class A79200 { public static void main(String[] v) throws Exception { File file = new File(v[2]); java.awt.image.BufferedImage image = read(file); for (int i = 0, j, height = image.getHeight(), width = image.getWidth(); i < height; i++) for (j = 0; j < width; ) { Color color = new Color(image.getRGB(j, i)); float[] arr = new float[3]; color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), arr); image.setRGB(j++, i, color.HSBtoRGB((arr[0] + Float.valueOf(v[1]) / 360 + (i * width + j) * Float.valueOf(v[0]) / width / height) % 1, arr[1], arr[2])); } write(image, "png", file); } } ``` ### Explanation * Usage: Pretty straightforward. Compile with `java -c Q.java`. Run with `java Q <cycles> <offset> <imagepath>`. Will override the existing image, so be careful. * I was gonna make a method only solution at first but I didn't quite know how to handle imports on those, so I figured I'd go full [java](/questions/tagged/java "show questions tagged 'java'"), this is *probably* not going to win anyways :^) ### Results: `Image 1: 1 cycle, 0 offset` [![1](https://i.stack.imgur.com/bX5fV.png)](https://i.stack.imgur.com/bX5fV.png) `Image 1: 1 cycle, 180 offset` [![2](https://i.stack.imgur.com/Gngiq.png)](https://i.stack.imgur.com/Gngiq.png) `Image 2: 2 cycles, 60 offset` [![3](https://i.stack.imgur.com/9FpUb.png)](https://i.stack.imgur.com/9FpUb.png) `Image 3: 1 cycle, 120 offset` [![4](https://i.stack.imgur.com/NitRj.png)](https://i.stack.imgur.com/NitRj.png) `Image 4: 1 cycle, 0 offset` [![5](https://i.stack.imgur.com/3jSi1.png)](https://i.stack.imgur.com/3jSi1.png) `Image 4: 4 cycles, 0 offset` [![6](https://i.stack.imgur.com/YhrG8.png)](https://i.stack.imgur.com/YhrG8.png) `Image 4: 200 cycles, 0 offset` [![7](https://i.stack.imgur.com/QCuAd.png)](https://i.stack.imgur.com/QCuAd.png) `Bonus: The Starry Night, 1 cycle, 0 offset` [![enter image description here](https://i.stack.imgur.com/Bxsta.jpg)](https://i.stack.imgur.com/Bxsta.jpg) ]
[Question] [ Write a program that takes in a rectangular block of text made up of `X`'s and `.`'s, such as this rough `A`: ``` ...... ..XX.. .X..X. .XXXX. .X..X. .X..X. ``` Output a representation of this grid rotated 45 degrees counterclockwise by drawing a slash โ€” forward or backward depending on context โ€” everywhere an `X` borders a `.` or the side of the grid (with spaces filling in the rest): ``` /\/\ / /\ \ \/ / \ /\/ /\ \ \ / \/ \ \ \ \ \/ ``` The number of trailing and leading spaces (and newlines) doesn't matter as long as the shape of the `X`'s in the input is maintained by the slashes. It's ok to trim extra rows or columns of `.`'s. For I/O you may use any combination of stdin/stdout/files/command line parameters. For example your script might take in a file name of the `X.` pattern and rewrite the file with the slash pattern. Or your script might take in the `X.` pattern from stdin line by line (pressing `d` when done) and output the result to stdout. The input may be arbitrarily large, but you may assume it is always well formatted. No characters besides `/ \` and newlines should be in any output. # Scoring The shortest code in bytes wins. Use <https://mothereff.in/byte-counter> as a byte counter if you use non-ASCII characters. **Bonus:** Minus 50 bytes if you can change (replace, not remove) one character in your program so it outputs the slash grid rotated 45 degrees *clockwise*, e.g.: ``` /\/\ / /\ \ / \ \/ / /\ \/\ \/ \ / / / / / \/ ``` # Input Samples ``` XXXXXXXXX X.......X X.XXXXX.X X.X...X.X X.X.X.X.X X.X...X.X X.XXXXX.X X.......X XXXXXXXXX XXX...XXX....XXX...XXX X..X..X..X..X.....X... XXX...XXX...X.....X.XX X.....X.....X.....X..X X.....X......XXX...XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...X X...X...............X...............X...........X...................X...X X...X...XXXXXXXXX...X...XXXXX...XXXXXXXXX...XXXXX...XXXXX...XXXXX...X...X X...............X.......X...X...........X...........X...X...X.......X...X XXXXXXXXX...X...XXXXXXXXX...XXXXXXXXX...XXXXX...X...X...X...XXXXXXXXX...X X.......X...X...............X...........X...X...X...X...X...........X...X X...X...XXXXXXXXXXXXX...X...X...XXXXXXXXX...XXXXX...X...XXXXXXXXX...X...X X...X...............X...X...X.......X...........X...........X.......X...X X...XXXXXXXXXXXXX...XXXXX...XXXXX...X...XXXXX...XXXXXXXXX...X...XXXXX...X X...........X.......X...X.......X...X.......X...........X...X...........X X...XXXXX...XXXXX...X...XXXXX...X...XXXXXXXXX...X...X...X...XXXXXXXXXXXXX X.......X.......X...X...X.......X.......X.......X...X...X.......X.......X XXXXXXXXXXXXX...X...X...X...XXXXXXXXX...X...XXXXX...X...XXXXX...XXXXX...X X...........X...X...........X.......X...X.......X...X.......X...........X X...XXXXX...X...XXXXXXXXX...XXXXX...X...XXXXX...XXXXX...XXXXXXXXXXXXX...X X...X.......X...........X...........X.......X...X...X...............X...X X...X...XXXXXXXXX...X...XXXXX...XXXXXXXXX...X...X...XXXXXXXXXXXXX...X...X X...X...........X...X...X...X...X...........X...............X...X.......X X...XXXXXXXXX...X...X...X...XXXXX...XXXXXXXXX...XXXXXXXXX...X...XXXXXXXXX X...X.......X...X...X...........X...........X...X.......X...............X X...X...XXXXX...XXXXX...XXXXX...XXXXXXXXX...XXXXX...X...XXXXXXXXX...X...X X...X...................X...........X...............X...............X...X X...XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ``` ([maze source](http://ascii.co.uk/art/maze)) *Related Questions:* [Draw the Hilbert curve using slashes](https://codegolf.stackexchange.com/questions/34852/draw-the-hilbert-curve-using-slashes) [Align a horizontally-aligned, right-angled ASCII shape along a diagonal](https://codegolf.stackexchange.com/questions/21730/align-a-horizontally-aligned-right-angled-ascii-shape-along-a-diagonal) [Answer] # Python 2 - ~~236, 228, 226, 221, 250, 248~~ 246 - 50 = 196 ``` s=input().split() s=zip(*s[::-1]) X=len(s[0])+2 d=('.',) B=[d*X] s=B+[d+tuple(l)+d for l in s]+B Y=len(s) for x in range(X,-Y,-1):print' '*abs(x)+''.join(' \\'[s[y-1][x+y-1]!=s[y-1][x+y]]+' /'[s[y-1][x+y]!=s[y][x+y]]for y in range(1,Y)if 0<x+y<X) ``` I added the optional bonus feature that switches the direction from clockwise to counterclockwise. Basically, the second line simply rotates the input by 90 degrees. To switch between both options, replace `s=zip(...)` by something like `S=zip(...)` (i.e. assign to a variable that won't be used again). ``` .XX.X....X...XX.X.X X...X...X.X.X...X.X .X..X...XXX..X..XXX ..X.X...X.X...X.X.X XX..XXX.X.X.XX..X.X /\ /\/\ \ \ \/\ \ /\ \ \ /\ \/ \ \/ \ /\ \/ /\ /\ \ /\ \ \ \/\ / / / / \ \ \/ \/\/ / / \/ \ \ / / /\/\/\ \/ / / \/\/\/ \ \ /\/\ /\/\ /\ \ \ / /\/ \/\ \ / / \/ / \/\ /\/ \ \/ / /\ / \ /\ \ \/ / / /\/\ \ \ \/ / / \/\ \ /\ \ \ \/ /\ \/ \ \ \/ /\ \/ /\ /\ \ \ /\ \ \/\ / / / / \ \/ / \/\/ / / /\ \/ \ / / \/ / /\/\/\ \/ / /\ / \/\/\/ \/ / / /\ / / / / \/ \/ ``` [Answer] # MATLAB - 286 - 50 = 236 **Minified:** ``` S=input('');x=rot90(reshape(input('','s'),S),1);S=size(x);D=sum(S);[r,c]=ind2sub(S,find(x==88));A=zeros(D);f=@(o,p)sub2ind([D D],r+c+o-1,c-r+S(1)+p);A(f(1,1))=1;t=f(0,0);A(t)=A(t)+1;A(f(1,0))=3;t=f(0,1);A(t)=A(t)+3;fprintf('%s',char([(1-mod(A,2))*32+(A==1)*47+(A==3)*92,ones(D,1)*13]')) ``` **Expanded:** ``` S = input(''); x = rot90( reshape( input('','s'), S ), 1 ); S = size( x ); D = sum( S ); [r,c] = ind2sub( S, find( x==88 ) ); A = zeros( D ); f = @(o,p) sub2ind( [D D], r+c+o-1, c-r+S(1)+p ); A(f(1,1)) = 1; t = f(0,0); A(t) = A(t)+1; A(f(1,0)) = 3; t = f(0,1); A(t) = A(t)+3; fprintf( '%s', char( [(1-mod( A, 2 ))*32 + (A==1)*47 + (A==3)*92, ones( D, 1 )*13]' ) ) ``` The code can be further reduced by 6 characters (to tie the current lead) by eliminating the cast to type `char`, but this results in a warning from MATLAB, and I wasn't sure if that was allowed. It can be reduced by an additional 13 characters if the input is required to have a "marked up" format such as `['X..';'.X.';'..X']`, but I didn't figure this was allowed either. Currently the script just accepts two numbers (row and column dimensions) and then reads in a single string of grid characters. **Bonus** By changing the `1` in the call `x = rot90( ..., 1 );` to a `0`, the transformation changes from a CCW 45ยฐ rotation to a CW 45ยฐ rotation. In fact, all possible 45ยฐ + nยท90ยฐ rotations are possible by stepping this parameter from `0` to `3`. **Sample Outputs:** ``` XXX...XXX....XXX...XXX X..X..X..X..X.....X... XXX...XXX...X.....X.XX X.....X.....X.....X..X X.....X......XXX...XXX /\ / / / / /\ \/ / \ /\ \/\ \ \ \ / / /\ \ \/ / / / \/\/ / / \/ /\ /\ \ \ / / \ \/ / /\/\ \/\/ / /\/ / / /\ \ \/ / \ / \ \ /\/\ \ \ / /\/ \/ / / /\ \ \/ / \ / \ \ \ \ \/ /\ / \ / /\ \ / \ \/ / /\ \/\ \/ \/\/ /\ / \ / /\ \ / \ \/ / /\ \/\ \/ \/\/ /\/\ / /\ \ / / \ \ \/ \/ /\ \ \ \ \ /\/\ \/ / /\ \ / / \ \ \/ /\ \/ /\ \ \ \ \/ / \ / \/ ``` [Answer] # Perl - 409 ``` while(<>){$a[$.]=[/./g]}$l=$#a<($g=@{$a[1]})?$#a:$g;$r=$#a+$g-1;for$d(1..$r){for$e(1..$l){if(($b=$a[$c=($d>$g?$d-$g:0)+$e][$n=-($d-$c+1)])&&$n<0){$h[$d][$e]=$b;}}$h[$d]=[(0)x(($l-{@$h[$d]})/2),@{$h[$d]}];}sub z{"\0"x((reverse(1..$g),(2..$r-$g+1))[int($q++/2)-1]).join'',map{$_ eq'X'?($q%2?'/\\':'\/'):"\0\0"}@_}@i="\0"x2x$l;for$f(@h){$i[$#i]=(z@$f)^$i[$#i];$i[$#i+1]=z@$f}for$j(@i){print$j=~s/[\0s]/ /gr."\n"} ``` Reads from stdin and prints to stdout. Example outputs: ``` XXX X.. XXX ..X XXX /\ / / / / /\ \ \/ \ \ /\ \ \/ / / / / \/ XXXXXXXXX X........ X.XXXXXXX X.X.....X X.X..X..X X.XXXX..X X...X...X XXXXXXXXX /\ / / / / /\ / / / \ / / / /\ \ / / / / \ \ / / / / \ \ / / / / /\ \ \ / / / / \ \ / / \ \ \ \ / / / / \ \ \ \/ \/ / \ \ \ /\ / \ \ \/ / / \ \ / / \ \/ / \ / \/ ``` ]
[Question] [ ## Introduction Consider a sequence of integers and one of its subsequences, say **A = [4 2 2 4 4 6 5]** and **B = [2 4 5]**. We want to remove the elements of **B** from **A** in order, and there are several ways of doing that: ``` A = 4 2 2 4 4 6 5 B = 2 4 5 -> 4 2 4 6 A = 4 2 2 4 4 6 5 B = 2 4 5 -> 4 2 4 6 A = 4 2 2 4 4 6 5 B = 2 4 5 -> 4 2 4 6 A = 4 2 2 4 4 6 5 B = 2 4 5 -> 4 2 4 6 ``` In all cases, the remaining sequence is the same, **[4 2 4 6]**. If this happens, we say that **B** is *uniquely removable from* **A**. ## The task Your inputs are two sequences of nonnegative integers, **A** and **B**, where **B** is guaranteed to be a subsequence of **A**. The inputs may be equal, and they may be empty. You can take them in any order you want, in any reasonable format. Your output shall be a truthy value if **B** is uniquely removable from **A**, and a falsy value if not. ## Rules and scoring You can write a full program or a function. The lowest byte count wins. ## Test cases ``` [] [] -> True [0,3] [] -> True [1,0,1] [1] -> False [0,2] [0,2] -> True [2,2,1,1,2,2,2] [2,1] -> True [4,2,2,4,4,6,5] [4,5] -> False [10,5,10,10,5,10] [10,5,10] -> False [4,2,2,4,4,6,5] [2,4,5] -> True [1,1,1,0,0,0,1,1,1,0] [1,0,1,1] -> True [0,1,0,0,0,0,1,1,0,1] [1,0,1,1] -> False [0,4,0,0,4,1,4,2,2] [0,0,0,1,4] -> True [0,2,2,25,0,2,2,26,0,0,2] [2,0,0,0,2] -> True [1,1,1,3,2,1,3,2,2,3,3,2] [1,1,2,3,2] -> False [0,3,2,0,1,3,2,0,0,0,3,2] [0,1,2,0,3] -> False [5,7,2,7,7,1,7,7,5,2,7,7,5,2,2,7,5] [2,7,5,7,7,2] -> False [5,4,0,5,4,5,4,1,0,4,2,1,1,2,4,4,0,2,2,1] [4,0,1,1,2,1] -> False [0,1,4,0,1,4,0,1,5,1,4,4,2,0,0,1,1,1,2,4] [0,1,0,0,2,0,1,4] -> True ``` [Answer] # Haskell, ~~90~~ 84 bytes ``` a%[]=[a] (t:z)%x@(s:y)=[a|a<-z%y,t==s]++[t:s|s<-z%x] _%_=[] ((all=<<(==).head).).(%) ``` Construct the list of all possible subtracted sequences nondeterministically and checks whether they are all equal. Usage: ``` *Main> mapM_(\(a,b)->let r=(((all=<<(==).head).).(%)) a b in putStrLn$concat[show a," ",show b," -> ",show r]) [([],[]), ([0,3],[]), ([1,0,1],[1]), ([0,2],[0,2]), ([2,2,1,1,2,2,2],[2,1]), ([4,2,2,4,4,6,5],[4,5]), ([10,5,10,10,5,10],[10,5,10]), ([4,2,2,4,4,6,5],[2,4,5]), ([1,1,1,0,0,0,1,1,1,0],[1,0,1,1]), ([0,1,0,0,0,0,1,1,0,1],[1,0,1,1]), ([0,4,0,0,4,1,4,2,2],[0,0,0,1,4]), ([0,2,2,25,0,2,2,26,0,0,2],[2,0,0,0,2]), ([1,1,1,3,2,1,3,2,2,3,3,2],[1,1,2,3,2]), ([0,3,2,0,1,3,2,0,0,0,3,2],[0,1,2,0,3]), ([5,7,2,7,7,1,7,7,5,2,7,7,5,2,2,7,5],[2,7,5,7,7,2]), ([5,4,0,5,4,5,4,1,0,4,2,1,1,2,4,4,0,2,2,1],[4,0,1,1,2,1]), ([0,1,4,0,1,4,0,1,5,1,4,4,2,0,0,1,1,1,2,4],[0,1,0,0,2,0,1,4])] [] [] -> True [0,3] [] -> True [1,0,1] [1] -> False [0,2] [0,2] -> True [2,2,1,1,2,2,2] [2,1] -> True [4,2,2,4,4,6,5] [4,5] -> False [10,5,10,10,5,10] [10,5,10] -> False [4,2,2,4,4,6,5] [2,4,5] -> True [1,1,1,0,0,0,1,1,1,0] [1,0,1,1] -> True [0,1,0,0,0,0,1,1,0,1] [1,0,1,1] -> False [0,4,0,0,4,1,4,2,2] [0,0,0,1,4] -> True [0,2,2,25,0,2,2,26,0,0,2] [2,0,0,0,2] -> True [1,1,1,3,2,1,3,2,2,3,3,2] [1,1,2,3,2] -> False [0,3,2,0,1,3,2,0,0,0,3,2] [0,1,2,0,3] -> False [5,7,2,7,7,1,7,7,5,2,7,7,5,2,2,7,5] [2,7,5,7,7,2] -> False [5,4,0,5,4,5,4,1,0,4,2,1,1,2,4,4,0,2,2,1] [4,0,1,1,2,1] -> False [0,1,4,0,1,4,0,1,5,1,4,4,2,0,0,1,1,1,2,4] [0,1,0,0,2,0,1,4] -> True ``` Thanks to @Zgarb for saving 6 bytes! [Answer] # JavaScript (ES6), 141 ~~152 156 159~~ Recursive function - quite long ``` f=(a,b,i=0,j=0,r=a,S=new Set)=>(1/b[j]?1/a[i]&&f(a,b,i+1,j,r,S,a[i]-b[j]||f(a,b,i+1,j+1,r=[...r],r[i]=S)):S.add(0+r.filter(x=>1/x)),S.size<2) ``` *Less golfed* ``` f=(a, b, i = 0, // current position to match in a j = 0, // current position to match in b r = a, // current result so far, A with elements of B removed - start == A S = new Set // set of possible "A removed B" ) => ( 1 / b[j] // check if j is still inside B ? 1 / a[i] // if i is inside A && ( // in any case try to find current element of B in the remaining part of A f(a, b, i+1, j, r, S), a[i] == b[j] // if match was found between A and B && // mark current element in a copy of r and // look for the next element of B in the remaining part of A f(a, b, i+1, j+1, r=[...r], r[i]=S), ) // else - j is not inside B, we have a solution in r // use filter to get a copy without the marked elements // (note: 1/any_number == number_not_0, 1/Object == NaN) // then convert to string, to use as a key in S : S.add(0+a.filter(x=>1/x)), S.size<2 // return true if S has only 1 element ) ``` **Test** ``` f=(a,b,i=0,j=0,r=a,S=new Set)=>(1/b[j]?1/a[i]&&f(a,b,i+1,j,r,S,a[i]-b[j]||f(a,b,i+1,j+1,r=[...r],r[i]=S)):S.add(0+r.filter(x=>1/x)),S.size<2) out=(...x)=>O.textContent+=x.join` `+'\n' ;`[] [] -> True [0,3] [] -> True [1,0,1] [1] -> False [0,2] [0,2] -> True [2,2,1,1,2,2,2] [2,1] -> True [4,2,2,4,4,6,5] [4,5] -> False [10,5,10,10,5,10] [10,5,10] -> False [4,2,2,4,4,6,5] [2,4,5] -> True [1,1,1,0,0,0,1,1,1,0] [1,0,1,1] -> True [0,1,0,0,0,0,1,1,0,1] [1,0,1,1] -> False [0,4,0,0,4,1,4,2,2] [0,0,0,1,4] -> True [0,2,2,25,0,2,2,26,0,0,2] [2,0,0,0,2] -> True [1,1,1,3,2,1,3,2,2,3,3,2] [1,1,2,3,2] -> False [0,3,2,0,1,3,2,0,0,0,3,2] [0,1,2,0,3] -> False [5,7,2,7,7,1,7,7,5,2,7,7,5,2,2,7,5] [2,7,5,7,7,2] -> False [5,4,0,5,4,5,4,1,0,4,2,1,1,2,4,4,0,2,2,1] [4,0,1,1,2,1] -> False [0,1,4,0,1,4,0,1,5,1,4,4,2,0,0,1,1,1,2,4] [0,1,0,0,2,0,1,4] -> True` .split('\n').forEach(t=>{ var [a,b,_,k]=t.match(/\S+/g) var r=f(eval(a),eval(b)) out(r==(k[0]=='T')?'OK':'KO',a,b,r,k) }) ``` ``` <pre id=O></pre> ``` [Answer] # Pyth - 27 bytes On mobile in school right now, so not fully golfed. ``` JE!t{.DLQfqJ@LQT{I#{SM^UQlJ ``` [Test Suite](http://pyth.herokuapp.com/?code=JE%21t%7B.DLQfqJ%40LQT%7BI%23%7BSM%5EUQlJ&test_suite=1&test_suite_input=%5B%5D%0A%5B%5D%0A%5B0%2C+3%5D%0A%5B%5D%0A%5B1%2C0%2C1%5D%0A%5B1%5D%0A%5B4%2C2%2C2%2C4%2C4%2C6%2C5%5D%0A%5B2%2C4%2C5%5D%0A%5B4%2C2%2C2%2C4%2C4%2C6%2C5%5D%0A%5B4%2C5%5D&debug=0&input_size=2) [Answer] ## JavaScript (ES6), ~~116~~ ~~114~~ 113 bytes Returns `false` or `true`. ``` (a,b,p)=>((F=(a,i,m)=>1/b[i]?a.map((n,j)=>m>j|n-b[i]||F(a.filter((_,k)=>j-k),i+1,j)):p?r|=p!=a:p=a+'')(a,r=0),!r) ``` ### Formatted and commented ``` ( // given: a, b, // - a, b = input arrays p // - p = reference pattern, initially undefined ) => ( // (F = ( // F is our recursive search function, with: a, // - a = current working copy of the main array i, // - i = index in 'b' m // - m = minimum index of matching values in 'a' ) => // 1 / b[i] ? // if we haven't reached the end of 'b': a.map((n, j) => // for each element 'n' at index 'j' in 'a': m > j | n - b[i] || // if 'n' is a valid matching value, F( // do a recursive call to F(), using: a.filter((_, k) => j - k), // - a copy of 'a' without the current element i + 1, // - the next index in 'b' j // - 'j' as the new minimum index in 'a' ) // ) // : // else: p ? // if the reference pattern is already set: r |= p != a // check if it's matching the current 'a' : // else: p = a + '' // set the current 'a' as the reference pattern )(a, r = 0), // initial call to F() + initialization of 'r' !r // yields the final result ) // ``` ### Test cases ``` let f = (a,b,p)=>((F=(a,i,m)=>1/b[i]?a.map((n,j)=>m>j|n-b[i]||F(a.filter((_,k)=>j-k),i+1,j)):p?r|=p!=a:p=a+'')(a,r=0),!r) console.log(f([],[])); // -> true console.log(f([0,3],[])); // -> true console.log(f([1,0,1],[1])); // -> false console.log(f([0,2],[0,2])); // -> true console.log(f([2,2,1,1,2,2,2],[2,1])); // -> true console.log(f([4,2,2,4,4,6,5],[4,5])); // -> false console.log(f([10,5,10,10,5,10],[10,5,10])); // -> false console.log(f([4,2,2,4,4,6,5],[2,4,5])); // -> true console.log(f([1,1,1,0,0,0,1,1,1,0],[1,0,1,1])); // -> true console.log(f([0,1,0,0,0,0,1,1,0,1],[1,0,1,1])); // -> false console.log(f([0,4,0,0,4,1,4,2,2],[0,0,0,1,4])); // -> true console.log(f([0,2,2,25,0,2,2,26,0,0,2],[2,0,0,0,2])); // -> true console.log(f([1,1,1,3,2,1,3,2,2,3,3,2],[1,1,2,3,2])); // -> false console.log(f([0,3,2,0,1,3,2,0,0,0,3,2],[0,1,2,0,3])); // -> false console.log(f([5,7,2,7,7,1,7,7,5,2,7,7,5,2,2,7,5],[2,7,5,7,7,2])); // -> false console.log(f([5,4,0,5,4,5,4,1,0,4,2,1,1,2,4,4,0,2,2,1],[4,0,1,1,2,1])); // -> false console.log(f([0,1,4,0,1,4,0,1,5,1,4,4,2,0,0,1,1,1,2,4],[0,1,0,0,2,0,1,4])); // -> true ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 27 bytes ``` n:inXN!"1G@&)w2G=?}x]]tvdz~ ``` The longest test cases run out of time in the online compiler. [Try it online!](http://matl.tryitonline.net/#code=bjppblhOISIxR0AmKXcyRz0_fXhdXXR2ZHp-&input=WzQsMiwyLDQsNCw2LDVdClsyLDQsNV0) [Answer] # JavaScript (Firefox 30+), ~~159~~ 147 bytes ``` f=(a,b,i=f(a,b,0))=>i?i.every(x=>x+""==i[0]):b+b?a+a&&[for(n of a)if(a[i++]==b[0])for(x of f(a.slice(i),b.slice(1),0))[...a.slice(0,i-1),...x]]:[a] ``` Here's a couple of alternate approaches, both anonymous functions: ``` (a,b,f=(a,b,i=0)=>b+b?a+a&&[for(n of a)if(a[i++]==b[0])for(x of f(a.slice(i),b.slice(1)))[...a.slice(0,i-1),...x]]:[a],c=f(a,b))=>c.every(x=>x+""==c[0]) (a,b,f=(a,b,i=0)=>b+b?a+a&&[for(n of a)if(a[i++]==b[0])for(x of f(a.slice(i),b.slice(1)))[...a.slice(0,i-1),...x]]:[a])=>new Set(f(a,b).map(btoa)).size<2 ``` ### Test snippet ``` f=(a,b,i=f(a,b,0))=>i?i.every(x=>x+""==i[0]):b+b?a+a&&[for(n of a)if(a[i++]==b[0])for(x of f(a.slice(i),b.slice(1),0))[...a.slice(0,i-1),...x]]:[a] T.textContent = T.textContent.split` `.map(x => x + ` (${f(...x.split` `.slice(0,2).map(eval))})`).join` ` ``` ``` <pre id=T>[] [] -> True [0,3] [] -> True [1,0,1] [1] -> False [0,2] [0,2] -> True [2,2,1,1,2,2,2] [2,1] -> True [4,2,2,4,4,6,5] [4,5] -> False [10,5,10,10,5,10] [10,5,10] -> False [4,2,2,4,4,6,5] [2,4,5] -> True [1,1,1,0,0,0,1,1,1,0] [1,0,1,1] -> True [0,1,0,0,0,0,1,1,0,1] [1,0,1,1] -> False [0,4,0,0,4,1,4,2,2] [0,0,0,1,4] -> True [0,2,2,25,0,2,2,26,0,0,2] [2,0,0,0,2] -> True [1,1,1,3,2,1,3,2,2,3,3,2] [1,1,2,3,2] -> False [0,3,2,0,1,3,2,0,0,0,3,2] [0,1,2,0,3] -> False [5,7,2,7,7,1,7,7,5,2,7,7,5,2,2,7,5] [2,7,5,7,7,2] -> False [5,4,0,5,4,5,4,1,0,4,2,1,1,2,4,4,0,2,2,1] [4,0,1,1,2,1] -> False [0,1,4,0,1,4,0,1,5,1,4,4,2,0,0,1,1,1,2,4] [0,1,0,0,2,0,1,4] -> True</pre> ``` [Answer] # Mathematica, 128 bytes ``` h=Length;n=ToExpression;g=ToString;y=Array;h@Union@ReplaceList[#2,n@Riffle[y["a"<>g@#<>"___"&,t=h@#+1],#]->n@y["a"<>g@#&,t]]==1& ``` Unnamed function taking two list arguments, where the first is the subsequence and the second is the full sequence; outputs `True` or `False`. The core part is the following sequence, ungolfed for readability: ``` ReplaceList[#2, ToExpression @ Riffle[ Array["a" <> ToString@# <> "___" &, Length@# + 1] , # ] -> ToExpression @ Array["a" <> ToString@#& , Length@# + 1 ] ] ``` Here `#` represents the subsequenceโ€”for example, `{2,4,5}`. The first `Array` command creates a list of strings like `{"a1___","a2___","a3___","a4___"}`, which is then `Riffle`d together with `#` to yield a weird list like `{"a1___",2,"a2___",4,"a3___",5,"a4___"}`; then this list is cast into an actual Mathematica expression. For the example `{2,4,5}`, a partial evaluation of this core code is ``` ReplaceList[#2, {a1___,2,a2___,4,a3___,5,a4___} -> {a1,a2,a3,a4}] ``` which exactly gives a list of all possible ways to remove the subsequence `{2,4,5}` from `#2` and leave the rest of the list alone. After this list is generated, we simply remove duplicates using `Union` and test whether the length of the resulting output is 1 or not. ]
[Question] [ Piano keys are 3 characters wide, and 7 characters tall. However, if *every* key was 3 charactes wide, there wouldn't be enough room for the black keys. That's why some of the white keys have parts of them cut out. There are 3 types of white keys. Keys with the right half missing (R): ``` ____ | | | | | | | | | | | | |___| ``` Keys with the left half missing (L): ``` ____ | | | | | | | | | | | | |___| ``` And keys with the left and right halves missing (M): ``` ___ | | | | | | | | | | | | |___| ``` On a real keyboard, the pattern of these goes like this: ``` RMLRMML, RMLRMML, RMLRMML... ``` and repeats for a total of 88 keys. Now you can't see it when the keys are shown individually, but when you shove them together, you can see the black keys. ``` _________________________________________________________ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |___|___|___|___|___|___|___|___|___|___|___|___|___|___| ``` # Your task Given a positive integer *N*, print this ASCII-art of a piano with *N* white keys. You should be able to handle any *N* from 1 to 52 inclusive (since real 88-key pianos have 52 white keys). Here is test output from 1 to 8, and after that the pattern increases in a similar fashion. ``` 1 ____ | | | | | | | | | | | | |___| 2 ________ | | | | | | | | | | | | | | | | | | | | | | |___|___| 3 _____________ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |___|___|___| 4 ________________ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |___|___|___|___| 5 ____________________ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |___|___|___|___|___| 6 ________________________ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |___|___|___|___|___|___| 7 _____________________________ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |___|___|___|___|___|___|___| 8 ________________________________ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |___|___|___|___|___|___|___|___| ``` And last but not least, here is a full 52 key output: ``` _________________________________________________________________________________________________________________________________________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ``` Standard loopholes are banned, and the shortest answer in bytes wins! [Answer] ## JavaScript (ES6), ~~155~~ ~~149~~ 147 bytes ``` n=>[`_`[r=`repeat`](n*4+(9>>n%7&1)),s=[...Array(n*12/7|0)].map((_,i)=>1998>>i%12&1?` |`:` |`).join``,s,s,s,s=` |`[r](n),s,`___|`[r](n)].join`\n|` ``` Where `\n` represents the literal newline character. Leverages the fact that all the lines after the first start with a `|` character. Explanation: ``` f= n=>[ // Start by building up a list of rows `_`[r=`repeat`](n*4+ // 4 underscores per key (9>>n%7&1)), // Third and seventh keys have one extra s=[...Array(n*12/7|0)] // Calculate total of white and black keys .map((_,i)=> // Process each key in turn 1998>>i%12&1?` |`:` |` // Bitmap of narrow and wide keys ).join``, // Join the keys together s,s,s, // Repeated 4 times in total s=` |`[r](n), // Full width part of the white keys s, // Repeated twice in total `___|`[r](n) // Base of the white keys ].join`\n|` // Join the rows together ``` ``` <input type="number" oninput="o.textContent=f(this.value);"><pre id=o> ``` Edit: Saved 2 bytes by fixing my misreading of the spec on the height of the keys. [Answer] # Pyth, ~~68~~ ~~65~~ 63 bytes ``` *lJ:+\|s@Lj;*L" |"_j4536 7*4Q" $"k\_jb+*4]J*2]K+\|*Q" |":Kd\_ ``` [Try it online!](http://pyth.herokuapp.com/?code=%2AlJ%3A%2B%5C%7Cs%40Lj%3B%2AL%22%20%7C%22_j4536%207%2A4Q%22%20%24%22k%5C_jb%2B%2A4%5DJ%2A2%5DK%2B%5C%7C%2AQ%22%20%20%20%7C%22%3AKd%5C_&input=8&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=%2AlJ%3A%2B%5C%7Cs%40Lj%3B%2AL%22%20%7C%22_j4536%207%2A4Q%22%20%24%22k%5C_jb%2B%2A4%5DJ%2A2%5DK%2B%5C%7C%2AQ%22%20%20%20%7C%22%3AKd%5C_&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A55&debug=0) In this version, I just substituted the assignments (J and K) inside to save 2 bytes. Therefore, read the version below. ## Previous 65-byte version with explanation ``` J:+\|s@Lj;*L" |"_j4536 7*4Q" $"kK+\|*Q" |"*lJ\_jb+*4]J*2]K:Kd\_ ``` [Try it online!](http://pyth.herokuapp.com/?code=J%3A%2B%5C%7Cs%40Lj%3B%2AL%22%20%7C%22_j4536%207%2A4Q%22%20%24%22kK%2B%5C%7C%2AQ%22%20%20%20%7C%22%2AlJ%5C_jb%2B%2A4%5DJ%2A2%5DK%3AKd%5C_&input=8&debug=0) ``` J:+\|s@Lj;*L" |"_j4536 7*4Q" $"k This part generates the most irregular line. j;*L" |"_j4536 7 Generate the whole line by black magic @L *4Q Get the first (4*input) characters of it, with wrapping. +\| Add "|" in front of it (we took away the first "|") : " $"k Replace the ending space by nothing J Store the line to J. K+\|*Q" |" This part generates the line just below the irregular line. *Q" |" Repeat " |" input times +\| Prepend "|" K Store to K *lJ\_ Now we can actually start printing * \_ Repeat "_" ... lJ [the length of J] times (and implicitly print it out) jb+*4]J*2]K *4]J Repeat J 4 times *2]K Repeat K 2 times + Concatenate them together jb Join with newlines (and implicitly print it out) :Kd\_ :K Replace in K d " " \_ by "_" (and implicitly print it out) ``` ### Black magic ``` We find the irregular line from input=7, and cut out the first "|": " | | | | | | | | | | | |" 2 1 1 1 2 2 1 1 1 1 1 2 j;*L" |"_j4536 7 Black magic. j4536 7 4536 converted to base 7: [1,6,1,4,0] _ Reverse: [0,4,1,6,1] *L" |" Repeat " |" <each element> times: [""," | | | |"," |"," | | | | | |"," |"] j; Join by whitespace: " | | | | | | | | | | | |" ``` [Answer] # Ruby, 119 bytes ``` ->n{puts ?_*(1+n*4+(0<=>-n%7%4)),(0..6).map{|i|("01"+("%b"%[0xAADAAAD,13][i/4]*99)).tr('10',' |_|'[i/6*2,2])[0,1+n*4]}} ``` **Ungolfed in test program** ``` f=->n{ puts ?_*(1+n*4+(0<=>-n%7%4)), #Draw 1+n*4 _'s for top row (one less if -n%7%4>0, black note), then... (0..6).map{|i| #Cycle through remaining 7 rows ("01"+("%b"%[0xAADAAAD,13][i/4]*99)). #Generate string version of binary number corresponding to pattern, repeat 99 times. tr('10',' |_|'[i/6*2,2] #Binary 1-> space or underscore. Binary 0 -> | (These choices ensured no leading 0) )[0,1+n*4] #truncate to the right amount of keys. } } 10.times{|j|f[j]} ``` [Answer] # ><>, 188 182 bytes ``` &0"_"o011. .\:7%8g95*-"_"o1-:a1@@?.~~~1+:&:&=1+1$ .v~:7=?;ao"|"o1+:0$0$ .>:7%8g"0"-4*:9go1+:9go1+:9go1+9go1+:&:&=3$-1$ ^ .>"| _"{:}7=?$~::oooo1+:&:&(3*2+1$ >^ ^ 0120112 | | | | | ``` The number of white keys to display should be present on the stack at program start. **Edit**: I managed to shave off a few bytes through combining the output for lines 5/6 and 7. Previous version: ``` &0"_"o011. .\:7%8g95*-"_"o1-:a1@@?.~~~1+:&:&=1+1$ .v~ao"|"o1+:0$0$. .>:7%8g"0"-4*:9go1+:9go1+:9go1+9go1+:&:&=3$-1$ ^ .>"| "oooo1+:&:&(3*2+1$ ^ "|___"oooo1+:&:&=?; 0120112 | | | | | ``` [Answer] # PHP, 238 bytes ``` $n=$argv[1];$s=str_repeat;echo'_'.$s($a=$s('_',28),$m=($n-$r=$n%7)/7).substr($a,0,$k=4*$r-($r&&$r!=3))."\n",$g='|'.$s($b=' | | | | | | | | | | | |',$m).substr($b,0,$k)."\n",$g,$g,$g,$h='|'.$s(' |',$n)."\n",$h,'|'.$s('___|',$n)."\n"; ``` As usual, prepend the code with `<?php` , put it into a PHP file (let's name it `keyboard.php`) and run it using: ``` $ php -d error_reporting=0 keyboard.php 55 ``` Two more bytes can be saved on PHP7 by squeezing the initialization of `$n` and `$s` into their first use: ``` echo'_'.($s=str_repeat)($a=$s('_',28),$m=($n-$r=($n=$argv[1])%7)/7).substr($a,0,$k=4*$r-($r&&$r!=3))."\n",$g='|'.$s($b=' | | | | | | | | | | | |',$m).substr($b,0,$k)."\n",$g,$g,$g,$h='|'.$s(' |',$n)."\n",$h,'|'.$s('___|',$n)."\n"; ``` The ungolfed code, a test suite and other goodies can be found [on github](https://github.com/axiac/code-golf/blob/master/ascii-piano-keyboard.php). [Answer] # Python ~~3~~ 2, ~~191~~ ~~185~~ ~~180~~ ~~182~~ ~~171~~ ~~145~~ ~~144~~ ~~133~~ 132 bytes ``` def k(n):print"\n|".join(["_"*(4*n+(9>>n%7&1))]+[''.join(" ||"[1998>>j%12&1::2]for j in range(n*12/7))]*4+[" |"*n]*2+["___|"*n]) ``` This could use some golfing but I've fiddled with the code so much already that I may not see where the golfable spots are. Any golfing suggestions are welcome. **Edit:** Misread the spec on the height of the keys. This bug has been fixed. **Edit:** Borrowed [Neil's 12 key idea](https://codegolf.stackexchange.com/a/79358/47581) from his Javascript answer, removed some parentheses, and switched to Python 2 to save 11 bytes. **Edit:** Lots of changes to get the function down to one `for` loop. **Edit:** Now a program instead of a function. **Edit:** Now using `print"\n|".join()` as suggested by Neil to save 11 bytes. Turned the program back into a function to save a byte. [Answer] # C# 1683 bytes So....after seeing Neil's answer above this is pretty embarrassing, but I'll post it anyway 'cause it took me a while (bless). I used C# to create mine. Inside the "Fncs" class I created an array of the typical order of keys. Then, I created a function which can allow the user to get an appropriate index for this array based on a given integer. In order to edit individual lines, I created a "PianoKeyboard" class which contains a dictionary storing multiple strings representing the individual lines. Finally, I created the "DrawKey" function which appends the appropriate text to the individual lines and the "GetKeys" function which returns the overall string value. ``` namespace ASCIIPiano{public enum WhiteKeyType{Left,Middle,Right}public static class Fncs{public static WhiteKeyType[] Order{get{return new WhiteKeyType[]{WhiteKeyType.Left,WhiteKeyType.Middle,WhiteKeyType.Right,WhiteKeyType.Left,WhiteKeyType.Middle,WhiteKeyType.Middle,WhiteKeyType.Right};}}public static PianoKeyboard DrawKey(this PianoKeyboard keyboard, WhiteKeyType type){keyboard.Append(1,"_____");if (type == WhiteKeyType.Left){keyboard.Append( 2,"| | ");keyboard.Append( 3,"| | ");keyboard.Append( 4,"| | ");keyboard.Append( 5, "| | ");}else if (type == WhiteKeyType.Middle){keyboard.Append(2, " | | ");keyboard.Append(3," | | ");keyboard.Append( 4," | | ");keyboard.Append(5," | | ");}else{keyboard.Append( 2," | |");keyboard.Append(3, " | |");keyboard.Append(4," | |");keyboard.Append(5, " | |");}keyboard.Append(6,"| |");keyboard.Append(7,"| |");keyboard.Append(8,"|___|");return keyboard;}public static int GetWhiteKeyIndex(this int number){return number % 7;}public static string GetKeys(this int quantityofwhitekeys){PianoKeyboard keyboard = new PianoKeyboard();for (int i = 0; i < quantityofwhitekeys; i++){WhiteKeyType key=Fncs.Order[i.GetWhiteKeyIndex()];keyboard.DrawKey(key);}return keyboard.TOTALSTRING;}}public class PianoKeyboard{public PianoKeyboard(){}private Dictionary<int, string> lines = new Dictionary<int, string>();public void Append(int index,string value){if (index > 8 || index < 1){throw new Exception("URGH!");}else{if (lines.Keys.Contains(index)){lines[index] += value;}else{lines.Add(index, value);}}}public string TOTALSTRING{get{string returner = "";foreach (int key in lines.Keys){returner += lines[key] + "\n";}return returner;}}}} ``` ]
[Question] [ ## Challenge Given guitar tablature you must output the song represented by the tab. This may be to the speakers of your computer or to an audio file (.wav, .mp3, .midi, .aiff, etc.). There will also be a second input for timing. The tabs may be input via a file or straight to STDIN. The tab will be in [ASCII form](https://en.m.wikipedia.org/wiki/Tablature#Guitar_Tablature). ## Spec All tabs are for 6 six string guitars with standard E tuning: E2 (82.41 Hz), A2 (110.00 Hz), D3 (146.83 Hz), G3 (196.00 Hz), B3 (246.94 Hz), E4 (329.63 Hz). The only techniques (besides normal picking) you have to cater for are: * Bending (this will always be a half tone bend) * Hammering on * Pulling off * Sliding up/down Since you cannot synthesise the sound of a muted string, treat `x` as a `-`. When bending, output the full transition from unbent to string to bent to unbent again. The second input will be the time that each symbol on the tab represents in seconds. For example: For input: ``` e|--- B|--- G|--- D|--- A|--- E|--- ``` With timing `0.5`, because there are `3` columns of symbols (but no notes), the outputted audio file is (`3*0.5=1.5`) `1.5` seconds of silence. ## Example tabs ### 1 - [The Weight (Jack White, Jimmy Page + The Edge edition)](https://youtu.be/yG0rIJsDSHk) ``` e|----3-----3---3----2---------3--------------------| B|----3-----3---3----3--1-1----3--------------------| G|----0-----0---0----2--0-0----0--------------------| D|----0-----0---2-------2-2----0--------------------| A|----2-----0---2-------3-3----2--------------------| E|----3-----2---x----2--x-x----3--------------------| ``` ### 2 - [Smells Like Teen Spirit](https://youtu.be/hTWKbfoikeg) ``` e|--------------|---------------|-------------|-------------| B|--------------|---------------|-------------|-------------| G|-----8h10-----|-8-8b----6--5--|-6--5--------|-------------| D|-10--------6--|---------------|-------8-6-8-|-8b----6--5--| A|--------------|---------------|-------------|-------------| E|--------------|---------------|-------------|-------------| ``` ### 3 - [Star Spangled Banner](https://youtu.be/sjzZh6-h9fM) ``` e|---0-------2-5---9-7-5-----------9-7-5-4-2-4-5------| B|-----2---2-------------2-4-5---5---------------5-2--| G|-------2-------------------------------------------2| D|----------------------------------------------------| A|----------------------------------------------------| E|----------------------------------------------------| ``` [Answer] # MATLAB This is sort of unfinished. I used a quick and dirty method to make the audio as easily as possible. The method I used made it difficult to implement the bending/hammering (I also had never heard those words in this context before). Having said all of that, this script will read in a text file called "inputs.txt" containing the ascii-tab as required and play the song. ``` %timing t=0.25; %of course, this line could be 't=input('timing: '); %if you make t a wonky value such that t*8192 is not an integer, some %stuff will fail %frequencies and extra variables to allow some laziness later e = 329.63;eN = 1; B = 246.94;BN = 2; G = 196.00;GN = 3; D = 146.83;DN = 4; A = 110.00;AN = 5; E = 82.41;EN = 6; %this will store the song in a more computer friendly way song = zeros(1,6); %function to get frequency from v=frequency and f=fret w=@(v,f)v*(2^(f/12)); %get input and start the big loop file = fopen('input.txt'); line = fgetl(file); while ischar(line) %the first character of the line will give us the the line frequency lfreqv = eval(line(1)); %frequency lfreqN = eval([line(1),'N']); %horizontal index of frequency %start the small loop over each line for k = 3:(numel(line))-1 if (strcmp(line(k),'-'))||(strcmp(line(k),'|'))||(strcmp(line(k),'h'))||(strcmp(line(k),'b')) song(k-2,lfreqN) = 0; else song(k-2,lfreqN) = w(lfreqv,double(line(k))); end end line = fgetl(file); end fclose(file); %this will hold the song tune = []; vols = zeros(1,6); playf = zeros(1,6); for songIndex = 1:size(song,1) ctune = []; for k=1:6 if song(songIndex,k) == 0 vols(k) = 2*vols(k)/4; else vols(k) = 1; playf(k) = song(songIndex,k); end ctune(k,1:t*8192)=vols(k)*sin(0.5*pi*playf(k)*(1:(t*8192))/8192); end tune = [tune ctune]; end soundsc(sum(tune)); ``` [Here is a link to the sound of the first test input.](http://vocaroo.com/i/s1RSSkIeDtcw) [Here is a link to the sound of the third test input.](http://vocaroo.com/i/s1NqtEL69XVf) (Star Spangled Banner or Ice Cream Truck?) The second test input sounded pretty bad to me, but that may be because it uses a lot of `b`s and `h`s which the script ignores. As you can hear, the output is not quite the same quality as the original. It sort of sounds like there's a metronome playing in the background. I think these tunes have character. [Answer] # Python 3 I had to try this one. This converts a tab to a midi file as played by a piano. I have no idea how to do a string bending on a piano, so it can't do that, but hammer-on's and pull-off's are straightforward. I generated the test files like so: `$ python3 tab.py The-weight.txt 0.14` where `0.14` is the length of a single note in seconds. ``` from midiutil.MidiFile3 import MIDIFile import sys # Read the relevant lines of the file lines = [] if len(sys.argv) > 1: filename = sys.argv[1] try: beats_per_minute = 60 / float(sys.argv[2]) except: beats_per_minute = 756 else: filename = 'mattys-tune.txt' beats_per_minute = 756 with open(filename) as f: for line in f: if len(line) > 3 and (line[1] == '|' or line[2] == '|'): line = line.replace('\n', '') lines.append(line) assert len(lines) % 6 == 0 # Initialize the MIDIFile object (with 1 track) time = 0 duration = 10 volume = 100 song = MIDIFile(1) song.addTrackName(0, time, "pianized_guitar_tab.") song.addTempo(0, time, beats_per_minute) # The root-pitches of the guitar guitar = list(reversed([52, 57, 62, 67, 71, 76])) # Assume EADGBe tuning def add_note(string, fret): song.addNote(0, string, guitar[string] + fret, time, duration, volume) # Process the entire tab for current in range(0, len(lines), 6): # The current base string for i in range(len(lines[current])): # The position in the current string time += 1 for s in range(6): # The number of the string c = lines[current + s][i] try: next_char = lines[current + s][i + 1] except: next_char = '' if c in '-x\\/bhp': # Ignore these characters for now continue elif c.isdigit(): # Special case for fret 10 and higher if next_char.isdigit(): c += next_char lines[current + s] = lines[current + s][:i+1] + '-' + lines[current + s][i+2:] # It's a note, play it! add_note(s, int(c)) else: # Awww time -= 1 break # And write it to disk. def save(): binfile = open('song.mid', 'wb') song.writeFile(binfile) binfile.close() print('Done') try: save() except: print('Error writing to song.mid, try again.') input() try: save() except: print('Failed!') ``` The code is on github too, <https://github.com/Mattias1/ascii-tab>, where I also uploaded the result of the examples provided by the OP. I also tried it on some of my own tabs. It's quite weird to hear a piano play it, but it's not bad. ## Examples: I added some direct links, but not sure how long they stay, so I'll keep the old download links as well. 1. [The weight](https://github.com/Mattias1/ascii-tab/blob/master/The-weight.mid), or [play](http://onlinesequencer.net/114835) 2. [Smells like teen spirit](https://github.com/Mattias1/ascii-tab/blob/master/Smells-like-teen-spirit.mid), or [play](http://onlinesequencer.net/114830) 3. [Star sprangled banner](https://github.com/Mattias1/ascii-tab/blob/master/Star-sprangled-banner.mid), or [play](http://onlinesequencer.net/114834) 4. [Matty's tune](https://github.com/Mattias1/ascii-tab/blob/master/mattys-tune.mid), or [play](http://onlinesequencer.net/114829) 5. [dm tune](https://github.com/Mattias1/ascii-tab/blob/master/dm-tune.mid), or [play](http://onlinesequencer.net/114832) And the tab from Matty's tune (my favourite) below: ``` Am/C Am F G Am/C Am e |------------------------|----------------0-------|------------------------| B |-1--------1--1--------1-|-1--------1--3-----3----|-1--------1--1--------1-| G |-2-----2-----2-----2----|-2-----2--------------0-|-2-----2-----2-----2----| D |----2-----------2-------|----2-------------------|----2-----------2-------| A |-3-----2-----0----------|-------0--------0--2----|-3-----------0----------| E |-------------------3----|-1-----------3----------|------------------------| F G Am/C Am F G e |------------------------|------------------------|----------------0-------| B |-1--------3-------------|-1--------1--1--------1-|-1--------1--3-----3----| G |----------4-------------|-2-----2-----2-----2----|-2-----2--------------0-| D |-------3--5-------------|----2-----------2-------|----2-------------------| A |----3-----5--------0--2-|-3-----2-----0----------|-------0--------0--2----| E |-1--------3-----3-------|-------------------3----|-1-----------3----------| Am/C Am F G e |------------------------|------------------------| B |-1--------1--1--------1-|-1----------3-----------| G |-2-----2-----2-----2----|------------4-----------| D |----2-----------2-------|-------3---5------------| A |-3-----------0----------|----3------5------------| E |------------------------|-1--------3-------------| ``` [Answer] # JavaScript **Note: Uses Web Development Audio Kit; This is way out of IE's League; Tested in Google Chrome** You can put the tabs in the textarea. IE you could put Matty's tune from Matty's post in the textarea (with the letters over the notes) and it will still parse correctly. [Click to Run Program](http://jsfiddle.net/gringrant/cgLdkLb9/embedded/result/) JavaScript: ``` context = new AudioContext; gainNode = context.createGain(); gainNode.connect(context.destination); gain= 2; function getValue(i) { return document.getElementById(i).value; } function addValue(i, d) { document.getElementById(i).value += d; } function setValue(i, d) { document.getElementById(i).value = d; } document.getElementById("tada").onclick = updateLines; function updateLines(){ var e=getValue("ta").replace(/[^-0-9\n]/g,'').replace("\n\n","\n").split("\n"); for(var l=0;l<e.length;l+=6){ try{ addValue("littleE",e[l]); addValue("B",e[l+1]); addValue("G",e[l+2]); addValue("D",e[l+3]); addValue("A",e[l+4]); addValue("E",e[l+5]); }catch(err){} } updateDash(); } document.getElementById("littleE").oninput = updateDash; document.getElementById("B").oninput = updateDash; document.getElementById("G").oninput = updateDash; document.getElementById("D").oninput = updateDash; document.getElementById("A").oninput = updateDash; document.getElementById("E").oninput = updateDash; function updateDash() { max = 10; findDashMax("littleE"); findDashMax("B"); findDashMax("G"); findDashMax("D"); findDashMax("A"); findDashMax("E"); applyMax(); i = "littleE"; dash = new Array(); for (var l = 0; l < getValue(i).length; l++) { if (getValue(i).charCodeAt(l) == 45) { dash[l] = true; } else { dash[l] = false; } } /*applyDash("B"); applyDash("G"); applyDash("D"); applyDash("A"); applyDash("E");*/ } function findDashMax(i) { if (getValue(i).length > max) { max = getValue(i).length; } } function applyMax() { if (max < 50) { document.getElementById("stepe").size = 50; document.getElementById("littleE").size = 50; document.getElementById("B").size = 50; document.getElementById("G").size = 50; document.getElementById("D").size = 50; document.getElementById("A").size = 50; document.getElementById("E").size = 50; } else { document.getElementById("stepe").size = max + 1; document.getElementById("littleE").size = max + 1; document.getElementById("B").size = max + 1; document.getElementById("G").size = max + 1; document.getElementById("D").size = max + 1; document.getElementById("A").size = max + 1; document.getElementById("E").size = max + 1; } } function applyDash(i) { var old = getValue(i); setValue(i, ""); for (var l = 0; l < old.length || dash[l] == true; l++) { if (dash[l] == true) { addValue(i, "-"); } else { if (old.charCodeAt(l) != 45) { addValue(i, old.charAt(l)); } } } } document.getElementById("next").onclick = begin; function addDash(i) { while (getValue(i).length < max) { addValue(i, "-"); } } function begin() { setValue("littleE",getValue("littleE").replace(/[^-0-9]/g,'')); setValue("B",getValue("B").replace(/[^-0-9]/g,'')); setValue("G",getValue("G").replace(/[^-0-9]/g,'')); setValue("D",getValue("D").replace(/[^-0-9]/g,'')); setValue("A",getValue("A").replace(/[^-0-9]/g,'')); setValue("E",getValue("E").replace(/[^-0-9]/g,'')); addDash("littleE"); addDash("B"); addDash("G"); addDash("D"); addDash("A"); addDash("E"); setValue("next", "Stop"); //playing = true; findLength(); document.getElementById("next").onclick = function () { clearInterval(playingID); oscillator["littleE"].stop(0); oscillator["B"].stop(0); oscillator["G"].stop(0); oscillator["D"].stop(0); oscillator["A"].stop(0); oscillator["E"].stop(0); setValue("next", "Play"); document.getElementById("next").onclick = begin; } step = -1; playingID = setInterval(function () { step++; setValue("stepe", ""); for (var l = 0; l < step; l++) { addValue("stepe", " "); } addValue("stepe", "V"); if (lg[step]) { oscillator["littleE"].stop(0); oscillator["B"].stop(0); oscillator["G"].stop(0); oscillator["D"].stop(0); oscillator["A"].stop(0); oscillator["E"].stop(0); } qw=0 doSound("littleE"); doSound("B"); doSound("G"); doSound("D"); doSound("A"); doSound("E"); }, getValue("s") * 1000); } function doSound(i) { switch (getValue(i).charAt(step)) { case ("-"): case ("x"): case (""): case (" "): break; default: qw++; makeSound(fretToHz(getHz(i), getValue(i).charAt(step)), i); } checkTop(); } function checkTop(){ switch(qw){ case 0: break; case 1: gain=2; break; case 2: gain=1; break; case 3: gain=.5; break; default: gain=.3; break; } } function getHz(i) { switch (i) { case "littleE": return 329.63; case "B": return 246.94; case "G": return 196; case "D": return 146.83; case "A": return 110; case "E": return 82.41; } } function fretToHz(v, f) { return v * (Math.pow(2, (f / 12))); } /*function getTime() { var u = 1; while (lg[step + u] == false) { u++; } return u; }*/ function findLength() { lg = new Array(); for (var h = 0; h < getValue("littleE").length; h++) { lg[h] = false; fl(h, "littleE"); fl(h, "B"); fl(h, "G"); fl(h, "D"); fl(h, "A"); fl(h, "E"); } console.table(lg); } function fl(h, i) { var l = getValue(i).charAt(h); switch (l) { case "-": case "|": break; default: lg[h] = true; } } oscillator = new Array(); function makeSound(hz, i) { console.log("playing " + hz + " Hz" + i); oscillator[i] = context.createOscillator(); oscillator[i].connect(gainNode); oscillator[i].frequency.value = hz; oscillator[i].start(0); } soundInit("littleE"); soundInit("B"); soundInit("G"); soundInit("D"); soundInit("A"); soundInit("E"); function soundInit(i) { makeSound(440, i); oscillator[i].stop(0); } setInterval(function () { gainNode.gain.value = .5 * getValue("v") * gain; document.getElementById("q").innerHTML = "Volume:" + Math.round(getValue("v") * 100) + "%"; }, 100); ``` [Can you Identify this song?](http://grant.semiaxis.com/playmesong.php?speed=.15&song=e%7C-2-3---2---3------2-3---3---2--------0-2---0---2---------------------------%7C!B%7C-0---0------------1---0--------------3----------------3----1---------------%7C!G%7C------------------0----------------------2---------------------------------%7C!D%7C-2-----------------------------------0-------------------------------------%7C!A%7C------------------------------------------------------0--------------------%7C!E%7C-----------------------------------------------------------0---------------%7C!e%7C-2-3---2---3------3-2---3---2--------0-2---0---2---------------------------%7C!B%7C-0---0------------1---0--------------3----------------3--------------------%7C!G%7C------------------0----------------------2---------------------------------%7C!D%7C-2-----------------------------------0-------------------------------------%7C!A%7C------------------------------------------------------0--------------------%7C!E%7C---------------------------------------------------------------------------%7C) [Answer] # Java This program converts a tablature to 16-bit WAV format. Firstly, I wrote a whole bunch of tablature parsing code. I'm not sure if my parsing is entirely correct, but I think it's okay. Also, it could use more validation for data. After that, I made the code to generate the audio. Each string is generated separately. The program keeps track of the current frequency, amplitude and phase. It then generates 10 overtones for the frequency with made-up relative amplitudes, and adds them up. Finally, the strings are combined and the result is normalized. The result is saved as WAV audio, which I chose for its ultra-simple format (no libraries used). It "supports" hammering (`h`) and pulling (`p`) by ignoring them since I really didn't have the time to make them sound too different. The result sounds a bit like a guitar, though (spent some hours spectrum analyzing my guitar in Audacity). Also, it supports bending (`b`), releasing (`r`) and sliding (`/` and `\`, interchangeable). `x` is implemented as muting the string. You can try tweaking the constants in the start of the code. Especially lowering `silenceRate` often leads to better quality. ## Example results * [The Weight](https://soundcloud.com/user373087442/the-weight-tablaturesong) * [Smells Like Teen Spirit](https://soundcloud.com/user373087442/smells-like-teen-spirit-tablaturesong/s-1vEyJ) (sounds weird, I blame the tab :D) * [The Star Spangled Banner](https://soundcloud.com/user373087442/the-star-spangled-banner-tablaturesong) (modified tab for rhythm) * [Matty's Tune](https://soundcloud.com/user373087442/mattys-tune-tablaturesong) (from [this answer](https://codegolf.stackexchange.com/a/52614/30164)) ## The code I want to warn any Java beginners: do *not* try to learn anything from this code, it's terribly written. Also, it was written quickly and in 2 sessions and it was not meant to be used ever again so it has no comments. (Might add some later :P) ``` import java.io.*; import java.util.*; public class TablatureSong { public static final int sampleRate = 44100; public static final double silenceRate = .4; public static final int harmonies = 10; public static final double harmonyMultiplier = 0.3; public static final double bendDuration = 0.25; public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Output file:"); String outfile = in.nextLine(); System.out.println("Enter tablature:"); Tab tab = parseTablature(in); System.out.println("Enter tempo:"); int tempo = in.nextInt(); in.close(); int samples = (int) (60.0 / tempo * tab.length * sampleRate); double[][] strings = new double[6][]; for (int i = 0; i < 6; i++) { System.out.printf("Generating string %d/6...\n", i + 1); strings[i] = generateString(tab.actions.get(i), tempo, samples); } System.out.println("Combining..."); double[] combined = new double[samples]; for (int i = 0; i < samples; i++) for (int j = 0; j < 6; j++) combined[i] += strings[j][i]; System.out.println("Normalizing..."); double max = 0; for (int i = 0; i < combined.length; i++) max = Math.max(max, combined[i]); for (int i = 0; i < combined.length; i++) combined[i] = Math.min(1, combined[i] / max); System.out.println("Writing file..."); writeWaveFile(combined, outfile); System.out.println("Done"); } private static double[] generateString(List<Action> actions, int tempo, int samples) { double[] harmonyPowers = new double[harmonies]; for (int harmony = 0; harmony < harmonyPowers.length; harmony++) { if (Integer.toBinaryString(harmony).replaceAll("[^1]", "").length() == 1) harmonyPowers[harmony] = 2 * Math.pow(harmonyMultiplier, harmony); else harmonyPowers[harmony] = Math.pow(harmonyMultiplier, harmony); } double actualSilenceRate = Math.pow(silenceRate, 1.0 / sampleRate); double[] data = new double[samples]; double phase = 0.0, amplitude = 0.0; double slidePos = 0.0, slideLength = 0.0; double startFreq = 0.0, endFreq = 0.0, thisFreq = 440.0; double bendModifier = 0.0; Iterator<Action> iterator = actions.iterator(); Action next = iterator.hasNext() ? iterator.next() : new Action(Action.Type.NONE, Integer.MAX_VALUE); for (int sample = 0; sample < samples; sample++) { while (sample >= toSamples(next.startTime, tempo)) { switch (next.type) { case NONE: break; case NOTE: amplitude = 1.0; startFreq = endFreq = thisFreq = next.value; bendModifier = 0.0; slidePos = 0.0; slideLength = 0; break; case BEND: startFreq = addHalfSteps(thisFreq, bendModifier); bendModifier = next.value; slidePos = 0.0; slideLength = toSamples(bendDuration); endFreq = addHalfSteps(thisFreq, bendModifier); break; case SLIDE: slidePos = 0.0; slideLength = toSamples(next.endTime - next.startTime, tempo); startFreq = thisFreq; endFreq = thisFreq = next.value; break; case MUTE: amplitude = 0.0; break; } next = iterator.hasNext() ? iterator.next() : new Action(Action.Type.NONE, Integer.MAX_VALUE); } double currentFreq; if (slidePos >= slideLength || slideLength == 0) currentFreq = endFreq; else currentFreq = startFreq + (endFreq - startFreq) * (slidePos / slideLength); data[sample] = 0.0; for (int harmony = 1; harmony <= harmonyPowers.length; harmony++) { double phaseVolume = Math.sin(2 * Math.PI * phase * harmony); data[sample] += phaseVolume * harmonyPowers[harmony - 1]; } data[sample] *= amplitude; amplitude *= actualSilenceRate; phase += currentFreq / sampleRate; slidePos++; } return data; } private static int toSamples(double seconds) { return (int) (sampleRate * seconds); } private static int toSamples(double beats, int tempo) { return (int) (sampleRate * beats * 60.0 / tempo); } private static void writeWaveFile(double[] data, String outfile) { try (OutputStream out = new FileOutputStream(new File(outfile))) { out.write(new byte[] { 0x52, 0x49, 0x46, 0x46 }); // Header: "RIFF" write32Bit(out, 44 + 2 * data.length, false); // Total size out.write(new byte[] { 0x57, 0x41, 0x56, 0x45 }); // Header: "WAVE" out.write(new byte[] { 0x66, 0x6d, 0x74, 0x20 }); // Header: "fmt " write32Bit(out, 16, false); // Subchunk1Size: 16 write16Bit(out, 1, false); // Format: 1 (PCM) write16Bit(out, 1, false); // Channels: 1 write32Bit(out, 44100, false); // Sample rate: 44100 write32Bit(out, 44100 * 1 * 2, false); // Sample rate * channels * // bytes per sample write16Bit(out, 1 * 2, false); // Channels * bytes per sample write16Bit(out, 16, false); // Bits per sample out.write(new byte[] { 0x64, 0x61, 0x74, 0x61 }); // Header: "data" write32Bit(out, 2 * data.length, false); // Data size for (int i = 0; i < data.length; i++) { write16Bit(out, (int) (data[i] * Short.MAX_VALUE), false); // Data } out.close(); } catch (IOException e) { e.printStackTrace(); } } private static void write16Bit(OutputStream stream, int val, boolean bigEndian) throws IOException { int a = (val & 0xFF00) >> 8; int b = val & 0xFF; if (bigEndian) { stream.write(a); stream.write(b); } else { stream.write(b); stream.write(a); } } private static void write32Bit(OutputStream stream, int val, boolean bigEndian) throws IOException { int a = (val & 0xFF000000) >> 24; int b = (val & 0xFF0000) >> 16; int c = (val & 0xFF00) >> 8; int d = val & 0xFF; if (bigEndian) { stream.write(a); stream.write(b); stream.write(c); stream.write(d); } else { stream.write(d); stream.write(c); stream.write(b); stream.write(a); } } private static double[] strings = new double[] { 82.41, 110.00, 146.83, 196.00, 246.94, 329.63 }; private static Tab parseTablature(Scanner in) { String[] lines = new String[6]; List<List<Action>> result = new ArrayList<>(); int longest = 0; for (int i = 0; i < 6; i++) { lines[i] = in.nextLine().trim().substring(2); longest = Math.max(longest, lines[i].length()); } int skipped = 0; for (int i = 0; i < 6; i++) { StringIterator iterator = new StringIterator(lines[i]); List<Action> actions = new ArrayList<Action>(); while (iterator.index() < longest) { if (iterator.get() < '0' || iterator.get() > '9') { switch (iterator.get()) { case 'b': actions.add(new Action(Action.Type.BEND, 1, iterator.index(), iterator.index())); iterator.next(); break; case 'r': actions.add(new Action(Action.Type.BEND, 0, iterator.index(), iterator.index())); iterator.next(); break; case '/': case '\\': int startTime = iterator.index(); iterator.findNumber(); int endTime = iterator.index(); int endFret = iterator.readNumber(); actions.add(new Action(Action.Type.SLIDE, addHalfSteps(strings[5 - i], endFret), startTime, endTime)); break; case 'x': actions.add(new Action(Action.Type.MUTE, iterator.index())); iterator.next(); break; case '|': iterator.skip(1); iterator.next(); break; case 'h': case 'p': case '-': iterator.next(); break; default: throw new RuntimeException(String.format("Unrecognized character: '%c'", iterator.get())); } } else { StringBuilder number = new StringBuilder(); int startIndex = iterator.index(); while (iterator.get() >= '0' && iterator.get() <= '9') { number.append(iterator.get()); iterator.next(); } int fret = Integer.parseInt(number.toString()); double freq = addHalfSteps(strings[5 - i], fret); actions.add(new Action(Action.Type.NOTE, freq, startIndex, startIndex)); } } result.add(actions); skipped = iterator.skipped(); } return new Tab(result, longest - skipped); } private static double addHalfSteps(double freq, double halfSteps) { return freq * Math.pow(2, halfSteps / 12.0); } } class StringIterator { private String string; private int index, skipped; public StringIterator(String string) { this.string = string; index = 0; skipped = 0; } public boolean hasNext() { return index < string.length() - 1; } public void next() { index++; } public void skip(int length) { skipped += length; } public char get() { if (index < string.length()) return string.charAt(index); return '-'; } public int index() { return index - skipped; } public int skipped() { return skipped; } public boolean findNumber() { while (hasNext() && (get() < '0' || get() > '9')) next(); return get() >= '0' && get() <= '9'; } public int readNumber() { StringBuilder number = new StringBuilder(); while (get() >= '0' && get() <= '9') { number.append(get()); next(); } return Integer.parseInt(number.toString()); } } class Action { public static enum Type { NONE, NOTE, BEND, SLIDE, MUTE; } public Type type; public double value; public int startTime, endTime; public Action(Type type, int time) { this(type, time, time); } public Action(Type type, int startTime, int endTime) { this(type, 0, startTime, endTime); } public Action(Type type, double value, int startTime, int endTime) { this.type = type; this.value = value; this.startTime = startTime; this.endTime = endTime; } } class Tab { public List<List<Action>> actions; public int length; public Tab(List<List<Action>> actions, int length) { this.actions = actions; this.length = length; } } ``` ]
[Question] [ Each character in this 64 by 64 block of text has been chosen randomly and uniformly from the 95 [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters. ``` /rq$:Zy5*g'$DeGXX2o8y "{@Cg:FR9qih}xh >5$DsF1Fs5Ao~smFp;.RJbV )U c4\(|Sx*V$10G9xO:NjHKasem%,\9[pPm@&kTaN~HC[;9`lgqlAH(7dt0a-5}LJ[ &sifw9V-.PLRoD~F'dJYA^Q)L#h>$9h!B4b&ceKp8~HndzDm#1/ySydrf5T8[Y%4 U9>HLQ74Qf[^V9tpWrKFcFxZJ::4?z/o]3u,V[B&hB9lFYA0:rW#yql5z9.d*D}U :M2*O9'7_HMGw_=%@hR>O+(@Dr6MIt(=/{-{4lia0Vmws32wr(fnTmT%HSo&7!uz \KZWG&KnXh+6E+Q>%pV(<Bnm-d+p~y~]Ta"aw9)]0A_AHz\tP3&}1R^/yPPSgN?8 ".7|Uj)S7-k[`yeLO~P2a?z3wiS(R-\k'?z(pVm;;D^k/q84?&7:,E*9$UQ"UbBJ ME]&*R ,*7PDF4Tw*-;De{YeP_al.CJcJX`@V_y+>^<h{L[^Y"!RxjN^lyA_/Y=( #C>Zo#Sl;UUD5ChIj'L@rkELk%S*]a$87j\\n;}796m/\NPL>8d-T-hR!7ftw ?A tV5"E309bAv$jhE6\'8f?VGlBb?z#V;F((3'|}$tfpiNB>"*mxc,X1s:/%x*JQAL rxYXUJsd?X}^yc|'16539vd=psU'>|y/!$-TRamKcJk^2-aD35h7CcaRNue"8#{; @yUq?*(72I8@I)So+]RwtKy:mLhjG/f#:U<TXml<PtX*+,ngfZt75-q*gSsyI2tS |*M*;yz6u2(LZ>W`bth-7G~>|dh'pm}]@"#Oq9%o\W)b,gh%b1O]4F:EGb7ERI=@ ehMo69slKw=S@<j*Q4sfd\1')#)V&yaPF%%ZG6VK\_-$Cab,nrlW"O(<tu&xU=I& |[g4k2L;FD)=yX0SsE-|vI(mDOccuU(+m\wxgrJxi8ZP[uD)L.!K@]%@q`!pk8Yx ?PZaS3;x,7nK~IHlrCGy~xq:@K/CJ1J^oeac&Tv?6[H>>0lu?(/bh@6J^@S?IY-| @tdN$K=Ci2;_0Du;L2OO'en|]<_`nX5p3Bes9`8{}fRCV$X&aoQGYS'$j%r<2709 UwETsAo^d!aUZ0vN5,Yq\n%JAIm}%O88FAJK^Jt&=jM\Q1^+^|X8\._"l%hlF+yH +c^FBFxTGz|f|#kElQs)mS64-3Z\An]|[rQo"OQ+ IP"ARdJ}/OYFQF_/{B 73mU UPvxNByN[2TT,XgRZ_LwolUVWuR)DjYI7j#mmA8m?&Y}}[_h8@Y-R*,#=1\D*&@* ePW.w{@z3moe3Vztd,>?*~ZQUvn8$+xw$$f92D*kPZ":;lcTr3m&{*?j$FgZK|cU IAd'0C{<4b}NuhX1B#gmk'oF4+(@fzP^T?hF/#]g^y rb5][)X-d4Q't~1]HE"tZ p2Z,%H0$EWF/%|UQm?&]E~=v;9YwxrSs%}df`[ `SfXMJWt86UY1duGAAKkFSrH! oUyB[soS!N%XYwX]%n K^}CcTE?~.,8`C&l)Jjjp5|z))!o/ "G)sj,{OETsi:KE 4E,':a=,T~YlxdF^<\$fE|f:_-RG}7=m%g\-9a*X]`n<P$D+q7O`+$P&!\"NUs7n hL@0s 7i^Xp\._4$lZIB9Ql AXX_00K=<hp%55KSO6yWH~cGe%|(p_WzlhPUbH{? o5b4pi(,]&&jB\hGa:\DQbrYc,n|,b)_E{n~i~+JSxn?%/qJVm|B 8"Jf||L.|M- KRxH;T^Z7%ZufyO=nI;[v1\8ZTg\_)ect4DvMTvqtoo(;b~J&'~E2TTD!w1BvGv Q+1sv>q%1$BaCm%(\%uGH*]emoFwejkhb$gKm=DVG#&:p'";s)&MY30q_cG=.CKJ q,aWTi|^w2wg3<G_y<n+^Xq2ymHFs#7z[x0l'Lz6N>Mpo?=hAd&58HVMhsh(kQH5 &kSivkn`,KON9xb:$M[L15!D6W?\ASWc#}V#2U;qxKhtil73,!iuG~(lr[tPJQ6w IZ)0Vp{kEUID:vgwmTMQ#Y]NdX6{'/3bI2x9k 4[>j)&Q0U,t,iA#A%4929o6+n_ SQe/!KubbuXthMe&2\%:'Z`,aaA)V&(v+]0^v-_@*Qg!^K!pCo"@e/|3}.3q^R|| 6hF>/jd>(=il~2$KY.^x~K_H)J8Fi)'LOcUr4xJir^v0,c fIsoT<|7K}Bls|36z MQ|-w=bp)_EY>YtGcW)!@/|Lc:I_<]x.~[|QSgJY1ZX9^e`ojAR6U#zt9!,44}># EJzH \gwosC>Z*)H!]1BPaIEYGyk{c0zv{d\#px2@#'-T{{.Qxknxv}"x3#K]w>; <X(\bNnY_6*7Yu7_3a+wInwt vh=1eBgz>7Bnhs!<t.T#&V{+?p+{.RTN:xz>|,E $upN*[F4A`~ZDMDt{.&2z+LZ7bcfeJfF9Uy3xX]ZzQ1FvB.U4S!hm$LYCp: wF7h 47-+lY$"}AExXQ@?!/6}biptH=6N-6&8-T\C8{`i56e'%cimv,0QKYTx) "nkFJ C:Enw=Q%6J;t6wS+2O,b0v'"OK6GMbr);y#-H86>pCE6wjdk*rR*=reWo57^2TFH ::Nq,t9_S">\o^NZzh|U\^qyh-yt0nvMs%'6\;$%(91gTC=&1q]q-*u*so KrXsE -Sz>q]l86[OO@\5W<'\XDc,%/=0sV0&1'Etty%f ~,c45IIqy=no.DY{8\?fa<9{ 6%3TP:i^q.JzU217CADu}iAzWT""E\{IEMbGDKZB6s*LmlM0|<WA8CP7sR}f?WSL S`T} 7Tn9!h8P\W 8J\#Mg\o;Qwt&4\UYKf{)O3G&B]sK.bw1!?7=:h$IIOIakD< H/O5v`ld*35MSsydSQoiAnJ*\!^?'_=6E?c> PtM!rw5y{ZT2xSco){3_?j|wtJp CT1!e~k8aNgw)LE:}oX4R*<u]TB%\IN8YoMK'bV%L2H{L3'c/|xoTY^&&WPKSyo< cXma$Rfjj^':^a\?$UOo48]791Wywj7aH1\iP|\l=sjjbjqZB2)-apvjV@q47Spw OP[kT<l@cKB="n;VC#6a*InmS~$TN{= j)r>S] uH9:E-}y>.Ygc'll$5Y$j]AYt jB="iGo7[qY~A*nv.\51[<]):^[iZs4s-D_bC'OfM%lHlz;MoxY$Ku]NCt72PYMB _(myN5'%] C!7FPoGX7+*,Yptuaz;Q6W,;R|U1XEhgq21R7<ncnDB<D_);j.:r0r Q6!k|Dq`!Jz7l="*n?w@f|h=PA_A)n._ii:s~'n~XsD}?JRIkC9AW^piUfBTU,ui nf+yZ`7P-(@{>s:{Vz'N 7qB&+UZbm4'0]D~HZNJq.w</3 \cL)WRDP(y]w~L4N/ !!lA+NK[+9#-iwx`PE53D.K2]]#M.Rm$^Cc'|!@cX6{yCg8K0|>E_jyup|+'=#c% Ao5$B);DoQ#jg[7GbdE+o:R,T#@`;UnX}.?2z\RJ98Se*_.*e8mCUF}Vw1u13cy1 2s}1@?{0);Jo6(J@l>[M 0CkeO6{ExN7,%Kv1#[!** czaX)=;Q~D;z',fkq!1W< % f(i#i`PQY!m7v#D:j5pyU]8:at2,k("BWZRI<WR??GQ$^1d[m,F(<e5CLv-m*B CD)zVpa95WpJ K@&}yN\Q8I<%z/*_/bPsR5=0\Z=#mWZDAfA5[k|$Yks@Q;@h,s/ Np.$gTvz>T+"0|$Nw::%m$GFYxG{2akv$Eh8\4|eW'oJEffNzJ>UxU4>oITZMe/' EMg$>kD|\ ^.W)Stzv/7z\^bdi]E@] U&-r8(B^?}$P56[?e~jE#_j)5=#~.yNP$ 'mgF3EAhXB 55)\WXp*e+fD#^&SHGx++7VO[R7*b(Q+:jESt'K%m~d$Bv^/{7=zr 5oCZDp& ;*Y*G`L$C]Nm`|^:y2NKaO!)u/{hwm(VjS`<qKgNw7[+~0 <be'sWjTo [[emailย protected]](/cdn-cgi/l/email-protection)*ml)pLeEVJ~8A$mgz*d>ajbg1FIYrg6J`D0xJMXi`ghA1V$ju *rJg/ o;6M7`(qTF.nO'4da,{ieM&NC9rg;nX*))*DK"DycYD66&6z/I@}y4@$<f 3S]~9g An{=Rj|y&A2Vh^F\3lb#N~8w0EMx<K$]z(eZS~zbmgeeV\i7,MY~zrc+; ``` Your task in this challenge is not to write your own code, but rather to extract code from this block of text as if it is a huge [Boggle](http://en.wikipedia.org/wiki/Boggle) grid and you're looking for a runnable program instead of a word. The submission with the program that produces the longest finite output wins. # Details Treat the 64 by 64 grid of text exactly like a 64 by 64 Boggle grid with additional characters. Construct a string that is a runnable program in some language by choosing a starting location in the grid and repeatedly moving one step vertically, horizontally, or diagonally (8 directions total) as many times as you want. **You may NOT use the same grid space more than once!** For example, these 4 lines were taken from near the middle of the text block: ``` EJzH \gwosC>Z*)H!]1BPaIEYGyk{c0zv{d\#px2@#'-T{{.Qxknxv}"x3#K]w>; <X(\bNnY_6*7Yu7_3a+wInwt vh=1eBgz>7Bnhs!<t.T#&V{+?p+{.RTN:xz>|,E $upN*[F4A`~ZDMDt{.&2z+LZ7bcfeJfF9Uy3xX]ZzQ1FvB.U4S!hm$LYCp: wF7h 47-+lY$"}AExXQ@?!/6}biptH=6N-6&8-T\C8{`i56e'%cimv,0QKYTx) "nkFJ ``` Starting with the `p` near the right end of the third line I can move to the by going diagonally down and right, then to the `"` by going right, then up 3 times over `zK`, and left 4 times over `#3x"`. This traces out the string `p " zK#3x"` which when run as a [Ruby](http://www.tutorialspoint.com/execute_ruby_online.php) program outputs `" zK#3x"`. The goal is to find a program that produces the longest **finite** output. **Only printable ASCII characters are considered when counting the length of the output (this means tabs and newlines are not counted), though other characters may be present.** The Ruby example only produces 8 characters. Also... * The program may be from 1 to 4096 characters long. * The program may not contain tabs, newlines, or non-printable ASCII (as they aren't in the grid). * The program should run and exit without errors. * There are no time or complexity constraints as long as the program would *eventually* terminate with finite output. * The grid does not loop around from left to right or top to bottom. Please mention where your program appears in the grid so we can quickly verify that it really is there. [Answer] # CJam, over (81182737^2813292)โ†‘โ†‘(10604499373-1) chars Okay I think I've finally sorted everything out. This was fun โ€” coming up with the code was like navigating a minefield. --- Before we dive in, let's start with a simpler example ([try it online](http://cjam.aditsu.net/)): ``` 1 3{(\1\{(\5*\}h;\}h; ``` `h` is a do-while loop that leaves the condition on the stack, and `{}` are code blocks. The inner block is: ``` ( Decrement \ Swap top two of stack 5* Push 5 and multiply \ Swap back ``` Suppose the top of the stack is `[1 10]` and we perform the do-while `{(\5*\}h;`. This is what happens: ``` [1 10] --decrement--> [1 9] --swap--> [9 1] --multiply--> [9 5^1] --swap--> [5^1 9] --decrement--> [5^1 8] --swap--> [8 5^1] --multiply--> [8 5^2] --swap--> [5^2 8] --decrement--> [5^2 7] --swap--> [7 5^2] --multiply--> [7 5^3] --swap--> [5^3 7] ... ``` This happens until the 10 decrements all the way down to 0 and the loop terminates, at which point we end up with `[5^10 0]` at the top of the stack. We can then use `;` to pop the zero, leaving `[5^10]`. In other words we have just performed exponentiation, with `[1 x]{(\5*\}h;` resulting in `[5^x]`. The outer block `{(\1\{(\5*\}h;\}h;` is similar, but instead of the `5*` in the middle we have our "exponentiate base 5" loop. So for our simple example, starting with `[1 3]` we get: ``` [1 3] -dec/swap-> [2 1] -push 1-> [2 1 1] -swap-> [2 1 1] -5^-> [2 5] -swap-> [5 2] -dec/swap-> [1 5] -push 1-> [1 5 1] -swap-> [1 1 5] -5^-> [1 5^5] -swap-> [5^5 1] -dec/swap-> [0 5^5] -push 1-> [0 5^5 1] -swap-> [0 1 5^5] -5^-> [0 5^5^5] -swap-> [5^5^5 0] ``` The top is zero, so we stop the loop and pop, leaving `[5^5^5]`. In other words, we have just created `5^5^5`, or `5โ†‘โ†‘3` in [Knuth's up arrow notation](https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation). You can switch 5 and 3 for other numbers but hyperexponentiation gets big **fast**, so I wouldn't recommend picking anything too large. --- Now for the real thing: ``` 1B);0D+9#{z(J Y=A*;\VC#UooJ87<W5^o\OO>;J6%_9=+NpXzH|>!p{Kdp(_E=XIK21^%^Z&&p\Y~!E<432|T|Z#00I0*boW)I^8227(*JEo*#09;*7XH+G^o9=pWdK>(2P-*I\6539K~>)#D@</CJ1(+^po\F"U$(jX?a"apV\|;}_V);;D00&phVA^^6pJP\<%o\8H>V1^+aoXY-Y&41-X)8/o!Jb;}"}:rM)<W?o:p'";h ``` [*(Path trace)*](https://i.stack.imgur.com/FOfYk.jpg) Anotated (anything without notes is filler): ``` 1 Push 1 B); 0D+9# Push 13^9 = 10604499373 { Start outer block z ( Decrement J Y=A*; \ Swap VC#Uoo J87< Push 1 W5^o \ Swap back OO>; J6%_9=+NpXzH|>!p { Start inner block Kdp ( Decrement _E=XIK21^%^Z&&p \ Swap Y~!E<432|T|Z#00I0*boW)I^8227(*JEo*# Push 81182737^2813292, <output 3 chars> 09; * Multiply by previous large number 7XH+G^o9=pWdK>(2P-*I\6539K~>)#D@</CJ1(+^po \ Swap back F"U$(jX?a"apV\|; } End inner block _V);; D00&p h Perform inner do-while loop VA^^6pJP\<%o Pop top of stack by outputting \ Swap back 8H>V1^+aoXY-Y&41-X)8/o!Jb; } End outer block "}:rM)<W?o:p'"; h Perform outer do-while loop ``` It's basically the same as the simple example, just with a lot of filler while navigating from one instruction to another in the grid. Instead of 5 and 3 we have `81182737^2813292` and `10604499373`, meaning that `(81182737^2813292)โ†‘โ†‘10604499373` gets outputted at the end (given enough time and memory, of course!). Note that this is merely a lower bound โ€” there's a lot of other printing that takes place, e.g. with 6 and 3 the output is over 2 million chars long even though `6^6^6` has only 36k digits. If you want to try this full version for yourself, test with: ``` 1B); 3 {z(J Y=A*;\VC#UooJ87<W5^o\OO>;J6%_9=+NpXzH|>!p{Kdp(_E=XIK21^%^Z&&p\ 5 09;*7XH+G^o9=pWdK>(2P-*I\6539K~>)#D@</CJ1(+^po\F"U$(jX?a"apV\|;}_V);;D00&phVA^^6pJP\<%o\8H>V1^+aoXY-Y&41-X)8/o!Jb;}"}:rM)<W?o:p'";h ``` replacing the 5 and 3 on the second and fourth lines with numbers of your choice. Note that the output will have a few extra digits around the important hyperexponentiated number (namely a preceding `010` and a trailing `0`). --- ## A few notes on CJam You might we wondering: why not use CJam's inbuilt exponentiation (`#`) instead of the inner do-while loop? Unfortunately, after digging through CJam's source, I learnt that for exponentiation the *base* can be a BigInt (arbitrary precision) but **the exponent gets converted to a normal 32-bit int**. This has some amusing, but annoying side effects: ``` 2 2 31# # --> java.lang.ArithmeticException: Negative exponent (should be 2^2^31) 2 2 32# # --> 1 (should be 2^2^32) ``` This meant that I couldn't use CJam's builtin exponentation when the exponent is too large, for overflow reasons. However, multiplication is different as multiplying two BigInts results in a new BigInt, so I decided to exploit that instead. [Answer] # TECO, ~2^31 \* 13 ~= 27.9 \* 10^9 ``` ?^e=<\RZK%B"svbk7,.c2z\R!Z~|bS|VM!2=9%MEX'1UC> ``` ![enter image description here](https://i.stack.imgur.com/rhFS4.png) Edit: Changed a couple of characters because I accidentally reused one, but that part was inside a comment so it doesn't make much difference. The `?` turns on command echoing, which I use to create most of the output. Then the characters `\RZK%B"s'1UC>` are printed in a loop. `%B"s` adds one to B and then tests if it is less than zero. Thus, this conditional should be entered after 2^31 cycles when it overflows to a negative number. Inside the conditional there is an `EX` command which exits the program. Currently I am attempting to run it to completion with the output directed to a file. [Answer] # [HQ9+](http://esolangs.org/wiki/HQ9+) (17195 characters) **Source:** ``` 9Q9 ``` (starts at 5:4 and then down) **Output:** The text to the song "99 bottles of beer" (8596 characters), the string `9Q9` (3 characters) and another copy of "99 bottles of beer" (8596 characters). This is a very lame answer and you should not upvote it, but someone had to post it. ]
[Question] [ It is Halloween and [Jimmy](https://codegolf.stackexchange.com/search?tab=newest&q=is%3aq%20title%3ajimmy) (`/o\`) has gone into a mysterious neighborhood for trick-or-treating (ask himself why). Now some evil ghosts are chasing him. Can Jimmy escape the ghosts? ## Challenge: **Input:** A board showing position of Jimmy, ghosts, solid objects and empty spaces. An example 10x5 board, `o` is Jimmy (we needed a single character Jimmy), `g`s are ghosts, `#`s are solid objects and `.`s are empty spaces: ``` ########## ......g... #.o....... #.....g... ########## ``` **Output:** A truthy value if Jimmy can escape at least in one scenario, otherwise a falsy value. ## How things work: Ghosts and Jimmy can move one space each turn. There are 4 possible movements: left, right, up, down (no diagonal movements, no skipping). On each turn, first ghosts move one space towards Jimmy. Ghosts always select the closest path to Jimmy, if two possible moves towards Jimmy have the same cost, the move going to left or right is chosen. Ghosts **can go through solid objects**, meaning at the end of a turn a ghost can be on same space as a solid object. Multiple ghosts can stay on same space too. This basically means all the ghosts on the same space will move exactly like each other after that point (they are all like a single ghost now). After all ghosts have moved, if any of the ghosts ends up on the same space as Jimmy, Jimmy is caught and you have to try another scenario. If Jimmy is not caught, he moves next. You have to decide on Jimmy's moves. Jimmy **cannot go through solid objects**. If Jimmy moves to a space with a ghost, he is caught. Jimmy **cannot move into a space he has already visited**. If Jimmy has no valid moves, consider him caught. After Jimmy has moved, if he ends up on an empty border space (i.e. a space on the edge of the grid without a ghost on it), he has escaped. If you can find at least one scenario where Jimmy can escape, output a truthy value. Also if the input position before doing any moves is already an escape position, it is valid and you should return truthy. If Jimmy is caught or out of valid moves in all possible scenarios, then return a falsy value. ## Challenge rules: * You can use any consistent characters that you like for Jimmy, ghosts, solid objects and empty spaces in the input. You cannot use same character for different types of items though. * The input board is always a rectangle or square with a minimum size of 2x2 and a maximum size of 10x10. * Input is flexible as long as you don't include anything more than initial board information (for example, you cannot include if the initial board is already an escape position or not). It can be a multi-line string, a list of strings, a 2d array or matrix of characters or numbers, etc. It can also be position of items, for example a `(x, y)` for Jimmy and two lists of `(x, y)`s for ghosts and solid objects. You can also pass board size as a separate input if you like. Basically any format and combinations of inputs that don't include more than the initial board information are allowed. * Input is guaranteed to always have a single Jimmy. * Input always has at least one ghost. * Input always has at least one solid object. * Input can never start in a position where more than one item is on same space. * Input can start in a position which already is an escaped position for Jimmy (any input with Jimmy on a border space), you should return truthy for cases like this. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes for every language wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: **Truthy:** *Jimmy can move left, up, left to escape:* ``` ########## ......g... #.o....... #.....g... ########## ``` *Jimmy is already on a border space, this is an escape:* ``` #. og ``` *If Jimmy moves only left or only right, he escapes:* ``` ######### ......... ....g.... ...g.g... ....o.... ...g.g... ....g.... ......... ``` *Jimmy has only two ways, one of them is an escape:* ``` ########## #g.o.....# ########.# #........# #.######## #........# ########.# #........# #.######## ``` **Falsy:** *Jimmy is caught by first move of any of the ghosts:* ``` ..... ..g.. .go.. ..... ..... ``` *Jimmy has no valid moves:* ``` ###....... #o#......g ###....... ``` *Jimmy will run out of valid moves before ghost can catch him:* ``` #####..... #o..#....g #####..... ``` *Remember, ghosts can go through solid objects:* ``` g#.# .#.# .#.# .#o# .#.# .#.# g#.# ``` *Oh poor Jimmy! It is a dead end...* ``` ########## #...o....g ########## ``` *Jimmy!!? How did you get there in the first place?* ``` #.######## #g.......# #....g...# #......g.# #..g.....# #....g...# #........# #....g...# #..g....o# ########## ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~236~~ ~~235~~ ~~227~~ 212 bytes ``` def f((x,y),G,M,U=[]): R=1-(len(M[0])-1>x>0<y<len(M)-1);H=[(u+cmp(x,u),v+cmp(y,v)*(u==x))for u,v in G];d,e=0,1 for _ in' '*4*(R<1>((x,y)in H)):J=z,w=x+d,y+e;d,e=-e,d;R|=M[w][z]>(J in U)<f(J,H,M,U+[J]) return R ``` [Try it online!](https://tio.run/##hVRNb@IwFDzjX2E1h9hgEKG0B8AcA0LiQukpG60QGEMFCcoHJdX@d/a9xEmAbrWWeDxPxuPhwXDKkl0Y9K7XjdrSLWMXkXExEXPxLj2fDwhdSKfNDipgc6/r87Yzvoy7o2yUI7Dlw6n0WNpaH09wNuXinLeZOPMmS6W8cL4NI5qKM90HdOIPN0LJrnAIRfg3gDa1m/0mW4yccXE98KacD2byS3zKS2sjspbKj7WV2AwXf@Tc@/S9L3/MZqj5zkdbNhNT9NzyZj4nNFJJGgV0cX1bOtK2batapJMvDS9idcJih22NVgsOEvK27OUKHRJqAzzfSRpFPFpq5J0u5HAb/gOreMUy0v0Ht5Y2Hq3KF7blKWxr7g36H25xm5vPprSuseqwNEVubLk9Y6saV2haTWrUcOvplFy4u@Ia1HDzj6vRZuemhLdbfGrYL4/DKUerv31p7mvxpd0Osh6DGX81HF20@kfCdzTnhtbjxRiidaRWiZqvTiyB/DRimXTi02GfMPtXYHPS@JSYnRjTNNwVPaBziNtwguVDsrYjIFmkgRHJRIS/chWkRxWBMLBBtXGMgAvvSLmI9T0lyimNPZiR0g7tAWhishBUBwNrezBpQXbxASqBJGw9R3R9D59bto/wHMBjBJ0J1Qf@OxByivZBQp@WUZrssieCNmI04UHkBIXUYHnG0vcHtGBvWbMeTsy5USm13NUhVvdaLmq5qOWiltvH8oLl9WfV618 "Python 2 โ€“ Try It Online") -15 bytes thx to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) As input, takes a tuple `(x,y)` as jimmy's initial position, a list `G == [(g1x,g1y), ...]` of initial ghost positions, and a list of lists `M` which is the 2-dimensional binary matrix where cells are `0` if they contain "an object" (i.e., `#`) and `1` otherwise. Returns `1` for truthy, `0` for falsey. Loosely speaking, the idea here is that we're going to depth-first recurse over down, left, up, right to seek a border cell. To start, ``` R=1-(len(M[0])-1>x>0<y<len(M)-1) ``` `R` is truthy if jimmy starts on a border cell. We could just return `R` if he does, but that would add an additional `return`. So in any case, we calculate where the ghosts would move to next. ``` H=[(u+cmp(x,u),v+cmp(y,v)*(u==x))for u,v in G] ``` `cmp(a,b)` returns the sign of `a-b` as `-1,0,1`; so this updates the ghosts positions with preference for horizontal movement if possible. Next, ``` for _ in' '*4*(R<1>((x,y)in H)): ``` executes a loop 4 times (`' '*4` is shorter than `range(4)`). Note that if jimmy is on the boundary (not `R<1`) or a ghost has landed on jimmy (not `1>((x,y)in H`), then we skip the for loop and so we return `1` if jimmy has escaped, or `0` if a ghost got him. ``` J=z,w=x+d,y+e;d,e=-e,d ``` `d,e` is the offset to jimmy's next position, starting as `0,1`; and each time through the loop, `d,e=-e,d` rotates us through the 4 possible orthogonal positions. ``` R|=M[w][z]>(J in U)<f(J,H,M,U+[J]) ``` `R` gets set to truthy if jimmy's next position `J` is not an on "object" (`M[w][z]>0`), AND we haven't visited this position before (`1>(J in U)`), AND via recursion, jimmy can escape starting at position `J` with ghosts at `H` (`0<f(J,H,M,U+[J])`). [Answer] # [Python 2](https://docs.python.org/2/), 199 bytes ``` def g(I,G,W,w,h): u,v=I.real,I.imag;R=1-(w-1>u>0<v<h-1);H=[z+cmp(u,z.real)+cmp(v,z.imag)*(u==z.real)*1jfor z in G] for d in(R<1>(I in H+W))*range(4):J=I+1j**d;R|=(J in W)<g(J,H,W+[I],w,h) return R ``` [Try it online!](https://tio.run/##lVRNj6JAED3bv6IzHOhGJIPjzEFtL5ugmOzFMfHAciAjNhgEw4fKZP@72wUNMs7sbqYTK1WP16@LR5fHMg@SeHi9bv0d5sTW5/pGP@sBHSNc6CdmG6nvRbpthAePT1bMHJDzwJwVs8fpaRoMTDpZMOe9/3Y4kkJ/r8i0qk6igj1UIwVj8olm7ndJit9xGOO5izAUW1GQ1dScERvgRX9DqZZ6MffJiI6XzO6be03bTla/GVkCY0OnnCz1hb7pO7ZbNYtw6udFGuPV9XVtMlVVlXYho1pc/JBiJHUF6Q1tl9iI0Ot6WCkYKOESePogKRVha6NRZbyWgzL5Amt59ZLSo7tuFS57VNq@IG12QXrjdtD/cOvTrMqbpnUOkSdNU6jTljWUbbV2JTLl6IZK7s2dhivObrkSldzqdTm0aXRC0i3hqWQ/35vTWMs/fTTrpf5oXSNvNkj7W3N4nfK/Ej6jFTdR7g@GuXkTlzv3f3rHHyQXg9PLWG5kxyjMiforVinqiTvKIj8mmfPoUr3KBLphzqVfypm4wNWur/2ZAlDegICGO1VRGcuc0nUurosVHIVZjpMdPntRlKHe/Fta/GstHiRZLsT23xJLOmLi/YTeMjwcStSTM7lv/lMQOqZhnOOHdVrkQfmAQC0DNUdMrY7F4EF4gjByx7hmc6J1/M0olTKNmOVFmf9RzAIxC8QsELNGEJ4hvPxD9voH "Python 2 โ€“ Try It Online") Rewrite of [Chas Brown's solution](https://codegolf.stackexchange.com/a/195091/78410) using complex numbers. All the coordinates are represented as a complex number `x+y*1j`. `I` is Jimmy's position, `G` is the list of ghosts and `W` is the list of walls. `w` and `h` are the width and height of the board, respectively. The output values and the algorithm are the same as the linked solution. [Answer] # Javascript (ES6), 208 bytes Recursive, depth-first search. A breadth-first approach would be probably faster, but less golfy. Input: a multi line string, using `1` for ghosts, `4` for solid objects, `6` for Jimmy and `2` for empty space. ``` f=(s,l=-~s.search` `,j=s.search(6),g=[...s],x=j%l)=>j<l|!g[j+l]|!x|x>l-3||(g[j]=6,![...g].some((a,i)=>a&1&&(g[--g[i],t=i%l,i+=t<x?1:t>x?-1:i<j?l:i>j?-l:0]|=1,i==j))&&[l,-l,1,-1].some(d=>2==g[d+=j]&&f(g,l,d))) ``` *Less golfed* ``` // using parameters with default values instead of declared variables f = (s, // input board (as a string at first call, then as an array) l = -~g.search('\n'), // line size +1, that is distance to next line // at first call it is calculated, for recursive calls is passed j = g.search(6), // position of jimmy in grid // at first call it is calculated, for recursive calls is passed grid = [...s], // modifiable copy of board (converted to char array) x = j % l, // x position of jimmy, always obtained from j ) => { // first, check if Jimmy is out if (j<l | !grid[j+l] | !x | x>l-3) // top,bottom,left,right border { return true } // move all ghosts and check if some ghost can take Jimmy // the loop is on a copy of grid, so I can safely modify grid during the loop var taken = [...grid].some( // check all ghosts (a,i) => a & 1 && ( // is it a ghost? --grid[i], // remove ghost from grid, as it will move t = i % l, // x position of ghost // move ghost towards Jimmy i += t < x ? 1 : t > x ? -1 : i < j ? l : i > j ? -l : 0, grid[i] |= 1, // put ghost on grid in its new position i == j // return true if it reached Jimmy ) return !taken && // if taken return false immediately // else recurse [l,-l,1,-1].some( // try to move Jimmy in all directions d => ( d+=j, 2==g[d] && f(grid, l, d)) ) ) } ``` **Test** ``` cases=['##########\n......g...\n#.o.......\n#.....g...\n##########\n' ,'#.\nog\n' ,'#########\n.........\n....g....\n...g.g...\n....o....\n...g.g...\n....g....\n.........\n' ,'##########\n#g.o.....#\n########.#\n#........#\n#.########\n#........#\n########.#\n#........#\n#.########\n' ,'.....\n..g..\n.go..\n.....\n.....' ,'###.......\n\#o#......g\n###.......\n' ,'#####.....\n#o..#....g\n#####.....\n' ,'g#.#\n.#.#\n\.#.#\n.#o#\n.#.#\n.#.#\ng#.#\n' ,'##########\n#...o....g\n##########\n' ,'#.########\n#g.......#\n#....g...#\n#......g.#\n#..g.....#\n#....g...#\n#........#\n#....g...#\n#..g....o#\n##########\n' ] f=(s,l=-~s.search` `,j=s.search(6),g=[...s],x=j%l)=>j<l|!g[j+l]|!x|x>l-3||(g[j]=6,![...g].some((a,i)=>a&1&&(g[--g[i],t=i%l,i+=t<x?1:t>x?-1:i<j?l:i>j?-l:0]|=1,i==j))&&[l,-l,1,-1].some(d=>2==g[d+=j]&&f(g,l,d))) cases.forEach(x=> ( console.log(x, f(x.replace(/#/g,4).replace(/\./g,2).replace(/o/,6).replace(/g/g,2|1))) )) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~94~~ 89 bytes ``` ร˜.,U$;N$+ยฎล’แนฌโ‚ฌร—8+ยฎล’แนฌยค+&7$ร‡โ‚ฌแบธ &โฑฎ8,2ล’แนชโ‚ฌแธขยฉ_ยฅ/แน 01ยฆแบ ยกโ‚ฌ+ฦฒแนชล’แนฌแธค+&13$ร‘ร‡Fแน€>8ฦฒ? |ร˜.ยฆ4Z$โบFแน€=12ฦฒร‡Fแน€>8ฦฒ? ``` [Try it online!](https://tio.run/##y0rNyan8///wDD2dUBVrPxXtQ@uOTnq4c82jpjWHp1vAeIeWaKuZqxxuB4o@3LWDS@3RxnUWOkYgqVUgoR2LDq2MP7RU/@HOBQaGh5Y93LXg0EKguPaxTUAFYAMe7gCaYGiscnji4Xa3hzsb7CyObbLnqgFae2iZSZTKo8ZdIFFbQ6Njm5AU/P//cPeWhzu6HjXM0VNOV8h/1DA3E2g1CDXMBCIjrYc75v2P5oo21FHAgmJ1uKINdBTgyAjORpExQpaEysCVWhCvh5A9KCiWKxYA "Jelly โ€“ Try It Online") A full program that takes an integer matrix as its argument, with 0 as space, 1 as wall, 2 as ghost and 8 as Jimmy. Returns 1 for escape and 0 for no escape. ]
[Question] [ Related to [this question](https://codegolf.stackexchange.com/questions/151501/how-lit-is-this-mountain). A *room* is defined to be a (not necessarily convex) non-intersecting polygon, expressed as an ordered list of 2-dimensional coordinates. A sufficiently bright lightbulb is placed at a specific point inside the room, and emits light in every direction. Your task is to find the total illuminated area of the room. You may take in input in any reasonable format. The points on the polygon/room as well as the coordinates of the light source are rational numbers. They can be taken in clockwise or counterclockwise, either format is fine. The test case in the problem is given counterclockwise. The following picture shows two example rooms, where the purplish dot represents the light source, and the shaded region represents the illuminated area.[![A drawing of an illuminated room - shaded area is illuminated](https://i.stack.imgur.com/ggWS0.jpg)](https://i.stack.imgur.com/ggWS0.jpg) Test case: ``` (1/2, 18) (1,3) (5,1/2) (7,5) (12,7) (16,3) (15,11) (8,19) (3,7) Light source located at (5,8) Answer: 815523/6710 โ‰ˆ 121.538 ``` Here is a graphical depiction of the solution to that test case. The two points that define the solution that are not on the original polygon are (55/61, 363/61) and (856/55, 357/55). [![enter image description here](https://i.stack.imgur.com/cWgdG.png)](https://i.stack.imgur.com/cWgdG.png) This formula may be helpful in calculating the area. [![https://en.wikipedia.org/wiki/Shoelace_formula](https://i.stack.imgur.com/BabEn.png)](https://i.stack.imgur.com/BabEn.png) Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. [Answer] # [Python 3](https://docs.python.org/3/), 388 ~~398~~ ~~408~~ ~~409~~ ~~415~~ ~~417~~ ~~493~~ bytes --- To make it more accurate, increase `n` ``` from random import* u=uniform c=lambda A,B,C:(C[1]-A[1])*(B[0]-A[0])>(B[1]-A[1])*(C[0]-A[0]) I=lambda A,B,C,D:c(A,C,D)!=c(B,C,D)and c(A,B,C)!=c(A,B,D) def a(l,v,n=9**6,s=0): g=lambda i:(min(x[i]for x in v),max(x[i]for x in v)) for _ in'x'*n: h=((u(*g(0)),u(*g(1))),l);s+=any([I(*f,*h)for f in list(zip(v,v[1:]+[v[0]]))])^1 return(abs(g(0)[0]-g(0)[1])*abs(g(1)[0]-g(1)[1]))*float(s/n) ``` Basic Monte-Carlo approach. Steps listed below. 1. Find x and y ranges that the shape occupies. 2. Create a list of edges created by the vertices 3. Iterate a large number of times (the more the better) 4. Create a random point (j,k) inside the x,y range. 5. Check if any of the edges intercept with the line-segment created by the light and the random point. If any of the edges intercept, increment the variable `s` 6. Divide `s` by the total numbers, then multiply by the total range area. ## Ungolfed version: ``` import random def ccw(A,B,C): return (C[1]-A[1])*(B[0]-A[0]) > (B[1]-A[1])*(C[0]-A[0]) def intersect(A,B,C,D): return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D) def lit_area(light, vertices): # points: list of points # i : x => i=0 # : y => i=1 get_range = lambda i: (min(x[i] for x in vertices), max(x[i] for x in vertices)) xr = abs(get_range(0)[0] - get_range(0)[1]) yr = abs(get_range(1)[0] - get_range(1)[1]) edges = list(zip(vertices, vertices[1:] + [vertices[0]])) num_sims = 1000000 num_successes = 0 for _ in range(num_sims): guess_x = random.uniform(*get_range(0)) guess_y = random.uniform(*get_range(1)) light_guess_line = ((guess_x, guess_y), light) if not any([intersect(*e, *light_guess_line) for e in edges]): num_successes += 1 return float(num_successes / num_sims) * (xr * yr) if __name__ == "__main__": points = [ (1/2, 18), (1,3), (5,1/2), (7,5), (12,7), (16,3), (15,11), (8,19), (3,7) ] light_source = (5,8) print("Area lit by light: %f"% lit_area(light_source, points)) ``` [Try it online!](https://tio.run/##XZHbbtswDIbv9RRcgaKkyqFRg7apBw9I05s@g@EVysGJAFs25AOSvXxGOTs484XI/wN/iqKbU3eo/fx8LkJdQbB@K8FVTR06rfq0966oQ6U2aWmr9dbCkt94leAqM/nXpRyk8S2bxXyW03fJ//HVX64@ruz8nmxwGSN9STc4EpKbIVJRI43ZO6ntrgCLJQ/s01etn7lNZ5Qo2P/p6BKsnMdj5nKZFI7gPAzElT3@z0hBVJ@i7o532ksXOKSIPeo9zoh4TAxJVtK39j61/oTZB@qC9YGitYiNStd2@NM1OPCQmSS/zwZ5Y06U0w@jIOy6Pni06xZj17iDMcaVXKD5Dc0ISRdlbTtsHzydm9r5roUUMpnt8qF5eGQwC@IJ4vlUPrHUTMELP12VP/LLlX6@9htpYKZgweZ1qufiH1WuSrc/dJ9t3YfNTuaUuxekmiBj480y7Kysp4P1Cca6BG6Lm9v4/yYuhssric6/AA "Python 3 โ€“ Try It Online") [Credit for line intersection algorithm](https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/) Also, credit to all the helpful commenters on how to golf this even further. [Answer] # [Haskell](https://www.haskell.org/), 559 ~~618~~ ~~632~~ bytes ``` r(a:b)=b++[a] s=zip<*>r (?)a=sum.zipWith(*)a o(a,b)=r a?b-a?r b (a,b)!(c,d)=(c-a,d-b) (a,b)#(c,d)=a*d-b*c x i a@(e,f)b j c d|let k@(g,h)=a!b;l=c!d;m=c!a;n=l#k;o=m#l/n;p=m#k/n;q|i>0=o<0||o>1|let=o<=0||o>=1;r|n==0||q||p<0||p*j>1=[]|let=[(e+o*g,f+o*h)]=r (a&b)(c:e@(d:_))|let(f,g)=span(/=d)b;h=zip f$r$f++[d]=concat[[k,l]|(i,j)<-h,[[k],[l]]<-[x 1 i j 0 a<$>[c,d]],and[x 0 m n 1 a o==[]|o<-[k,l],(m,n)<-h,(m,n)/=(i,j)]]++(a&g)e (_&_)_=[] z a b=sum[o$unzip[c,a,d]|e@(f:_)<-[[c|c<-b,and[all(==c)$x 1 d e 1 a c|(d,e)<-s b]]],(c,d)<-s$a&until((f==).head)r b$e++[f]]/2 ``` Exact solution (barring bugs). Haskell has built-in exact rational arithmetic. [Try it online!](https://tio.run/##bVHbbqMwEH3nK6YpquzENECbXpI47XtXWmn3YR@QFRkwgYRgCkRbVfx7duxclO4uD8zMmTNnLs5lu1Flud83RE5jyuPRKJLCaflnUc@Hi8YhL1Tydre9ReBX0eVkSKWjiWRIbkC@xJ58aSB2LHJFEpZSThJPstSL6QG9PqByiNAwcT6gAPlKFMtoDGtIIO1L1cHmlaxYjrSreFby5CqdbfEvZxUvrzczzbfX5bia1Wg3aN/7YuFzPff7Xi8CI4ABtxEPZk1fcRO8931tKPVwvQh4JCwvImqkhyuW4T@nguOO8iamJJmqV5JOl5QaGsnYivK2lhUZ85TGs9ycBDK3cTO8USp4oqtEdlG0YaXoScHWdO7lDGPBolKIuRd9QIC7rsEHOXcXEV5BCCarFBM@bKHCtATNzWAa6UaIkS2rrJB1xtwKCzEa4ZArqhyyvFnSJZY4n1gcm6eJtLurcDhsgGcXPa6R4RqoGCV9Mvdi21OWJeE8oa6ZKgVlmyc9SZlCaguxwOHsS2Hkyptd1RUlIRnn9DZXMqX4yq7C1TMhxuF@K4sKuANg3i7JVbKBsljlHdS6qLoWGtXuyg44pBpJh89QG4Q@v1KnU/ghu0JXsjxT6133s2u@VeDCwNKmMIDRCNpc/z5WYzRg0Gi9vcwdNP@rIxslL6mN8UiRmZn4aeAuVxVyyPc3OgBVtsoE6qNWSafSI@mLiEXovw0HA8TwRqk@nof4DHwKEfECBl5AGZBLx1rPOgLuz3rH2gmDJ1MbjEMWPB1K7oyZMISM88gmFg7Zo7UPh3yABCv9xIJnY@8wLzAMJpPwbvzwGPj072Yhg9A0swMbjUvHdglPiHFC/9jI5M5aXz9bGljiw8mxkJ397Nyfcgc2zhnePz@Pw5Du/wA "Haskell โ€“ Try It Online") Note that this gives `815523/6710`, not `814643/6710`, for the example room, and the first wall intersection is calculated as `(55/61, 363/61)`. I'm fairly sure this is correct because the Monte Carlo entry (slowly) converges to the same result. Legend: ``` z light roomPoints -- Main function, returns lit area. -- Compute list of visible corners in the room, then calls (&). (&) light roomPoints' visibleCorners -- Compute visibility polygon. visibleCorners is the subset of points -- that are visible from the light. The first point of roomPoints' -- must coincide with the first visibleCorner. x pEndpoints p1 p2 qSegment q1 q2 -- Intersect line segments (p1, p2) and (q1, q2). -- If pEndpoints, exclude endpoints p1, p2. -- If not qSegment, allow intersection to extend past q2 (i.e. raycast). r -- Rotate list by one, used to construct closed loops etc. s -- Construct closed loop (!) -- Vector between two points (?) -- Dot product (#) -- Cross product o -- Polygon area ``` Bonus: [Gloss](http://gloss.ouroborus.net/) GUI for testing. Click next to points to move them. ``` import qualified Graphics.Gloss as G import qualified Graphics.Gloss.Interface.IO.Interact as GI solnPoly a b|let c@(d:_)=[c|c<-b,and[all(==c)$x 1 d e 1 a c|(d,e)<-s b]]=a&until((d==).head)r b$c++[d] solnArea = z main = let fromRatP (x, y) = (fromRational x, fromRational y) displayScale = 10 scalePoints = G.scale (fromInteger displayScale) (fromInteger displayScale) displayMode = G.InWindow "" (512, 512) (0, 0) drawBasePoly pointSz ps = mconcat $ G.lineLoop ps : [G.translate x y (G.circleSolid pointSz) | (x, y) <- ps] drawVisPolyOf light ps = G.color G.blue $ drawBasePoly 0.2 $ map fromRatP $ solnPoly light ps drawLight (x, y) = G.translate x y $ G.color G.yellow (G.circleSolid 0.5) <> G.circle 0.5 draw (light, ps) = mconcat [ scalePoints $ drawLight (fromRatP light), scalePoints $ drawBasePoly 0.4 (map fromRatP ps), scalePoints $ drawVisPolyOf light ps, G.translate (-200) (-50) $ G.scale 0.2 0.2 $ G.color G.blue $ G.text $ "Lit area: " ++ show (solnArea light ps) ] event (GI.EventKey (GI.MouseButton GI.LeftButton) GI.Down _ (curx_, cury_)) (light, ps) = let dist (x,y) (x',y') = (x'-x)^2 + (y'-y)^2 curx = curx_ / fromInteger displayScale cury = cury_ / fromInteger displayScale cursorR = (fromInteger$round curx, fromInteger$round cury) maxDist = 3 snapAmount = 1 (d, i) = minimum [(dist p cursorR, i) | (p, i) <- zip (light : ps) [0..]] snapTo n a = fromInteger$n*round(a/fromInteger n) snapCursor = (snapTo snapAmount curx, snapTo snapAmount cury) light' | i == 0 && d < maxDist^2 = snapCursor | otherwise = light ps' | i > 0 && d < maxDist^2 = take (i-1) ps ++ [snapCursor] ++ drop i ps | otherwise = ps in (light', ps') event _ state = state state0 = ((2, 2), [(0, 0), (10, 0), (10, 5), (20, 0), (20, 20), (15, 5), (10, 10), (6, 10), (10, 12), (0, 12), (4, 10), (0, 10)]) in G.play displayMode G.white 60 state0 draw event (\_ -> id) ``` [![Screenshot](https://i.stack.imgur.com/LQC8q.png)](https://i.stack.imgur.com/LQC8q.png) [Answer] # APL+WIN This is an ungolfed version of this interesting challenge which I offer to demonstrate my logic. My ancient version of APL+WIN is not well suited to golfing nested control structures. More modern APLs could well do better - challenge? If readers validate the logic I will have a go at golfing this solution. If the logic is wrong I will simply delete. ``` rโ†b Room v โSeparate x and y coordinates of vertices xโ†v[;1] โ‹„ yโ†v[;2] โIntercept and slope of each line segment and ray through each vertex sโ†(y,ยจ1โŒฝy)โŒนยจ(1Eยฏ9+1,[1.1]ยจx,ยจ1โŒฝ1Eยฏ9+x) lโ†(y,ยจb[2])โŒนยจ(1Eยฏ9+1,[1.1]ยจx,ยจb[1]+1Eยฏ9) โCoordinates of vertices xโ†x,ยจ1โŒฝx โ‹„ yโ†y,ยจ1โŒฝy โInitialise intersection matrix rโ†((โดs),0)โด0 โEvaluate intersection matrix :for i :in โณโดl tโ†0โด0 :for j :in โณโดs tโ†t,โŽ1โ•โˆŠ((โ†‘โˆŠl[i])-โ†‘โˆŠs[j])รท((1โ†“โˆŠs[j])-1โ†“โˆŠl[i]) :endfor zโ†rโ†r,t :endfor โIdentify x coordinates of valid intersections in the direction of the ray :for i :in โณโดl tโ†(r[i;i]) :for j :in โณโดs :if t<b[1] r[j;i]โ†r[j;i]ร—(r[j;i]<t)^r[j;i]>โŒŠ/โˆŠx[i] :else r[j;i]โ†r[j;i]ร—(r[j;i]>t)^r[j;i]<โŒˆ/โˆŠx[i] :endif :endfor :endfor โIdentify the edges intersected eโ†(+/rโ‰ 0)/โณโดl โIntersection x coordinates cxโ†(+/r)[e] โIntersection y coordinates cyโ†โŽ1โ•+/ยจ(s[e])ร— 1,ยจ(+/r)[e] โReplace original coordinates that are in shadow x[e]โ†(1โ†“ยจx[e]),ยจcx y[e]โ†(1โ†“ยจy[e]),ยจcy โCalculate lit area rโ†+/.5ร—(|-/ยจx)ร—|-/ยจy ``` [Answer] # [R](https://www.r-project.org/), ~~296~~ 255 bytes ``` function(s,l,u=cbind(s,s[,1]),d=t(diff(t(u))),q=l-u,r=apply(s,1,range),g=c(diff(r)))mean(replicate(1e6,!any((q[i<-1:ncol(s)*2]*(p=runif(2)*g+r[1,]-u)[j<-i-1]>p[i]*q[j])!=(q[i+2]*p[i+1]>q[i+1]*p[i+2])&(p[i]*d[j]>p[j]*d[i])!=(q[i]*d[j]>q[j]*d[i]))))*prod(g) ``` [Try it online!](https://tio.run/##PZDLboQwDEX3fAWzqWwwqgKaGVqR/gjKgvJSUBogwGK@nprXZJNj@9xEiVsbP4vWZrHlrHsLExlaZPmrbcU85SQUUiVnqHTTwAwLItIoTbSQk8UwmBdrglxh2xqpleUhOtb@6sKCqwejy2KuQdQJ3Qr7AhhznUXi25a9gQmDWAUwSLdY3UCMQRu6XJCKFsy7LNKRUD9DrlUw5p3Cm9zSIUe4F/Jo3Le9ihV@wK5WrHKo20hfobM9vtu8gsH1FbS4TvwJ/vFqz/dLEJ8x@SJFOipKTroTT05@0v2ax/S88PF2Bcvi5JTE14kJux56Zr@RD/RT9Jrt33H9Bw "R โ€“ Try It Online") This is a further reduced version of the [Python answer](https://codegolf.stackexchange.com/a/179946/42248). The core Monte Carlo method is the same, but I rearranged some of the functions to make them shorter. In my first iteration, I'd been over-aggressive in rearrangement, and I then realised I could optimise both length and speed by returning to a version of the intersection algorithm closer to the python. Here's an ungolfed version that also plots the results: ``` find_lit_ungolf <- function(shape, light, plot = TRUE) { lines <- cbind(shape ,shape[,1]) diffs <- t(diff(t(lines))) light_minus_lines <- light - lines shape_range <- apply(s,1,range) shape_range_diff <- c(diff(shape_range)) successes <- t(replicate( n = 1e5, { random_point <- runif(2) * shape_range_diff + shape_range[1, ] random_minus_lines <- random_point - lines q <- light_minus_lines p <- random_minus_lines d <- diffs i <- 1:ncol(s)*2 success <- !any((q[i]*p[i-1]>p[i]*q[i-1])!=(q[i+2]*p[i+1]>q[i+1]*p[i+2])&(p[i]*d[i-1]>p[i-1]*d[i])!=(q[i]*d[i-1]>q[i-1]*d[i])) c(random_point, success) })) colnames(successes) <- c("x", "y", "success") if (plot) { shape <- t(shape) colnames(shape) <- c("x", "y") print(ggplot(as_tibble(successes), aes(x, y)) + geom_point(aes(colour = factor(success)), alpha = 0.3) + geom_polygon(data = as_tibble(shape), alpha = 0.2) + annotate("point", light[1], light[2], col = "yellow")) } mean(successes[, 3]) * prod(shape_range_diff) } find_lit_ungolf(s, l) ``` [![Plot of light in room](https://i.stack.imgur.com/TqaSJ.png)](https://i.stack.imgur.com/TqaSJ.png) ]
[Question] [ Given a possibly nested, non-empty array of single-digit positive integers (not guaranteed unique), output the ASCII-art representation as a tree, using the box-drawing characters `โ”Œ โ”ด โ” โ”€ โ”‚ โ”ฌ โ”ผ`. (These were copied from Code Page 437, but you can use any equivalent representation). Every integer of the array should be a leaf of the tree. Elements the same level deep in the array should be present at the same level of the tree. All elements should be separated by enough whitespace to be distinct (up to you to determine how wide, minimum of one space between). For example, given array `[[1, [2]], [3, [4, 5]]]`, output the following tree ``` โ”Œโ”€โ”ดโ”€โ” โ”Œโ”ดโ” โ”Œโ”ดโ”€โ” 1 โ”‚ 3 โ”Œโ”ดโ” 2 4 5 ``` For array `[1, 2, 3]` the tree could look like ``` โ”Œโ”€โ”ผโ”€โ” 1 2 3 ``` But the array `[[1, 2, 3]]` would look like ``` โ”‚ โ”Œโ”€โ”ผโ”€โ” 1 2 3 ``` While the array `[1, [1, [1, [1]]]]` could look like ``` โ”Œโ”€โ”ดโ” 1 โ”Œโ”ดโ”€โ” 1 โ”Œโ”ดโ” 1 โ”‚ 1 ``` As a more complicated example, `[1, [[[2, 3], 4], 5]]` could be ``` โ”Œโ”ดโ”€โ”€โ”€โ” 1 โ”Œโ”€โ”ดโ” โ”Œโ”€โ”ดโ” 5 โ”Œโ”ดโ” 4 2 3 ``` or several other variations. --- * Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can print it to STDOUT or return it as a function result. * Either a full program or a function are acceptable. * Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [Python 3](https://docs.python.org/3/), 400 393 390 bytes ``` L=len S,*K=' โ”ดโ”ผโ”‚123456789' def T(x): try:return[str(x+0)] except: z=[*map(T,x)];q=max(map(L,z)) for p in z:p+=[S*L(p[0])]*(q-L(p)) b=[S.join(a)for a in zip(*z)];t=b[0];l=L(t);s=0;e=L(z);r=[S]*l if e<2:return['โ”‚'.center(l),*b] for i in range(l): if t[i]in K:s+=1;r[i]='โ”ฌโ”Œโ”'[(s<e)-(s>1)] elif 0<s<e:r[i]='โ”€' c=l//2;r[c]=K[r[c]=='โ”ฌ'];return[''.join(r),*b] ``` Returns a list of strings from top to bottom. EDIT 1: Trimmed 7 bytes by avoiding duplication of `โ”ดโ”ผ` (net save of 2 bytes), cutting out 0 from the one string, changing how drawing characters are selected from `โ”ฌโ”Œโ”` (use `<` instead of `==`), and replacing a `L(z)` I missed with `e` EDIT 2: -2 bytes thanks to ovs and -1 byte thanks to Kevin Cruijssen [Try it online!](https://tio.run/##NY87coMwFEV7VqFOH2Mb2/kiKxswnd1pVACREzJYloUyg6kyqVOkYBkpU2Y1bIQ8SFy9z33nzn327J@PZtX3iSi1CbYh2wiMuva7a3@69n2xXF1d39ze3ePgUe/RjtQ0DpB359hp/@qMrLwj9SSiKkC6zrX1IKNGSHZILdmFNVX8JA5pTYY5CRtKQd8fHbKoMKiJ7UTILUuIlZGiipHTFPrxKANh9nIsDEnpAKQjUFjCGjD1IgOClyIhnvJKRFxD21DuAFOsBINij/R6eQmK4Rs8y7Xx2pGShixT/0mKwdil5knDfog/kF4WCtabuJqIBXcwCXD46tqPrv3EklRrTaekelgMnyOkS2CiNWzjy@0bBiEX5Xy@BD5XYiPHMvpgxS@58N@TbozU978 "Python 3 โ€“ Try It Online") ### Ungolfed ``` def layer(item): if isinstance(item, int): return [str(item)] else: subs = [layer(sub) for sub in item] longest = max(map(len, subs)) for sub in subs: sub += [' ' * len(sub[0])] * (longest - len(sub)) below = [' '.join(l) for l in zip(*subs)] top = below[0] l = len(top) if len(subs) == 1: return ['โ”‚'.center(l), *below] seen = 0 expected = len(subs) builder = [' '] * l for i in range(l): c = top[i] if c in 'โ”ดโ”ผโ”‚123456789': seen += 1 if seen == 1: builder[i] = 'โ”Œ' elif seen == expected: builder[i] = 'โ”' else: builder[i] = 'โ”ฌ' elif 0 < seen < expected: builder[i] = 'โ”€' center = l // 2 if builder[center] == 'โ”ฌ': builder[center] = 'โ”ผ' else: builder[center] = 'โ”ด' return [''.join(builder), *below] ``` Builds a tree from the leaves up, one layer at a time. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~544~~ 506 bytes *Escapes are used to avoid invalid UTF-8 on SE/TIO but counted as one byte as they're valid literals* ``` import StdEnv,Data.List;::T=I Int|L[T];$l#m= @l#k=map maxList(transpose m)=flatlines[[last[' ':[(\_|v<0|w<[j]|q>hd w|q<last w|any((==)q)w|q==j='\305'='\302'|q==j='\301'='\304'='\277'='\332'='\263'=toChar v+'0')0\\[v,r,j:w]<-m|r/2==p&&q>=hd w&&q<=last w]]\\q<-[0..k!!3]]\\p<-[0..k!!1]];@(L l)#p=twice(\p=[[v,r+1:[e+sum([2\\[v:_]<-i|0<=v]++zipWith(\c j=j!!2-c!!3)t(takeWhile(\[z:_]=v+z< -1)(tl t)))-x!!1\\e<-x]]\\i<-inits p&t<-tails p&[v,r:x]<-p])(concatMap@l)#g=[g\\[_,2,g:_]<-p]=[[-1,0,(hd g+last g)/2:g]:p];@(I i)=[[i,0,0,0]]; ``` [Try it online!](https://tio.run/##rVTLbtNAFN33KyZpVc8odvEjocLxVJUoi0hBQkqlLuxRNXVcZ1K/Yk8erbJArFmw4DNYsuRr@BDMHTsNhbJggSzdx5lzH/O4DpOIZ3WaT5dJhFIusmEt0iIvJZrI6ZtspV9wyU/GopJD172kIzTK5HbsX7LhUXKYUnSeHN7RlBcQu1EsLEueVUVeQTZCbxMuE5FFle8nvJK@hjTXx8H1duWZ27Xnz9l2cTabovV24SkCGDy7x5hSsiAAUjqnWuCYA61RtvYLslqor5R9etp4jt14Lx2Nyvz1jJdo1dNMjZhB4K/0Up@7a@YZ6bZ8YVNaHB8vzqgqDoZH2/KMBcHCM3zz5OSu03GUW@xdi7HhOR6jhBwWVK5FGOGgoL5K3bNcP@pVyxT7tirmXkMhsTU9umK93oMoroSc4SBEczrvdGwjhOQEDovfRVczkUAi/wFi6Kr34CHDIlgmSBJCjA2UDYLIMzaqFwFJMyErVBxLz5BcJMpUDbgbKFgwgsM8C7l8y4tzaDOmfgztXOu2HjctFQz6NSzd1DHsPO41u47JC9uNmVuo7Y2QIMARQIEPdlxPJIfnQBFeZinPYngnOZL5RJYii8E8IgiP/RGy9EfZaqSUzVhrOK3q62iEBuwRtf5Qe6dNYiv2qRKO/nuJ56H/muFvS0zJfiNfNb099XbNPgl6yh88W/0fKcnw4GA3hpfRRg4P9kdfyRKu4jZPpgkOKoRDvSQAlFGR8DCaLG929xKiElWkofu4q2aiq3e/f/7QJToCH2apqyMAvuyBQQt8ewScHePjnmG1wNcdAFPXAp/2jH4LvO8SVv8IYfrjqjZG4/riPuOpCFvnHfwUbvMyrY2b2pjVA9NMfwI "Clean โ€“ Try It Online") Takes input in the format `L[I 3, L[I 4, I 5], I 2]..` Connects the trees from the bottom up, left to right, then adjusts the distances from right to left. Prettified, sort-of: ``` import StdEnv, Data.List; :: T = I Int | L [T]; $ l #m = @l #k = map maxList (transpose m) = flatlines [ [ last[ ' ': [ if(v < 0) if(w < [j]) if(q > hd w) if(q < last w) if(any ((==) q) w) ( if(q == j) '\305' '\302' )( if(q == j) '\301' '\304' ) '\277' '\332' '\263' (toChar v + '0') \\ [v, r, j: w] <- m | r/2 == p && q >= hd w && q <= last w ] ] \\ q <- [0..k!!3] ] \\p<-[0..k!!1] ]; @ (L l) #p = twice ( \p = [ [ v, r + 1: map ( (+) ( sum [2 \\ [v: _] <- i| 0 <= v] + sum ( zipWith ( \[_, _, _, c: _] [_, _, j: _] = j - c ) t ( takeWhile (\[v: _] = v < 0) (tl t) ) ) * (1 - sign (v + 1)) - x!!1 ) ) x ] \\ i <- inits p & t <- tails p & [v, r: x] <- p ] ) (concatMap @ l) #g = [g \\ [_, 2, g: _] <- p] =[[-1, 0, (hd g + last g)/2: g]: p]; @ (I i) = [[i, 0, 0, 0]]; ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~127~~ 123 bytes ``` โ†ถโ‰”โŸฆโŸฆฮธโŸงโŸงฮท๏ผฆฮทยซโ‰”โŠŸฮนฮถยฟโผ๏ผฉฮถโชซโŸฆฮถโŸงฯ‰โŠžฯ…โŠž๏ผฏฮนฮถ๏ผฆ๏ผฌฮถโŠžฮทโบฮนโŸฆโŠ–๏ผฌฮถฮบยงฮถฮบโŸงยป๏ผทฯ…ยซโ‰”โŒŠฯ…ฮนโ‰”ฮฆฯ…ยฌโผฮบฮนฯ…๏ผชยฑโŠ—๏ผฌฯ…โŠ˜โŠ–๏ผฌฮน๏ผฉโŠŸฮน๏ผทฮนยซโ‰”โŠŸฮนฮถยฟฮถยซโ†ยงโ”โ”ฌโ€นฮถโŠŸฮน๏ผทโผ๏ผซ๏ผซฯˆโ†โ”€โ‰”โฐฮนยปยฟโŠŸฮนโ”Œยถโ”ดยฆโ”‚ ``` [Try it online!](https://tio.run/##bZLNTsJAFIXX9CluWE2TMfF3oysiGiWIXeiq6aLChU6YttCZAcU0Ma5duOAxXPpEvEidOy0BjUnTJveeOefraYdJXAzzWFZVRykxyVgYzqOIQ@JfeOO8AJb48Oq1mmWQz5jwOazstiXGwK7mJpaKXcZKs5Vd9HJhLVbWYOn7PgRGJcxw97yfYRHrvGCCzpMBSoXgQvqYTXRiHZojiT0ijSJpOOXQxWGBKWYaR3tSDh19m43wma04TP2IPEtvmQiJwMw@9p3IRGpSO@QgKLmZXwupsSDAQa637zIlDbkbUvZMOnvI2QAnsUbWzc2T3EEYp7uJ5cLO/oEkHzIJCpFpdv444@Caqmt0qwZXONy/NY9I8XeIbkjlE/SIKtvZtzfr97YTuHJJhbX1FqKPY71rzuo/N@uvNoc@KsWQMh1Xa0vWtBIgTplNf9nl1U7W4a1O3IIeNiW3SnAQe@lW/NGIf0N/19PSs1dZVWF4ZL98GB5zOKG/MTy1t7MoiqqDhfwB "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` โ†ถ ``` Change the default drawing direction to up since we don't draw anything to the right. ``` โ‰”โŸฆโŸฆฮธโŸงโŸงฮท ``` The first step is to convert the nested array representation into an index representation which is a list of all the entries together with the indices of the subarrays, e.g. for the input `q=[1, [[[2, 3]], [4], 5]]` the `5` is `q[1][2]` and therefore the list we want is `1, 2`. We start with a single entry to process which is a list containing a list of the current indices (i.e. none so far) and the original input. ``` ๏ผฆฮทยซ ``` Loop over the arrays as we process them. (Conveniently Charcoal will continue to iterate over a list if you push to it during iteration.) ``` โ‰”โŠŸฮนฮถ ``` Get the next array to process. ``` ยฟโผ๏ผฉฮถโชซโŸฆฮถโŸงฯ‰ ``` Is this actually a scalar rather than an array? ``` โŠžฯ…โŠž๏ผฏฮนฮถ ``` If so, then the list we had actually belongs on the final list of lists of indices. ``` ๏ผฆ๏ผฌฮถ ``` Otherwise, loop over each element in this array... ``` โŠžฮทโบฮนโŸฆโŠ–๏ผฌฮถฮบยงฮถฮบโŸงยป ``` ... and save it with its new index list so far for further processing. The maximum index of the array is also saved which is used to special-case the last element of the array. ``` ๏ผทฯ…ยซ ``` We are now ready to loop over the list of index lists. However, the list is not in lexicographical order, so we can't iterate it directly. ``` โ‰”โŒŠฯ…ฮน ``` Find the next element in lexicographical order. ``` โ‰”ฮฆฯ…ยฌโผฮบฮนฯ… ``` Remove it from the list. ``` ๏ผชยฑโŠ—๏ผฌฯ…โŠ˜โŠ–๏ผฌฮน ``` Jump to the position of the scalar in the output. We can calculate this given that we can keep count of the number of scalars we output and we also know the number of entries in its index list. ``` ๏ผฉโŠŸฮน ``` Actually print the scalar. ``` ๏ผทฮนยซ ``` Loop over the entries in the index list. Again, this isn't simple iteration, because the entries come in pairs, and we also need to be able to break out of the loop. ``` โ‰”โŠŸฮนฮถ ``` Extract the next index from the list. ``` ยฟฮถยซ ``` If this is not the first element in the list... ``` โ†ยงโ”โ”ฌโ€นฮถโŠŸฮน ``` ... then print `โ”` or `โ”ฌ` depending on whether this is the last element in the list... ``` ๏ผทโผ๏ผซ๏ผซฯˆโ†โ”€ ``` ... and print enough `โ”€`s to fill up to the previous entry at this level... ``` โ‰”โฐฮนยป ``` ... and clear the variable to break out of the loop since we're done here. ``` ยฟโŠŸฮนโ”Œยถโ”ด ``` Otherwise if this is (the first element of) a multiple-element list then print the `โ”Œโ”ด`, leaving the cursor above the `โ”ด` to deal with this level's parent. ``` ยฆโ”‚ ``` Otherwise if this is a 1-element list then just print a `โ”‚` and move up a line to deal with this level's parent. ]
[Question] [ ## Buzzby Berkeley Robot Hokey Pokey ### Task Write a program or function to produce an ASCII art animation depicting a line of robots dancing to the lyrics of the Hokey Pokey (or Cokey, if you prefer) in the style of a Busby Berkeley number! ### Example Output [![enter image description here](https://i.stack.imgur.com/TH806.gif)](https://i.stack.imgur.com/TH806.gif) ### Input Accepts three arguments (assumed to be valid): **N** = number of robots in the line (Min=6) **B** = duration of one "beat" in milliseconds (Min=10) **D** = delay in ms between successive robots (Min=0) (In the example output above: N=8, B=380, C=75) ### Specifications 1. **N** robots are shown in a row upon a stage. 2. One line of text from "the verse" is shown at a time beneath the stage (centred to within 1 character, and enclosed in quotation marks.) 3. The robots perform the actions for each line as it is shown until the verse has been repeated 5 times. 4. An action is performed by depicting a robot using a set of ASCII characters and waiting a specified duration before performing the next action. The duration of an action is measured in "beats". The duration of 1 beat is a number of milliseconds, **B**. 5. The first robot starts performing the actions for each line of verse immediately when the line's text is displayed. 6. Each subsequent robot delays starting its actions until a specific time (**D**) after the robot to its right (your left!) begins its actions. 7. Robots' depictions vary by the ASCII characters which represent a robot's "antenna", of which there are 5 possible types, distributed randomly every time the program is run. 8. Each type of antenna must be used by at least one robot, but the same type must not appear on any robots separated by fewer than 3 other robots. The amounts of any two types of antennae may differ by no more than 1 (e.g. 1xType\_4 and 3xType\_5's is illegal since 3-1>1 ) ### Verse and Actions The whole verse is repeated 5 times, 1 line at a time... ``` Line Text Action/Beats, ---- ----------------------------- ------------------------------------ 1 You put your ? in ??/4 2 You take your ? out AA/4 3 You put your ? in ??/4 4 And you shake it all about AA/1, ??/1, AA/1, ??/1 5 You do the Hokey Pokey and... ...you turn yourself around AA/1, H[1-7]/1 6 That's what it's all about! AA/4, ZZ/4 ``` For each repetition (R) of the verse, substitute ? and ??... ``` R ?= ??= -- ----------- --- 1. right foot RF 2. left foot LF 3. right hand RH 4. left hand LH 5. whole self WS ``` ### Actions and ASCII patterns Each labelled action is represented by 5 lines of 8 ASCII symbols. The representation of each action is as follows... ``` 1 | 12 12 12 12 12 12 12 2 | [''] [''] [''] [''] [''] [''] \[*-] 3 | โ””[__]โ”˜ โ””[__]โ”˜ โ””[__]โ”˜โ”Œ[__]โ”˜ โ””[__]โ” โ”Œ[__]โ” [__]\ 4 | || /< >\ <\ /> / \ /| 5 |-------------------------------------------------------- |\__AA__/\__RF__/\__LF__/\__RH__/\__LH__/\__WS__/\__ZZ__/ 1 | 12 12_ 34_ 34 _34 _12 12 2 | [''] [" ] [ _] [__] [_ ] [ "] [''] 3 | >[__]< [_<] [<.] <[..]> [.>] [>_] <[__]> 4 | || |\ || /| || |\ || 5 |-------------------------------------------------------- |\__H1__/\__H2__/\__H3__/\__H4__/\__H5__/\__H6__/\__H7__/ ``` In row 1, replace "1-4" with corresponding symbol for each antenna type... ``` 1 | 1234 1234 1234 1234 1234 | \/\/ |โ”Œโ”| )||( |||| โ”/\โ”Œ <-- Symbols 1-4 for... | 1 2 3 4 5 <-- ...antenna types 1-5 ``` ### Output The entire scene must be rendered at least once immediately whenever the content of the scene changes in any way. (I.e. assuming the delay between robots' actions is > 0, the output may be rendered no less than **N** times per action.) Ideally, for an animation the console or equivalent output area is cleared before each update is rendered. To provide for languages unable to clear the console, output may also be rendered in a continuous stream, subject to the same requirement described above. ### Scoring Winners are the shortest programs in each language, as well as the shortest overall. **Exception 1** Because clearing the console each render is preferable though not required, bytes used exclusively for this luxurious purpose do not count towards the total bytes. This includes commands to clear the console, and padding output with blank lines to scroll the console contents out of view. **Exception 2** CSS or effectively similar means used exclusively for the purpose of styling the output beyond the minimum requirements do not count towards the total bytes. E.g. `*{color:blue;text-align:center;}` counts as only 32-10=**22 bytes** since `color:blue;` doesn't serve to satisfy any specification, whereas centred text is specified. ### Meta Inspired by (showing my age) the [TRS-80 Dancing Demon](https://www.youtube.com/watch?v=7N5rvVJULqw), [Android Nim](https://www.youtube.com/watch?v=osPYppC33OI), and of course [Busby Berkeley](https://www.youtube.com/watch?v=TLsTUN1wVrc) (and no, I'm not **that** old). [Answer] Ladies and Gentlemen, please welcome our lovely # Full Frontend-Stack Dance Group, 1,320 ~~1,378~~ ~~1,425~~ ~~1,495~~ bytes JavaScript: **1,195 bytes** | CSS: **103 bytes** | HTML: **22 bytes** --- This is a cute challenge. It also has lots of special cases. Oh boy, so many special cases. And those antennas โ€ฆ It will run forever and restart after all actions (`left foot`, `right foot` etc.) are completed. You can [try it on jsFiddle](https://jsfiddle.net/26vrvsm7/) or by using the code snippet thingy below: ``` t=setTimeout c=l=a=i=0 _=(x,y,z)=>{if(!i)for(;++i<=x;q=~~(Math.random()*10))s.append(document.createElement('pre')) for(i=l=0,c=a+1;i<33;)(i=>{t($=>{if(4==i){c=0 l=1}if(8==i){c=a+1 l=0}if(12==i|14==i){c=0 l=2}if(13==i|15==i)c=a+1 if(16==i){c=0 l=3}if(16<i&24>i)c=i-10 if(24==i){c=0 l=4}if(28==i)c=6 if(31<i){a=++a%5 _(x,y,z)}for(j=0;j<x;)(j=>{t($=>s.childNodes[j][h]=(-1<[1,3,8,9].indexOf(c)?' ':2==c||4==c?' ' :' ')+(11==c||12==c?'_':'')+['\\/\\/','|โ”Œโ”|',')||(','||||','โ”/\\โ”Œ'][(q+j)%4].substring($=8<c&12>c?2:0,$+2)+(8==c||9==c?'_':'')+'\n'+[` [''] โ””[__]โ”˜ ||`,` [''] โ””[__]โ”˜ /<`,` [''] โ””[__]โ”˜ >\\`,` [''] โ”Œ[__]โ”˜ <\\`,` [''] โ””[__]โ” />`,` [''] โ”Œ[__]โ” / \\`,` \\[*-] [__]\\ <\\`,` [''] >[__]< ||`,` [" ] [_<] |\\`,` [ _] [<.] ||`,` [__] <[..]> /|`,` [_ ] [.>] ||`,` [ "] [>_] |\\`,` [''] <[__]> ||`][c]+'\n-------',j*z)})(j++) p[h='innerText']='"'+["You put your $ in","You take your $ out","And you shake it all about","You do the Hokey Pokey and you turn yourself around","That's what it's all about!"][l].replace('$',['right foot','left foot','right hand','left hand','whole self'][a])+'"'},i*y)})(i++)} // let's dance (not included in the byte count โ€“ as if it would make any difference) _(8, 400, 50) ``` ``` *{text-align:center}x pre{display:inline-block;width:55px;text-align:left}pre{line-height:16px;margin:0 ``` ``` <x id=s></x><pre id=p> ``` --- Tested in Chrome and Firefox on macOS, Windows 10 and Ubuntu --- **Edits** * *Saved* **70 bytes** by removing the extra container to hold the antennas. Thanks to [Bumpy](https://codegolf.stackexchange.com/users/69158/bumpy). Also found some more whitespaces, removed the now unnecessary caching of `createElement` and removed the long access to `.firstChild`. * *Saved* **47 bytes** โ€“ย just realized that I actually don't need to call `getElementById`. This also makes the caching of `document` unnecessary. * *Saved* **4 bytes** by replacing `||` and `&&` with bitwise `&` and `|`. Thanks to [TheLethalCoder](https://codegolf.stackexchange.com/users/38550/thelethalcoder). * *Saved* **54 bytes** by simplifying lots of small things and by optimizing the CSS. [Answer] ## C#, 1188 1376 1382 bytes after exceptions Compacted: ``` namespace System.Threading{using S=String;void H(int n,int b,int d){Console.CursorVisible=false;int t,u=0,v=5,w,x,y,z;S[]i=",That's what it's all about!,,You do the Hokey Pokey and you turn yourself around,And you shake it all about,,You take? out,You put? in".Split(',');i[0]=i[1];i[2]=i[3];i[5]=i[7];for(b=b<d*n?0:b-d*n;v-->0;)for(w=32;w-->0;Thread.Sleep(b))for(t=u,z=0;z++<n;Thread.Sleep(d)){S s="",r=i[w/4].Replace("?"," your "+(v<1?"whole self":(v%2<1?"right ":"left ")+(v/3<1?"hand":"foot")));u="88880000765432109090999900009999"[w];u=u>56?9+v:u-48;for(y=4;y-->0;s+="\n")for(x=0;x<n;x++)s+=S.Format(@"{0}{0} |\ {0} /| {0} |\ {0} /|{4} / \{4} />{4}<\{4}{4}>\{4}/<{4} โ””{1}โ”˜ >{1}< [_<]{4}[<.] <[..]> [.>]{4}[>_] <{1}> {1}\ โ”Œ{1}โ” โ””{1}โ”โ”Œ{1}โ”˜{4}โ””{1}โ”˜โ””{1}โ”˜ {2} {2} ["" ]{4}[ _]{4}{1}{4}[_ ]{4}[ ""] {2} \[*-] {2} {2}{2}{4}{2}{2} {3}{3} 12_{4} 34_{4} 34{4} _34{4} _12 {3}{3}{3} {3} 12{4} {3} 12{4}", " || ","[__]"," [''] "," 12 "," ").Substring(y*14+(x<z?u:t)<<3,8).Replace("12",@"\/|โ”Œ)|||โ”/".Substring(x%5*2,2)).Replace("34",@"\/โ”||(||\โ”Œ".Substring(x%5*2,2));Console.Clear();Console.Write(s+new S('-',n*8)+"\n"+new S(' ',n*4-r.Length/2)+r);}}} ``` Slightly nicer formatting and wrapped in an executable program: ``` namespace System.Threading{ using S=String; //** Not counted towards score: execution wrapper class P{ static void Main(S[]a){ new P().H(int.Parse(a[0]),int.Parse(a[1]),int.Parse(a[2])); } //** End not counted towards score void H(int n,int b,int d){ Console.CursorVisible=false; // Not counted under exception 2 int t,u=0,v=5,w,x,y,z; S[]i=",That's what it's all about!,,You do the Hokey Pokey and you turn yourself around,And you shake it all about,,You take? out,You put? in".Split(','); i[0]=i[1]; i[2]=i[3]; i[5]=i[7]; for(b=b<d*n?0:b-d*n;v-->0;) for(w=32;w-->0;Thread.Sleep(b)) for(t=u,z=0;z++<n;Thread.Sleep(d)){ S s="",r=i[w/4].Replace("?"," your "+(v<1?"whole self":(v%2<1?"right ":"left ")+(v/3<1?"hand":"foot"))); u="88880000765432109090999900009999"[w]; u=u>56?9+v:u-48; for(y=4;y-->0;s+="\n") for(x=0;x<n;x++) s+=S.Format(@"{0}{0} |\ {0} /| {0} |\ {0} /|{4} / \{4} />{4}<\{4}{4}>\{4}/<{4} โ””{1}โ”˜ >{1}< [_<]{4}[<.] <[..]> [.>]{4}[>_] <{1}> {1}\ โ”Œ{1}โ” โ””{1}โ”โ”Œ{1}โ”˜{4}โ””{1}โ”˜โ””{1}โ”˜ {2} {2} ["" ]{4}[ _]{4}{1}{4}[_ ]{4}[ ""] {2} \[*-] {2} {2}{2}{4}{2}{2} {3}{3} 12_{4} 34_{4} 34{4} _34{4} _12 {3}{3}{3} {3} 12{4} {3} 12{4}", " || ","[__]"," [''] "," 12 "," ").Substring(y*14+(x<z?u:t)<<3,8).Replace("12",@"\/|โ”Œ)|||โ”/".Substring(x%5*2,2)).Replace("34",@"\/โ”||(||\โ”Œ".Substring(x%5*2,2)); Console.Clear(); // Not counted under exception 1 Console.Write(s+new S('-',n*8)+"\n"+new S(' ',n*4-r.Length/2)+r); } } } // Not counted towards score: end class } ``` ### Try it online! 1. Visit this link: [tutorialspoint.com](http://www.tutorialspoint.com/compile_csharp_online.php?PID=0Bw_CjBb95KQMcVBtNVU5bFpVUzQ) 2. In the **Default Term** tab at the bottom of the screen, type: `mono main.exe 8 400 40` ### Edit 1 Replaced `string.Format(i,j)` with `i.Replace("?",j)` saving 6 bytes overall. ### Edit 2 Complete revamp with suggestions from the comments. [Answer] ## JavaScript, 948 bytes Probably poor form to answer your own question, but anyway... Tried all sorts of ways to compress the text, but most ended up longer than the original with the key+algorithm included. I'm certain there's still a more optimal way to compress it all down, but I have to draw the line somewhere. Interestingly, the search yielded one or two ideas for some other challenges which I might refine and post later. ``` <pre id=O/> f=(N,B,D)=>{Q=c=>(K={},k='~',[...c].map(v=>v<k?K[k=v]='':K[k]+=K[v]||v),K[k]) x=``,A=`//,||,)||(,,/`.split(',').sort(new Date) r=new Array(N).fill(0),t=i=v=0,n=`\n`,T=setTimeout C=_=>(w=Q(`ouhand t t's ake Y y all abtokey righlefwhole fooself ,${v+1},,1yr ${x[v*2]+x[v*2+1]}puintt,,Ashi,do the HPaturn yrarnd,,7,8,90123,Twi!,,6,`).split(',')[i++])<'A'?(r.map((_,m)=>T((a,b)=>R(r[N-a]=b),m*D,m,w)),i>22?(v++,i=0):0,v<3?T(C,B*(i<7||i>21?4:1)):0):C(t=w),R=_=>{for(o='',m=4;m--;o+=n){for(w=N;w--;)o+=Q(`โ”Œโ”โ””โ”˜\\/||/${A[w%5]} [__] [''] ||] _ __ _ [*-][" ][ _][_ ][ "] โ” โ”><[_<] [<.]<[..]>[.>] [>_]<> /<></>/ //`).substr(r[w]*8+(3-m)*112,8)} O.innerHTML=o+'-'.repeat(N*8)+' '.repeat(((N*8)-t.length)/2)+t} C()} ``` (**NB:** Contains some characters in the range 1-31 whose representations are a bit odd when posted here) Watch the full [psychedelic dance cycle on CodePen](https://codepen.io/CookieJon/full/JJvLVy/)! ]
[Question] [ Given 3 integers, determine the lowest possible base for the first two integers to multiply into the third. If you think of the Answer to the Ultimate Question of Life, The Universe, and Everything, 6 \* 9 == 42, is true in Base 13. The inputs can include any numbers whose digits use the characters 0-9, a-z, and A-Z, where `a` equals 10 in Base 10, and `Z` is 61 in Base 10. The inputs should be inputted in any way you like (except for hard-coding), and you can write either an individual function or an entire program. The maximum base that must be considered is Base 62, and the minimum base is Base 2. You can assume that the first two values are smaller than the third. You can also conclude that the minimum base is one greater than the highest digit/character from the inputs (for example, if the inputs are `3 1a 55`, the minimum base would be Base 11, because `a` is the highest digit). If there is no such base, return a junk value of your choice. This is code golf, so the shortest code wins. **Test Cases** ``` 6 9 42 --> 13 a a 64 --> 16 aA bB 36jk --> 41 2 3 20 --> <junk value> 10 10 100 --> 2 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 [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") ``` โŠข{3โŠƒe=ร—/2โ†‘eโ†โตโŠฅโบ:โตโ‹„โบโˆ‡โต+1}1+โŒˆ/โˆ˜, ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT//vmfeobUL1o76pnv5AhsGj7pZHvZ2PevY@apsIJA@tMDPSeNS54FFX26OuRZqPerc@6t38qHcFUL2LDpBw1AFyLAwtH/VsA/Fq/wNVVRs/6mpOtT08Xd8IaEgq0FSQtq6lj3p3WYFYIBt2PepoB7K1DWsNtR/1dOg/6pih8z8NrLQP4pau5kPrjUGO6JsaHOQMJEM8PIP/pyl45qmbKVgqmBipc4E5iQqJCmYmMI6jQpKTgrFZVjZUwNBAAYwMoHwjBWMFIwN1AA "APL (Dyalog Unicode) โ€“ Try It Online") Thanks to Adรกm for the help. Explanation: ``` โŠข{3โŠƒe=ร—/2โ†‘eโ†โตโŠฅโบ:โตโ‹„โบโˆ‡โต+1}1+โŒˆ/โˆ˜, โ โŠข โ left argument โบ: the vector (do nothing) 1+โŒˆ/โˆ˜, โ right argument โต: our starting base. , โ start by flattening the matrix of arguments โŒˆ/ โ reduce by max (find the highest number) โˆ˜ โ compose both of these together 1+ โ increment by one { โตโŠฅโบ } โ convert inputs to the current base { eโ† } โ store the converted values in 3 { 2โ†‘ } โ take the first 2 values { ร—/ } โ multiply them together (reduce-multiply) { e= } โ compare with e (the converted inputs) {3โŠƒ } โ only keep the result of the comparison with the 3rd element (expected result) { :โต } โ if truthy, return the current base. { โ‹„ } โ otherwise... { โบโˆ‡โต+1} โ ...recurse with the base incremented ``` We use a helper function, `In`, to receive the input into a more palatable format. Otherwise the input is received a matrix of 3 columns. `'3 9 42'` would give, for example (read top-down then left-to-right): ``` 0 0 4 3 9 2 ``` And for `'aA bB 36jk'` (same here. `a` is 10, `b` is 11, `A` is 36, etc) ``` 0 0 3 0 0 6 10 11 19 36 37 20 ``` [Answer] ## CJam, ~~52~~ ~~51~~ 48 bytes ``` 63,{_ea{i32b~\([G-35-9]=-_Xe>:X;}f%fbW%~*=\X>*}# ``` [Test it here.](http://cjam.aditsu.net/) The online tester doesn't support input via ARGV. The closest alternative is to put put the input like `6 9 42` into STDIN and use: ``` lS/:E; 63,{_E{i32b~\([G-35-9]=-_Xe>:X;}f%fbW%~*=\X>*}# ``` This prints `-1` if no valid base up to 62 can be found. Many thanks to Peter for the digit parsing code! I fixed a lot of problems which added 14 bytes to the count. The following explanation is still for my original submission, and I'll update it some time tomorrow. ``` 63,{_ea{i32b~\([G-35-9]=-_Xe>:X;}f%fbW%~*=\X>*}# 63, "Push the array [0 1 .. 62]."; { }# "Find the first index for which the block returns a truthy value."; _ "Duplicate the current base."; ea "Read ARGV into an array of strings."; { }f% "Apply this block to each character."; i32b "Convert to code point, and then to base-32. The most significant digit now identifies the 'type' of digit."; ~\( "Unwrap the array. Swap the digits. Decrement."; [G-35-9] "Push array [16 -35 -9] of digit offsets."; =- "Select the relevant offset and subtract it from the least significant digit."; _ "Duplicate the current digit D."; Xe>:X; "X := max(X,D). X is predefined as 1."; fb "Convert all numbers to the current base."; W% "Reverse the list of numbers."; ~ "Unwrap the array."; *= "Multiply factors. Check equality with product."; \ "Swap result with current base."; X> "Ensure base is greater than X."; * "Multiply boolean results."; ``` The index is printed automatically at the end of the program. [Answer] # Python 2 - ~~197~~ 213 What a monster... (compared to CJam) ``` from string import* I=raw_input() x,y,z=I.split() B=lambda s,b:sum(b**i*(digits+lowercase+uppercase).find(s[-i-1])for i in range(len(s))) print([b for b in range(B(max(I),10)+1,62)if B(x,b)*B(y,b)==B(z,b)]+[0])[0] ``` Unfortunately `int`'s base conversion can only handle bases up to 36. So I needed to implement it by myself. (See [this wonderful solution](https://stackoverflow.com/a/1119769/3419103).) [Answer] ## CJam, 53 bytes ``` lA,s'{,97>+'[,65>+f#_$W=1e>)63,>_@Wa/W%f{fb~*=}1#\0+= ``` Takes the three input from STDIN like ``` 6 9 42 ``` Prints `0` if product in any base is not possible Will try to golf it further. [Try it here](http://cjam.aditsu.net/) [Answer] # Prolog - 195 bytes Basically the same idea as my Erlang answer: ``` :-use_module(library(main)). main(A):-between(2,62,B),maplist(x(B),A,[F,G,P]),0is F*G-P,write(B). c(I,B,Q,O):-Q=[H|T]->(H<65->D=48;H<97->D=29;D=87),H-D<B,c(I*B+H-D,B,T,O);O=I. c(B)-->name,c(0,B). ``` In readable: ``` :- use_module(library(main)). main(Args) :- between(2, 62, Base), maplist(convert(Base), Args, [Factor1, Factor2, Product]), 0 is Factor1 * Factor2 - Product, write(Base). convert(Accumulator, Base, List, Output) :- List = [Head|Tail] -> ( Head < 65 -> Offset = 48; Head < 97 -> Offset = 29; Offset = 87), Head - Offset < Base, convert(Accumulator * Base + Head - Offset, Base, Tail, Output); Output = Accumulator. convert(Base, Input, Output) :- name(Input, List), convert(0, Base, List, Output). ``` Invocation: ``` $ swipl -qg main x.pl 6 9 42 13 $ swipl -qg main x.pl aA bB 36jk 41 $ swipl -qg main x.pl 2 3 20 ERROR: Unknown message: goal_failed(main([2,3,20])) ``` [Answer] # JavaScript (E6) 129 ~~139~~ Recursively try all bases from 2 up to 62, returning -1 if no value is ok. JavaScript parseInt function works with base up to 36, so a little help is needed for greater bases. Beware, the parameters x,y,z are strings, not numbers. It's more difficult than it seems. Thanks to Martin for pointing out a basic bug in the first version. ``` F=(x,y,z,b=2,N=n=>[for(d of(t=0,n))t=(v=parseInt(d,36)+(d>'@'&d<'a')*26)<b?t*b+v:NaN]&&t)=>b<63?N(x)*N(y)!=N(z)?F(x,y,z,b+1):b:-1 ``` **Less golfed** ``` F=(x,y,z,b=2, D=d=>parseInt(d,36)+(d>'@'&d<'a')*26, // parse a single digit N=n=>[for(d of(t=0,n))t=(v=D(d))<b?t*b+v:NaN]&&t // parse a string )=>b<63?N(x)*N(y)!=N(z)?F(x,y,z,b+1):b:-1 ``` **Test** In FireFox/FireBug console. The test tries 1000 numbers with different bases (up to 36, not 62). It's worth noting that the found base could be correct but less than the base that generated the test case. ``` for(i=0;i<1000;i++) { x=Math.random()*100|0,y=Math.random()*100|0,z=x*y,b=Math.random()*35+2|0 bx=x.toString(b),by=y.toString(b),bz=z.toString(b), nb=F(bx,by,bz) nx=parseInt(bx,nb),ny=parseInt(by,nb),nz=parseInt(bz,nb) // if (nx*ny != nz) // uncomment to se output for errors only console.log(x,y,z,'base '+b,bx,by,bz, 'found base '+nb,nx,ny,nz,nx*ny) } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` ๏ผฉโŒŠฮฆโ€ฆโŠ•โ˜โŒˆโบโบฮธฮทฮถโถยฒยฆโถยณโผร—โ˜ฮธฮนโ˜ฮทฮนโ˜ฮถฮน ``` [Try it online!](https://tio.run/##VYw7DsIwEESv4nIjhYZIaagIAokiUgRcYAmreMF2FH8QyuWNY5qwxSvezGwv0fYjqhg7y8bDAZ2Hlg3roOHEypOFC5qB4Gx6S5qMpwc06Ojq02CAFj@526ngfphKIYtSzEVCvc2sEo5TQOXgxprc@kGqc4pXRi7mX81ZLbeLEffi3oiqfr7i5q2@ "Charcoal โ€“ Try It Online") Link is to verbose version of code. Outputs `None` if no valid base can be found. Explanation: ``` ฮธ First input โบ Concatenated with ฮท Second input โบ Concatenated with ฮถ Third input โŒˆ Maximum character (by ordinal) โ˜ Converted from base โถยฒ Literal 62 โŠ• Incremented โ€ฆ Range up to โถยณ Literal 63 ฮฆ Filtered by ฮธ First input โ˜ Converted from base ฮน Current value ร— Multiplied by ฮท Second input โ˜ Converted from base ฮน Current value โผ Equals ฮถ Third input โ˜ Converted from base ฮน Current value โŒŠ Minimum ๏ผฉ Cast to string Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` 62แธŠแธ…แนช=PฦŠยฅ@ฦ‡eoแธข{ษ— ``` [Try it online!](https://tio.run/##y0rNyan8/9/M6OGOroc7Wh/uXGUbcKzr0FKHY@2p@Q93LKo@Of3/w91bFA5tVTg6@eHOxY8a5ujq2j1qmKsAlCx51LgNSG9SODzD6eik4kNLMh9tXKfyqGmNwqOGmQqH2zWPTnq4cwbQdAVLBRMjBRAAagaShsZciQqJCmYmyGJmXImOCklOCsZmWdlQMRNDLiMFYwUjAyR1NlmledkKZYk5pal2XIYGCmBkAJM1AgA "Jelly โ€“ Try It Online") Takes input similar to the [APL answer](https://codegolf.stackexchange.com/a/180994/66833). For example, `aA bB 36jk` is input as `[10, 36], [11, 37], [3, 6, 19, 20]`. The Footer does this for you. If this isn't acceptable, [+10 bytes](https://tio.run/##y0rNyan8///wDKejk4ozH21cB0KNOx41zDy01czo4Y6uhztaH@5cZRtwrOvQUodj7an5D3csqj45/f/D3VsUDm1VODr54c7Fjxrm6OraPWqYqwCULHnUuA1Ib1KAmHloCchUlUdNaxSAhiocbtc8Ounhzhn//5spWCqYGCmAAFAzkDQ05kpUSFQwM0EWM@NKdFRIclIwNsvKhoqZGHIZKRgrGBkgqbPJKs3LVihLzClNteMyNFAAIwOYrBEA) to convert from a list of strings. Outputs `1` as the junk value. ## How it works I'll explain the preceding 10 bytes for the longer version first, as both share the same ending 16 bytes: ``` ร˜Bล’siโฑฎโฑฎโธโ€™ยต - Main link. Takes a list of strings on the left ร˜B - Yield '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' ล’s - Swap-case โฑฎโธ - Over each string in the left argument: โฑฎ - Over each character: i - 1-based index โ€™ - Decrement to 0-index ยต - Use this list of numbers as the argument from now on 62แธŠแธ…แนช=PฦŠยฅ@ฦ‡eoแธข{ษ— - Main link. Takes an list of lists of integers on the left 62 - Yield 62 แธŠ - Dequeue; [2, 3, 4, ..., 62] ฦ‡ - Filter this array... ยฅ - ...on the following, ... @ - ...with the list on the right: แธ… - Convert from base ฦŠ - To this array of integers: แนช - Does the tail... = - equal... P - ...the product without the tail? ษ— - Using the input on the right and the filtered array on the left: e - Is the filtered array in the input? แธข{ - Yield the first element of the filter o - If the filtered array is in the input, return 1, else the first element ``` [Answer] # Erlang (escript) - 200 ``` main(X)->m(2,X). m(63,_)->0;m(C,X)->try[F,G,I]=[c(0,C,Y)||Y<-X],I=F*G,io:fwrite("~p",[C])catch _:_->m(C+1,X)end. c(A,B,[H|T])->D=H-if$A>H->$0;$a>H->29;0<1->87end,if D<B->c(A*B+D,B,T)end;c(A,_,_)->A. ``` Add two leading newlines which must be present. In readable: ``` #!/usr/bin/env escript main(Args) -> test(2, Args). test(63, _) -> 0; test(Base, Args) -> try [Factor1, Factor2, Product] = [convert(0, Base, Arg) || Arg <- Args], Product = Factor1 * Factor2, io:fwrite("~p", [Base]) catch _:_ -> test(Base + 1, Args) end. convert(Accumulator, Base, [Head|Tail]) -> Digit = Head - if Head < $A -> $0; Head < $a -> $A - 10 - 26; true -> $a - 10 end, if Digit < Base -> convert(Accumulator * Base + Digit, Base, Tail) end; convert(Accumulator, _, _) -> Accumulator. ``` Invocation: ``` $ escript x.erl 6 9 42 13 $ escript -i x.erl a a 64 16 $ escript -i x.erl aA bB 36jk 41 $ escript -i x.erl 2 3 20 (no output) $ escript -i x.erl 10 10 100 2 ``` [Answer] # Haskell 216 char (177?) Tried to golf this as much as possible. If imports are counted, then this is my shortest code (216) ``` import Data.Char import Data.List m=maximum j[]=0;j(x:_)=x f=reverse.map(\x->ord x-48) g[]_=0;g(m:n)x=m+x*g n x main=do l<-getLine let k@[x,y,z]=words l print$j[n|n<-[2..62],g(f x)n*g(f y)n==g(f z)n,n>(m.map(m.f)$k)] ``` However, were imports not counted, then this is my best version (177): ``` import Data.Char import Data.List import Control.Applicative m=maximum j[]=0;j(x:_)=x f=reverse.map(\x->ord x-48) g[]_=0;g(m:n)x=m+x*g n x main=words<$>getLine>>= \k@[x,y,z]->print$j[n|n<-[2..62],g(f x)n*g(f y)n==g(f z)n,n>(m.map(m.f)$k)] ``` This treats each number as a polynomial P(x) where x is the base, on condition that no coefficient is larger than x; I then evaluate the polynomials over each possible base, stopping when I reach one that satisfies the equality P(x)\*Q(x)=R(x). The 'base is bigger than largest digit' rule is enforced with the last guard in the pattern match, namely `n>(m.map(m.f)$k)`. I know that different golfing challenges and different challenge-makers have different policies regarding imports vis-a-vis scoring, so take the second one with a grain of salt. [Answer] # [Julia](http://julialang.org/), 122 bytes (79 with bending rules) Julia has an in-built up to base 62 integer parser, but the problem is uppercase characters come before lowercase ``` f(l,n=2)=try L=[parse(Int,join(i+32(i>'9')-64(i>'Z') for i=j),base=n) for j=l] L[1]L[2]==L[3]||$ n catch n<62&&f(l,n+1)end ``` `$` isn't define and will raise an error when the equality isn't right [Try it online!](https://tio.run/##LY3BisIwFEX3@YpHEZtgp9i0BASfoLuBfsGELGJtmWTCszQRRvDfO1UH7uLcs7jX34Kz1e88DzwUhFJgmu6sRT3aKfb8k1Lhr46429SSu0O@y8WHap70lQsYrhM49KI429gjvYXHYFirK9NqaRBbXZvHY8WIdTZ134z2Sq7Xr7tNJXq6zKmPKQKCZpmCHTQyY5kFC6p5whHOJ6iV/1mKhBrkdoFqC68sbNg4OUqBSv4eKvEAQ8njGFz6d0KI@Q8 "Julia 1.0 โ€“ Try It Online") # [Julia](http://julialang.org/), 79 bytes by swapping uppercase and lowercase If I'm allowed to swap lowercase and uppercase, It would shave off a lot of bytes (or at least if there was a `swapcase` function) ``` f(l,n=2)=try L=parse.(Int,l,base=n) L[1]L[2]==L[3]||$ n catch n<62&&f(l,n+1)end ``` [Try it online!](https://tio.run/##LYzRCsIgGEbvfYqfEWPSkOlCCDJYd5VvIF645WghMqZBwd7d1gq@i/Odi/N4usHQV0p94UovGBZxeiMpRjMFS4qzj6UrWxOs8BhJRbVUTAshVa3neYM86kzs7sgfOMvztbGl2PpbijbEAAIUyjjsYccylDXQAN99wcCphZpfrsthUAOrFqAVrFtYo3EafHSeFL8QEUfoSRFGN8S/wxinDw "Julia 1.0 โ€“ Try It Online") ]
[Question] [ ## Speed Clue [Cluedo/Clue](http://en.wikipedia.org/wiki/Cluedo) is a classic board game with a compelling deduction gameplay component. Speed Clue is a 3-6 player variant that emphasizes this component by using only the cards. The result is that the only difference between standard Cluedo and Speed Clue is that each player still in the game may make any suggestion he pleases on his turn instead of waiting to reach a specific room at the mercy of dice rolls and other players' suggestions. If you have never played Cluedo before, or want to be certain of the explicit differences between the two versions, you may find a [complete Speed Clue rule set here](https://github.com/sadakatsu/SpeedClueContest/tree/master/speed_clue_rules.md). --- ## Goal Write and submit an AI program to play Speed Clue before 15 May 2014 00:00 GMT. After that time, I will run a [tournament](https://github.com/sadakatsu/SpeedClueContest/tree/master/tournament.md) using all the legal entries. The entrant whose AI wins the most games in the tournament wins the challenge. --- ## AI Specifications You can write your AI in pretty much any language you choose, using whatever techniques you use, so long as it strictly uses [the application protocol](https://github.com/sadakatsu/SpeedClueContest/tree/master/protocol.md) over a TCP/IP connection to play games with the server. A detailed explanation of all the restrictions can be found [here](https://github.com/sadakatsu/SpeedClueContest/tree/master/ai_restrictions.md). --- ## How to Play Start by forking the [contest GitHub repository](https://github.com/sadakatsu/SpeedClueContest). Add a directory under the [`entries`](https://github.com/sadakatsu/SpeedClueContest/tree/master/entries) directory named using your StackExchange user name, and develop your code in that folder. When you are ready to submit your entry, make a pull request with your revisions, then follow [these instructions](https://github.com/sadakatsu/SpeedClueContest/tree/master/submission.md) for announcing your entry on this site. I have provided some code and JARs in the [`core`](https://github.com/sadakatsu/SpeedClueContest/tree/master/core) directory for getting you started; see [my site](http://sadakatsu.com) for a rough guide for the materials. In addition, other players are submitting helper code in addition to their entries to help you get up and running. Take some time to explore the entries, and don't forget to test your entry against others' entries before submitting! --- ## Results ``` Place | User | AI | Result ------+--------------+--------------------+------------------------------------------------------- 1 | gamecoder | SpockAI | 55.75% 2 | Peter Taylor | InferencePlayer | 33.06% 3 | jwg | CluePaddle | 20.19% 4 | Peter Taylor | SimpleCluedoPlayer | 8.34% 5 | gamecoder | RandomPlayer | 1.71% ---- | ray | 01 | Player "ray-01" [3] sent an invalid accuse message: "" ``` The results above show the win percentage each qualified AI had of the 25,200 valid matches in which it participated. There were 30,000 matches in total that counted toward the results, and 6,100 or so that were discounted when `01` was disqualified. An honorable mention needs to go to ray's `01` AI. My initial testing showed that it was the strongest, and I expected it to win the competition. However, it appears to have a very intermittent bug that, as far as I can guess, leads it to eliminate all possible solutions. The tournament had finished all the three-player matches and had started the four player matches (12,000 games in!) when `01`'s bug was revealed. If I just consider the 3-player match standings, the results look like this: ``` Place | User | AI | Result ------+--------------+--------------------+-------- 1 | ray | 01 | 72.10% 2 | gamecoder | SpockAI | 51.28% 3 | Peter Taylor | InferencePlayer | 39.97% 4 | Peter Taylor | SimpleCluedoPlayer | 17.65% 5 | jwg | CluePaddle | 16.92% 6 | gamecoder | RandomPlayer | 2.08% ``` I had planned on doing some data mining on the results, but I am exhausted. I had technical difficulties in getting the competition to run all the way through (power failures, system reboots) that necessitated completely rewriting the contest server to save its progress as it proceeded. I will comment and commit all the changes to the code with all the results files that were generated in case anyone is still interested. If I decide to do the data mining as well, my results will also be added to the repository. --- ## Thanks for Playing! [Answer] # AI01 - Python 3 I can't find a better name for it yet :-P . **Identifier**: ray-ai01 **Technology**: Python 3 **Selected**: yes **Arguments**: `ai01.py identifier port` **Description**: Work by inference. When the number of cards that the owner is not known is less than a threshold, this AI starts to eliminate all impossible solutions by recursive global inference. Otherwise, it use local inference. ``` #!/usr/bin/env python import itertools from speedclue.playerproxy import Player, main from speedclue.cards import CARDS from speedclue.protocol import BufMessager # import crash_on_ipy class Card: def __init__(self, name, type): self.name = name self.possible_owners = [] self.owner = None self.in_solution = False self.disproved_to = set() self.type = type def __repr__(self): return self.name def log(self, *args, **kwargs): pass def set_owner(self, owner): assert self.owner is None assert self in owner.may_have for player in self.possible_owners: player.may_have.remove(self) self.possible_owners.clear() self.owner = owner owner.must_have.add(self) self.type.rest_count -= 1 def set_as_solution(self): # import pdb; pdb.set_trace() assert self.owner is None self.type.solution = self self.in_solution = True for player in self.possible_owners: player.may_have.remove(self) self.possible_owners.clear() self.type.rest_count -= 1 def __hash__(self): return hash(self.name) class CardType: def __init__(self, type_id): self.type_id = type_id self.cards = [Card(name, self) for name in CARDS[type_id]] self.rest_count = len(self.cards) self.solution = None class PlayerInfo: def __init__(self, id): self.id = id self.must_have = set() self.may_have = set() self.selection_groups = [] self.n_cards = None def __hash__(self): return hash(self.id) def set_have_not_card(self, card): if card in self.may_have: self.may_have.remove(card) card.possible_owners.remove(self) def log(self, *args, **kwargs): pass def update(self): static = False updated = False while not static: static = True if len(self.must_have) == self.n_cards: if not self.may_have: break for card in self.may_have: card.possible_owners.remove(self) self.may_have.clear() static = False updated = True if len(self.must_have) + len(self.may_have) == self.n_cards: static = False updated = True for card in list(self.may_have): card.set_owner(self) new_groups = [] for group in self.selection_groups: group1 = [] for card in group: if card in self.must_have: break if card in self.may_have: group1.append(card) else: if len(group1) == 1: group1[0].set_owner(self) updated = True static = False elif group1: new_groups.append(group1) self.selection_groups = new_groups if len(self.must_have) + 1 == self.n_cards: # There is only one card remain to be unknown, so this card must # be in all selection groups cards = self.may_have.copy() for group in self.selection_groups: if self.must_have.isdisjoint(group): cards.intersection_update(group) for card in self.may_have - cards: static = False updated = True self.set_have_not_card(card) # assert self.must_have.isdisjoint(self.may_have) # assert len(self.must_have | self.may_have) >= self.n_cards return updated class Suggestion: def __init__(self, player, cards, dplayer, dcard): self.player = player self.cards = cards self.dplayer = dplayer self.dcard = dcard self.disproved = dplayer is not None class AI01(Player): def prepare(self): self.set_verbosity(0) def reset(self, player_count, player_id, card_names): self.log('reset', 'id=', player_id, card_names) self.fail_count = 0 self.suggest_count = 0 self.card_types = [CardType(i) for i in range(len(CARDS))] self.cards = list(itertools.chain(*(ct.cards for ct in self.card_types))) for card in self.cards: card.log = self.log self.card_map = {card.name: card for card in self.cards} self.owned_cards = [self.card_map[name] for name in card_names] self.players = [PlayerInfo(i) for i in range(player_count)] for player in self.players: player.log = self.log self.player = self.players[player_id] for card in self.cards: card.possible_owners = list(self.players) n_avail_cards = len(self.cards) - len(CARDS) for player in self.players: player.may_have = set(self.cards) player.n_cards = n_avail_cards // player_count \ + (player.id < n_avail_cards % player_count) for card in self.owned_cards: card.set_owner(self.player) for card in self.cards: if card not in self.owned_cards: self.player.set_have_not_card(card) self.suggestions = [] self.avail_suggestions = set(itertools.product(*CARDS)) self.possible_solutions = { tuple(self.get_cards_by_names(cards)): 1 for cards in self.avail_suggestions } self.filter_solutions() def filter_solutions(self): new_solutions = {} # assert self.possible_solutions join = next(iter(self.possible_solutions)) for sol in self.possible_solutions: for card, type in zip(sol, self.card_types): if card.owner or type.solution and card is not type.solution: # This candidate can not be a solution because it has a # card that has owner or this type is solved. break else: count = self.check_solution(sol) if count: new_solutions[sol] = count join = tuple(((x is y) and x) for x, y in zip(join, sol)) self.possible_solutions = new_solutions updated = False for card in join: if card and not card.in_solution: card.set_as_solution() updated = True self.log('found new target', card, 'in', join) # self.dump() return updated def check_solution(self, solution): """ This must be called after each player is updated. """ players = self.players avail_cards = set(card for card in self.cards if card.possible_owners) avail_cards -= set(solution) if len(avail_cards) >= 10: return 1 count = 0 def resolve_player(i, avail_cards): nonlocal count if i == len(players): count += 1 return player = players[i] n_take = player.n_cards - len(player.must_have) cards = avail_cards & player.may_have for choice in map(set, itertools.combinations(cards, n_take)): player_cards = player.must_have | choice for group in player.selection_groups: if player_cards.isdisjoint(group): # Invalid choice break else: resolve_player(i + 1, avail_cards - choice) resolve_player(0, avail_cards) return count def suggest1(self): choices = [] for type in self.card_types: choices.append([]) if type.solution: choices[-1].extend(self.player.must_have & set(type.cards)) else: choices[-1].extend(sorted( (card for card in type.cards if card.owner is None), key=lambda card: len(card.possible_owners))) for sgi in sorted(itertools.product(*map(lambda x:range(len(x)), choices)), key=sum): sg = tuple(choices[i][j].name for i, j in enumerate(sgi)) if sg in self.avail_suggestions: self.avail_suggestions.remove(sg) break else: sg = self.avail_suggestions.pop() self.fail_count += 1 self.log('fail') self.suggest_count += 1 return sg def suggest(self): sg = [] for type in self.card_types: card = min((card for card in type.cards if card.owner is None), key=lambda card: len(card.possible_owners)) sg.append(card.name) sg = tuple(sg) if sg not in self.avail_suggestions: sg = self.avail_suggestions.pop() else: self.avail_suggestions.remove(sg) return sg def suggestion(self, player_id, cards, disprove_player_id=None, card=None): sg = Suggestion( self.players[player_id], self.get_cards_by_names(cards), self.players[disprove_player_id] if disprove_player_id is not None else None, self.card_map[card] if card else None, ) self.suggestions.append(sg) # Iter through the non-disproving players and update their may_have end_id = sg.dplayer.id if sg.disproved else sg.player.id for player in self.iter_players(sg.player.id + 1, end_id): if player is self.player: continue for card in sg.cards: player.set_have_not_card(card) if sg.disproved: # The disproving player has sg.dcard if sg.dcard: if sg.dcard.owner is None: sg.dcard.set_owner(sg.dplayer) else: # Add a selection group to the disproving player sg.dplayer.selection_groups.append(sg.cards) self.possible_solutions.pop(tuple(sg.cards), None) self.update() def update(self): static = False while not static: static = True for card in self.cards: if card.owner is not None or card.in_solution: continue if len(card.possible_owners) == 0 and card.type.solution is None: # In solution card.set_as_solution() static = False for type in self.card_types: if type.solution is not None: continue if type.rest_count == 1: card = next(card for card in type.cards if card.owner is None) card.set_as_solution() static = False for player in self.players: if player is self.player: continue if player.update(): static = False if self.filter_solutions(): static = False def iter_players(self, start_id, end_id): n = len(self.players) for i in range(start_id, start_id + n): if i % n == end_id: break yield self.players[i % n] def accuse(self): if all(type.solution for type in self.card_types): return [type.solution.name for type in self.card_types] possible_solutions = self.possible_solutions if len(possible_solutions) == 1: return next(possible_solutions.values()) # most_possible = max(self.possible_solutions, key=self.possible_solutions.get) # total = sum(self.possible_solutions.values()) # # self.log('rate:', self.possible_solutions[most_possible] / total) # if self.possible_solutions[most_possible] > 0.7 * total: # self.log('guess', most_possible) # return [card.name for card in most_possible] return None def disprove(self, suggest_player_id, cards): cards = self.get_cards_by_names(cards) sg_player = self.players[suggest_player_id] cards = [card for card in cards if card in self.owned_cards] for card in cards: if sg_player in card.disproved_to: return card.name return max(cards, key=lambda c: len(c.disproved_to)).name def accusation(self, player_id, cards, is_win): if not is_win: cards = tuple(self.get_cards_by_names(cards)) self.possible_solutions.pop(cards, None) # player = self.players[player_id] # for card in cards: # player.set_have_not_card(card) # player.update() else: self.log('fail rate:', self.fail_count / (1e-8 + self.suggest_count)) self.log('fail count:', self.fail_count, 'suggest count:', self.suggest_count) def get_cards_by_names(self, names): return [self.card_map[name] for name in names] def dump(self): self.log() for player in self.players: self.log('player:', player.id, player.n_cards, sorted(player.must_have, key=lambda x: x.name), sorted(player.may_have, key=lambda x: x.name), '\n ', player.selection_groups) self.log('current:', [type.solution for type in self.card_types]) self.log('possible_solutions:', len(self.possible_solutions)) for sol, count in self.possible_solutions.items(): self.log(' ', sol, count) self.log('id|', end='') def end(): return ' | ' if card.name in [g[-1] for g in CARDS] else '|' for card in self.cards: self.log(card.name, end=end()) self.log() for player in self.players: self.log(' *'[player.id == self.player.id] + str(player.id), end='|') for card in self.cards: self.log( ' ' + 'xo'[player in card.possible_owners or player is card.owner], end=end()) self.log() if __name__ == '__main__': main(AI01, BufMessager) ``` The AI code can be found [here](https://github.com/ZhanruiLiang/SpeedClueContest/tree/ray_ai_contest/entries/ray). [Answer] ## SimpleCluedoPlayer.java This class uses `AbstractCluedoPlayer`, which handles all the I/O and lets the logic work with a simple typed interface. The whole thing is [on github](https://github.com/pjt33/SpeedClueContest/commit/30f5dc682d5c3c57a7d4f0ce120e1ed847d9ec24). This beats the random player with high probability (in the worst case it takes 15 suggestions, whereas the random player takes an average of 162), but it will be easily beaten. I offer it to get the ball rolling. ``` package org.cheddarmonk.cluedoai; import java.io.IOException; import java.io.PrintStream; import java.net.UnknownHostException; import java.util.*; /** * A simple player which doesn't try to make inferences from partial information. * It merely tries to maximise the information gain by always making suggestions involving cards which * it does not know to be possessed by a player, and to minimise information leakage by recording who * has seen which of its own cards. */ public class SimpleCluedoPlayer extends AbstractCluedoPlayer { private Map<CardType, Set<Card>> unseenCards; private Map<Card, Integer> shownBitmask; private Random rnd = new Random(); public SimpleCluedoPlayer(String identifier, int serverPort) throws UnknownHostException, IOException { super(identifier, serverPort); } @Override protected void handleReset() { unseenCards = new HashMap<CardType, Set<Card>>(); for (Map.Entry<CardType, Set<Card>> e : Card.byType.entrySet()) { unseenCards.put(e.getKey(), new HashSet<Card>(e.getValue())); } shownBitmask = new HashMap<Card, Integer>(); for (Card myCard : myHand()) { shownBitmask.put(myCard, 0); unseenCards.get(myCard.type).remove(myCard); } } @Override protected Suggestion makeSuggestion() { return new Suggestion( selectRandomUnseen(CardType.SUSPECT), selectRandomUnseen(CardType.WEAPON), selectRandomUnseen(CardType.ROOM)); } private Card selectRandomUnseen(CardType type) { Set<Card> candidates = unseenCards.get(type); Iterator<Card> it = candidates.iterator(); for (int idx = rnd.nextInt(candidates.size()); idx > 0; idx--) { it.next(); } return it.next(); } @Override protected Card disproveSuggestion(int suggestingPlayerIndex, Suggestion suggestion) { Card[] byNumShown = new Card[playerCount()]; Set<Card> hand = myHand(); int bit = 1 << suggestingPlayerIndex; for (Card candidate : suggestion.cards()) { if (!hand.contains(candidate)) continue; int bitmask = shownBitmask.get(candidate); if ((bitmask & bit) == bit) return candidate; byNumShown[Integer.bitCount(bitmask)] = candidate; } for (int i = byNumShown.length - 1; i >= 0; i--) { if (byNumShown[i] != null) return byNumShown[i]; } throw new IllegalStateException("Unreachable"); } @Override protected void handleSuggestionResponse(Suggestion suggestion, int disprovingPlayerIndex, Card shown) { if (shown != null) unseenCards.get(shown.type).remove(shown); else { // This player never makes a suggestion with cards from its own hand, so we're ready to accuse. unseenCards.put(CardType.SUSPECT, Collections.singleton(suggestion.suspect)); unseenCards.put(CardType.WEAPON, Collections.singleton(suggestion.weapon)); unseenCards.put(CardType.ROOM, Collections.singleton(suggestion.room)); } } @Override protected void recordSuggestionResponse(int suggestingPlayerIndex, Suggestion suggestion, Card shown) { shownBitmask.put(shown, shownBitmask.get(shown) | (1 << suggestingPlayerIndex)); } @Override protected void recordSuggestionResponse(int suggestingPlayerIndex, Suggestion suggestion, int disprovingPlayerIndex) { // Do nothing. } @Override protected Suggestion makeAccusation() { Set<Card> suspects = unseenCards.get(CardType.SUSPECT); Set<Card> weapons = unseenCards.get(CardType.WEAPON); Set<Card> rooms = unseenCards.get(CardType.ROOM); if (suspects.size() * weapons.size() * rooms.size() == 1) { return new Suggestion(suspects.iterator().next(), weapons.iterator().next(), rooms.iterator().next()); } return null; } @Override protected void recordAccusation(int accusingPlayer, Suggestion accusation, boolean correct) { // Do nothing. } //*********************** Public Static Interface ************************// public static void main(String[] args) throws Exception { try { System.setOut(new PrintStream("/tmp/speed-cluedo-player" + args[0]+".log")); new SimpleCluedoPlayer(args[0], Integer.parseInt(args[1])).run(); } catch (Throwable th) { th.printStackTrace(System.out); } } } ``` [Answer] ## SpockAI **Identifier:** `gamecoder-SpockAI` **Repo Entry:** [click here](https://github.com/sadakatsu/SpeedClueContest/tree/master/entries/gamecoder/SpockAI) **Selected:** Yes **Technology:** Java 7 based upon `com.sadakatsu.clue.jar` **Arguments:** `{identifier} portNumber [logOutput: true|false]` **Description:** `SpockAI` is a Speed Clue player built upon a class called `Knowledge` that I wrote. The `Knowledge` class represents all the possible states that the game could have given what has happened thus far. It represents the game's solutions and players' possible hands as sets, and uses iterative deductions to reduce these sets as far as possible every time something is learned. `SpockAI` uses this class to determine which suggestions are assured to have the most helpful worst-case results and randomly selects one of those suggestions on its turns. When it needs to disprove a suggestion, it tries to either show a card it has already shown the suggesting AI or to show it a card from the category for which it has reduced the possibilities the least. It only makes an accusation when it knows the solution. The heuristic I used for determining the best suggestion is as follows. After all information has been learned from a suggestion, the possible solution and possible player hand sets will have been reduced (unless the suggestion reveals no new information). Theoretically, the best suggestion is the one that most reduces the number of possible solutions. In the case of a tie, I assume that a suggestion that most reduces the number of possible hands for players is better. So, for each suggestion, I try every possible outcome that does not lead to a contradiction in knowledge. Whichever outcome has the least improvement in solution/hand counts is assumed to be the result the suggestion will have. Then I compare all the suggestions' results, and pick which one has the best result. In this way, I guarantee optimal worst-case information gain. I am considering adding a brute force combination analysis of possible solutions and possible player hands to make `SpockAI` even stronger, but since `SpockAI` is already the slowest, most resource-intensive entry, I will probably skip that. **Disclaimer:** I had intended to release an AI for this contest weeks ago. As it stands, I wasn't able to start writing my AI until Friday last week, and I kept finding ridiculous bugs in my code. Because of this, the only way I was able to get `SpockAI` to work before the deadline was to use a large thread pool. The end result is that (currently) SpockAI can hit +90% CPU utilization and 2GB+ memory usage (though I blame the garbage collector for this). I intend to run `SpockAI` in the contest, but if others feel that is a violation of [the rules](https://github.com/sadakatsu/SpeedClueContest/blob/master/ai_restrictions.md), I will award the title of "winner" to second place should `SpockAI` win. If you you feel this way, please leave a comment to that effect on this answer. [Answer] ## InferencePlayer.java [Full code on Github](https://github.com/pjt33/SpeedClueContest/blob/inferencePlayer/entries/peter_taylor/src/org/cheddarmonk/cluedoai/InferencePlayer.java) (note: this uses the same `AbstractCluedoPlayer` as my earlier `SimpleCluedoPlayer`). The true core of this player is its `PlayerInformation` class (here slightly trimmed): ``` private static class PlayerInformation { final PlayerInformation[] context; final int playerId; final int handSize; Set<Integer> clauses = new HashSet<Integer>(); Set<Card> knownHand = new HashSet<Card>(); int possibleCards; boolean needsUpdate = false; public PlayerInformation(PlayerInformation[] context, int playerId, boolean isMe, int handSize, Set<Card> myHand) { this.context = context; this.playerId = playerId; this.handSize = handSize; if (isMe) { knownHand.addAll(myHand); possibleCards = 0; for (Card card : knownHand) { int cardMask = idsByCard.get(card); clauses.add(cardMask); possibleCards |= cardMask; } } else { possibleCards = allCardsMask; for (Card card : myHand) { possibleCards &= ~idsByCard.get(card); } if (playerId == -1) { // Not really a player: this represents knowledge about the solution. // The solution contains one of each type of card. clauses.add(suspectsMask & possibleCards); clauses.add(weaponsMask & possibleCards); clauses.add(roomsMask & possibleCards); } } } public void hasCard(Card card) { if (knownHand.add(card)) { // This is new information. needsUpdate = true; clauses.add(idsByCard.get(card)); // Inform the other PlayerInformation instances that their player doesn't have the card. int mask = idsByCard.get(card); for (PlayerInformation pi : context) { if (pi != this) pi.excludeMask(mask); } if (knownHand.size() == handSize) { possibleCards = mask(knownHand); } } } public void excludeMask(int mask) { if (knownHand.size() == handSize) return; // We can't benefit from any new information. if ((mask & possibleCards) != 0) { // The fact that we have none of the cards in the mask contains some new information. needsUpdate = true; possibleCards &= ~mask; } } public void disprovedSuggestion(Suggestion suggestion) { if (knownHand.size() == handSize) return; // We can't benefit from any new information. // Exclude cards which we know the player doesn't have. needsUpdate = clauses.add(mask(suggestion.cards()) & possibleCards); } public void passedSuggestion(Suggestion suggestion) { if (knownHand.size() == handSize) return; // We can't benefit from any new information. excludeMask(mask(suggestion.cards())); } public boolean update() { if (!needsUpdate) return false; needsUpdate = false; // Minimise the clauses, step 1: exclude cards which the player definitely doesn't have. Set<Integer> newClauses = new HashSet<Integer>(); for (int clause : clauses) { newClauses.add(clause & possibleCards); } clauses = newClauses; if (clauses.contains(0)) throw new IllegalStateException(); // Minimise the clauses, step 2: where one clause is a superset of another, discard the less specific one. Set<Integer> toEliminate = new HashSet<Integer>(); for (int clause1 : clauses) { for (int clause2 : clauses) { if (clause1 != clause2 && (clause1 & clause2) == clause1) { toEliminate.add(clause2); } } } clauses.removeAll(toEliminate); // Every single-card clause is a known card: update knownHand if necessary. for (int clause : clauses) { if (((clause - 1) & clause) == 0) { Card singleCard = cardsById.get(clause); hasCard(cardsById.get(clause)); } } // Every disjoint set of clauses of size equal to handSize excludes all cards not in the union of that set. Set<Integer> disjoint = new HashSet<Integer>(clauses); for (int n = 2; n <= handSize; n++) { Set<Integer> nextDisjoint = new HashSet<Integer>(); for (int clause : clauses) { for (int set : disjoint) { if ((set & clause) == 0) nextDisjoint.add(set | clause); } } disjoint = nextDisjoint; } for (int set : disjoint) excludeMask(~set); return true; } } ``` It unifies information on suggestions which the player didn't disprove (indicating that they hold none of those cards), suggestions which they did disprove (indicating that they hold at least one of those cards), and cards whose location is certain. Then it iteratively applies some basic rules to compact that information into its essence. I don't think there's any more deterministic information to be obtained (except from via false accusations, which I'm assuming to be too rare to bother with), although I may have overlooked something. There *is* potential for a more sophisticated player to estimate probabilities that player X has card Y... The other area which probably admits significant improvement is in deciding which suggestion to make. I attempt to maximise the information gain using a fairly clunky heavy-force approach, but there's a lot of poorly justified heuristic in evaluating the relative merits of the knowledge gained from different hypothetical disproofs. However, I'm not going to try tuning the heuristics until someone else posts a worthy opponent. [Answer] # CluePaddle (ClueStick / ClueBat / ClueByFour) - C# I have written ClueBot, a C# client for which it is straightforward to implement AIs, and various AIs, including the most serious attempt called CluePaddle. The code is at <https://github.com/jwg4/SpeedClueContest/tree/clue_paddle> with a pull request started to merge it into upstream. ClueStick is a proof-of-concept which basically just guesses and ignores most of what happens. ClueBat is another stupid AI, except that it tries to exploit a flaw in ClueStick to force it to do false accusations. ClueByFour is a reasonable AI in that it makes reasonable suggestions and remembers the cards it is shown by others. CluePaddle is the most intelligent. It tries to figure out who has what based not only on what disproofs have been offered, but also based on which players didn't offer a disproof of a given suggestion. It doesn't take into account how many cards each player has atm but this is to be fixed. It includes a couple of quite long classes so I won't post the whole code here, but the following method gives a flavor. ``` public void Suggestion(int suggester, MurderSet suggestion, int? disprover, Card disproof) { List<int> nonDisprovers = NonDisprovers(suggester, disprover).ToList(); foreach (var player in nonDisprovers) { m_cardTracker.DoesntHaveAnyOf(player, suggestion); } if (disprover != null && disproof == null) { // We know who disproved it but not what they showed. Debug.Assert(disprover != m_i, "The disprover should see the disproof"); Debug.Assert(suggester != m_i, "The suggester should see the disproof"); m_cardTracker.DoesntHaveAllOf(suggester, suggestion); m_cardTracker.HasOneOf((int)disprover, suggestion); } if (disproof != null) { // We know who disproved it and what they showed. Debug.Assert(disprover != null, "disproof is not null but disprover is null"); m_cardTracker.DoesHave((int)disprover, disproof.Value); } } ``` If the 4 play against each other, CluePaddle wins by far the most games, with ClueByFour second and the other two nowhere. **Only CluePaddle is a competitive entry (so far).** Usage: ``` CluePaddle.exe identifier port ``` If anyone else wants to make a C# AI, just create a ConsoleApplication project in the soltution, implement the `IClueAI` interface in a class, and then make your `Program` derive from `ProgramTemplate` and copy what the other projects do for `Main()`. The only dependency is NUnit for unit testing and you could easily remove all the testing from the code (but don't, just install NUnit). ]
[Question] [ You are a secret agent trying to communicate with your fatherland. Of course the information needs to be hidden so no one eaves drops your message. What would be better suited than a cat? Everyone loves funny pictures of cats [citation needed], so they won't suspect secret information hiding in there! --- Inspired by [the algorithm the game Monaco uses to save the level information of shared levels](https://www.facebook.com/note.php?note_id=437497056995) it is your tasks to write a program that encoded information into the least significant bit of the colors of an image. Encoding format: * The first 24 bits determine the length of the remaining encoded byte-string in *bits* * The image is read from left to right and from top to bottom, obviously starting in the upper left pixel * The channels are read from red to green to blue * The least significant bit from each channel is read * Bits are saved in Big Endian order Rules: * Your program takes a single byte-string to be encoded and a single image filename for the base image * The resulting image must be come out as a true color PNG file * You may use I/O in whatever form you like (ARGV, STDIN, STDOUT, writing / reading from a file), as long as you state how to use your program * You must choose a random image of a funny cat and encode your program into it to show that your program works * You may assume that you are only provided valid input, if the amount of bits are not sufficient, the image is not in true color format, the image does not exist or similar problems you may do what you want * You may assume that the provided image does not contain any alpha channel * Length is counted in UTF-8 bytes without BOM You may use this PHP script to test your solution, provide the name of the PNG file as the first command line argument: ``` <?php if ($argc === 1) die('Provide the filename of the PNG to read from'); $imageSize = @getimagesize($argv[1]); if ($imageSize === false) die('Not a PNG file'); list($width, $height) = $imageSize; $image = imagecreatefrompng($argv[1]); $read = 0; $bits = ''; for ($y = 0; $y < $height; $y++) { for ($x = 0; $x < $width; $x++) { $colorAt = imagecolorat($image, $x, $y); $red = ($colorAt >> 16) & 0xFF; $green = ($colorAt >> 8) & 0xFF; $blue = ($colorAt >> 0) & 0xFF; $bits .= ($red & 1).($green & 1).($blue & 1); $read += 3; if ($read == 24) { $length = (int) bindec($bits); $bits = ''; } else if ($read > 24 && ($read - 24) > $length) { $bits = substr($bits, 0, $length); break 2; } } } if (strlen($bits) !== $length) die('Not enough bits read to fulfill the length'); $parts = str_split($bits, 8); foreach ($parts as $part) { echo chr(bindec($part)); } ``` [Answer] ## Mathematica, ~~255~~ ~~234~~ 206 bytes ~~I've seen so many `255`s while testing this, I'm unreasonably happy about the size of the code. :)~~ And then my ambition to golf it down even further got the best of me... ``` f=(j=ImageData[Import@#2,t="Byte"];k=(d=IntegerDigits)[j,2,8]~Flatten~2;n=1;(k[[n++,-1]]=#)&/@d[Length@#,2,24]~Join~#&[Join@@d[ToCharacterCode@#,2,8]];ArrayReshape[#~FromDigits~2&/@k,Dimensions@j]~Image~t)& ``` It's technically a function and not a "program", but then again this is pretty much how you write "programs" in Mathematica, if that concept is even valid there. Call it like ``` f["my secret", "fully/qualified/cat.png"] ``` It will return an actual image expression (because that's the most natural way to return an image in Mathematica), so if you want a file, you need to export it: ``` Export["output-cat.png", f["my secret", "input-cat.png"]] ``` Here is the required example: ![enter image description here](https://i.stack.imgur.com/CMnyr.png) I'd love to show you the decoded message here, but it doesn't fit... so run it through the OP's decoder. ;) Btw, I could make it work with UTF-8 secrets for just 7 bytes (change `ToCharacterCode@#` into `#~ToCharacterCode~"utf8"`). Ungolfed code: ``` f[secret_, filename_] := ( bits = Join @@ IntegerDigits[ToCharacterCode[secret], 2, 8]; bits = Join[d[Length @ bits, 2, 24], bits]; data = ImageData[Import@#2, "Byte"]; dims = Dimensions@data; data = Flatten[IntegerDigits[data, 2, 8], 2]; m = n = 1; While[m <= Length @ bits, data[[n++, -1]] = bits[[m++]] ]; Image[ArrayReshape[FromDigits[#, 2] & /@ data, dims], "Byte"] ) ``` [Answer] # PHP, 530 byte ``` <?php function p($i,$j){return str_pad(decbin($i),$j,0,0);}extract(getopt("i:o:t:"));$t=file_get_contents($t);$_=imagecreatefrompng($i);list($w,$h)=getimagesize($i);$b="";for($i=0;$i<strlen($t);)$b.=p(ord($t[$i++]),8);$l=strlen($b);$b=p($l,24).$b;$l+=24;for($i=$x=$y=0;$y<$h;$y++){for(;$x<$w;){$C=imagecolorat($_,$x,$y);$R=($C>>16)&0xff;$G=($C>>8)&0xff;$B=$C&0xff;$i<$l&&$R=$b[$i++]|$R&~1;$i<$l&&$G=$b[$i++]|$G&~1;$i<$l&&$B=$b[$i++]|$B&~1;imagesetpixel($_,$x++,$y,imagecolorallocate($_,$R,$G,$B));if($i>$l){imagepng($_,$o);die;}}} ``` Run like `php 25443.php -i<input image> -o<output image> -t<file to hide>`. And here's a sample image. ![https://i.stack.imgur.com/38t8l.png](https://i.stack.imgur.com/38t8l.png) Ungolfed code is hidden in the sample image. Tested with OP's decoder. Sorry for not funny cat picture. [Answer] ## Perl & ImageMagick (Linux), ~~198~~ 190 **Edit:** By some coincidence, earlier I tested on a computer with Q8 (8 bit depth) version of ImageMagick installed. 'Standard' Q16 version requires explicit `-depth 8` on command line. On Linux, `identify` result requires newline to be removed, too. Both factors lead to code size increase, therefore I post Linux (probably Mac too) version as an answer, with fixes applied, and also with some Windows-only stuff removed (cr-lf conversion, binary vs text etc.). Portable (slightly longer) version is posted near the end. With newlines for readability: ``` $/=$1; <>=~/\n/; $_=`identify -format %wx%h $\``; chop; open O,"|convert -size $_ -depth 8 rgb: $`.png"; $_=`convert $\` rgb:`; print O$_&y//\376/cr|unpack('B*',pack(NX,2048*length$').$')&y//\1/cr ``` Run: ``` perl cat.pl ``` It reads from STDIN, image file name on first line, 'secret' message follows, terminated with `ctrl-D`. Output file name is original with `.png` appended - not very nice, it's only done for brevity. Here's an image with some very secret information hidden within: ![enter image description here](https://i.stack.imgur.com/WWzip.png) And with some comments: ``` # Undef input record separator, because we'll slurp input. $/=$1; # Read from STDIN, separate first line. # $` (prematch) contains image file name, # $' (postmatch) - text to encode. <>=~/\n/; # Get IM's 'identify' output, width and height of the image. # Note: we don't have to separate them, \d+x\d+ string will # do just fine. $_=`identify -format %wx%h $\``; chop; # Open output pipe - IM's 'convert' command that takes raw RGB data from # STDIN and writes output to PNG file. Interpolated into this command # line is previous IM's 'identify' result. Convert wants '-size' command # option in case of raw RGB input - for obvious reason. open O,"|convert -size $_ -depth 8 rgb: $`.png"; # Get raw RGB data into $_. $_=`convert $\` rgb:`; # Last line does all the job. # y//\376/cr --- create string same length as $_, fill with 0xFE # $_&y//\376/cr --- zero least significant bit for all image bytes (1). # pack(NX,2048*length$') --- multiply by 8 (bytes to bits count) and # shift left by 8 (because we'll pack long integer into 3 bytes) - # i.e. multiply by 2048. # unpack('B*',pack(NX,2048*length$').$') ---- append 'secret text' to # its encoded length and convert to 'binary' (consisting of 1 and # 0 characters) string. # ... &y//\1/cr --- equivalent of tr/01/\0\1/. We don't have to worry # that raw RGB length is larger than encoded text length, because # '&' truncates longer string argument (2). # Then bitwise-'or' (1) and (2) strings. print O$_&y//\376/cr|unpack('B*',pack(NX,2048*length$').$')&y//\1/cr ``` Next is portable version, runs on both Windows (use `ctrl-Z` to terminate input) and Linux, byte count is 244. ``` $_=do{local$/;<>}; /\n/; $_=`identify -format %wx%h $\``; chomp; open I,'-|:raw',"convert $` rgb:"; open O,'|-:raw',"convert -size $_ -depth 8 rgb: $`.png"; $_=do{local$/;<I>}; print O$_&y//\376/cr|unpack('B*',pack(NX,2048*length$').$')&y//\1/cr ``` ]
[Question] [ Lighthouses on an island have blink codes that let ships know which lighthouse they are seeing. Input should be strings of S and L. Here is a (Python) example of codes for 4 lighthouses as a list of strings: ``` ['SLS', 'SLL', 'SSS', 'LSL'] ``` where: S = short ON (1 sec) L = long ON (3 sec) Long and short ON's are both followed by 1 sec OFF, except the last in the code, which is followed by a *7-second LONG OFF pause* to signify end of code. The code for the first lighthouse in the above example corresponds to this blink *schedule* in seconds : 1 ON, 1 OFF, 3 ON, 1 OFF, 1 ON, 7 OFF [repeat] **Challenge:** n Lighthouses come on simultaneously, each at the start of its schedule. Write a program that takes a series of blink codes (strings in the above format) and outputs the total number of seconds that *exactly* zero, one, two, three, ... n lighthouses were on at the same time *after the first hour of lighthouse operation* (So the output numbers will always total 3600.) **Test Cases**: ``` Input -> Output ['SLS', 'SLL', 'SSS', 'LSL'] -> 1125, 890, 652, 590, 343 ['S', 'L', 'SS'] -> 2250, 630, 540, 180 ['SLSL', 'S'] -> 1850, 1450, 300 ['SLS'] -> 2314, 1286 ['SS', 'SS', 'L'] -> 2520, 360, 0, 720 ``` **Rules**: There can be one or more lighthouses (code strings). All lighthouses come on simultaneously, each at the start of its code schedule. Codes can be any length >= 1 and don't have to be unique (however off-shore mayhem may ensue). Just for clarity, the 652 in the first example is the time in seconds that *exactly* 2 lighthouse (not 2 or more) were on. The shortest code in bytes wins ([code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24 22 21~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` O%9ร„แนฌ;ร˜แปตยฌแนโฝยฝc)Sฤ‹โฑฎLลป$ ``` A monadic Link that accepts the list of lists of `S` and/or `L` characters and yields the ascending list of multiplicity counts. **[Try it online!](https://tio.run/##y0rNyan8/99f1fJwy8Oda6wPz3i4e@uhNQ93Nj5q3Htob7Jm8JHuRxvX@RzdrfL///9o9WCfYHUdBSDlA6aCwTyfYB/1WAA "Jelly โ€“ Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/99f1fJwy8Oda6wPz3i4e@uhNQ93Nj5q3Htob7Jm8JHuRxvX@RzdrfL/cPujpjX//0dHqwf7BKvrKAApHzAVDOb5BPuox3LpAGXBPIgMVAQkB@LDuVBGMFQVWENsLAA "Jelly โ€“ Try It Online"). ### How? ``` O%9ร„แนฌ;ร˜แปตยฌแนโฝยฝc)Sฤ‹โฑฎLลป$ - Link: lighthouse patterns, P ) - for each pattern in P: say, 'SLSL' O - cast to ordnials [83,76,83,76] %9 - modulo nine [2,4,2,4] ร„ - cumulative sums [2,6,8,12] แนฌ - untruth [0,1,0,0,0,1,0,1,0,0,0,1] ;ร˜แปต - concatenate "aeiouy" [0,1,0,0,0,1,0,1,0,0,0,1,'a','e','i','o','u','y'] ยฌ - logical NOT [1,0,1,1,1,0,1,0,1,1,1,0,0,0,0,0,0,0] (the "full-pattern" of this lighthouse) โฝยฝc - 3600 แน - (full-pattern) moulded-like (3600) -> above repeated to length 3600 S - sum (vectorises) -> counts at each second $ - last two links as a monad, f(P): L - length of P ลป - zero-range -> [0..length(P)] โฑฎ - for each n in [0..length(P)]: ฤ‹ - count occurrences of n in the counts at each second ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes ``` ฮตโ‚ฌC9%ร…10.รฝหœ7ร…0ยซ60nโˆ}รธOZรยข ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3NZHTWucLVUPtxoa6B3ee3qO@eFWg0OrzQzyHnX01h7e4R91eO6hRf//RysF@wQr6SgAKR8wFQzm@QT7KMUCAA "05AB1E โ€“ Try It Online") ``` ฮต } # for each lighthouse in the implicit input: โ‚ฌC # convert each character from binary 9% # modulo 9: S -> 28 %9 = 1, L -> 21%9 = 3 ร…1 # for each number in the resulting list get a list of that many 1's 0.รฝ # intersperse with 0's หœ # flatten into a list of 1's and 0's 7ร…0ยซ # append 7 0's 60nโˆ # extend the list to length 60^2=3600 by cycling the values รธ # after the loop: transpose the list of lists O # sum every one of the 3600 sublists Zร # get the range [0 .. max(a)] ยข # for each value in the range, count occurences in the long list ``` Try the `S/L` to `0/1` conversion with step-by-step output: [Try it online!](https://tio.run/##NcxPasJQEAbwfU4xBCQWRJ4LEQsuiigE3OUEz2ZiHiQz4b3x37YgdNMb9AYt9ATdNEtv4UWio3Qxm/l938fBrh12XZxSs5XneBDNojiaM@3QCxSea0jWjqw/JoqXt@@5BmrOtxXDVH/T3r3i0QpC5YIE4AJGSVBsTyPVlAR9aG6HsHdSgnmwaX@G7a8mlpUVQQIpHyOq50@Vl6ZBymHy35m0J/P3pbI4iIowVEib2@rYQP@1tLTBHAr2kGPNFMRbcUxPWh6by/vHrOuyVXYF "05AB1E โ€“ Try It Online") [Answer] # [J](http://jsoftware.com/), 60 53 52 bytes ``` _1+(0,#\)#/.~@,[:+/(3600$(6$0),~&;19<@#:@|14+3&u:)&> ``` [Try it online!](https://tio.run/##dY5LC8IwEITv/RWLlbahsd08rfFBQfCUkzkqWBBFvHjyJv71ukGrJyEZlsw3s7n2oyo/w9JBDhwQHN1JBeut3/QHURbI0z1L6@rZ8p0r60JZxHFhx8j4M5uL2aJNXfsQulTZ3bFs1bPkdLzc4AzBhy5434UQOh/8@7kQQhoOzQw5WCM5mDgprYDBxP1NSWliQJEYTSIaHPguskN5EzGhoyrEXyUxQ5MSmhDZ2I/L3SInIh98I2PYktCZym8JfYt2Jf0L "J โ€“ Try It Online") -7 after reading Jonathan Allen's idea of doing arithmetic on the character codes, though I use a different method which converts S to 2 and L to 14, and then converts those to binary. ## idea * For each pattern, convert it into a bitmask where 1 is on, 0 is off * Extend that bitmask cyclically to 3600. Now we have an `n x 3600` matrix. * Sum columns. Now we have the numbers 0-n, each some number of times. * Prepend the numbers 0-n to that list, in case any happen to be missing, and so the result will be ordered from 0 to n. * Group and count. * Subtract 1 from each count. [Answer] # JavaScript (ES6), 113 bytes Expects an array of strings. Returns an object. ``` a=>(n=3600,g=L=>n--?g(o[a.map(s=>t+=~~(s=s.replace(/./g,c=>c>g?10:1110))[n%(s.length+6)],t=0),t]=-~o[t]):o)(o={}) ``` [Try it online!](https://tio.run/##bY/NboQgFEb3fQo2jZBB5UccOwnOC7hzaVwQx6GdWDAj6aapr25Bm7TpSMh3L4tzLvemPtTU3d9GFxt76ZerXJQsoZE8JwRrWcnSxPFZQ9uo5F2NcJKlO8h59s2U3PtxUF0P0yTVuJNlV@ozJSdKKUGoMc9wSobeaPd6yFGLnSQIu1bGs21ci04WQSs/v9DSWTPZoU8Gq@EVNlFd1REGvlRrqddXVVdRixAAaQooZQKD4oVgkAuGgQgdzzgATw@uld08G//3eBdjImi4D5H5oAXZsYTpwfGo2Cy0CBaaheSEgF3FLvz7EU4zr2BFvkfXPyus2/z3BFqwMDr34e@RkeUb "JavaScript (Node.js) โ€“ Try It Online") [Answer] # Python 2, ~~125~~ 117 bytes ``` lambda a:map(map(sum,zip(*[sum([2*(c<'S')*[1]+[1,0]for c in C],[0]*6)*500for C in a]))[6:3606].count,range(len(a)+1)) ``` -8 thanks to Jonathan Allan. [Answer] # [Python 3](https://docs.python.org/3/), 154 bytes Very trivial approach: convert the code strings into sequences of 1s and 0s representing the seconds in which each lighthouse is ON or OFF; then cumulate the sum of seconds depending on how many lighthouses are on at the same time. ``` def f(h): t=[0]*(len(h)+1) for i in range(3600):t[[c[i]for c in[(x.replace('S','10').replace('L','1110')+'0'*6)*450for x in h]].count('1')]+=1 print(t) ``` [Try it online!](https://tio.run/##TYxBDoMgEEX3noLdMNoYiK0LE2/AjiVhYShUE4PG0MSe3gJtbFcz/72Zv77CuPjmOO7WEUdH7AoSesV0SWfrY644FsQtG5nI5Mk2@IelTcsYdkEpoyadnIlO0b3e7DoPxlKQcAHOAH9EJMITq4BB2WJ5vbH0u6feUevaLE8fKHBAXfW8IOs2xRzwcFSBFLGSxCHykDkJKUBjkX3OH3ey5BP5A@cqv7f5TePxBg "Python 3 โ€“ Try It Online") --- *Un-golfed function with comments* ``` def f(lighthouses): """ function that takes as input the list of lighthouses' blink codes """ # replace in the codes 'S' and 'L' with '1's # corresponding to the effective ON duration in seconds # '0' is needed for the OFF separation period lighthouses = [x.replace('S', '10') for x in lighthouses] lighthouses = [x.replace('L', '1110') for x in lighthouses] # LONG OFF period # only 6s because one '0' is already added on the last character lighthouses = [x + '0'*6 for x in lighthouses] # repeat the sequence for at least 1h # minimum code duration 'S' = 8s # 3600/8=450 then repeat 450 times to be sure to have at least 1h lighthouses = [x * 450 for x in lighthouses] # initialize the list to keep the total number of seconds tot = [0] * (len(lighthouses) + 1) # loop over 1h of repeated sequences for i in range(3600): # increase the counter # the index corresponds to how many lighthouses are ON at the same time # counting how many '1's there are at a given position in all the sequences tot[[c[i] for c in lighthouses].count('1')] += 1 # outputs the list with total seconds print(tot) ``` [Answer] # [R](https://www.r-project.org/), ~~119~~ 116 bytes *Edit: -3 bytes thanks to Giuseppe* ``` function(a)table(c(rowSums(sapply(a,function(x)!1:3600%in%cumsum(rep(c(utf8ToInt(x)%%9,!!1:6),999)))),0:sum(a>0)))-1 ``` [Try it online!](https://tio.run/##fc49C8MgEAbgv9IMEgULhkKogXYvuNldjDVUiBr8IO2vT68ZOvaWlxeeOy5tofrRJhUnla2J4ZHV6spTBTW7ctmmGkxxMWBNih5niw1OcZXVZ5z1ssxvrOnPvEjTDaeeMeQCMmCqx8kusFPLdL7HWyhgEOK0AdgTyjknMJQNX6qvDMqx@/sSHGulkC09QIg95N6EFC0h2wc "R โ€“ Try It Online") [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 24 bytes ``` .:0,,$,`?.`'.@<3600^~:+.$.\`,%$9`$$.,6 0+$@ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWN7X1rAx0dFR0Euz1EtT1HGyMzQwM4uqstPVU9GISdFRVLBNUVPR0zBQMtFUcIFpgOjWilaJjlIJ9gmOUdBRADB8oIxgq4hMMFIlVioVqAAA) This program is a bit complicated. ``` .:0,,$,`?.`'.@<3600^~:+.$.\`,%$9`$$.,6 0+$@ . For each :0, n from 0 to , length $ input ,`? number of occurences @ of n in . +$ sum each sublist of `' transpose . for each @ blink code from the input <3600 take the first 3600 items of ^~ repeat infinitely : join + concatenate . for each $ letter from the blink code . `$$ sign of each number in \ reversed `, range from 0 up to (excluding) %$9 the letter modulo 9 .,6 0 with six zeroes ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), `AB` 37 bytes ``` :ฦ›`SL`โŸจโ‚€|1110โŸฉฤฟ\06ฮตJแน…รžฤ‹60ยฒแบŽvโŒŠ;โˆ‘$Lส€ยจVO ``` The first start may be slow (or time-off) due to the use of the infinite lazy list, but then everything works well [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBQiIsIiIsIjrGm2BTTGDin6jigoB8MTExMOKfqcS/XFwwNs61SuG5hcOexIs2MMKy4bqOduKMijviiJEkTMqAwqhWTyIsIiIsIlsnU0xTJywgJ1NMTCcsICdTU1MnLCAnTFNMJ11cblsnUycsICdMJywgJ1NTJ11cblsnU0xTTCcsICdTJ11cblsnU0xTJ10gXG5bJ1NTJywgJ1NTJywgJ0wnXSJd) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` ๏ผฉ๏ผฅโŠ•๏ผฌฮธโ„–๏ผฅยณโถโฐโฐฮฃโญ†ฮธยงโบโชซ๏ผฅฮฝร—1โˆจโผฯ€Sยณ0ร—0โทฮปฮน ``` [Try it online!](https://tio.run/##LYzLCoMwEEV/JWTjCCmkCO2iqyJdWFIqpDtxETRoII6PxNK/T43t6szcOXObXi3NqGwI5WLQQ66ch4eaoMBm0YNGr1sQGjvfw5ymjOTjij8jO3HOiFwHkH777WI2M3L1Bbb6A6VdHdxHg7uMjLzMoB3QI2XkucBtXpV1MDFCJd16szS2Ux7nv8k38xxTm@5HE3EJoaoSKWTCyAaxQ@6bkCKp63B42y8 "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: For each number of "on" lighthouses and each second of the hour, calculate the "on" pattern for each lighthouse and count how many of the seconds had that number of lighthouses "on". ``` ฮธ Input array ๏ผฌ Length โŠ• Incremented ๏ผฅ Map over implicit range ยณโถโฐโฐ Literal `3600` (seconds) ๏ผฅ Map over implicit range ฮธ Input array โญ† Map over elements and join ฮฝ Current blink code ๏ผฅ Map over characters 1 Literal string `1` ร— Repeated by ฯ€ Current character โผ Equals S Literal string `S` โˆจ Logical Or ยณ Literal `3` โชซ Join with 0 Literal string `0` โบ Concatenated with 0 Literal string `0` ร— Repeated by โท Literal `7` ยง Indexed by ฮป Current second ฮฃ Sum i.e. count of "on" lighthouses โ„– Count of ฮน Outer index ๏ผฉ Cast to string Implicitly print ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 119 bytes ``` Rest@BinCounts@Total[PadRight[#,3600,#]&/@(Flatten@Join[Characters[#]/.{"S"->{1,0},"L"->{1,1,1,0}},Array[0#&,6]]&/@#)]& ``` [Try it online!](https://tio.run/##TUy9CsIwGNx9CkmgKEQbEdyUaMFBMpTGLWT4qMUE2hTSz0FKnr32Z5Eb7o77aQBt1QC6EgZ7HoqqQ3FzPms/HjvxbBFqncOrcG@LmrLjiXNGTZKKzb0GxMqLR@u8ziwEKLEKnaYm3fdEkd2lPzAeGZGLnMBjZNcQ4Ks5TdjJTEd0a5IhD86jsGIcSkXYeiQ5k5qdVJLE1V9p6SwZicMP "Wolfram Language (Mathematica) โ€“ Try It Online") Seems similar to others (yet DIY and worse), but I couldnโ€™t get past the challenge with the word "Lighthouse" 8) ]
[Question] [ When writing [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") programs, I usually end up using some numeric constants. I always put them in decimal because that's how I think, but I just realized that my language supports other number formats that might let me shorten my code slightly. # Challenge Given a non-negative integer less than 2^53-1, decide whether that integer has the shortest representation in: * Decimal * Hexadecimal * Scientific Notation ### Decimal Since this is the default format of my language, there is no extra notation needed for this format. Every number is represented as usual for decimal. ### Hexadecimal My languages uses the `0x` prefix for hexadecimal constants. This means that if a number has 4 hexadecimal digits, it will take 6 bytes to represent that number. ### Scientific notation My language uses the following format for scientific notation: > > [Real base]e[Integer exponent of 10] > > > For example, `700` would be represented as `7e3`, and `699` would be represented as `6.99e3`, because *the base must be between -10 and 10* (non-inclusive). For the purposes of this challenge, the base will always be at least 0, since the inputted number is non-negative. # Output You should return a way of identifying which format is shortest (i.e. 0 for decimal, 1 for hex, 2 for scientific). Alternatively, you may output the smallest representation of the number itself. # Test cases ``` Decimal | Hexadecimal | Scientific | Winner --------------|--------------|-------------------|------------- 0 | 0x0 | 0e0 | Decimal 15 | 0xF | 1.5e1 | Decimal 6999 | 0x1B57 | 6.999e3 | Decimal 7000 | 0x1B58 | 7e3 | Scientific 1000000000000 | 0xE8D4A51000 | 1e12 | Scientific 1000000000001 | 0xE8D4A51001 | 1.000000000001e12 | Hexadecimal 1000000001000 | 0xE8D4A513E8 | 1.000000001e12 | Hexadecimal 1000001000000 | 0xE8D4B45240 | 1.000001e12 | Scientific ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer in the shortest bytes for each language wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes ``` hgรŒยนgD<g>ยนร€รฐรฌร0รœรฐรœg+)Wk ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/I/1wz6Gd6S426XaHdh5uOLzh8JrDjQaH5wAZc9K1NcOz//83NAABCGkAAA "05AB1E โ€“ Try It Online") -1 thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna). `0` for hexadecimal, `1` for decimal, `2` for scientific. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes ``` Dg<ยนร€'.รฌร0รœ'.รœโ€ฆรฟeรฟIhโ€ฆ0xรฟ)รฉยฌ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fJd3m0M7DDep6h9ccbjQ4PAfImPOoYdnh/amH93tmAFkGFYf3ax5eeWjN//@GRsYmBgYGAA "05AB1E โ€“ Try It Online") **Explanation** ``` D # duplicate input, one copy will be used as decimal notation g< # len(input)-1 ยนร€ # push input and rotate left '.รฌร # prepend a dot and rotate right 0รœ'.รœ # remove trailing zeroes and then any trailing dot โ€ฆรฟeรฟ # format scientific notation Ih # input converted to hex โ€ฆ0xรฟ # format hex ) # wrap in a list รฉ # sort by length ยฌ # get the first (shortest) item ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Tแน€ยตแปŠยฌ+โ€˜ DยตLโ€™DL+ร‡,L bโดL+2;ร‡แปคแธข ``` A monadic link returning `1`, `2`, or `3` for hexadecimal, scientific, or decimal respectively. **[Try it online!](https://tio.run/nexus/jelly#ATcAyP//VOG5gMK14buKwqwr4oCYCkTCtUzigJlETCvDhyxMCmLigbRMKzI7w4fhu6ThuKL///83MDAw "Jelly โ€“ TIO Nexus")** or see a [test suite](https://tio.run/nexus/jelly#@x/ycGfDoa0Pd3cdWqP9qGEGl8uhrT6PGma6@Ggfbtfx4Up61LjFR9vI@nD7w91LHu5Y9B/E6H7UMMcjtSIxJTU5MzcxB8gLTs5MzSvJTMtMBnJcYMJzuY7uOdz@qGmNNxBH/v9voKNgaKqjYGZpaamjYG5gAOIbIAFUriES1xBJFir4NS9fNzkxOSMVAA). *I thought this would be shorter, but I can't see it so am posting.* ### How this monstrosity works... ``` Tแน€ยตแปŠยฌ+โ€˜ - Link 1, length of mantissa + "e": list of decimal digits e.g. [7,0,1,0] T - truthy indexes [1, 3 ] แน€ - maximum 3 ยต - monadic chain separation, call that m แปŠ - insignificant? (abs(m)<=1) -- here: 1 for m=1, 0 otherwise 0 ยฌ - logical not i.e. 1 if a "." will be used 1 + - add m 4 โ€˜ - increment always uses an 'e' 5 DยตLโ€™DL+ร‡,L - Link 2, lengths of scientific and decimal notations: non-negative-integer, n D - cast to decimal list ยต - monadic chain separation, call that d L - length of d (number of decimal digits of n) โ€™ - decrement (value of exponent) D - cast to decimal list (exponent's digits) L - length (number of characters in the exponent) ร‡ - call last link (1) as a monad(d) (number of characters in mantissa + "e") L - length of d (number of decimal digits of n) , - pair bโดL+2;ร‡แปคแธข - Main link: non-negative-integer, n โด - literal 16 b - convert n to base 16 L - length (number of hexadecimal digits) +2 - add two (number of characters including the "0x") ร‡ - call the last link (2) as a monad (characters in scientific and decimal) ; - concatenate ([charsInHexadecimal, charsInScientific, charsInDecimal]) แปค - sort indexes by value แธข - head (1-based-index in the above list of (one of) the shortest) ``` [Answer] # JavaScript (ES6), 90 bytes Returns 0 for decimal, 1 for hexadecimal, -1 for scientific. ``` n=>(l=Math.log,D=l(n)/l(10),H=l(n)/l(16)+2,S=n.toExponential().length-1,S<H?-(S<D):+(H<D)) ``` ``` f= n=>(l=Math.log,D=l(n)/l(10),H=l(n)/l(16)+2,S=n.toExponential().length-1,S<H?-(S<D):+(H<D)) console.log( f(0), f(15), f(6999), f(7000), f(1000000000000), f(1000000000001), f(1000000001000), f(1000001000000) ) ``` ## Explanation * `log(n) / log(10)`: base-10 logarithm of `n`; roughly the length of `n` as a decimal. * `log(n) / log(16) + 2`: base-16 logarithm of `n` plus 2; roughly the length of `n` as a hexadecimal plus the prepended `0x`. * `n.toExponential().length - 1`: [`n.toExponential()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) returns a string with `n` in scientific format (e.g. `7e+3`) but we subtract 1 from its length to account for the extraneous `+`. Now that we have the lengths of all 3 representations `D`, `H`, and`S`, we compare: `S<H?-(S<D):+(H<D)` --- # JavaScript (ES6), 97 bytes This one outputs the number in the format with the shortest length. Inspired by [@Shaggy's deleted attempt](https://codegolf.stackexchange.com/a/124193/47097). ``` n=>[n+'','0x'+n.toString(16),n.toExponential().replace('+','')].sort((x,y)=>x.length-y.length)[0] ``` ``` f= n=>[n+'','0x'+n.toString(16),n.toExponential().replace('+','')].sort((x,y)=>x.length-y.length)[0] console.log( f(0), f(15), f(6999), f(7000), f(1000000000000), f(1000000000001), f(1000000001000), f(1000001000000) ) ``` [Answer] # C#, ~~106~~ ~~97~~ ~~96~~ ~~143~~ 132 bytes ``` using System.Linq;n=>new[]{n+"",$"0x{n:X}",(n+"").Insert(1,".").TrimEnd('0','.')+"e"+((n+"").Length-1)}.OrderBy(s=>s.Length).First() ``` Annoyingly in C# the `ulong.ToString` format specifier `e` loses precision on the higher numbers so I've had to do it manually. There's probably a shorter way to do it but this works for now. It also formats it incorrectly for this challenge so I would have to manually strip it's output anyway. If I set a string to the value of `n` as `var s=n+"";` it works out longer because of the explicit return and extra curly braces. It returns the shortest value from the array of each different value where `[0] = decimal, [1] = hexadecimal, [2] = scientific`. Full/Formatted version: ``` using System.Linq; Func<ulong, string> f = n => new[] { n + "", $"0x{n:X}", (n + "").Insert(1, ".").TrimEnd('0', '.') + "e" + ((n + "").Length - 1) }.OrderBy(s => s.Length).First(); ``` The correct way to calculate the scientific output is: ``` (n < 1 ? n + "" : (n + "").Insert(1, ".").TrimEnd('0', '.')) + "e" + ((n + "").Length - 1) ``` However, seeing as `0` is shorter than `0e0` I can remove that special case. [Answer] # Python 2, ~~83~~ 77 bytes Outputs the smallest representation of the number. ``` import re lambda n:min(`n`,hex(n),re.sub('\.?0*e\+0?','e','%.15e'%n),key=len) ``` [**Try it online**](https://tio.run/##VYpBCoMwFET3OUU2ksTakFjSoiBexIVKvxiq35BGWk@fuijYDszivRm3hXHBPA5VE6du7u8dxXK2yFtssxHeHEXmQT7XnrNG1iqF5qRqljHYm0htgCX75QFbNQEKYme3@EA9xNdoJ6C6dN5ioAO36NbAhYiKaEOuRVGQm1I7qJ/8kT5IH9vXkTxNzeWcfwA) **Ungolfed:** ``` import re n=input() d=`n` h=hex(n) s=re.sub('(.)\.?0*e\+0?',r'\1e','%.15e'%n) print min(d,h,s,key=len) ``` The regex removes trailing zeros and the decimal point if necessary, as well as the plus sign and leading zero from the exponent if there is one. [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 35 bytes ``` lโ”ผxl2+โ”ผDRรฎsRlโ‰ฅalโ‰คDlaยฐโ”ผรฎa/รฌ\?โ‰ฅ;+WDโ•คk ``` [Try it online!](https://tio.run/##y8/I/f8/59GUPRU5RtpAyiXo8LrioJxHnUsTgcQSl5zEQxuAwofXJeofXhNjDxS31g53eTR1Sfb//4YGCGAIAA "Ohm โ€“ Try It Online") Outputs 0 for decimal, 1 for hex and 2 for scientific. Explanation: ``` l Implicit input, get length โ”ผ Input again x To hex l Get length 2+ Add 2 because of "0x" โ”ผ Get input again D Duplicate on the stack RรฎsR Remove zeroes at the end (reverse, to int, to string, reverse) l Get length (= length of base) โ‰ฅ Add 1 because to count "e" in the scientific notation a Swap top two values on the stack lโ‰ค Get length - 1 ( = get the exponent of 10 in scientific notation) D Duplicate on the stack l Get length ( = length of the exponent) a Swap. Now on top of the stack we have the exponent again ยฐ 10^exponent โ”ผรฎ Get input for the fourth time a/ Divide input by the 10^exp calculated earlier รฌ\? If this thing is not an integer... โ‰ฅ; ...add one to count the "." + Sum base length ( + "e") + exponent length ( + ".") W Wrap stack in array D Duplicate โ•คk Get index of min value ``` [Answer] # [PHP](https://php.net/), 90 bytes prints 0 for decimal, 1 for hexadecimal and 2 for scientific in case of a tie the highest number will be print ``` <?=array_flip($m=[$l=log10($a=$argn)^0,2+(log($a,16)^0),strlen(($a/10**$l).$l)])[min($m)]; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkaGhkbGJgYKBkzWVvB5SyTSwqSqyMT8vJLNBQybWNVsmxzclPNzTQUEm0BWvRjDPQMdLWAAoChXQMzYB8TZ3ikqKc1DwNoIi@oYGWlkqOph4Qx2pG52bmAY3RjLX@/x8A "PHP โ€“ Try It Online") # [PHP](https://php.net/), 91 bytes prints 0 for decimal, 1 for hexadecimal and 2 for scientific in case of a tie the lowest number will be print ``` <?=array_search(min($m=[$l=log10($a=$argn)^0,2+(log($a,16)^0),strlen(($a/10**$l).$l)]),$m); ``` [Try it online!](https://tio.run/##HcvBCsIwEATQez@j7CFbQ91U6aWu/RBRCVIaIYlh24tfHxcPc5g3TAmlXuYSSgNe1sytc8PpTETt1MxXndiL@O9zW7y8gknvbCDxDSLHz@rIgOf/ER9kh4NRVLJu1I522yUu2agcHXUdROw1d7SQcKr1Bw "PHP โ€“ Try It Online") # [PHP](https://php.net/), 103 bytes prints 0 for decimal, 1 for hexadecimal and 2 for scientific in case of a tie all numbers will be print ``` foreach($m=[$l=log10($a=$argn)^0,2+(log($a,16)^0),strlen(($a/10**$l).$l)]as$k=>$v)echo$v-min($m)?"":$k; ``` [Try it online!](https://tio.run/##HczBDsIgEATQu59B9sBW1KUaD1bshxhNSIOlKQVCTX8fNx7mMC@TyT7Xe5993oEtYzRC6/Z8ISLR1U8qzg5ewmKeEExIoyYJ1vyX@CbV7iUjk9JX7qjWbwkuSpaTpqaBgEfOy64wmwds6AafYDssU@RT7IW4wdzV@gM "PHP โ€“ Try It Online") # [PHP](https://php.net/), 109 bytes Output an array with the shortest solutions ``` for(;!$p=preg_grep("#^.{".++$i."}$#",[$a=$argn,"0x".dechex($a),$a/10**($l=log10($a)^0)."e$l"]););print_r($p); ``` [Try it online!](https://tio.run/##HctBCsIwEADAu79wu4ekLXFjvcXgQ8SWoDEphHZZPBTEt0f0OjCcuZ4vnHmHQdLiwdrjcCIicPW5inJ7ZM8S05QksoJmNG8wXYezgQ820F8x@H/tgTYwj3jPcVMYdI/hYKltFRZf1mTphyNpAxEL3LTTjmVeXpMoZO1q/QI "PHP โ€“ Try It Online") [Answer] # C, 187185 bytes ``` main(){long long N;scanf("%lli",&N);long long D=log10(N)+1,H=log(N)/log(16)+3,F,S,i=1;while(N>i&&!(N%i))i*=10,F++;S=ceil(log10(D-1))+1+D-F+(D-F>1);printf("%i",N?H>D?2*(D>S):1+(H>S):N);} ``` Decompressed: ``` void main(){ long long N; scans("%lli", &N); long long D = log10(N) + 1; // Length of number (decimal) long long H = log(N)/log(16) + 3; // Length of number (hexadecimal) long long F; // Number of 0s at the end of decimal number long long S; // Length of number (scientific notation) long long i; // Counter (more or less) // Get number of zeros at the end of decimal number while(N > i && (N % i) == 0){ i = i * 10; F++; } S = ceil(log10(D - 1)) + 1 + D - F + (D-F>1); // (Power) + (e) + (multiplier + (1 if len(multiplier) > 1)) printf("%i", N!=0 ? (H > D ? 2 * (D > S) : 1 + (H > S)) : 0); // Print the shortest number } ``` Prints 0 for decimal, 1 for hex, 2 for scientific notation. [Answer] # TI-Basic, 130 bytes ``` Input N:If not(N:Goto 0:1+int(log(Nโ†’D:3+int(logBASE(N,16โ†’H:0โ†’F:1โ†’I:While N>I and not(fPart(N/I:10Iโ†’I:F+1โ†’F:End:log(D-1โ†’L:1+D-F+(D-F>1):Ans+int(L)+(0โ‰ fPart(Lโ†’S:(H>D)2(D>S)+(Hโ‰คD)(1+(H>S)โ†’N:Lbl 0:N ``` Or, alternatively: ``` ๏ฟฝN>ฮธN>๏ฟฝ0>1p๏ฟฝ๏ฟฝND>3p๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝBASEN+16H>0F>1I>๏ฟฝNlI@๏ฟฝ๏ฟฝN๏ฟฝI>10II>Fp1F>๏ฟฝ>๏ฟฝDq1L>1pDqFpDqFl1>rp๏ฟฝLp0o๏ฟฝLS>HlD2DlSpHmD1pHlSN>๏ฟฝ0>N ``` Or, in hex: ``` dc4e3eceb84e3ed7303e3170b1c04e04443e3370b1bbbcbbbfbbb642415345104e2b313604483e3004463e3104493ed14e6c4940b8ba4e83493e31304904493e46703104463ed43ec0447131044c3e317044714670104471466c31113e7270b14c117010306fba4c04533e10486c44113210446c53117010486d441110317010486c5311044e3ed6303e4e ``` Prints 0 for decimal, 1 for hex, 2 for scientific notation ]
[Question] [ An [Abjad](https://en.wikipedia.org/wiki/Abjad) is a writing system where each symbol stands for a consonant, and where vowels are omitted. An impure Abjad is an abjad in which there are additionals symbols for vowels, usually diacritics. Write a program or function that, given a string of lowercase text (i.e. nothing but ASCII letters from `a` to `z`, commas and spaces), outputs a corresponding impure abjad English transcript with the following rules: ### Representation of vowels Each vowel (i.e. `a e i o u`) is represented as an accent on the immediately preceding consonant. For instance, assuming the accent representing the vowel `e` is `ฬ`, the word `wet` will be transcribed as `wฬt`. If a vowel is not preceded by a consonant (two or more vowels in a row, or a word starting with a vowel), the symbol `o` is used as a "blank consonant". For example, the word `peep` will be transcribed as `pฬoฬp` ### Accent placement Consonants that have ascenders are unpleasant to read when accentuated. Therefore, for those consonants, the symmetric accent will be displayed below the symbol instead of above. For instance, the letter combination `te` will be written `tฬ–` rather than `ฬt` Those consonants are `b d f h k l t`. ### Accents for vowels We are using Unicode combining characters to display accents on every consonant possible. The combining characters used can be found [here](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). Combining accents are placed directly after the symbol they are to be put on. The accents are presented on arbitrary consonants in this list. * **a** Above accent: U+0x0304, example: `cฬ„` Below accent: U+0x0320, example: `dฬ ` * **e** Above accent: U+0x0301, example: `cฬ` Below accent: U+0x0316, example: `dฬ–` * **i** Above accent: U+0x0307, example: `cฬ‡` Below accent: U+0x0323, example: `dฬฃ` * **o** Above accent: U+0x030c, example: `cฬŒ` Below accent: U+0x032d, example: `dฬญ` * **u** Above accent: U+0x0311, example: `cฬ‘` Below accent: U+0x032e, example: `dฬฎ` Here is the list of all possible characters: ``` bฬ  bฬ– bฬฃ bฬญ bฬฎ cฬ„ cฬ cฬ‡ cฬŒ cฬ‘ dฬ  dฬ– dฬฃ dฬญ dฬฎ fฬ  fฬ– fฬฃ fฬญ fฬฎ gฬ„ gฬ gฬ‡ gฬŒ gฬ‘ hฬ  hฬ– hฬฃ hฬญ hฬฎ jฬ„ jฬ jฬ‡ jฬŒ jฬ‘ kฬ  kฬ– kฬฃ kฬญ kฬฎ lฬ  lฬ– lฬฃ lฬญ lฬฎ mฬ„ mฬ mฬ‡ mฬŒ mฬ‘ nฬ„ nฬ nฬ‡ nฬŒ nฬ‘ pฬ„ pฬ pฬ‡ pฬŒ pฬ‘ qฬ„ qฬ qฬ‡ qฬŒ qฬ‘ rฬ„ rฬ rฬ‡ rฬŒ rฬ‘ sฬ„ sฬ sฬ‡ sฬŒ sฬ‘ tฬ  tฬ– tฬฃ tฬญ tฬฎ vฬ„ vฬ vฬ‡ vฬŒ vฬ‘ wฬ„ wฬ wฬ‡ wฬŒ wฬ‘ xฬ„ xฬ xฬ‡ xฬŒ xฬ‘ yฬ„ yฬ yฬ‡ yฬŒ yฬ‘ zฬ„ zฬ zฬ‡ zฬŒ zฬ‘ oฬ„ oฬ oฬ‡ oฬŒ oฬ‘ ``` ### Test cases * Input: `programming puzzles and code golf` Output: `prฬŒgrฬ„mmฬ‡ng pฬ‘zzlฬ–s oฬ„nd cฬŒdฬ– gฬŒlf` * Input: `the quick brown fox jumps over the lazy dog` Output: `thฬ– qฬ‘oฬ‡ck brฬŒwn fฬญx jฬ‘mps oฬŒvฬr thฬ– lฬ zy dฬญg` * Input: `beautiful` Outpu: `bฬ–oฬ„oฬ‘tฬฃfฬฎl` * Input: `one ring to rule them all, one ring to find them, one ring to bring them all and in the darkness bind them` Output: `oฬŒnฬ rฬ‡ng tฬญ rฬ‘lฬ– thฬ–m oฬ„ll, oฬŒnฬ rฬ‡ng tฬญ fฬฃnd thฬ–m, oฬŒnฬ rฬ‡ng tฬญ brฬ‡ng thฬ–m oฬ„ll oฬ„nd oฬ‡n thฬ– dฬ rknฬss bฬฃnd thฬ–m` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program or function in bytes wins. [Answer] # GNU sed, 168 158 134 105 98 85 bytฬ–s ว’r 75 chฬ rs (bฬญth ศฏnclฬฎแธng +1 fฬญr thฬ– `-r` flฬ g). ``` s/([bdfhklt])([aeiou])/\1\u\2/g;y/aeiouAEIOU/ฬ„ฬฬ‡ฬŒฬ‘ฬ ฬ–ฬฃฬญฬฎ/;s/\B[^ ,a-z]/o&/g ``` ### รณxplฬ nฬ„แนญว’n Wรณ sฬ„vฬ ล แธ…t ศแนกng thฬ– ฤnstrฬ„ศฏnt thฬ t ศฏnpฬ‘t ศฏs ลll แธฝแบƒr-cฬ„ล›. Wรณ ศpcฬ„ล› ลny vฬŒแบƒl fฬญlแธฝแบ‡ng ล ฤnลกnฬ„nt, bฬ–fฬญล• ฤnvฬrแนญng ลll vฬŒแบƒls แนฑ ลcฤ‡nts. ``` #!/bin/sed -rf s/([bdfhklt])([aeiou])/\1\u\2/g # upcase vowel following ascender y/aeiouAEIOU/ฬ„ฬฬ‡ฬŒฬ‘ฬ ฬ–ฬฃฬญฬฎ/ s/\B[^ ,a-z]/o&/g # precede with 'o' if needed ``` Thฬ– ว’dd-แธฝว’แธณng chฬ rฬ„ctฬ–rs ลล• `//` ฤntฬ ศฏแน…ng ลll tฬ–n ลcฤ‡nts (`/ฬ„ฬฬ‡ฬŒฬ‘ฬ ฬ–ฬฃฬญฬฎ/`). รณxpฬ„ndฬ–d ว’ศt แบ‡th spฬ„ฤ‡s, thฬ–y wฬŒศld แธฝว’k แธทkฬ– `/ ฬ„ ฬ ฬ‡ ฬŒ ฬ‘ ฬ  ฬ– ฬฃ ฬญ ฬฎ /`. ### ว’ศtpฬ‘t > > > ``` > pล™grฬ„mแนng pฬ‘zzlฬ–s ลnd ฤdฬ– วงlf > thฬ– qฬ‘ศฏck bล™wn fฬญx jฬ‘mps ว’vฬr thฬ– lฬ zy แธ“g > bฬ–ลศแนญfฬฎl > ว’ล„ แน™ng แนฑ ศ“lฬ– thฬ–m ลll, ว’ล„ แน™ng แนฑ fฬฃnd thฬ–m, ว’ล„ แน™ng แนฑ bแน™ng thฬ–m ลll ลnd ศฏn thฬ– dฬ rkล„ss แธ…nd thฬ–m > > ``` > > [Answer] # CJam, ~~63~~ 62 bytes ``` Qq{_"aeiou"#:I){;___eu='o*\"bdfhklt"&"F<IST""*'-27"?I=730+}&}/ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=Qq%7B_%22aeiou%22%23%3AI)%7B%3B___eu%3D'o*%5C%22bdfhklt%22%26%22F%3CIST%22%22*'-27%22%3FI%3D730%2B%7D%26%7D%2F&input=programming%20puzzles%20and%20code%20golf). ### How it works ``` Qq e# Push an empty string and read from STDIN. { e# For each character in the input: e# Push a copy of the character. "aeiou"# e# Find its index in "aeiou" (-1 for not found). :I) e# Save in I and add 1. { e# If I + 1 != 0: ; e# Discard the character. ___ e# Copy the previous character (or the empty array) three times. eu= e# Convert the last copy to uppercase and check for equality. e# This pushes 1 for non-letters and 0 for letters. 'o* e# Push a string of that many o's. \ e# Swap the last copy with the string of o's. "bdfhklt"& e# Intersect with that string. "F<IST" e# Push that string. "*'-27" e# Push that string. ? e# Select the first iff the intersection is non-empty. I= e# Retrieve the character at index I. 730+ e# Add 730 to its code point. }& e# }/ e# ``` [Answer] # [Rฬtฬฃnฬ„ 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 71 bytฬ–s ``` T`aei\ou`ฬ„ฬฬ‡ฬŒฬ‘ T`ฬ„ฬฬ‡ฬŒฬ‘`ฬ ฬ–ฬฃฬญฬฎ`[bdfhklt]*. +`([^a-z])([ฬ„ฬฬ‡ฬŒฬ‘ฬ ฬ–ฬฃฬญฬฎ]) $1o$2 ``` [Try oฬ‡t oฬŒnlฬฃnฬ!](https://tio.run/##VY6xTsMwEIZ3P8UNHVoVKsGzdEuDbNfn1MTxBcemkA0JiYWFhRmJuX2Se6fQFFDb7e7@77//j5hcUMOwlArdirLkV37hN37nD7E8WyR/8Sd/8473stDGbmqfyvlCzOW0uFPXfTmbFif6BJczMbmhye0wtJGqqJrGhQra3PceO1DBwJoMQkXeCpE2CA/ZrWvQkbYBLD3BfW7aDugRI4yyV/0zGKqE0KhycjZ7ISggxPFvIojZ40g2oLy/gnPJukPcKF2e9e/wZzl2cuEYZlSsA3Yd6H/nDw "Retina 0.8.2 โ€“ Try It Online") ### Oฬxplฬ nฬ„tฬฃoฬŒn ``` T`aei\ou`ฬ„ฬฬ‡ฬŒฬ‘ rฬplฬ cฬs thฬ– chฬ rฬ„ctฬ–rs aeiou wฬ‡th thฬ– cฬŒrrฬspฬŒnsฬ‡ng dฬฃoฬ„crฬ‡tฬฃcs oฬ„bฬญvฬ. T`ฬ„ฬฬ‡ฬŒฬ‘`ฬ ฬ–ฬฃฬญฬฎ`[bdfhklt]+. rฬplฬ cฬs thฬ– dฬฃoฬ„crฬ‡tฬฃcs oฬ„bฬญvฬ wฬ‡th dฬฃoฬ„crฬ‡tฬฃcs bฬ–lฬญw oฬ‡f prฬcฬdฬ–d by oฬŒnฬ oฬŒr sฬvฬrฬ„l chฬ rฬ„ctฬ–rs wฬ‡th oฬ„scฬndฬ–rs. +`([^a-z])([ฬ„ฬฬ‡ฬŒฬ‘ฬ ฬ–ฬฃฬญฬฎ]) oฬ‘ntฬฃl thฬ– oฬ‡npฬ‘t stฬญps chฬ ngฬ‡ng, rฬplฬ cฬ oฬvฬry dฬฃoฬ„crฬ‡tฬฃc nฬŒt prฬcฬdฬ–d by oฬ„ lฬ–ttฬ–r... $1o$2 ...wฬ‡th thฬ– sฬ„mฬ chฬ rฬ„ctฬ–rs bฬฎt wฬ‡th oฬ„n o bฬ–twฬoฬn thฬ–m. ``` [Answer] # Julia, 269 bytes This is really long and can probably be golfed further, but I'm just psyched that I was able to come up with a working solution at all! ``` s->(u=700+[72,69,75,80,85];l=800+[0,-10,3,13,14];R=replace;r(m)=(i=findin("aeiou",m[2])[1];j=m[1]โˆˆ"bdfhklt"?l[i]:u[i];string(m[1],char(j)));t(m)=string("o",char(u[findin("aeiou",m)[1]]));R(R(R(s,r"(?![eiou])[b-z][aeiou]",r),r"(?<=^| )[aeiou]",t),r"(?<=\S)[aeiou]",r)) ``` This creates an unnamed function that accepts a string and returns a string. Ungolfed + explanation: ``` function f(s) # Construct arrays of integers representing the unicode accents # u is for the upper accents and l is for the lower u = 700 + [72,69,75,80,85] l = 800 + [0,-10,3,13,14] # Define a function to accent consonants followed by vowels r(m) = begin # m is the consonant-vowel pair from the regex match i = findin("aeiou", m[2])[1] j = m[1] โˆˆ "bdfhklt" ? l[i] : u[i] string(m[1], char(j)) end # Define a function to accent vowels t(m) = string("o", char(u[findin("aeiou", m)[1]])) # Accent consonants rep1 = replace(s, r"(?![eiou])[b-z][aeiou]", r) # Accent vowels at the start of a string or before a space rep2 = replace(rep1, r"(?<=^| )[aeiou]", t) # Accent remaining unaccented vowels rep3 = replace(rep2, r"(?<=\S)[aeiou]", t) # Return rep3 end ``` Examples: ``` julia> println(f("beautiful")) bฬ–oฬ„oฬ‘tฬฃfฬฎl julia> println(f("programming puzzles and code golf")) prฬŒgrฬ„mmฬ‡ng pฬ‘zzlฬ–s oฬ„nd cฬŒdฬ– gฬŒlf ``` Note that if you look at the raw text in the post, the "t" in the first example is accented correctly but for some reason it doesn't display that way in the rendered markdown, at least for me. ]
[Question] [ disclaimer: I'm not aware of any non-bruteforce solutions A Graeco-Latin square is, for two sets of same length \$n\$, a \$n \times n\$ arrangement of cells, each containing a unique (across the entire square) pair of a element of the first set and a element of the second set, such that all first elements and all second elements of the pairs are unique in their row and column. The most common sets used are, as one could guess, the first \$n\$ letters of the Greek and the Latin alphabets. Here is a picture of a 4x4 Graeco-Latin square:[![enter image description here](https://i.stack.imgur.com/jVIJv.png)](https://i.stack.imgur.com/jVIJv.png) Graeco-Latin squares are as useful as they sound (the [Wikipedia article](https://en.wikipedia.org/wiki/Graeco-Latin_square) mentions "design of experiments, tournament scheduling and constructing magic squares"). Your task is, given a positive integer \$n\$, to generate a \$n\times n\$ Graeco-Latin square. ## Input A positive integer \$n > 2\$; it is guaranteed that a \$n\times n\$ Graeco-Latin square exists (that is, \$n \ne 6\$). ## Output A Graeco-Latin square with side length n as a two-dimensional array, a array of arrays, a flattened array or outputted directly. ## Notes * You do not have to use the Greek and Latin alphabets specifically; for example, outputting pairs of positive integers is allowed as well. * If you choose to use a alphabet that can't be extended arbitrarily, you have to (theoretically; your code doesn't have to finish before the heat death of the universe) support a maximal side length of at least 20. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26~~ ~~23~~ 22 bytes *-3 bytes thanks to Emigna* *-1 byte thanks to Kevin Cruijssen* ``` Lรฃล“.ฮ”IรดDฮถยซDโ‚ฌรญยซฮตโ‚ฌะฝร™gQ}P ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f5/Dio5P1zk3xPLzF5dy2Q6tdHjWtObz20OpzW4GMC3sPz0wPrA34XwuUPrT7vzEA "05AB1E โ€“ Try It Online") [Answer] # [R](https://www.r-project.org/), ~~164~~ 148 bytes -many bytes thanks to Giuseppe. ``` n=scan() `!`=function(x)sd(colSums(2^x)) m=function()matrix(sample(n,n^2,1),n) while(T)T=!(l=m())|!(g=m())|!t(l)|!t(g)|1-all(1:n^2%in%(n*l+g-n)) l g ``` [Try it online!](https://tio.run/##TY3BCoMwEETv@Yp6EHbbeNDeCvkKPYvB1jSwWcUoVWq/PdW2YC/D8GaG6UOjmpHrwbYMszz4WvMOcMZnYLVBQFFF1R5N6K9Qt5SPzkNWTojC/Q2dHno7gdeuoxuw5DKTKUpG8bjblRRYqAhIOUBcIjA/MwB91OCSJpoI0su6jC3HwEc6mYTXHxImdL3lrSy@xqB4iQbOGN4 "R โ€“ Try It Online") Dramatically inefficient - I think it's even worse than other brute force approaches. Even for `n=3`, it will probably time out on TIO. [Here](https://tio.run/##TYzBDoIwDIbvewo5kLQKB/BmwlPImbBMmEu6QjaIEPHZJ6gJXpqv39/@LrRFO7IaTMcwJwevJO8CZ3wGLjYJKOqo3qMJ/Q1UR9fResirCVHYv0crB2cmcE1PRsmhAU68tD2tgJgwisfdrEuJZREBFRYQlwj0Dwagz9S4ZKkkguzCVR4bjoGPdNLpWiJI6NA7w9ux@IJG8RItnDG8AQ) is an alternate version (155 bytes) which works for `n=3` in about 1 second. Works by rejection. The function `m` draws a random matrix of integers between \$1\$ and \$n\$ (without forcing each integer to appear exactly \$n\$ times, or in different columns - this explains the slowness of the code, and is the only thing changed in the faster version). Call this function twice, to get the "latin" and "greek" squares `l` and `g`. Then we check: 1. `all(1:n^2%in%(n*l+g-n))`: are there \$n^2\$ different pairs of values in `l` \$\times\$ `g`? 2. are `l` and `g` latin squares? To check that a matrix is a latin square, use the function `!`. Since point 1. above has been validated, we know that each integer appears \$n\$ times in each of `l` and `g`. Compute the column-wise sums of `2^l`: these sums are all equal if and only if each integer appears once in each column (and the value of the sum is then \$2^{n+1}-2\$). If this is true for both `l` and its transpose `t(l)`, then `l` is a latin square; same for `g`. The function `sd`, which computes the standard deviation, is an easy way to check whether all values of a vector are equal. Note that it doesn't work for the trivial cases \$n=0\$ and \$n=1\$ , which is OK according to the OP. A final note: as often in R code golf, I used the variable `T`, which is initialized as `TRUE`, to gain a few bytes. But this means that when I needed the actual value `TRUE` in the definition of `m` (parameter `replace` in `sample`), I had to use `1` instead of `T`. Similarly, since I am redefining `!` as a function different from negation, I had to use `1-all(...)` instead of `!all(...)`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Nick Kennedy (flat output option allows a byte save of `ลผ"รพ`แบŽแบŽQฦ‘$ฦ‡` \$\rightarrow\$ `Fโ‚ฌp`Zโ‚ฌQฦ‘ฦ‡`) ``` ล’!แน—โธZโ‚ฌQโ‚ฌฦ‘ฦ‡Fโ‚ฌp`Zโ‚ฌQฦ‘ฦ‡แธข ``` **[Try it online!](https://tio.run/##y0rNyan8///oJMWHO6c/atwR9ahpTSAQH5t4rN0NSBckgEVA3Ic7Fv3//98YAA "Jelly โ€“ Try It Online")** (Too slow for `4` in 60s on TIO, but if we replace the Cartesian power, `แน—`, with Combinations, `ล“c`, [it will complete](https://tio.run/##y0rNyan8///oJMWjk5MfNe6IetS0JhCIj0081u4GpAsSwCIg7sMdi/7//28CAA "Jelly โ€“ Try It Online") - although 5 certainly will not!) ### How? ``` ล’!แน—โธZโ‚ฌQโ‚ฌฦ‘ฦ‡Fโ‚ฌp`Zโ‚ฌQฦ‘ฦ‡แธข - Link: integer, n ล’! - all permutations of [1..n] โธ - chain's left argument, n แน— - Cartesian power (that is, all ways to pick n of those permutations, with replacement, not ignoring order) Zโ‚ฌ - transpose each ฦ‡ - filter, keeping those for which: ฦ‘ - invariant under: Qโ‚ฌ - de-duplicate each Fโ‚ฌ - flatten each ` - use this as both arguments of: p - Cartesian product Zโ‚ฌ - transpose each ฦ‡ - filter, keeping those for which: ฦ‘ - invariant under: Q - de-duplicate (i.e. contains all the possible pairs) แธข - head (just one of the Latin-Greaco squares we've found) ``` [Answer] # JavaScript (ES6), ~~159 147~~ 140 bytes Returns a flat array of \$n\times n\$ pairs of non-negative integers. This is a simple brute force search, and therefore very slow. ``` n=>(g=(m,j=0,X=n*n)=>j<n*n?!X--||m.some(([x,y],i)=>(X==x)+(Y==y)>(j/n^i/n&&j%n!=i%n),g(m,j,X),Y=X/n|0,X%=n)?o:g([...m,[X,Y]],j+1):o=m)(o=[]) ``` [Try it online!](https://tio.run/##LY3BboMwEETv/YrNgWDXBlK1p8CS3zCiVIoSQLbCuoK0ApV@O10rPaxGu292xp2/z9NltJ/3hPy13TrcCEvRoxi0w4M2SM8ksXQF62lnkmRdh3TyQytEPeul0ZapMIizVKJCXGQpXEYfNqP93kW0QxuR1H3I00bqCk1GKwdHSPLkj72o0zQddG101TTaqRd59DhI4bFu5Nb5URAgvOZAUCC8sSol4ecJYGwnJp0gmfMWnP7rzpc41mBZF55DzlIA5RCYYvhOjJeQET7mh2d@eOZw/jdyem2VakBBDHFouHia/K1Nb74PTdz6u/0B "JavaScript (Node.js) โ€“ Try It Online") (with prettified output) ### Commented ``` n => ( // n = input g = ( // g is the recursive search function taking: m, // m[] = flattened matrix j = 0, // j = current position in m[] X = n * n // X = counter used to compute the current pair ) => // j < n * n ? // if j is less than nยฒ: !X-- || // abort right away if X is equal to 0; decrement X m.some(([x, y], i) => // for each pair [x, y] at position i in m[]: (X == x) + // yield 1 if X is equal to x OR Y is equal to y (Y == y) // yield 2 if both values are equal // or yield 0 otherwise > // test whether the above result is greater than: ( j / n ^ i / n && // - 1 if i and j are neither on the same row j % n != i % n // nor the same column ), // - 0 otherwise // initialization of some(): g(m, j, X), // do a recursive call with all parameters unchanged Y = X / n | 0, // start with Y = floor(X / n) X %= n // and X = X % n ) ? // end of some(); if it's falsy (or X was equal to 0): o // just return o[] : // else: g( // do a recursive call: [...m, [X, Y]], // append [X, Y] to m[] j + 1 // increment j ) // end of recursive call : // else: o = m // success: update o[] to m[] )(o = []) // initial call to g with m = o = [] ``` [Answer] # [Haskell](https://www.haskell.org/), ~~207 143~~ 233 bytes ``` (p,q)!(a,b)=p/=a&&q/=b e=filter f n|l<-[1..n]=head$0#[(c,k)|c<-l,k<-l]$[]where ((i,j)%p)m|j==n=[[]]|1>0=[q:r|q<-p,all(q!)[m!!a!!j|a<-[0..i-1]],r<-(i,j+1)%e(q!)p$m] (i#p)m|i==n=[[]]|1>0=[r:o|r<-(i,0)%p$m,o<-(i+1)#e(`notElem`r)p$r:m] ``` [Try it online!](https://tio.run/##Vc0xb4QgFAfwuX4KiN4FUuR06GKkW7d26khIj7vDiAIienHhu1tMpy4veS///@/1chmVMfuOPJkxRJLcMPMXJs/n@cJumWKdNqsKWQdcNG3Ja0qdYL2Sj6LKObqTEcd7WxoypiEKLrZeBZW9IKTJgE8e2zgw5hjnQsT6vWJ8bkKc29ITaQyaIeYWQgnhEGXiK0p1WQtBQlsewmuNT@pI@cKKpOr8EPV/MTRT/MtX6WNhyXQsqZordHXT@mGUvYZEhMaK3UrtAANW@q8fgPxz/V7Dp6NPt03hsdB0B0s/bRgUoANv@y8 "Haskell โ€“ Try It Online") OK, I think I finally got it this time. It works fine for n=5, n=6 times out on TIO but I think that might just be because this new algorithm is INCREDIBLY inefficient and basically checks all possibilities until it finds one that works. I'm running n=6 on my laptop now to see if it terminates with some more time. Thanks again to @someone for pointing out the bugs in my previous versions [Answer] # [Haskell](https://www.haskell.org/), 187 bytes ``` import Data.List import Data.List.Split t=transpose c a e h=[s|p<-a,s<-c(a\\[p])(e++[p])h,and[r==nub r|d<-h<$>t s,m<-[d,t d],r<-m]]++[e] f n=head$c[[a,b]|a<-[1..n],b<-[1..n]][]$chunksOf n ``` [Try it online!](https://tio.run/##XcuxbgMhDAbgnafwcEOiwElVVujUMVWHjMSD76AC5SAInO3e/UIqRZG6@P9tfQ7Urn5Zti2mcqsMX8Q0nmJj8f8wnssSWbDhSrmVW/NiBgIPwdi2Fq1INq3mHV0utuB@5w@HZwZJ2dlqTL5PUFenVdDDJ0OTSSvrJINDWbVKiP3Bo/iFbIInN8zWkpxwpe4@xjGjnF4NLQ5zuOdr@@l8Y98YMhhIVL6h1JgZBniDvvQpEsUn@tPH7QE "Haskell โ€“ Try It Online") This is equivalent to a DFS Brute-Force Approach. Times out for `n>3` on TIO, so only `n=1` and `n=3` work correctly. ## Explanation ``` import Data.List -- used for nub, transpose, and difference (\\) import Data.List.Split -- used for chunksOf, shorter than a custom definition using splitAt or take/drop -- we store each pair as [a,b]::[Int] instead of (a,b)::(Int,Int) to save bytes t=transpose -- c :: [[Int]] -> [[Int]] -> Int -> [[[Int]]] -- recursive algorithm that yields a (lazy) list of all possible GL squares using -- a = available pairs left (avoids duplicates) -- e = existing square state, flattened (first `length e` pairs of the square in LTR reading order) -- h = chunksOf n c a e h=[ s| -- where each possible square comes from p<-a, -- some available pair to add s<-c -- each square comes from recursion with (a\\[p]) -- that pair taken from the list of available pairs (e++[p]) -- that pair added to the existing square state h, and[r==nub r| -- such that every "row" contains no duplicates d<-h<$>t s, -- d<-(list of [the rows of the first element of each pair, the rows of the second element of each pair]) m<-[d,t d], -- m<-(rows of the square, columns of the square) r<-m -- row r<-m ] ] ++[e] -- base case: only reached if a==[] or if no valid possibilities exist (n==2 || n==6, not required to be handled) f :: Int -> [[Int]] f n=head$c -- the first valid GL square found from the initial conditions: [[a,b]|a<-[1..n],b<-[1..n]] -- all possible pairs [] -- empty existing GL square $chunksOf n -- given chunksOf function ``` [Answer] ## C#, 520 506 494 484 bytes ``` class P{static void Main(string[]a){int n=int.Parse(a[0]);int[,,]m=new int[n,n,2];int i=n,j,k,p,I,J;R:for(;i-->0;)for(j=n;j-->0;)for(k=2;k-->0;)if((m[i,j,k]=(m[i,j,k]+ 1) % n)!=0)goto Q;Q:for(i=n;i-->0;)for(j=n;j-->0;){for(k=2;k-->0;)for(p=n;p-->0;)if(p!=i&&m[i,j,k]==m[p,j,k]||p!=j&&m[i,j,k]==m[i,p,k])goto R;for(I=i;I<n;I++)for(J=0;J<n;J++)if(I!=i&&J!=j&&m[i,j,0]==m[I,J,0]&&m[i,j,1]==m[I,J,1])goto R;}for(i=n;i-->0;)for(j=n;j-->0;)System.Console.Write(m[i,j,0]+"-"+m[i,j,1]+" ");}} ``` The algorithm of findinf a square is very simple. It is... bruteforce. Yeah, it's stupid, but code golf is not about speed of a program, right? The code before making it shorter: ``` using System; public class Program { static int[,,] Next(int[,,] m, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < 2; k++) { if ((m[i, j, k] = (m[i, j, k] + 1) % n) != 0) { return m; } } } } return m; } static bool Check(int[,,] m, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < 2; k++) { for (int p = 0; p < n; p++) { if (p != i) if (m[i, j, k] == m[p, j, k]) return false; } for (int p = 0; p < n; p++) { if (p != j) if (m[i, j, k] == m[i, p, k]) return false; } } } } for (int i_1 = 0; i_1 < n; i_1++) { for (int j_1 = 0; j_1 < n; j_1++) { int i_2 = i_1; for (int j_2 = j_1 + 1; j_2 < n; j_2++) { if (m[i_1, j_1, 0] == m[i_2, j_2, 0] && m[i_1, j_1, 1] == m[i_2, j_2, 1]) return false; } for (i_2 = i_1 + 1; i_2 < n; i_2++) { for (int j_2 = 0; j_2 < n; j_2++) { if (m[i_1, j_1, 0] == m[i_2, j_2, 0] && m[i_1, j_1, 1] == m[i_2, j_2, 1]) return false; } } } } return true; } public static void Main() { int n = 3; Console.WriteLine(n); int maxi = (int)System.Math.Pow((double)n, (double)n*n*2); int[,,] m = new int[n, n, 2]; Debug(m, n); do { m = Next(m, n); if (m == null) { Console.WriteLine("!"); return; } Console.WriteLine(maxi--); } while (!Check(m, n)); Debug(m, n); } static void Debug(int[,,] m, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(m[i, j, 0] + "-" + m[i, j, 1] + " "); } Console.WriteLine(); } Console.WriteLine(); } } ``` Now, if you want to test it with n=3 you wil have to wait like an hour, so here is another version: ``` public static void Main() { int n = 3; Console.WriteLine(n); int maxi = (int)System.Math.Pow((double)n, (double)n*n*2); int[,,] result = new int[n, n, 2]; Parallel.For(0, n, (I) => { int[,,] m = new int[n, n, 2]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { m[i, j, 0] = I; m[i, j, 1] = I; } while (true) { m = Next(m, n); if (Equals(m, n, I + 1)) { break; } if (Check(m, n)) { Debug(m, n); } } }); } ``` Update: forgot to remove "public". Update: used "System." instead of "using System;"; Also, thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen), used "a" instead of "args". Update: thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner) and [someone](https://codegolf.stackexchange.com/users/36445/someone). [Answer] # [Octave](https://www.gnu.org/software/octave/), 182 bytes Brute force method, TIO keeps timing out and I had to run it a bunch of times to get output for n=3, but theoretically this should be fine. Instead of pairs like (1,2) it outputs a matrix of complex conjugates like 1+2i. This might be stretching the rule a bit, but in my opinion it stll fits the output requirements. There must be a better way to do the two lines under the functino declaration though, but I'm not sure at the moment. ``` function[c]=f(n) c=[0,0] while(numel(c)>length(unique(c))||range([imag(sum(c)),imag(sum(c.')),real(sum(c)),real(sum(c.'))])>0) a=fix(rand(n,n)*n);b=fix(rand(n,n)*n);c=a+1i*b; end end ``` [Try it online!](https://tio.run/##ZY4xDoMwEAR7fyR3BEWOUiLzEeTCmMNYsg@F4ISCvzumCUWKLWZWWu1sV/OmnMfEdvUzd1arERiFVZ2spRafyQcCTpECWGwDsVsnSOyfiYrAfV8MO4LOR@PgleIh6xNul4ILmfDrTjg6ja1EYdToNyhLA3DNWDE2/b@yylzvvuobQTwcyVs5@8D8BQ "Octave โ€“ Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 123 bytes ``` P=Permutations T=Transpose g:=#&@@Select[T[Intersection[x=P[P@Range@#,{#}],T/@x]~Tuples~2,2<->4],DuplicateFreeQ[Join@@#]&]& ``` [Try it online!](https://tio.run/##VY1BS8QwEIXv@RUDhR4kUlx7Wo3MgiiKYHRzGwYJy1ALbbomKSwsu3@9Rvbk6b0HH98bff6W0ed@55fFGitxnHOZU0jKGRd9SPspierWpqoRtzLILpOjl5AlptILSQdjyeKnD51gpY/VibVr8MBnN@8HSeeVXt1fP7SsH8suT1meosgHvU59QKy45nqxsQ@ZOmxZKdWn57ftD/kvhrWBPwwQwUPTwH/FnXoPuElJYlaXoM0wuDgLHW/0rW5PGi4ywCvomJdf "Wolfram Language (Mathematica) โ€“ Try It Online") I use `TwoWayRule` notation `Transpose[...,2<->4]` to swap the 2nd and 4th dimensions of an array; otherwise this is fairly straightforward. Ungolfed: ``` (* get all n-tuples of permutations *) semiLSqs[n_] := Permutations@Range@n // Permutations[#, {n}] &; (* Keep only the Latin squares *) LSqs[n_] := semiLSqs[n] // Intersection[#, Transpose /@ #] &; isGLSq[a_] := Join @@ a // DeleteDuplicates@# == # &; (* Generate Graeco-Latin Squares from all pairs of Latin squares *) GLSqs[n_] := Tuples[LSqs[n], 2] // Transpose[#, 2 <-> 4] & // Select[isGLSq]; ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~271~~ ~~267~~ 241 bytes Brute-force approach: Generate all permutations of the pairs until a Graeco-Latin square is found. Too slow to generate anything larger than `n=3` on TIO. Thanks to [alexz02](https://codegolf.stackexchange.com/users/85686/alexz02) for golfing 26 bytes and to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for golfing 4 bytes. [Try it online!](https://tio.run/##fU/LasMwELzrK/aoRws16YO6@EuMDiaRGwV5JVYrSCntr7uS0wbaQy/L7szOMJPe@Bhxt64zxQU8O@IYQwa/pEisxcHNMEtUvYA80ISvrh4vYQgOBcyRgMAjJEdL4Yl9xCwTxUPZs8w3WTUd@BmmEOQY5Pt5vLNNdW4qGr3G/vazTvuh9EZ3/9E0njQab79NTu0r/6G6X9QwoNb3DfEbYlVPjgtV91UgDLATIhZOheveeorr70/Z1iCRR5Z63B9Jtgrm@UmZy9FZ8/ig4Jr64rZFl950qoa3Sqxf "Python 3 โ€“ Try It Online") ``` from itertools import* def f(n): s=range(n);l=len for r in permutations(product(s,s)): if all([l({x[0]for x in r[i*n:-~i*n]})*l({x[1]for x in r[i*n:-~i*n]})*l({r[j*n+i][0]for j in s})*l({r[j*n+i][1]for j in s})==n**4for i in s]):return r ``` Explanation: ``` from itertools import * # We will be using itertools.permutations and itertools.product def f(n): # Function taking the side length as a parameter s = range(n) # Generate all the numbers from 0 to n-1 l = len # Shortcut to compute size of sets for r in permutations(product(s, s)): # Generate all permutations of all pairs (Cartesian product) of those numbers, for each permutation: if all([l({x[0] for x in r[i * n : (- ~ i) * n]}) # If the first number is unique in row i ... * l({x[1] for x in r[i * n:(- ~ i) * n]}) # ... and the second number is unique in row i ... * l({r[j * n + i][0] for j in s}) # ... and the first number is unique in column i ... * l({r[j * n + i][1] for j in s}) # ... and the second number is unique in column i ... == n ** 4 for i in s]): # ... in all columns i: return r # Return the square ``` ]
[Question] [ Many old [**Game Boy**](https://en.wikipedia.org/wiki/Game_Boy_line) games often required string input from the user. However, there was no keyboard. This was handled by presenting the user with a "keyboard screen" like so: [![Pokemon Ruby Keyboard](https://i.stack.imgur.com/glQuY.png)](https://i.stack.imgur.com/glQuY.png) The 'character pointer' would begin on letter A. The user would navigate to each desired character with the [D-Pad](https://en.wikipedia.org/wiki/D-pad)'s four buttons (`UP`, `DOWN`, `LEFT` and `RIGHT`), then press `BUTTON A` to append it to the final string. *Please note:* * ***The grid wraps around***, so pressing `UP` whilst on letter A would take you to T. * The 'character pointer' stays put after appending a letter # The Challenge The above keyboard has options to change case and is an irregular shape. So, for simplicity, in this challenge we will use the following keyboard (the bottom right is ASCII char 32, a space): ``` 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 . ``` Typing on keyboards like this is extremely slow - so, to make this easier, your task is to write a program which tells the user the ***fastest possible way*** to type a given string. If there are multiple fastest ways, you only need to show one. The output key should be: * `>` for `RIGHT` * `<` for `LEFT` * `^` for `UP` * `v` for `DOWN` * `.` for `BUTTON A` (append current letter to string) For example, when given the string `DENNIS`, the solution would look like this: ``` >>>.>.>>v..>>.>>>v. ``` # Rules / Details * Please remember, the grid wraps around! * You may submit a full program or a function, as long as it takes the initial string and produces a solution string. Whitespace / trailing newlines are irrelevant as long as the output is correct. * You can assume input will only consist of characters typable on the specified keyboard, but it may be empty. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. Standard code-golf loopholes apply. # Test Cases *There are usually multiple solutions of the same length. For each test case, I've included the optimum length, and an example. You don't need to print the length in your answer, just the solution.* ``` FLP.TKC -> 25 steps: <<.<v.<<<v.<<<v.^.<<^.<^. MOYLEX -> 23 steps: <<v.>>v.>>>v.>^^.^.<<^. FEERSUM -> 18 steps: <<.<..<vv.>.>>.<^. MEGO -> 14 steps: <<v.<^.>>.>vv. A CAT -> 17 steps: .<^.>>>v.<<.<<vv. BOB -> 10 steps: >.<vv.>^^. (space) -> 3 steps: <^. (empty) -> 0 steps: (empty) ``` You can view my testcase generator [on repl.it](https://repl.it/E304) - please notify me if there are any bugs. Thank you everyone for the submissions! User ngn is currently the winner with 61 bytes, but if anyone can find a shorter solution, the little green tick can be moved ;) [Answer] ## JavaScript (ES6), 147 bytes ``` s=>s.replace(/./g,c=>(q=p,p="AHOVBIPWCJQXDKRYELSZFMY.GNU ".indexOf(c),"<<<>>>".substring(3,((p>>2)+10-(q>>2))%7)+["","v","vv","^"][p-q&3]+"."),p=0) ``` An interesting behaviour of `substring` is that it exchanges the arguments if the second is less than the first. This means that if I calculate the optimal number of left/right presses as a number between -3 and 3, I can add 3, and take the substring of `<<<>>>` starting at 3 and I will get the correct number of arrows. Meanwhile the down/up presses are simply handled by looking up an array using a bitwise and of the difference in rows with 3; this way is slightly shorter as there are fewer array elements. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 61 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) [`4 7โˆ˜{โˆŠ'.',โจโ‰โ†‘bโดยจยจ'^v' '<>'โŒทยจโจโŠ‚ยจa>bโ†aโŒŠโบ-aโ†โบ|โ†“2-/0,โบโŠคโตโณโจโŽ•a,'.'}`](http://tryapl.org/?a=%u2395io%u21900%20%u22C4%204%207%u2218%7B%u220A%27.%27%2C%u2368%u2349%u2191b%u2374%A8%A8%27%5Ev%27%20%27%3C%3E%27%u2337%A8%u2368%u2282%A8a%3Eb%u2190a%u230A%u237A-a%u2190%u237A%7C%u21932-/0%2C%u237A%u22A4%u2375%u2373%u2368%u2395a%2C%27.%27%7D%20%A8%20%27FLP.TKC%27%20%27MOYLEX%27%20%27FEERSUM%27%20%27MEGO%27%20%27A%20CAT%27%20%27BOB%27%20%27%27&run) assumes `โŽ•IOโ†0` `โŽ•a,'.'` the alphabet followed by a full stop `โตโณโจ` find the argument's chars there as indices 0..26 (`' '` and all others will be 27) `โบโŠค` encode in base 7 (note the left arg `โบ` is bound to `4 7`), get a 2ร—n matrix `0,` prepend zeros to the left `2-/` differences between adjacent columns `โ†“` split the matrix into a pair of vectors `aโ†โบ|` take them modulo 4 and 7 respectively, assign to `a` `bโ†aโŒŠโบ-a` make `b` the smaller of `a` and its modular inverse `'^v' '<>'โŒทยจโจโŠ‚ยจa>b` choose `^` or `v` for the first vector and `<` or `>` for the second, based on where `a` differs from `b` `bโดยจยจ` repeat each of those `b` times `โ‰โ†‘` mix the two vectors into a single matrix and transpose it, get an nร—2 matrix `'.',โจ` append `.`-s on the right `โˆŠ` flatten [Answer] # Ruby, 107 bytes ``` ->s{c=0 s.tr(". ","[\\").bytes{|b|b-=65 print ["","^","^^","v"][c/7-b/7],(d=(c-c=b)%7)>3??>*(7-d):?<*d,?.}} ``` **Ungolfed in test program** ``` f=->s{ #Input in s. c=0 #Set current position of pointer to 0. s.tr(". ","[\\"). #Change . and space to the characters after Z [\ bytes{|b| #For each byte b, b-=65 #subtract 65 so A->0 B->1 etc. print ["","^","^^","v"][c/7-b/7], #Print the necessary string to move vertically. (d=(c-c=b)%7)>3? #Calculate the horizontal difference c-b (mod 7) and set c to b ready for next byte. ?>*(7-d):?<*d, #If d>3 print an appropriate number of >, else an appropriate number of <. ?. #Print . to finish the processing of this byte. } } #call like this and print a newline after each testcase f["FLP.TKC"];puts f["MOYLEX"];puts f["FEERSUM"];puts f["MEGO"];puts f["A CAT"];puts f["BOB"];puts ``` [Answer] **Mathematica, 193 bytes** **Golf** ``` StringJoin@@(StringTake[">>><<<",Mod[#ใ€š2ใ€›,7,-3]]<>StringTake["vv^",Mod[#ใ€š1ใ€›,4,-1]]<>"."&/@Differences[FirstPosition[Partition[ToUpperCase@Alphabet[]~Join~{"."," "},7],#]&/@Characters["A"<>#]])& ``` **Readable** ``` In[1]:= characters = ToUpperCase@Alphabet[]~Join~{".", " "} Out[1]= {"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", ".", " "} In[2]:= keyboard = Partition[characters, 7] Out[2]= {{"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", ".", " "}} In[3]:= characterPosition[char_] := FirstPosition[keyboard, char] In[4]:= xToString[x_] := StringTake[">>><<<", Mod[x, 7, -3]] In[5]:= yToString[y_] := StringTake["vv^", Mod[y, 4, -1]] In[6]:= xyToString[{y_, x_}] := xToString[x] <> yToString[y] <> "." In[7]:= instructionsList[input_] := xyToString /@ Differences[characterPosition /@ Characters["A" <> input]] In[8]:= instructions[input_] := StringJoin @@ instructionsList[input] In[9]:= instructions["DENNIS"] Out[9]= ">>>.>.>>v..>>.>>>v." ``` [Answer] ## Python 2, 298 bytes This is longer than it should be, but... ``` def l(c):i="ABCDEFGHIJKLMNOPQRSTUVWXYZ. ".index(c);return[i%7,i/7] def d(f,t,a=abs): v,h=l(t)[1]-l(f)[1],l(t)[0]-l(f)[0] if a(h)>3:h=h-7*h/a(h) if a(v)>2:v=v-4*v/a(v) return'^v'[v>0]*a(v)+'<>'[h>0]*a(h) s="A"+input() print''.join([d(p[0],p[1])+'.'for p in[s[n:n+2]for n in range(len(s))][:-1]]) ``` Any help would be greatly appreciated! Takes input in quotation marks. `l` returns the location of a character in the keyboard. The two `if` statements in the middle of `d` are for checking if it would be optimal to 'wrap' around the keyboard. The input, `s` has `"A"` prepended to it because the initial position of the cursor is `A`. We loop through the string in pairs, discarding the last one (which is not a pair: `[:-1]`), finding the minimum distance between the two halves of the pair. Thanks to Flp.Tkc for telling me that I can do `a=abs` instead of saying `abs` every time! [Answer] # Java 8, 1045 bytes ## Golf ``` staticchar[][]a={{'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','.',''}};staticintm=Integer.MAX_VALUE;staticStringn="";staticboolean[][]c(boolean[][]a){boolean[][]r=newboolean[4][];for(inti=0;i<4;i)r[i]=a[i].clone();returnr;}staticvoidg(inti,intj,boolean[][]v,chard,Stringp){v[i][j]=true;if(a[i][j]==d&&p.length()<m){m=p.length();n=p;}if(i-1<0){if(!v[3][j])g(3,j,c(v),d,p"^");}elseif(!v[i-1][j])g(i-1,j,c(v),d,p"^");if(i1>3){if(!v[0][j])g(0,j,c(v),d,p"v");}elseif(!v[i1][j])g(i1,j,c(v),d,p"v");if(j-1<0){if(!v[i][6])g(i,6,c(v),d,p"<");}elseif(!v[i][j-1])g(i,j-1,c(v),d,p"<");if(j1>6){if(!v[i][0])g(i,0,c(v),d,p">");}elseif(!v[i][j1])g(i,j1,c(v),d,p">");}publicstaticvoidmain(String[]args){boolean[][]v=newboolean[4][7];Scannerx=newScanner(System.in);Strings=x.next();Stringpath="";intp=0;intq=0;for(inti=0;i<s.length();i){chart=s.charAt(i);g(p,q,c(v),t,"");path=n".";n="";m=Integer.MAX_VALUE;for(intj=0;j<4;j){for(intk=0;k<7;k){if(a[j][k]==t){p=j;q=k;}}}}System.out.println(path);} ``` ## Readable ``` static char[][] a = { {'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','.',' '} }; static int m = Integer.MAX_VALUE; static String n=""; static boolean[][] c(boolean[][] a){ boolean [][] r = new boolean[4][]; for(int i = 0; i < 4; i++) r[i] = a[i].clone(); return r; } static void g(int i, int j,boolean[][] v,char d,String p) { v[i][j] = true; if (a[i][j]==d && p.length()<m){ m=p.length(); n=p; } if (i-1<0) { if(!v[3][j]) g(3, j, c(v), d, p + "^"); } else if (!v[i-1][j]) g(i-1, j, c(v), d, p + "^"); if (i+1>3) { if(!v[0][j]) g(0, j, c(v), d, p + "v"); } else if(!v[i+1][j]) g(i+1, j, c(v), d, p + "v"); if (j-1<0) { if(!v[i][6]) g(i, 6, c(v), d, p + "<"); } else if (!v[i][j-1]) g(i, j-1, c(v), d, p + "<"); if (j+1>6) { if (!v[i][0]) g(i, 0, c(v), d, p + ">"); } else if (!v[i][j+1]) g(i, j+1, c(v), d, p + ">"); } public static void main(String[] args) { boolean[][] v = new boolean[4][7]; Scanner x = new Scanner(System.in); String s = x.next(); String path=""; int p=0; int q=0; for(int i=0;i<s.length();i++){ char t=s.charAt(i); g(p,q,c(v),t,""); path+=n+"."; n=""; m=Integer.MAX_VALUE; for(int j=0;j<4;j++){ for(int k=0;k<7;k++){ if(a[j][k]==t) { p=j; q=k; } } } } System.out.println(path); } ``` ## Explanation The solution is a direct approach: poorly optimized brute force. The method `g(...)` is a basic depth first search going through each permutation (up, down, left, right). With some slight modifications in ordering for the test cases I get the output: ``` <<.v<.v<<<.v<<<.^.^<<.^<. v<<.v>>.v>>>.^^>.^.^<<. <<.<..^^<.>.>>.^<. v<<.^<.>>.^^>. .^<.v>>>.<<.^^<<. >.^^<.^^>. ^<. // new line for the last ``` ]
[Question] [ Who will rule the realm? You are given a family tree which contains: name, sex, date of birth, date of death and a list of heirs, for each family member. You may use any convenient (nested) list format to represent the tree. The following examples will use JSON. Determine who will rule the realm and in which order. The succession rules are the following: 1. When a king dies the realm goes to its oldest legit male child. 2. If there is none it passes to the oldest legit female child. 3. In case the king had no heirs the realm goes to the oldest legit king's brother 4. If there are no male brothers the realm will go to the oldest legit king's sister 5. If all legit relatives are dead the realm goes to the closest bastard, applying the above rules 6. If no legit nor bastard relatives are alive print `LINE EXTINCT` We define a legit son as one who has the same "house" name as its father. Examples: Input `{}` Output `LINE EXTINCT` Input ``` { "name" : "Maegor", "house" : "Targaryen", "birth" : 12, "death" : 48, "sex" : "male", "heirs" : [] } ``` Output `12-48: Maegor, LINE EXTINCT` Input ``` { "name" : "Jaehaerys", "house" : "Targaryen", "birth" : 34, "death" : 103, "sex" : "male", "heirs" : [ { "name" : "Viserys", "house" : "Targaryen", "birth" : 77, "death" : 129, "sex" : "male", "heirs" : [] } ] } ``` Output `34-103: Jaehaerys, 103-129: Viserys, LINE EXTINCT` Input ``` { "name" : "Eddard", "house" : "Stark", "birth" : 263, "death" : 299, "sex" : "male", "heirs" : [ { "name" : "Robb", "house" : "Stark", "birth" : 283, "death" : 300, "sex" : "male", "heirs" : [] }, { "name" : "Jon", "house" : "Snow", "birth" : 284, "death" : 384, "sex" : "male", "heirs" : [] }, { "name" : "Sansa", "house" : "Stark", "birth" : 286, "death" : 320, "sex" : "female", "heirs" : [] }, { "name" : "Arya", "house" : "Stark", "birth" : 289, "death" : 350, "sex" : "female", "heirs" : [] }, { "name" : "Brann", "house" : "Stark", "birth" : 290, "death" : 315, "sex" : "male", "heirs" : [] }, { "name" : "Rickon", "house" : "Stark", "birth" : 295, "death" : 319, "sex" : "male", "heirs" : [] } ] } ``` Output: `263-299: Eddard, 299-300: Robb, 300-315: Brann, 315-319: Rickon, 319-320: Sansa, 320-350: Arya, 350-384: Jon, LINE EXTINCT` Note that the output can be formatted in any way you wish, its only requirements is that it contains the time of reign and the name of the reigning king during those years. I've used kings from the ASOIAF as demonstrative example, however the code needs to be valid for all input. You may assume that no twins will be born. This is a code golf challenge, so the shortest code in bytes wins Good luck!!! [Answer] ## PHP, 664 bytes I'm not sure if 664 bytes fit for code golfing, but here it is: ``` $k=json_decode($argv[1]);$s=[];$f='array_shift';$r='heirs';$e='death';$y='year';function s ($k,&$e){uasort($e,function($a,$b)use($k){$c=$a->{$h='house'};$d=$b->$h;$e=$k->$h;if($c==$e &&$d!=$e)return-1;elseif($c!=$e&&$d==$e)return 1;elseif($a->sex<$b->sex)return 1;elseif($a ->sex>$b->sex)return -1;else return$a->birth-$b->birth;});}function d(&$e,$y){foreach($e as$i=>$h)if($h->death<=$y)unset($e[$i]);};($x=(array)$k)&&$k->$y=$k->birth;$l=[];while($x) {$l[]=$k;$z=$k->$e;s($k,$k->$r);d($k->$r,$k->$e);if($k->$r){$s=$k->$r;$k=$f($s);}else{s($k ,$s);d($s,$k->$e);$k=$f($s);}if(!$k)break;$k->$y=$z;}foreach($l as$k) echo"{$k->$y}-{$k->$e}: $k->name, ";echo"LINE EXTINCT"; ``` It receives the JSON string input as the first command line argument. The algorithm follows the steps described in the challenge (starts from the king, then sorts the heirs and then the siblings to find the next king). [Demo](http://ideone.com/YxXisC) [Answer] # [jq](https://stedolan.github.io/jq/), ~~429..410~~ 392bytes ``` def s(x;y):sort_by(.sex,-.birth)[]|select(.death>x.death and(.house==x.house|y));def i:index([[.[1:][]|select(.!=[])][0]]);def b(z;x;y):[.[i+z][:z+length-1]|s(x;y)];def h(x;y):[x.heirs|s(x;y)];[[],[],[],[],sort_by(-.birth)?]|until(i|not;.[i][-1]as$r|[.[0]+[$r+{t:(.[0][-1].death//$r.birth)}],h($r;.),h($r;not),b(0;$r;.),b(i%2;$r;not)])|[.[0][]|"\(.t)-\(.death):\(.name)"]+["LINE EXTINCT"]|.[] ``` [Try it online!](https://tio.run/##vZLRbtMwFIbveYoQFclW0yxt6UQSFQSoF0NoF9sukLwj5CweMesc4XgibdNnL47TtUlGClIHViTb5z8@5//sfP@x2cTs1spQHi5wkKVSfY0WyM1Y7gzciEuVYAJFxubsRiE3ZlQlb/NqtqiIkZukDxmbTvNqUSwwDsuCPOAiZjkixCXDAGo1Xk4JYCAeQJUZoWVomutM3l8CCZb9ORPfVDIY6lPGGJjMpDJJdC/GZbbTCAFn9z0iPLp/B8WDUHyOeCFSFeoeQHRhmvVkoTt60Cc92V@pAJWbUqroTk56cltiDU6CejJ0cTXrOtiJkBdWsQjxV6NwGwdcVdXA9jVyFR5cb68NB3ol6D3Dtu5pfz47n1mzL1dn5x@vbChcApsNWb2wtsMuM20rsOxZHFMZ285eMjdttEtF5V1dMoZLaXQ6roWNARP2/VpYv7Ipc0/nrNGgvN5SIbtYOVaN3d7hRRpFteN/8Njy@WbcknZex57Xkjr8tjxDQ1g7BxhqEJ9S0SrZgBDpzydyDeJ1W9tTPNUOYBzPcUlFRg@R/OY5Giin3Sgjrwvllv0TmPdycRSL380yeUaWv4P5IKkQR9D4XjfNcPJff7ILfnOXHsUyOcDiPw/L/lkqYQ2/AA) **Explanation:** ``` def s(x;y):sort_by(.sex,-.birth)[] #Function: sorts by sex lexicographically, then by birth date in descending order [youngest female -> oldest male] |select( and selects those who .death > x.death did not die before the previous ruler and (.house == x.house|y) and have the same house (if y := not, selects those with a different house) ); def i:index([[.[1:][]|select(.!=[])][0]]); #Function: returns index of the first not-empty array (ignoring first array) def b(z;x;y):[.[i+z][:z+length-1]|s(x;y)]; #Function: drops the last z (0 or 1) elements of the (i+z)th array and applies s on the resulting array def h(x;y):[x.heirs|s(x;y)]; #Function: takes the heirs of x and applies s [ An array containing five bins: [], 0. Result [], 1. Heirs from same house [], 2. Heirs from another house [], 3. Siblings from same house sort_by(-.birth)? 4. Siblings from another house (initial: sorted input (The ? is necessary for empty inputs)) |until( Until i|not there is no such index i ; .[i][-1]as$r set the last element of the ith array as the current ruler |[ Update the array: .[0]+[$r+{t:(.[0][-1].death//$r.birth)}], Add the current ruler + new attribute (the beginning time of reign) to the result array h($r;.), Heirs from same house h($r;not), Heirs from another house b(0;$r;.), Siblings from same house b(i%2;$r;not) If the ruler is heir from the same house as the previous one, store the heirs from a different house here else siblings from a different house ] ) | [ .[0][] Takes the result array |"\(.t)-\(.death):\(.name)" Writes time of reign and ruler ] +["LINE EXTINCT"] Writes "LINE EXTINCT" |.[] Prints on seperated lines ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~294~~ ~~248~~ ~~244~~ 245 bytes ``` t=>{for(s(t),o(t.b,t);t;)o(t.d,t=n(t,0))} s=(r,p)=>r.c.sort((a,b)=>a.s-b.s||a.b-b.b,r.g=p?(r.u=p.h!=r.h,p.c):[]).map(h=>s(h,r)) n=(k,b,j)=>[...k.c,...k.g].map(h=>j=j||h.u==b&h.d>k.d&&h)&&j||b?j:n(k,1) o=(f,h)=>alert(h?[f,h.d,h.n]:'LINE EXTINCT') ``` [Try it online!](https://tio.run/##jdJBT9swFAfwez6Fl0OwNfOUAt2WVk61TT0wTRyAw6QqEnaS1iSdHdkeMLX97J0dGi4rG77k/6K8n96z0vAHbktz37lTpat6z9e1ceyJ5aVWVq9rWOsVfnp/d0eiJds7lm@W2mCLHaEaOxDUkambkpAr6pjCjqaE7CLLsKEdYbmBEqw2DmNOha852FMBdrvlIHwQ1MCKdTNs4BfrQL5jBiTtoCSTRUHgJ@@wZLnFkhpCIsVwSwVtvLMAgBZK2j9WxfBlw5rtVnqLiURClbdQJYkkSeJfi1kzUR4YkUgzvKQyjBP2xXK28KXfQIIqJiffL6/maP7j9vLq6@0J2T9wg5ypa8TQJkL@xCqeoHheVdxUMUWxDOWN46YNlfDV2Ydzn6qQsswn61NKn5tLnxd9DGdz0K61EL4bHdU@Ddp5mr5oB6lAO/qX9k2rHhs0pR9DfdAuBq1P/9duuLK87z8228dBOxtmG/1T@2x@89c3zQZt/Dbti@FKvTZblg7aaPymTa/vy7a/uqPa@EXLjmg9VkS7aInD30Km@z8 "JavaScript (Node.js) โ€“ Try It Online") -82 bytes thanks to Shaggy! ]
[Question] [ For the purpose of this challenge, we say that a regex pattern matches a string if the *entire* string is matched by the pattern, not just a substring. Given two regex patternsโ€€*A*โ€€andโ€€*B*, we say thatโ€€*A*โ€€is **more specialized** thanโ€€*B*โ€€ if every string that is matched byโ€€*A*โ€€is also matched byโ€€*B*โ€€ but not the other way around. We say thatโ€€*A*โ€€is **equivalent** toโ€€*B*โ€€if both patterns match exactly the same set of strings. If neither pattern is more specialized than the other nor are they equivalent, we say thatโ€€*A*โ€€andโ€€*B*โ€€are **incomparable**. For example, the pattern `Hello, .*!` is more specialized than `.*, .*!`; the patterns `(Hello|Goodbye), World!` and `Hello, World!|Goodbye, World!` are equivalent; and the patterns `Hello, .*!` and `.*, World!` are incomparable. The relation "more specialized than" defines a strict partial order on the set of regex patterns. In particular, for all patternsโ€€*A*โ€€andโ€€*B*, exactly one of the following is true: * *A*โ€€is more specialized thanโ€€*B*โ€€(*A* < *B*). * *B*โ€€is more specialized thanโ€€*A*โ€€(*A* > *B*). * *A*โ€€andโ€€*B*โ€€are equivalent (*A* = *B*). * *A*โ€€andโ€€*B*โ€€are incomparable (*A* โˆฅ *B*). Whenโ€€*A*โ€€andโ€€*B*โ€€are incomparable, we can further distinguish between two cases: * *A*โ€€andโ€€*B*โ€€are **disjoint** (*A* โˆฅ *B*), meaning that no string is matched by both of them. * *A*โ€€andโ€€*B*โ€€are **intersecting** (*A* โ‰ฌ *B*), meaning that some strings are matched by both. ## Challenge Write a **program** or a **function** that takes a pair of regex patterns and compares them using the above order. That is, if the two patterns areโ€€*A*โ€€andโ€€*B*, the program should determine whetherโ€€*A* < *B*,โ€€*A* > *B*, *A* = *B*โ€€orโ€€*A* โˆฅ *B*. **ร—92% Bonus**โ€€An additional bonus is given if, when the patterns are incomparable, the program determines whether they're intersecting or disjoint. ## Input and Output The program should accept two regex patterns, as strings, in the flavor defined below. You may read the input through **STDIN**, the **command line**, as **function arguments** or an **equivalent method**. You may assume that the patterns are valid. The program should produce one of exactly four distinct outputs (or five distinct outputs if you're going for the above bonus,) depending on the result of the comparison (the exact outputs are up to you.) You may write the output to **STDOUT**, return it as the **function's result** or use an **equivalent method**. ## Regex Flavor You may support whatever regex features you like, but you *must* support the following ones: * **Alternation** with `|`. * **Quantification** with `*`. * **Grouping** with `(` and `)`. * Matching **any character** (possibly excluding newlines) with `.`. * **(Optional: ร—80% Bonus)**โ€€Matching simple and negated **character classes** with `[โ€ฆ]` and `[^โ€ฆ]`, respectively. You don't have to support any predefined character classes (e.g. `[:digit:]`) but you should support character ranges. * Character **escaping** with `\`. It should at least be possible to esacpe special characters (i.e. `|*().[^-]\`) and preferably also common special characters in other flavors (e.g. `{}`), but the behavior when escaping nonspecial characters is unspecified. In particular, you don't have to support special escape sequences such as `\n` for a newline and the like. A possible implementation is simply to take the character following the `\` as a literal. You may assume the existance of an input character that cannot be matched by any literal (i.e. it can only be matched by `.` and negated character classes.) ## Additional Rules * You may use regex libraries or builtin regex functionality only for the purpose of string matching and replacement. * You may ignore any locale-related issues, such as collation rules. * To state the obvious: your program must terminate. It should execute in a reasonable amount of time given typical patterns (definitely no more than an hour, preferably a lot less.) ## Scoring This is code-golf. Your score is the **product** of the **code size**, in bytes, and any of the **bonuses**. The **lowest score** wins. ## Test Cases The format of the test cases is as follows: ``` <Test ID> <Pattern A> <Ordering> <Pattern B> <Test ID> <Pattern A> <Ordering> <Pattern B> ... ``` Where `<Test ID>` is an identifier for the test case, `<Pattern A>` and `<Pattern B>` are the regex patterns and `<Ordering>` is the ordering between them, and is one of: * `<`: `<Pattern A>` is more specialized than `<Pattern B>`. * `>`: `<Pattern B>` is more specialized than `<Pattern A>`. * `=`: The patterns are equivalent. * `|`: The patterns are incomparable and disjoint. * `X`: The patterns are incomparable and intersecting. The special value `<empty pattern>` stands for the empty pattern. **A. Basic patterns** ``` A1 Hello = Hello A2 Hello | World A3 Hell(|o) = Hell|Hello A4 x < . A5 . > x A6 \. < . A7 x|y = y|x A8 x|y X y|z A9 x|y | a|b A10 x|y|z > x|z A11 x. X .x A12 .* > <empty pattern> A13 ()* = <empty pattern> A14 x* > xxxx A15 x* > x|xx|xxxx* A16 x* = |x|xx|xxxx* A17 x* < .* A19 (.|..)* = .* A20 (...)* X (..)* A21 ...* X (..)* A22 ...* < ..* A23 (...)* | Four A24 a* X a.* A25 a* | b.* A26 x* = (x|)* A27 (((.*)*)*)* = .* ``` **B. Complex patterns** ``` B1 aaa* = aa*a B2 aa*a = a*aa B3 a* X aaax||a|aa|aaa B4 aaaaaaaaaaaaaa* X (aa)*|(aaa)* B5 a*b* < (a|b)* B6 ((a|b)(a|b))* > (ab|ba)* B7 ((a|b)(a|b))* = (aa|ab|ba|bb)* B8 .*.* = .* B9 (x*y*z*)* = (x|y|z)* B10 (...|.....)* > .........* B11 (...|.....)* = |...|.....|......|.........* B12 (...|......)* < |...|.......* B13 (...|....|.....)* = |....* B14 (...|x...............|x..x)* > (...|x..............|x..x)* B15 (...|x...............|x..x)* < (..|...|x..............|x..x)* B16 (____)*_x__(____)* | (____)*x___(____)* B17 (____)*_x__(____)* X (_____)*x_____(_____)* B18 (____)*_x__(____)* | (______)*x______(______)* B19 (____)*_x__(____)* < _*x__* ``` **C. Basic patterns with character classes** ``` C1 [x] = x C2 [xy] | xy C3 [abc] = a|b|c C4 [abc] > [ab] C5 [abc] < [abcd] C6 [ab] X [bc] C7 [ab] | [cd] C8 [abc]* > (a|b)* C9 [^xyz] > a C10 [^xyz] | x C11 [^xyz] | [xyz] C12 [^xyz] X [wxyz] C13 [^xyz] X [^abc] C14 [0-9] = [0123456789] C15 [a-z] > [b-y] C16 [a-z] = a|[b-y]|z C17 [^0-9]* > Hello, World! C18 [^0-9]* | 123 C19 [^abc] < . C20 [^abc]* X . C21 [^a]|a = . C22 [^abcd]|[a-c]|d = . C23 [^a]* X b[^c]* C24 [^a]* | a[^c]* ``` **D. Complex patterns with character classes** ``` D1 http://[^/][^/]*/.* > http://(www\.|)google\.com/.* D2 http://[A-Za-z][A-Za-z]*\.wikipedia\.org/ X (http://|)en\.wikipedia\.org/(|wiki(|/.*)) D3 [A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z]) X [[emailย protected]](/cdn-cgi/l/email-protection) D4 [A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z]) > email@address\.com D5 [A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z]) > [A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@gmail\.com D6 JohnDoe@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z]) < [A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z]) D7 [A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@gmail\.com X JohnDoe@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z]) D8 [^, a-z][^,]*(|(, [^, ][^,]*)* and [^, ][^,]*)\. > One, two and three\. D9 [^, a-z][^,]*(|(, [^, ][^,]*)* and [^, ][^,]*)\. | one, two and three\. D10 [^, a-z][^,]*(|(, [^, ][^,]*)* and [^, ][^,]*)\. | One, two\. D11 [^, a-z][^,]*(|(, [^, ][^,]*)* and [^, ][^,]*)\. < (.*(,|))* D12 [A-Z][^,]*(|(, [a-z][^,]*)* & [a-z][^,]*)\. < [^, a-z][^,]*(|(, [^, ][^,]*)* (and|et|[&+]) [^, ][^,]*)\. ``` ## Test Program The following snippet can be used to compare regex patterns: ``` <style>#main {display: none;}#main[loaded] {display: inline;}.pattern_container {position: relative;}.pattern_underlay, .pattern {font: 12pt courier, monospace;overflow: hidden;white-space: pre;padding: 7px;box-sizing: border-box;}.pattern_underlay {background-color: #dddddd;color: #707070;border-radius: 4px;box-shadow: 0.5px 0.5px 2.5px #aaaaaa;}.pattern_underlay[error] {background-color: #ffccbb;}.pattern {position: absolute;left: 0px;top: 0px;background: none;border: none;width: 100%;height: 100%;resize: none;white-space: normal;}#ordering {min-width: 28pt;text-align: center;font-size: 16pt;}#status {padding: 5px;background-color: #fffdce;box-shadow: 1.5px 1.5px 3.5px #aaaaaa;font-size: 10pt;white-space: pre;display: none;}#status[error] {display: inline;background-color: #ffe8df;}#status[loading] {display: inline;}.inline_code {background-color: #dddddd;font: 12pt courier, monospace;padding: 2px;}.placeholder {visibility: hidden;}.error_text {background-color: #fffcb7};</style><span id="main"><table><tr><td><div class="pattern_container"><div class="pattern_underlay" id="pattern1_underlay"></div><textarea class="pattern" id="pattern1" oninput="compare()">Hello, .*!</textarea></div></td><td id="ordering"></td><td><div class="pattern_container"><div class="pattern_underlay" id="pattern2_underlay"></div><textarea class="pattern" id="pattern2" oninput="compare()">.*, .*!</textarea></div></td></tr></table><br></span><span id="status" loading>Loading...</span><script type='text/javascript'>var Module = {setStatus: function (status) {document.getElementById("status").innerHTML = status;if (status == "") {compare();document.getElementById("status").removeAttribute("loading");document.getElementById("main").setAttribute("loaded", 1);}}};function underlay_chars(str) {if (/^\n*$/.exec(str))return str.split("\n").map(function () { return '<span class="placeholder"> \n</span>'; });if (str.indexOf("\n") >= 0)str = str.replace(/\s*$/gm, function (m) { return m.replace(/[^\n]/g, "\0"); });return (str + "\n").split("").map(function (c) {if (c == "\0") return "ยท";else return '<span class="placeholder">' + c + '</span>';});}function underlay_str(str) {return underlay_chars(str).join("");}function str_to_array32(str) {a = [];for (c of str) {n = c.charCodeAt(0);a.push(n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, n >> 24);}a.push(0, 0, 0, 0);return a;}function compare() {try {for (e of ["pattern1_underlay", "pattern2_underlay", "status"])document.getElementById(e).removeAttribute("error");for (e of ["pattern1", "pattern2"])document.getElementById(e + "_underlay").innerHTML = underlay_str(document.getElementById(e).value);c = Module.ccall("regex_compare", "number", ["array", "array"], [str_to_array32(document.getElementById("pattern1").value),str_to_array32(document.getElementById("pattern2").value)]);if (c >= 0)document.getElementById("ordering").innerHTML = "โˆฅโ‰ฌ<>="[c];else {i = Module.ccall("regex_error_index", "number", [], []);l = Module.ccall("regex_error_length", "number", [], []);e = document.getElementById("pattern" + -c + "_underlay");t = underlay_chars(document.getElementById("pattern" + -c).value);e.setAttribute("error", 1);e.innerHTML =t.slice(0, i).join("") +'<span class="error_text">' + t.slice(i, i + l).join("") + "</span>" +t.slice(i + l).join("");e.setAttribute("error", 1);throw "Pattern error: " + Module.ccall("regex_error", "string", [], []).replace(/`(.*?)'/g, '<span class="inline_code">$1</span>');}} catch (e) {document.getElementById("ordering").innerHTML = "??";document.getElementById("status").innerHTML = e;document.getElementById("status").setAttribute("error", 1);}}</script><script async type="text/javascript" src="https://gist.githack.com/anonymous/91f27d6746566c7b4e4c/raw/c563bf84a01c3a1c6e5f021369a3e730a2e74a1a/rpo.js"></script> ``` [Answer] # Python 2, 522 bytes \* .92 = 480.24 ~~537.28~~ **Edit 2**: -60 bytes **Edit**: Added explanation. Defined is the function `f` which takes the two pattern strings as arguments and returns `'<'`, `'='`, `'>'`, `'|'`, or `'X'`. Less than one minute is needed to process all test cases. The code consists of the following, but with `\r`, `\n` `\t`, and hex escapes (but not `\0`) replaced with their actual byte values. ``` #encoding=Latin exec"""x\xda]RMo\xdb0\x0c\xbd\xe7Wx\'K\x96\x92\xc5mOR\xb8\xdf1@%|\x98%X\x80a\x19\x96\x02\x03n\xf2\xdfG:i;\xec$\x92z|\x8f_\x1b\x84%m~\xca\xbe\x1c\x0e\xbd\x0fU\x10Agi\x0e\x87\xea\n\x1f\xf9n{=\xea\0\x93\x08\xd2\xaez\xd0\x99\xcc,m\x07g\xbb\x80s\x9b\x08\xee\x8cRo"\xf3\x8bHy!-\x95\xd7\xa9\x8aS\xb50O5\xc3&\xb68\x0b\xe7\xb1\x19t\x92\x8a\x1d\xaf]\xc2f\x94\x92\x111T\xf3\xf1j\xba\x1b\x081r\xa2\x97\xea\xa5\x11\x03\x9bI\xca\xe6\xed\xe7\xab\xbd\xde`\xb6\x8b"\xd1\xc5\xf7\xd7?^l\xa7\xaeKK\xd7i\x91\x92\x8b\xaaE\x16\x8e\x9c\x12#3\x86\xe0"\xc6\xc9\x15\xfd\x86\xae\\\xde\xcc^\xa7\x94;,\xea\x94t\x08\x84\xa6J\x82\xee%\xb1\xe8\xacW\xb9\xb3\x14f\xd9\x84\xeb\x89\xe1\x8b\xd5\xa3r\xeb\xbf\x81D\rS\xf5\x8b/\xd7e\xaao\xf0\xeb\xf2\xbbv\xdd\xf1\x15\x1f\x93\xe4Aq\xff\x19\xc6\x98\x8b\xa8E\xad\xb2\xaae-m\x843\xc5\xd7!\x8e\xbe\xca.\x1a4\x01\xe8E;@-\xe4\xad9\xd5\xa7\x10\xa7\x9eg\xcea\x10\x83\x0e\xd2\r\x973\xb2o\xb8\xd7\x06\xc2\x0f\xa8\xdf\xdfk\x1b\x15\xb4v\x84H\xc9\xad]\xc1\x83C;\x03m\xc3\x16p\x1f\xe3\x1d\xbf\xa4\xe2\xbe\x8d\x1eX)\x1e\t\x9dv\xf3\xa9\xcd\xe8xGU\x9e\x0b\t\x97\xd6\x0c\x8c\xf2\nxa\xa9\x19u\xaf\xf2iN3\r\xd1\xae\x0f\xe3\x13\x0c@h\xb5W\xb0\xaad3\xef\t\x91s]R=~\xc3^Lv\xc7\x16\x15\xf4\xfb\xa7\x88ze_~B\x06\x80\x99\x03\x86\x7f\x0bY\x06U\xd2.\xeaV\x95\x87$\xd1\xce\xff\x8b\xbf\x9a\x99\xe0\x03u\xa1 =o0<n\xd0\xef]s`b\xb7\x98\x89\xael\xd2\x85\xceO:>\x80j\xfa\xdeb\x95\x95k\x91N\xbe\xfc'5\xac\xe7\xe8\x15""".decode('zip') ``` The above statement causes the following code to be executed: ``` z=frozenset def f(f,s): u={s};d,l,f=n(f);w,h,s=n(s);_=0;r=[[z(f[0]),z(s[0])]] for e,o in r: p=z(zip([e]*h,o)+zip(e,[o]*l)) if p-u:_|=((l in e)+2*(h in o))*4/3;u|=p;r+=[[reduce(z.__or__,(oo[i+1]for i in ii if ff[i]in[t,4][t<4:]),z())for ii,oo,ff in(e,f,d),(o,s,w)]for t in z([d[i]for i in e]+[w[i]for i in o])] return'|=><X'[_-3] def n(s): s=list('('+s+')');i=0 while s[i:]:f=s[i];h='()|*.'.find(f);s[i]=(h,f)[h<0];s[i:i+1]*=f!='\\';i+=1;l=i;h=1;w=e=[];p=[0];t=[{l}] while i: d=[i];i-=1;o=[i];f=s[i];t=[{i}]+t if f<1:h-=1;e+=zip(o*l,d+s.pop());w.pop() if f==1:h+=1;w=w+o;s+=[[]];e+=[o+d] if f==2:s[-1]+=d;e+=[(i,w[-1])] if h==p[-1]:e+=[t[-1:]+o,[i,1+t.pop()]];p.pop() if f==3:p+=[h];t+=o for f,o in e: for n in t:n|=(n,t[o])[f in n] return s+[1],l,t ``` If the second code sample is stored in the string `s`, something similar to the first can be produced by the expression `'#encoding=Latin\nexec"""%s"""'%__import__('zlib').compress(s)`. It may be necessary to fix some characters such as null bytes or backslashes. The unzipped code is nearly ~~1000~~ 800 bytes so perhaps it is more obfuscated than golfed...but at least I managed to golf the encoding a bit: from `Latin1` to `Latin`. **Explanation** The program works by using the indices of the string as a crude way to keep track of the states of parsing a string. The `n` function builds transition tables. First it parses the string and finds all instances of two kinds of transitions. First, there are transitions that don't involve adding another letter to the string. For example, jumping from a `*` to the beginning of a quantified expression. Secondly, there are transitions of adding a character, which simply move forward by one index. Then the transitive closure of the no-character transitions is calculated, and those are substituted for the destinations of the 1-character transitions. So it returns a mapping of an index and a character to a set of indices. The main function does a BFS over possible input strings. It tracks a set of all possible indices for whatever fragment of a string it is considering. What we are interested in finding is states that are either accepted by both regexes, or by one and not the other. To show that a regex is accepted, it is only necessary to find one possible path of transitions to the end of the pattern. But to show that one is rejected, it is necessary to have analyzed all possible paths. Therefore, to determine if the sets of possible states for pattern A and pattern B are already covered by ones that have been analyzed before, pairs of a single state in one regex and the set of all possible states in the other are recorded. If there are no new ones, then it is OK to go back. Of course, it would also be possible, and less characters, to simply record pairs of the sets of all states for both patterns, but then the computer would explode. [Answer] # Haskell, ~~560~~ ~~553~~ 618 might get some of the bonuses done in the future. this is not fully golfed yet. ``` import Data.List c%j|'\\':h:s<-j=[s|c==h]|(a,b):_<-[(a,b)|x<-[0..length j],(a,'|':b)<-[splitAt x j],snd(k b)==[]]=c%a++c%b|'(':s<-j,(a,_:'*':b)<-k s=map(++j)(c%a)++c%b|'(':s<-j,(a,_:b)<-k s=map(++b)(c%a)|h:'*':s<-j=map(++j)(c%[h])++c%s c%"."=[""|c>'\0'] c%s@[_]=c%('\\':s) c%(a:b)=map(++b)(c%[a]) c%s=[""|c>'\0'] a&b=nub[(x,nub$b>>=(c%))|c<-[' '..'~'],x<-c%a] g e(k@(a,l):r)|j<-a&l\\e=g(k:e)(j++r) g e[]=e a#b=or[all(null.('\0'%))m|(x,m)<-g[][(a,[b])],""<-'\0'%x] a!b|a#b,b#a='x'|a#b='>'|b#a='<'|0<1='=' k"("=("","(") k(c:s)|'('<-c,(x,y)<-k$tail b=('(':a++')':x,y)|')'<-c=("",')':s)|0<1=(c:a,b)where(a,b)=k s k j=(j,j) ``` a hand-wavy explanation of the algorithm: `reg!reg'` returns the required char, one of "=<>x". `a#b` is true iff not every string that `a` matches is also matched by `b`. `c%reg` is a list of regular expressions such that `reg` matches `c:s` iff one of the regexps in the output matches `s`. i is basically partially matches the regex. except if `c` is `'\0'`. then it forces `reg` to not get any more input, returning `[]` if `reg` must get more input to match and `[""]` otherwise. `#` works by generating a finite list of all possible "regex-state" the two regexps will be in after an arbitrary string. then to check if `a<b` we check weather there is a "regex-state" in which `a` is fully matched but `b` isn't fully matched. ]
[Question] [ ## Intro You are sitting in a board room at the end of a long table. You look around and see Tim Cook, the Apple Board of Directors, the ghost of Steve Jobs, and Jack Donaghy. Apple has called this meeting because they have realized how much cooler the Android lock screen is, and they want to 1-UP them. Everyone in the room stares at you as Ghost Steve cries, "Help me, CodeGolf Man! You're my only hope!" ## The Problem The Android lock screen is a 3 x 3 grid of dots that can be connected by swiping a finger from one dot to the next, creating a path. A password is considered any possible path that includes any number of dots, and excludes any number of dots. (On an actual phone, the path must be at least 4 dots long. For this challenge, ignore that restriction.) Apple plans to replace the 3 x 3 grid with an M x N grid, which is (M\*N)/9 times better! Rules: - A zero dot path is not a password, but a 1 dot path is - A path can cross itself - A path cannot cross directly over a dot without including that dot - A dot can only be used once - Paths that are identical by rotation are not the same password - Paths that are identical but ordered in reverse are not the same password For example, on a 3x3 grid with dots numbered from 1 to 9: ``` 1 2 3 4 5 6 7 8 9 ``` Some valid paths are: ``` 1 3 7,2,3 1,5,9,2 1,8,6,5,4 4,2,3,5,6,7,8,9 5,9,6,4 ``` And some invalid paths are: ``` 1,3 1,9,5 7,5,4,7 4,6 ``` Your input will be three numbers: ``` (M,N,d) ``` Where the grid is M x N, and d is the length of the path ``` 1 <= M <= 16 1 <= N <= 16 1 <= d <= M * N ``` Your program or function will be given the input as a comma separated string, and it must return the number of possible passwords of that length. For example: ``` Input: 2,2,1 Output: 4 Input: 2,2,2 Output: 12 Input: 7,4,1 Output: 28 ``` Standard code golf rules apply, shortest code wins! ``` //If I've made a mistake or the rules are unclear, please correct me! ``` [Answer] ## Python - 170 bytes ``` from fractions import* p=lambda m,n,d,l=0,s=set():d<1or sum([p(m,n,d-1,i,s|{i})for i in range(m*n)if not(s and(s&{i}or set(range(l,i,abs(i-l)/gcd(i%n-l%n,i/n-l/n)))-s))]) ``` I realize that the brackets inside `sum([...])` are not strictly necessary, but there's a large performance penalty for not including them. Output for all 3x3s: ``` for i in range(4, 10): print p(3, 3, i) ``` Produces: ``` 1624 7152 26016 72912 140704 140704 ``` For testing/confirmation purposes, the first 6 values for a 4x5 board: ``` 20 262 3280 39644 459764 5101232 ``` 4x5 is an interesting case to verify, because it has 2x2, 3x3, and 2x4 peg jumps. --- ### Brief Explanation In general, this is an exhaustive search, with cumulative pruning. For example, because `p(3, 3, 4)` is 1624, `p(3, 3, 5)` will only check 8120 posibilities, rather than naรฏvely checking all 15120. Most of the logic is contained in the condition: ``` if not(s and(s&{i}or set(range(l,i,abs(i-l)/gcd(i%n-l%n,i/n-l/n)))-s)) ``` In plain english, this can be understood as: ``` If no pegs have been used yet OR the target peg has not yet been used AND each of the pegs directly between the target peg and the current peg (a.k.a. "jumped over") have already been used ``` ]
[Question] [ You are given the functions: h1(f,\*args) and h2(f,\*args) Both are methods which are already defined for you (here the asterisk indicates a variable number of arguments) f is a function, \*args is a list of parameters to be passed to that function h1 returns a boolean value: True if the function f ever halts when called on \*args and False if it doesn't (assuming the machine running it has infinite time and memory and that the interpreter/compiler for the language you're writing in knows how to handle infinite time and memory). If f(\*args) would ever make a call to h1 or h2, h1 throws an exception h2 behaves exactly like h1 except that if f makes calls to h1, then h2 will not throw an exception In as few characters as possible, write a program which takes no input and should output: ``` The Collatz Conjecture is {True/False} Goldbach's Conjecture is {True/False} The Twin Primes Conjecture is {True/False} ``` based on the validity of each of those conjectures. Here are wikipedia links explaining each of the conjectures: <http://en.wikipedia.org/wiki/Collatz_conjecture> <http://en.wikipedia.org/wiki/Goldbach%27s_conjecture> <http://en.wikipedia.org/wiki/Twin_prime> You may assume any big integer library in whatever language you choose to use will successfully represent arbitrary large integers. In other words, we'll assume any language/library which is capable of expressing `3**(3**10)` is also capable of expressing `3**(3**(3**10))` on a sufficiently beefy machine. Obviously since it's impossible to run your program, please provide an explanation of how it works along with the code [Answer] # Haskell, 242 ``` p n=and[rem n r>0|r<-[2..n-1]] c 1=1 c n|odd n=c$3*n+1|0<1=c$div n 2 s!f=putStr(s++" Conjecture is ")>>print(not$h2$all(h1.f)[4..]) main=do"The Collatz"!c;"Goldbach's"! \n->or[p$n-r|r<-[2..n-2],p r];"The Twin Primes"! \n->or[p$r+2|r<-[n..],p r] ``` because in Haskell variables can contain not only values, but computations (this is called laziness) I let myself make `h1, h2` take a single argument and return weather or not it's evaluation will halt. somewhat ungolfed code: ``` h1 = undefined h2 = undefined prime n=and[rem n r>0|r<-[2..n-1]] collatz 1=1 collatz n |odd n=collatz (3*n+1) |0<1 =collatz (div n 2) s!f=do putStr (s++" Conjecture is ") print$not$h2$all(h1.f)[4..] main=do "The Collatz"!c --collatz "Goldbach's"! \n->or[prime (n-r)|r<-[2..n-2],prime r] --goldbach "The Twin Primes"! \n->or[prime (r+2)|r<-[n..],prime r] --twin primes ``` a bit of explanation: when `all` is applied to an infinite list, it will halt iff one of the elements of the list is `False`, due to laziness (short-circuiting, for all non-Haskell folks out there). we use this to compute the collatz conjecture and the twin primes conjecture. `!` packages this trickery along with printing. the result is `True` when `f` terminates on all the numbers `4..`. (this doesn't matter for the collatz conjecture or the twin primes conjecture, because we already know they are true for such small numbers). the code for the collatz conjecture is `"The Collatz"!c`. it prints "The Collatz Conjecture is " and the result, which is weather `c` terminates on all numbers `4..`. the code for the goldbach conjecture is `"Goldbach's"! \n->or[p$n-r|r<-[2..n-2],p r]`. `\n->or[p$n-r|r<-[2..],p r,r<n+1]` is a function which given `n`, if it is a sum of two primes, returns `True`, but otherwise loops indefinitely. thus, if it halts for every `4..` goldbach's conjecture is true. the code for the twin primes conjecture is `"The Twin Primes"! \n->or[p$r+2|r<-[n..],p r]`. `\n->or[p$r+2|r<-[n..],p r]` is a function which given `n`, if there are twin primes greater than `n`, returns True, but otherwise loops indefinitely. thus, if it halts for every `4..` the twin prime conjecture is true. [Answer] # J, 207 ``` (('The Collatz';'Goldbach''s';'The Twin Primes'),.<'Conjecture is'),.((>:^:((((-:`>:@*&3)^:(~:&1))^:_)&f)^:_ g 2)((+&2)^:(+./@1&p:@(-p:@_1&p:))^:_ f 4)(>:^:((4&p:)^:(2&~:&(-~4&p:))&f)^:_ g 3){'True':'False') ``` I chose to use `f` and `g` in place of `h1` and `h2`, as according to the bounty; two additional lines with **10** total characters prior is sufficient to switch: `f=:h1`,`g=:h2`. And the actual logic: ### Collatz ``` >:^:((((-:`>:@*&3)^:(~:&1))^:_)&f)^:_ g 2 ``` `((-:`>:@*&3)^:(~:&1))^:_` is the meat of it; it's essentially a loop that does `while (x != 1) x = collatz(x)`. If we call that sentence `reduce`: ``` >:^:(reduce&f)^:_ g 2 ``` `reduce&f` is meant to be a monadic verb (see end), where `reduce&f n` is true iff `reduce(n)` halts. The other loop-y bits, `>:^:()^:_`, are essentially an infinite loop (`>:` is increment, `^:` can be used as a conditional and an iterator) which breaks upon encountering a Collatz reduction that does not halt. Finally the `g` is called to see if the infinite loop ever terminates. ### Goldbach ``` (+&2)^:(+./@1&p:@(-p:@_1&p:))^:_ f 4 ``` The same logic, for the most part, the obvious difference being the core calculation is now `+./@1&p:@(-p:@_1&p:)`. `-p:@_1&p:` calculates the difference between a number and all the primes less than that number, `1&p:` is an `isPrime` function, and `+./` is logical OR. Hence, if the difference between a number and any prime less than that number is also a prime, then the Goldbach conjecture is satisfied, and the infinite loop continues on. Again, `f` is used in a final test of whether said infinite loop is truly infinite. ### Twin Primes ``` >:^:((4&p:)^:(2&~:@(-~4&p:))&f)^:_ g 3 ``` Same as above, excepting `(4&p:)^:(2&~:@(-~4&p:))`. `4&p:` returns the next largest prime after a given number. `-~4&p:` returns the difference between a number and the next largest prime after it. `2&~:` is `!= 2`. So the innermost loop is analogous to `while (nextPrimeAfter(p) - p != 2) p = nextPrimeAfter(p)`. ### Notes There may be syntactical errors, since I haven't tested with dummy `f` and `g` yet. Also, I assumed that `f` and `g` would take some sort of form that can be composed with a verb on the left and a noun on the right, which I'm not completely sure adheres to the J grammar in any way. They're inherently higher order functions, and I'm too tired to look up a proper construction as adverbs/conjunctions/what-have-you at the moment, if there even is such an appropriate construct. I didn't really use proper string concatenation, and instead opted to leave individual strings boxed. The output (assuming all else is correct) would therefore be a 3 column table, with the left column being "The Collatz", etc., the middle column being "Conjecture is", and the right column "True"/"False". I'm also pretty sure J doesn't convert integers to arbitrary precision by default, and the crucial prime number utility function `p:` does not have an arbitrarily large domain. On the other hand, given that J does support a standard arbitrary precision number type, I'm not sure how much effort it'd take to get this code up to par. [Answer] ## APL (234) It's obviously untested, but the logic seems sound. Printing commands are all included, the output is `104` characters and the actual logic is `130`. ``` Zโ†' Conjecture is 'โˆ˜,ยจ'True' 'False' โŽ•โ†'The Collatz',Z[1+{~{1=โต:โฌโ‹„2|โต:โˆ‡1+3ร—โตโ‹„โˆ‡โตรท2}h1โต:โฌโ‹„โˆ‡โต+1}h2 1] โŽ•โ†'Goldbach''s',Z[1+{~โตโˆŠโˆ˜.+โจN/โจ~NโˆŠโˆ˜.ร—โจNโ†1+โณโต:โฌโ‹„โˆ‡โต+2}h1 2] โŽ•โ†'The Twin Primes',Z[1+{~(Tโ†{โˆง/{2=+/(โŒˆ=โŒŠ)โตรทโณโต}ยจNโ†โต+1:Nโ‹„โˆ‡N})h1โต:โฌโ‹„โˆ‡Tโต}h2 4 2] ``` Ungolfed: ``` โ Environment assumptions: โŽ•IO=1 โŽ•ML=1 โ I've also assumed h1 and h2 are APL operators โ i.e. x F y = f(x,y); x (F h1) y = h1(F,x,y) โ 'Conjecture is True', 'Conjecture is False' Zโ†' Conjecture is 'โˆ˜,ยจ'True' 'False' โโโ Collatz Conjecture โ halts iff 1 is reached from given โต collatzLoopโ†{ 1=โต:โฌ โ โต=1: halt 2|โต:โˆ‡1+3ร—โต โ โต uneven: loop with new val โˆ‡โตรท2 โ โต even: loop with new val } โ halts iff 1 is *not* reached from a value โ‰ฅ โต (collatz false) collatzHaltโ†{~collatzLoop h1 โต:โฌโ‹„โˆ‡โต+1} โ does it halt? โŽ•โ†'The Collatz',Z[1+ collatzHalt h2 1] โโโ Goldbach's Conjecture โ Can โต be expressed as a sum of two primes? sumprimesโ†{ Nโ†1+โณโต โ N=[2..โต+1] Pโ†(~NโˆŠNโˆ˜.ร—N)/N โ P=primes up to โต+1ร—โต+1 โตโˆŠPโˆ˜.+P โ can two P be summed to โต? } โ halts iff Goldbach is false goldbachHaltโ†{ ~sumprimes โต:โฌ โ not a sum of primes: halt โˆ‡โต+2 โ try next even number } โ does it halt? โŽ•โ†'Goldbach''s',Z[1+ goldbachHalt h1 2] โโโ Twin Primes โ is it a prime? isPrimeโ†{ 2=+/(โŒŠ=โŒˆ)โตรทโณโต โ โต is a prime if โต is divisible by exactly two โ numbers in [1..โต] (i.e. 1 and โต) } โ find next twin nextTwinโ†{ Nโ†โต+1 โ next possible twin โˆง/ isPrimeยจ N:N โ return it if twin โˆ‡N โ not a twin, search on } โ halts iff no next twin for โต twinPrimeHaltโ†{ ~nextTwin h1 โต: โฌ โ if no next twin for โต, halt โˆ‡nextTwin โต โ otherwise try next twin } โ does it halt? โŽ•โ†'The Twin Primes',Z[1+ twinPrimeHalt h2 4 2] ``` ]
[Question] [ I'm looking to find the fastest racer around. Show me your fastest lap around this 18x14 track shown below. ``` ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ``` Your job is to move the car below around the track once in all possible positions. ``` _ | | |_| /\ / / \/ __ |__| /\ \ \ \/ ``` The car can drive in 3 spaces in a row before turning. Here's an example of what a lap should look like. ``` ______ / \ / \ / ____ \ / / \ \ /_ / \ \ || || | | ||_|| | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | _ | | | || || | | ||_|| | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | _ | | | || || | | ||_|| | | \ \ / / \ \____/ / \ / \ / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | /\| | | \\ \\ / / \\/ \____/ / \ / \ / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ /\\ / / \\ \\____/ / \\/ / \ / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ /\\____/ / \\ \ / \\/ / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ __ / \ |__| / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ __ / \ |__| / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ __ / \ |__| / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____//\ / \ / // \ \// \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ //\ / \ \____// // \ \// \ / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | |/\ | \ \ // // \ \____/ \// \ / \ / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | | | | | _ | | | || || | | ||_|| \ \ / / \ \____/ / \ / \ / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ \ | | | _ | | | || || | | ||_|| | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / \ / \ / ____ \ / / \ \ / / \ _\ | | || || | | ||_|| | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / \ / \ / ____ \ / / \ /\\ / / \\ \\ | | |\/ | | | | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / \ / \ / ____ /\\ / / \\ \\ / / \\/ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / \ / /\\ / ____\ \\ / / \\/ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / __ \ / |__| \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / __ \ / |__| \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / __ \ / |__| \ / ____ \ / / \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / \ //\ \ // /____ \ / \// \ \ / / \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / \ / \ //\ ____ \ // // \ \ / \// \ \ | | | | | | | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ______ / \ / \ / ____ \ //\ / \ \ // // \ \ | \/| | | | | | | | | | | | | | | \ \ / / \ \____/ / \ / \ / \______/ ``` --- ## Rules * The output should show the car in all possible positions. 3 positions in each of the 8 sections of the track mean there are 24 possible positions to show. * The car positions must be shown in sequence. (You can't teleport to another part of the track!) * The starting position and direction (clockwise/counter clockwise) are not important. * Output can be in any reasonable format for text. * No input. * Standard code-golf rules. The fewer bytes your code has, the faster your car runs. [Answer] # JavaScript (ES6), 371 bytes Rotates clockwise. Probably still golfable. ``` f=(i=24,A=[])=>i--?A.map(r=>r.join``,g=(s,x,y)=>[...s].map(c=>(j=c.charCodeAt(),d='12221',m=k=>(x-=~-d[j&7],y-=~-d[j-2&7],k--)&&((A[y]=A[y]||Array(18).fill` `)[x]='|/_\\'[j&3],k&&m(k)))(j/8&7)),g('voF`ir@kBdm',5,1),g('fWF`Qb@SBdU',6,4),g(['NFPJAT','MDWFI@S','VFHRAL','UDOFQ@K'][i/3&3],'0x'+'111123678ABCEEECBA876321'[i],'0x'+'678BCDDDDEDC876654222567'[i])).join` `+f(i):A ``` [Try it online!](https://tio.run/##NZDbToNAEIbvfQqv2N24UIEWiMlWllM8a621F5QIQqnLoTTQNJA0vjouVedi8s/MNzOZyaJD1MQ12@3FbZWs@z4lkBFljCnxA0SmTBSvqVRGO1iTaS1lFduGId4Q2OAWdxzwJUlqghMRkynMSCzFX1Ft82F0DxFOCJAVRZEBLknOgVYk32LiZ4Ie4O5Pi8oQ5aKIBAFC6ncBGdzxSOs66qBsICllRRGeh8hvAwKOo4/VCvAZKu8ShBLmCCGYjQxBRwhvIDhUXshqM7eSEuAJlk/JdOmFs09zbiULgDU8HpI@ePJe7ugbwODRWXq35pyrd@/mlT5wsXCevZl5DwKfjdRhGbhswQWQuSmqphvUsl3XtS1q6JrKT/TZP8KLlu1wcx2bF7XJmP9goukDgtDvG8/CixQydEX7uNo2VbGWimoDU4hQ/wM "JavaScript (Node.js) โ€“ Try It Online") ### Animated version ``` f=(i=24,A=[])=>i--?A.map(r=>r.join``,g=(s,x,y)=>[...s].map(c=>(j=c.charCodeAt(),d='12221',m=k=>(x-=~-d[j&7],y-=~-d[j-2&7],k--)&&((A[y]=A[y]||Array(18).fill` `)[x]='|/_\\'[j&3],k&&m(k)))(j/8&7)),g('voF`ir@kBdm',5,1),g('fWF`Qb@SBdU',6,4),g(['NFPJAT','MDWFI@S','VFHRAL','UDOFQ@K'][i/3&3],'0x'+'111123678ABCEEECBA876321'[i],'0x'+'678BCDDDDEDC876654222567'[i])).join` `+f(i):A F = 0; setInterval(_ => O.textContent = f().substr((F++ % 24) * 285 + 1, 285), 200) ``` ``` <pre id=O style="font-size:9px"></pre> ``` ### Less golfed ``` // i = frame counter, A[] = drawing matrix f = (i = 24, A = []) => i-- ? A.map(r => r.join``, // g() draws the shape described by s, starting at (x, y) g = (s, x, y) => [...s].map(c => ( // j holds the direction in bits 0-2 and the length in bits 3-5 // a length of 0 means 'move without drawing' j = c.charCodeAt(), d = '12221', // m() either draws a line or just moves the pen by 1 step m = k => ( x -= ~-d[j & 7], y -= ~-d[j - 2 & 7], k-- ) && ( (A[y] = A[y] || Array(18).fill` `)[x] = '|/_\\'[j & 3], k && m(k) ) )(j / 8 & 7)), // draw the outer boundary of the track g('voF`ir@kBdm', 5, 1), // draw the inner boundary of the track g('fWF`Qb@SBdU', 6, 4), // draw the car, using the correct shape for this frame and hard-coded coordinates g(['NFPJAT', 'MDWFI@S', 'VFHRAL', 'UDOFQ@K'][i / 3 & 3], '0x'+'111123678ABCEEECBA876321'[i], '0x'+'678BCDDDDEDC876654222567'[i] ) ).join`\n` + f(i) : A ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 131 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ๏ฝ›โ†”๏ผฝ รธ๏ผ•๏ผ๏ผ’๏ผ’โ•‹___๏ผ—๏ผ‘โ•‹__๏ผ˜๏ผ”โ•‹|ยถ|๏ผ‘๏ผ—โ•‹|ยถ|๏ผ•๏ผ—โ•‹๏ผ’๏ผ๏ผ–๏ผ•โ•‹โ•ฌ ๏ผ“๏ผปโต __ยถ|__|ยฒ๏ผ–๏ผ‹๏ผ’โ•‹๏ผฝ ๏ผ“๏ผปโต _ยถ| |ยถ|_|๏ผ’๏ผ•ยฒ๏ผ‹โ•‹๏ผฝ ๏ผ“๏ผปโต /\ยถ/ /ยถ\/๏ผ–ยฒ๏ผ๏ผ’ยฒ๏ผ‹โ•‹๏ผฝ โทโธโ‡ต๏ฝ›โ†•๏ผฝโˆ”โถ๏ฝ›โ†•๏ผฝโˆ”โธ๏ฝ›โ†•โ†”๏ผฝโˆ”โทโ‡ตโดโˆ”โธโ‡ตโดโˆ”โถโดโˆ”โธโˆ” ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjVCJXUyMTk0JXVGRjNEJTBBJUY4JXVGRjE1JXVGRjBGJXVGRjEyJXVGRjEyJXUyNTRCX19fJXVGRjE3JXVGRjExJXUyNTRCX18ldUZGMTgldUZGMTQldTI1NEIlN0MlQjYlN0MldUZGMTEldUZGMTcldTI1NEIlN0MlQjYlN0MldUZGMTUldUZGMTcldTI1NEIldUZGMTIldUZGMEYldUZGMTYldUZGMTUldTI1NEIldTI1NkMlMEEldUZGMTMldUZGM0IldTIwNzUlMjBfXyVCNiU3Q19fJTdDJUIyJXVGRjE2JXVGRjBCJXVGRjEyJXUyNTRCJXVGRjNEJTBBJXVGRjEzJXVGRjNCJXUyMDc1JTIwXyVCNiU3QyUyMCU3QyVCNiU3Q18lN0MldUZGMTIldUZGMTUlQjIldUZGMEIldTI1NEIldUZGM0QlMEEldUZGMTMldUZGM0IldTIwNzUlMjAvJTVDJUI2LyUyMC8lQjYlNUMvJXVGRjE2JUIyJXVGRjBEJXVGRjEyJUIyJXVGRjBCJXUyNTRCJXVGRjNEJTBBJXUyMDc3JXUyMDc4JXUyMUY1JXVGRjVCJXUyMTk1JXVGRjNEJXUyMjE0JXUyMDc2JXVGRjVCJXUyMTk1JXVGRjNEJXUyMjE0JXUyMDc4JXVGRjVCJXUyMTk1JXUyMTk0JXVGRjNEJXUyMjE0JXUyMDc3JXUyMUY1JXUyMDc0JXUyMjE0JXUyMDc4JXUyMUY1JXUyMDc0JXUyMjE0JXUyMDc2JXUyMDc0JXUyMjE0JXUyMDc4JXUyMjE0,v=2) [Answer] # [Python 2](https://docs.python.org/2/), ~~641~~ ~~639~~ ~~592~~ 576 bytes ``` for i in range(24): t='s ______s Xs / 642 \s Xs/875310 \sX /:;8____ \ X /<9:/s\ \ X />=</s \ \ X|A@?|ss| |X|BCB|ss| |X|DED|ss| |X|FHG|ss| |X \ILK\s / / X \KJM\____/ / X \MNPRTVs/ Xs\POQSUW /sXs \______/s '.replace('s',4*' ') for c,C in[zip([chr(x)for x in range(48,88)],' '*ord(s)+r+' '*40)for s,r in zip("\0\n !",'|____|?| ____|?\/\/?/\/\ ?\ / //\ ?_| ||_?_ | |_?_| ||_?\/\/\ ?\/\/?/ \ /\ ?| ____|?| ____|'.split('?'))][abs(12-i)]+zip('\/!','!\/')*(i>12):t=t.replace(c,C) print'\n'.join(l[::2*(i<13)-1]for l in t.split('X')) ``` [Try it online!](https://tio.run/##RVBNT9tAEFVPVTlUlXpAgkMnXHY3MdnYuK0xCea7fEOhH5YykRVCAKPIsbw@ANr/HmZiQlYazby3szvzXv5cPowzbzK5GxeQQppB0c/uh9LzVbgAZUcYgGR6qIgNaPjhewBoCOjg5/c1t8UoBgAdbgTcSCVSEKXb66E2WBEx6M1OW5vqFiG221uRNcYSsrHd2d2Zg739vTk4OPz1DgCPTk9oOO3BQTPw5PgMeWzFMAV4dn559eefYSo2eHnx@/rvf7o1JAArNbSHaBbDfNQfDKUwwvHrAoRaAPZh4OySE92XNJfdwUMhnxSzT3N3/MAJAtVz6El9XNxKoxpFg4HfmrYap@Bm/mAFWx8@Yvbp85evi8tL32orjrC8gI0sVBk16ogCIUKWoLlKLFibRAlQTmYI37qmD9hDRrNv3rJomnyUllJEQqlet39jpOutpqrX4G0E6ppwRA21UHWZbrqeCstO@e4EKScP8iLNSoGZaD6O00yOumHoUXfbXVOrbo8FjlheORsV06jJ5BU "Python 2 โ€“ Try It Online") * -2 bytes, thanks to Kevin Cruijssen * -30 bytes, thanks to Mnemonic * -16 bytes, thanks to Jonathan [Answer] # Deadfish~, 26942 bytes ``` {iii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{iiiii}ddc{dddddd}dddcc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiicc{{d}i}ddc{{i}d}iicc{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiicc{ddd}ic{iii}dcc{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddc{iiiiii}iiic{dddddd}dddc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddc{{i}d}iicc{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiicc{ddd}ic{iii}dcc{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{iiiiii}iiic{dddddd}dddc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddc{{i}d}iicc{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiicc{ddd}ic{iii}dcc{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{i}iiiiic{iiii}iiiiic{iii}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}cc{dddddd}c{iiiiii}cc{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}cc{dddd}dddddc{d}dddddc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}c{i}iiiiic{iiii}iiiiicc{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}cc{dddddd}c{iiiiii}cciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}cc{dddd}dddddc{d}dddddcccccccc{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}c{i}iiiiic{iiii}iiiiicciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}cc{dddddd}c{iiiiii}c{dddddd}ccccccc{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}cc{dddd}dddddc{d}dddddcccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}ccc{iiiiii}iiicc{dddddd}dddccccc{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}c{{i}d}iic{ddd}icc{iii}dc{{d}i}ddccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}cccc{iiiiii}iiicc{dddddd}dddcccc{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cc{{i}d}iic{ddd}icc{iii}dc{{d}i}ddcc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}ccccc{iiiiii}iiicc{dddddd}dddccc{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}ccc{{i}d}iic{ddd}icc{iii}dc{{d}i}ddc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iicc{iiii}iiiiic{dddddd}c{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}ccccccc{i}iiiiic{d}dddddc{i}iiiiicc{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccc{iiiiii}c{dddd}dddddcc{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiicc{iiii}iiiiic{dddddd}c{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iicc{d}dddddc{i}iiiiicc{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}cccccccc{iiiiii}c{dddd}dddddcc{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}ii}iiic{iiii}iiiiic{dddddd}c{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiicc{d}dddddc{i}iiiiicc{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddc{iiiiii}c{dddd}dddddcc{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddc{iiiiii}iiic{dddddd}dddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iicc{{d}i}ddc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iicc{ddd}ic{iii}dcc{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddc{iiiiii}iiic{dddddd}dddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iicc{{d}i}ddc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iicc{ddd}ic{iii}dcc{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}cc{iiiiii}iiicdddc{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iicc{{d}i}ddc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iicc{ddd}ic{iii}dcc{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}c{i}iiiiic{iiii}iiiiicc{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}cc{dddddd}c{iiiiii}cc{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{ddd}ddc{dddd}dddddc{d}dddddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddc{i}iiiiic{iiii}iiiiicc{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}cc{dddddd}c{iiiiii}cc{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}cc{dddd}dddddc{d}dddddc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccc{i}iiiiic{iiii}iiiiicc{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiiccccdddc{dddddd}c{iiiiii}cc{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}cc{dddd}dddddc{d}dddddc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddccc{iiiiii}iiicc{dddddd}dddc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddccc{{i}d}iic{ddd}icc{iii}dc{{d}i}ddc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcc{iiiiii}iiicc{dddddd}dddcc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcc{{i}d}iic{ddd}icc{iii}dc{{d}i}ddcc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddc{iiiiii}iiicc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddc{{i}d}iic{ddd}icc{iii}dc{{d}i}ddccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiicc{iiii}iiiiic{dddddd}cccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiicc{d}dddddc{i}iiiiic{iiiii}ddcccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddc{iiiiii}c{dddd}dddddcc{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiicc{iiii}iiiiic{dddddd}c{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiicc{d}dddddc{i}iiiiicc{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddc{iiiiii}c{dddd}dddddcc{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic{dddd}iiic{ii}iicccccc{iiiiii}iiicccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddccc{iiiiii}iiicccc{dddddd}dddccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiicc{iiii}iiiiic{dddddd}c{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiicc{d}dddddc{i}iiiiicc{d}dddddcccccc{iiiiii}c{dddddd}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddc{iiiiii}c{dddd}dddddc{{i}dd}dddc{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccc{{i}d}iic{{d}i}ddcccccccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iic{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}ccc{iiiiii}ciiicccc{ddddd}iic{d}dddddccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciiicccccc{ddddd}iic ``` ]
[Question] [ **Update:** There are 6 mazes. They are included in the controller. There is a tar.gz of the mazes and their .bmp files [here](https://www.dropbox.com/s/kmlak8qvjdjk99i/mazes.tar.gz?dl=0) (dropbox). There is also a utility for making more mazes at that link (the maze\_4.txt file is incorrect in archive). At this point, please feel free to run your own entry and update your score. Details on how to do so are included at the bottom. If you have questions or trouble, please ping me in chat. --- You're a mouse. You're in a maze. Find the cheese. **Concept** You are in a maze that exists on a rectangular grid. Each space of the grid contains one of several things: * `!` - An impassable wall * - An empty space, which is traversable * `O` - You, the mouse * `+` - The cheese, your goal Please use the same characters so that I do not have to modify the controller. On each turn, you will be given the tiles that are North, South, East, and West of your current position. You must then output the direction that you wish to travel. You win when you get to the cheese. Fewer steps is better. **Input** You will be given input through stdin in the following fashion: `nesw`, where each letter represents the tile at that compass point. For example, if the current state looks like ``` ! <--- Wall !O <--- You + <--- Cheese ``` then you will be given the string `! +!`. At the end of the game, the controller will send you a string of four zeroes: `0000`. **Upon receiving this string, your program should terminate.** No other input given will contain the `0` character. Please ignore all other inputs. **Output** You are to output one letter `n`, `s`, `e`, or `w`, to indicate which direction you want to travel, followed by a new line character. **Scoring** Your score on each test is the number of steps it takes you to find the cheese. Your overall score will be the sum of your average score per maze across a battery of mazes of variable sizes, all of which will fit inside a square of length 50. For example, if it takes your bot 100 moves to complete each of the 6 mazes, then your score is 600. If your bot is not deterministic, please try each maze 10 times and use average as the score for that maze. Your final score will be the sum of all the averages. **Rules** * Each maze will fit inside a 50x50 square. * Each maze will have at least one valid path from start to cheese. * Each maze will be entirely walled in, except that **the cheese will always be on the outer wall** so that it essentially serves as an exit to the maze. * If you run into a wall, your submission is disqualified. * If your submission takes too long (as determined by me, as I start testing), it will be disqualified. This is in large part to prevent infinite loops. The soft limit will be one minute per maze, although I reserve the right to change this at any time in either direction. * Entries need not be deterministic, but if you are too random, you will likely be disqualified by the above point. * At some point, the battery of mazes will be released, future answers may not optimize toward them, and they are subject to change. **Submissions**: Your submission is a full program that takes input via stdin and output via stdout. This is important because the submission will be interacting with the maze controller. I'm not going to ban languages that are not freely available, but know that someone else will have to offer their time to run the tests if I do not have access to the language. Please include instructions on how to run your submission. Please state whether your submission is deterministic or not, so that I know whether I need to run it multiple times. **Test Mazes** In the test mazes, `.` characters outline the shortest route to the cheese. They are the same as the (space) character. They are not visible to your submission. The controller replaces them with spaces. ``` !!!!!!!!+! !O..!....! ! !.!.! !! ! !.!.! ! ! !.!.!! ! !!!.!.!! ! ! .!.! !! !!!... ! !!!!!!!!!! ``` 31x31 test maze. [Shamelessly stolen](https://codegolf.stackexchange.com/a/26012/45459). ``` !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! O...!.......! ! .....!.....! ! ! ! !!!!!.!.! !!!.! !!! !.!!!.!.!!!.!!!!!!! !!! !!!!!!!!! !!! ! ! ! ! !...! !.! !.! !.!.! !.! ! ! ! ! ! ! ! !!!!! !!! !.!!!!!!!.! !.!.! !.! !!!!!!! !!! ! !!!!!!! !!! ! ! ! ! !.........! !...!...! ! ! ! ! ! ! ! ! ! !!! !!!!!!!!!!!!!!!!! !!!!!.!!! !!! !!! ! ! !!! !!! !!! !!! ! ! ! ! ! !.....! ! ! ! ! ! ! ! ! ! !!!!!!!!!!! ! ! !!! !!! !.!!!!!!!!!!!!! ! !!! ! !!!!!!! !!! ! ! ! ! ! !.! ! ! ! ! ! ! !!!!!!! !!!!!!! !!!!!!!.! !!!!!!!!!!!!!!! !!!!!!! !!!!!!!!!!! ! ! ! ! ! !...!.! ! ! ! ! ! ! !!! ! ! ! ! !!!!!!!.!.!.! !!!!!!!!! ! ! !!!!!!! ! ! !!!!!!! ! ! ! ! ! ! !.!...! ! ! ! ! ! ! ! ! ! !!! ! !!!!! !!!!!!! !.!!!!!!! !!!!!!!!! !!! !!!!! ! !!! ! !!! ! ! ! ! ! ! !...! ! ! ! ! ! ! ! ! ! !!!!! ! ! ! !!!!!!!!!.! !!!!! !!! !!!!! !!!!!!!!!!! ! ! ! ! ! ! ! ! ! ! !...! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!! !!! ! ! !.!!! !!!!!!! ! !!!!!!! ! ! !!!!!!! !!! ! ! ! ! ! !...! ! ! ! ! ! ! ! !!!!!!!!!!!!!!!!!!! !!!.!!!!!!! ! !!!!! ! !!! !!!!!!!!!!!!!!! ! ! ! !...! ! ! ! ! ! ! ! !!!!!!!!!!!!! ! ! !.!!! !!!!!!! !!!!!!!!! !!! !!! !!! ! !!! ! ! ! ! ! ! !.! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!! !!!!!!! !.! ! !!! ! ! ! ! !!! !!!!!!! !!! !!!!! !!! ! ! ! ! ! !.! ! ! ! ! ! ! ! ! ! !!!!! ! ! !!! !!! ! !.!!!!!!! !!!!!!! ! ! !!! ! !!!!!!!!! !!! ! ! ! ! ! ! !.......! ! ! ! ! ! ! ! ! ! !!!!! !!! !!! !!!!!!!!!!!.!!!!!!! ! ! ! !!!!!!! ! !!!!!!! ! ! ! ! ! !...! ! ! ! ! ! ! ! ! !!!!!!!!!!! !!!!!!!!!!! !.!!! !!!!!!! ! !!!!! ! !!! !!!!!!!!! ! ! ! ! ! !.! ! ! ! ! ! ! ! !!!!!!! !!!!! ! !!! !!!.!!!!!!! ! !!!!! ! ! !!!!! ! !!!!!!!!! ! ! ! ! ! ! !.......! ! ! ! ! ! ! ! !!! !!!!! ! !!! !!! !!!!!!!.! !!!!!!!!! !!!!!!!!!!!!!!!!! ! ! ! ! ! ! ! ! !.! ! ! ! ! ! !!!!!!!!!!! ! !!! !!! ! ! ! !!!.! ! !!!!! !!! ! !!! ! !!!!!!! ! ! ! ! ! ! !...! ! ! ! ! ! ! ! ! ! !!!!!!!!!!! !!!!!!!!!!!!! !.!!! !!!!!!!!!!! ! ! ! ! !!! ! !!! ! ! ! ! !.! ! ! ! ! ! ! ! ! ! !!!!!!! !!! !!!!!!!!!!!!! ! !.! !!! ! !!!!!!! ! !!! !!!!! ! ! ! ! ! ! ! ! !.! ! ! ! ! ! ! ! ! !!!!!!! !!!!!!! ! !!!!! ! !.!!! !!!!!!! ! ! !!! !!!!!!!!!!!!! ! ! ! ! ! !.! ! ! ! ! ! ! ! !!!!!!! ! ! !!! !!!!!!!.! !!!!!!!!!!! ! !!!!!!!!!!!!!!! ! ! ! ! ! ! ! ! ! !.....! ! ! ! !...............! ! ! !!! !!! ! !!!!! !!! !.!!!!! ! ! ! !!!!!!! !.!!!!!!!!!!!!!.! ! ! ! ! ! ! !...! ! ! !.! !...! !!!!! !!! ! !!! ! !!!!!!!!!.!!!!!!! !!!!!!!!!!!.!!!!! !!!!!.!!! ! ! ! ! ! !.......! !...!.....! .! ! ! !!!!! !!!!! !!!!! !!!!! !!!!!!!.!!!!!!!!!.!.!!!!!.!!!!!!!.! ! ! ! ! ! ! ! !...........!...!...!.....!...! ! !!!!!!!!! !!!!! ! !!! ! !!! ! !!!!!!!!!!!!!!!.!.!!!.!!!.!!!.! ! ! ! ! ! ! ! ! !.!..... !...!.! !!! !!! !!!!!!!!! !!!!! !!!!!!!!! ! !!!!!!! !!!.! !!!!!!!!!.!.! ! ! ! ! ! ! ! ! ! !...! !.........!.! ! !!!!!!! ! ! ! ! !!! ! !!!!!!! ! !!!!!!!!! !.!!!!!.!!!!!!!!!.! ! ! ! ! ! ! ! ! ! ! !.!.....! !.! ! !!!!! !!!!!!!!! ! !!!!!!!!!!! !!! ! ! ! ! !.!.!!!!! !!!!! !.! ! ! ! ! ! ! ! ! ! !.!...! ! !.! ! ! !!!!!!!!!!!!!!!!! !!! !!!!! ! ! !!!!!!!!!.!!!.! !!!!!!!!!.! ! ! ! ! .....! .! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!+! ``` **Controller** The controller is in [Rust](https://www.rust-lang.org/) (1.11 Nightly) ``` type Maze = Vec<Vec<char>>; fn str_to_maze(input: &str) -> Result<Maze,i32> { let mut maze: Vec<Vec<char>> = vec![ vec![] ]; let mut row: Vec<char> = vec![]; for c in input.chars() { if c == '!' || c == '+' || c == 'O' || c == ' ' { row.push(c); } else if c =='.' { row.push(' '); } else if c == '#' { maze.push(row); row = vec![]; } else if c =='\0' { break; } else { println!("Bad character in maze: {}, exiting.", c); return Err(1); } } return Ok(maze); } fn display_maze(maze: &Maze, position: [usize;2]) { for y in 0..maze.len() { for x in 0..maze[y].len() { if [x,y] == position { print!("O"); } else if maze[y][x] == '#' { println!("\n"); } else { print!("{}",maze[y][x]); } } println!(""); } println!("\n"); } fn get_starting_position(maze: &mut Maze) -> Result<[usize;2],&str> { for y in 0..maze.len() { for x in 0..maze[y].len() { if maze[y][x] == 'O' { maze[y][x] = ' '; return Ok([x,y]); } } } return Err("No mouse found"); } enum State { Continue([char;4]), Win, Disqualify, } fn output(maze: &Maze, position: [usize;2]) -> State { let x = position[0]; let y = position[1]; if maze[y][x] == '+' { return State::Win; } else if maze[y][x] == '!' { return State::Disqualify; } let n = maze[y-1][x]; assert!(y+1<maze.len()); let s = maze[y+1][x]; let w = maze[y][x-1]; assert!(x+1<maze[y].len()); let e = maze[y][x+1]; return State::Continue([n,e,s,w]); } fn get_input() -> char { use std::io; use std::io::Read; let mut buffer: [u8;2] = [0;2]; io::stdin().read_exact(&mut buffer).unwrap(); //println!("{:?}", buffer); // to see exactly what the input is return buffer[0] as char; } fn next_position(current_position: [usize;2], direction: char) -> Result<[usize;2],char> { let mut x = current_position[0]; let mut y = current_position[1]; if direction == 'n' { y -= 1; } else if direction == 'e' { x += 1; } else if direction == 's' { y += 1; } else if direction == 'w' { x -= 1; } else { return Err(direction); } return Ok([x,y]); } fn play(maze: &mut Maze) -> (State, usize) { let mut position: [usize;2]; match get_starting_position(maze) { Ok(pos) => position = pos, Err(s) => { println!("{}",s); std::process::exit(2); } } let mut moves = 0; loop { let state = output(maze, position); /* uncomment below to view the maze at each step */ //display_maze(&maze, position); /* ----------------------------------------------*/ match state { State::Win => { //println!("You found the cheese"); return(State::Win, moves); } State::Disqualify => { //println!("You were disqualified"); return(State::Disqualify, moves); } State::Continue(out) => { println!("{}{}{}{}",out[0],out[1],out[2],out[3]); } } // only get here with Continue let input = get_input(); moves += 1; match next_position(position, input) { Err(c) => { println!("Invalid input: {}", c as u8); return (State::Disqualify, moves); } Ok(next_pos) => position = next_pos, } } } fn main() { let mut arg_counter = 0; for argument in std::env::args() { if arg_counter != 0 { let mut maze = match argument.as_str(){ "1" => maze_1(), "2" => maze_2(), "3" => maze_3(), "4" => maze_4(), "5" => maze_5(), "6" => maze_6(), _ => { println!("invalid input: {}, breaking", argument); break; } }; let game_result = play(&mut maze); println!("0000"); match game_result.0 { State::Win => println!("WIN"), State::Disqualify => println!("DISQUALIFY"), _ => println!("Error"), } println!("moves: {}", game_result.1 ); } arg_counter += 1; } } fn maze_1() -> Maze { let maze_str = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\ !O ! ! !#\ !. ! !!!!!!!!!!!!!!!!!! ! !!!!!!#\ !. ! ! ! !#\ !. ! !!!!!!!!!!!!!!!!!!!! ! !! !#\ !. !........... ! !!.+#\ !. !.!!!!!!!!!.!!!!!!!!!!!!!!!.!#\ !.!..! ...............!.!#\ !.!.!! !!!!!!!!!!!!!!!!!!!!!.!.!#\ !.!.!! !!! ! .!.!#\ !.!.!! !!! !!!!!!!!!!!!!!!!.!.!#\ !...!! !!! .!.!#\ ! ! !! !!! .!.!#\ ! ! !! !!! !!!!!!!!! !!!!!!.!.!#\ ! ! !! !!! ! !! ! .!.!#\ ! ! !! !!! ! !!!!!!! ! .!.!#\ ! ! !! !!! ! !! ! .!.!#\ ! ! !! !!! ! !! ! .!.!#\ ! ! !! ! ! !! ! .!.!#\ ! ! !! ! ! !!!!!! !! ! .!.!#\ ! ! !! ! ! ! !! ! ...!#\ ! ! !! ! ! ! !! ! !#\ ! ! !! ! ! ! !! ! ! !#\ ! ! !! ! ! ! !!!!!! ! ! !#\ ! ! !! ! ! ! !! ! ! !#\ ! ! ! ! !! ! ! !#\ ! !!!!!! !!!!!!!! !! ! ! !#\ ! ! !! ! ! !#\ ! !!!!!!!!!!! !!!! !! ! ! !#\ ! ! ! !#\ ! !!!!!!!! !!!! ! !#\ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\ "; match str_to_maze(&maze_str) { Ok(x) => return x, Err(i) => std::process::exit(i), } } fn maze_2() -> Maze { let maze_str = "!!!!!!!!!!!!!!!#\ ! .......!#\ ! !!! !.!!!! .!#\ ! ! !.!!O!!.!#\ !!! !....! .!#\ ! !!!!!!!!!.!#\ ! !! ..!#\ ! !!!!!!!!!.!!#\ ! ..+#\ !!!!!!!!!!!!!!!#\ "; match str_to_maze(&maze_str) { Ok(x) => return x, Err(i) => std::process::exit(i), } } fn maze_3() -> Maze { let maze_str = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\ ! !!!#\ ! ! !!! !!!!!!!!!!!!!!!!!! !#\ ! ! ! !!! !!! ! !#\ ! ! ! !!!!!!!!!!!!!!!! !! !#\ ! ! ! !!!! !#\ ! !! !!!!!!!!!! !! ! !#\ ! ! ! !!!! !!!!! !!! !#\ !! ! ! !!!! ! ! !#\ !! ! ! !!!! !!!!!!!!!!!!!! ! !#\ !! ! ! !!!! ! ! ! !#\ !! ! ! !!!! ! ! !!!! ! ! !#\ !! ! ! !!!! ! ! ! !!! ! ! !#\ ! ! ! !!!! ! ! ! !!! ! ! !#\ ! ! ! !!!! ! ! !!!!! ! !#\ ! ! ! !!!! !!! ! !! ! !!!#\ ! ! ! !!! !! ! !!! ! !!!#\ ! ! ! ! !! !!!! !! ! !!!#\ ! ! !! ! !! ! !! ! !!!#\ ! ! ! !! !! !!! ! !!!#\ ! !! !!!! !!! !! ! !#\ !! ! !! ! !!! !! !!! !#\ !! ! ! ! ! !#\ !! !!!!!! !! !!!!!!!!!!! !#\ ! !!!! !!!!!!!!!!! !#\ ! ..........O!!!! !!!!!!!!!!!.+#\ !! .!!!!!! !! !!!!!!!!!!!.!#\ !! .! ! ! ! .!#\ !!..! !! ! !!! !! !!!.!#\ ! .!! !!!! !!! !! !...!#\ ! .! ! !! !! !!! !.!!!#\ ! .! !! ! !! ! !! !.!!!#\ ! .! ! ! !! !!!! !! !.!!!#\ ! .! ! !!! !! ! !!! !.!!!#\ ! .! ! !!!! !!! ! !! !.!!!#\ ! .! ! !!!! ! ! !!!!! !...!#\ ! .! ! !!!! ! ! ! !!! ! !.!#\ !!.! ! !!!! ! ! ! !!! ! !.!#\ !!.! ! !!!! ! ! !!!! ! !.!#\ !!.! ! !!!! ! ! !.!#\ !!.! ! !!!! !!!!!!!!!!!!!! !.!#\ !!.! ! !!!! ! ! .!#\ !..! ! !!!! !!!!! !!!.!#\ !.!! !!!!!!!!!! !! !.!#\ !.! ! !!!! .!#\ !.! ! !!!!!!!!!!!!!!!! !!.!#\ !.! ! !!! !!! !.!#\ !.! !!! !!!!!!!!!!!!!!!!!!...!#\ !............................!!!#\ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\ "; match str_to_maze(&maze_str) { Ok(x) => return x, Err(i) => std::process::exit(i), } } fn maze_4() -> Maze { let maze_str = "!!!!!!!!!!!!!!!!!+!!!!!!!!!!!!!!#\ !................. !!!#\ !.! !!! !!!!!!!!!!!!!!!!!! !#\ !.! ! !!! !!! ! !#\ !.! ! !!!!!!!!!!!!!!!! !! !#\ !.! ! !!!! !#\ !.!! !!!!!!!!!! !! ! !#\ !..! ! !!!! !!!!! !!! !#\ !!.! ! !!!! ! ! !#\ !!.! ! !!!! !!!!!!!!!!!!!! ! !#\ !!.! ! !!!! ! ! ! !#\ !!.! ! !!!! ! ! !!!! ! ! !#\ !!.! ! !!!! ! ! ! !!! ! ! !#\ ! .! ! !!!! ! ! ! !!! ! ! !#\ ! .! ! !!!! ! ! !!!!! ! !#\ ! .! ! !!!! !!! ! !! ! !!!#\ ! .! ! !!! !! ! !!! ! !!!#\ ! .! ! ! !! !!!! !! ! !!!#\ ! .! !! ! !! ! !! ! !!!#\ ! .! ! !! !! !!! ! !!!#\ ! .!! !!!! !!! !! ! !#\ !!. ! !! ! !!! !! !!! !#\ !!. ! ! ! ! !#\ !!. !!!!!! !! !!!!!!!!!!! !#\ ! ........... !!!! !!!!!!!!!!! !#\ ! . !!!! !!!!!!!!!!! !#\ !! !!!!!! . !! !!!!!!!!!!! !#\ !! ! ! . ! ! !#\ !! ! !! ! . !!! !! !!! !#\ ! !! !!!! . !!! !! ! !#\ ! ! ! !!.!! !!! ! !!!#\ ! ! !! !.!! ! !! ! !!!#\ ! ! ! !.!! !!!! !! ! !!!#\ ! ! ! !!!..!! ! !!! ! !!!#\ ! ! ! !!!!.!!! ! !! ! !!!#\ ! ! ! !!!!.! ! !!!!! ! !#\ ! ! ! !!!!.! ! ! !!! ! ! !#\ !! ! ! !!!!.! ! ! !!! ! ! !#\ !! ! ! !!!!.! ! !!!! ! ! !#\ !! ! ! !!!!.! ! ! !#\ !! ! ! !!!!. !!!!!!!!!!!!!! ! !#\ !! ! ! !!!!.....O! ! !#\ ! ! ! !!!! !!!!! !!! !#\ ! !! !!!!!!!!!! !! ! !#\ ! ! ! !!!! !#\ ! ! ! !!!!!!!!!!!!!!!! !! !#\ ! ! ! !!! !!! ! !#\ ! ! !!! !!!!!!!!!!!!!!!!!! !#\ ! !!!#\ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\ "; match str_to_maze(&maze_str) { Ok(x) => return x, Err(i) => std::process::exit(i), } } fn maze_5() -> Maze { let maze_str = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\ +......!!!! !!! !!! !!!! !!#\ ! .! !! !!!!!#\ ! !!!.! !! !!! !!!! !!!!!!!!! !!! !#\ ! !!...! !!!!! !! ! !! !! !#\ !!!..!! ! !! ! ! ! !!#\ !! .!!........ !! !!! ! ! ! ! !!#\ !!!. !. ! !. ! !!!!! !! ! ! !! !!!#\ !!!. !. ! !. ! !!!!! ! !! ! !!!#\ !!.. !. ! !.. ! ! ! !! ! ! !!#\ !!.! !.! ! ! .. ! !!!!!! ! ! ! ! !!#\ !!.! !.! ! !! . ! ! ! ! ! ! !!#\ !!.! !.! ! ! . ! !! !! !!!! ! ! ! !!#\ !!.! !.!! ! ! . ! !!! !!!! ! ! !! !!#\ !!.! !. ! ! ! . ! !! ! ! ! ! !!#\ ! .!!!. ! ! !!. ! ! ! ! ! ! !#\ ! .!!!. ! ! !. ! ! ! ! ! ! !#\ ! .! !. ! ! !. ! ! ! ! ! ! !#\ ! .! !. ! !! !....!!! ! !! ! ! ! !#\ ! .! ..! ! ! ...!!!! ! ! ! ! ! !#\ ! .! .! ! !!!!!!.... !!!!!!! ! ! !#\ ! .! !!.! !! ! !!!! .! !#\ ! .!!!!.! !!!! !!! .! !!!!! !!!!!!!!!!! !#\ ! .. !!.! !!! !! !.!! !#\ !!!.. !. ! !!! !..! !!! ! ! !#\ !!! .... ! !!!! ! .! ! !!#\ !!!!!!!!!!!!!!!!!!!!!!! .! !!!!!!!!!!!!!!!!!!!! !!#\ !!! ! .! !!!#\ !! ! !!! !! .! !!#\ !! ! ! !! !!!!!!.! !!!!!! !!#\ !! ! ! !! !!!!!!.! !!!!!!!! ! !!#\ !! ! ! !! !!!!!!!.! !!!!!! !! ! ! !!#\ !! ! ! ! !!!!!!!!.! !!! ! ! ! !!#\ !! ! ! ! !!!!!!!!!.! !!!! ! ! ! ! ! !!#\ !! ! ! ! .! !! ! ! ! ! !!#\ !! !!! ! ! !!!!!! .! ! !! !!#\ !! ! ! ! ! ! !!. ! !!! ! ! !!#\ !! ! ! ! ! ! ! . ! ! !! ! ! !!#\ !! ! ! ! ! ! !! !!. !!! !! ! ! ! !!#\ !! ! ! ! !! ! !!! ! ..... !! ! ! !!#\ !! ! ! ! ! ! !!!!!!! . ! ! !!#\ ! ! ! ! ! ! !!! ! .!!!! ! ! !#\ ! ! ! ! !! ! ! .! !!.......... !#\ ! !! ! ! ! !!!!!!!!! .! !! .! !!!!. !#\ ! ! ! ! !! !!! .!!!!! .. ! . !#\ ! ! ! !! !!! !!! .......... !!!! . !#\ ! ! ! !! !!!! !!!!!!!!!!!! !. !#\ ! ! ! !!!!!! O. !#\ ! ! !#\ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\ "; match str_to_maze(&maze_str) { Ok(x) => return x, Err(i) => std::process::exit(i), } } fn maze_6() -> Maze { let maze_str = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\ ! !!!! ....!!! !!! !!!! !!#\ ! ! .!!.......... !!!!!#\ ! !!! ! !! ...!!! !!!!. !!!!!!!!! !!! !#\ ! !! ! !!!!!.. !! !. !! !! !#\ !!! !! !. !! !..... ! ! !!#\ !! !! .. !! !!! . ! ! ! ! !!#\ !!! ! ! ! .! !!!!! . !! ! ! !! !!!#\ !!! ! ! ! .! !!!!!. ! !! ! !!!#\ !! ! ! ! .! ! !. !! ! ! !!#\ !! ! ! ! ! ! . ! !!!!!! ! .. ! ! ! !!#\ !! ! ! ! ! !! . ! ! ! .....! ! ! !!#\ !! ! ! ! ! ! . ! !! !! !!!!.! ! ! !!#\ !! ! ! !! ! ! ..! !!! !!!! .! ! !! !!#\ !! ! ! ! ! ! .! !! ! .! ! ! !!#\ ! !!! ! ! !! . ! ! ! .! ! ! !#\ ! !!! ! ! ! ..! ! ! . ! ! ! !#\ ! ! ! ! ! ! .! ! ! . ! ! ! !#\ ! ! ! ! !! ! .!!! ! !! . ! ! ! !#\ ! ! ! ! ! ...!!!! ! . ! ! ! ! !#\ ! ! ! ! !!!!!!.... !!!!!!! . ! ! !#\ ! ! !! ! !! ! !!!! .! . !#\ ! !!!! ! !!!! !!! .! !!!!! .!!!!!!!!!!! !#\ ! !! ! !!! !! !.!!.......... !#\ !!! ! ! !!! !. !. !!! ! ! !#\ !!! ! !!!! !. !. ! !!#\ !!!!!!!!!!!!!!!!!!!!!!!. !.!!!!!!!!!!!!!!!!!!!! !!#\ !!! ! . !.....................!!!#\ !! ! !!! !! O..... ! ..!!#\ !! ! ! !! !!!!!! ! !!!!!! .!!#\ !! ! ! !! !!!!!! ! !!!!!!!! ! .!!#\ !! ! ! !! !!!!!!! ! !!!!!! !! ! ! .!!#\ !! ! ! ! !!!!!!!! ! !!! ! ! ! .!!#\ !! ! ! ! !!!!!!!!! ! !!!! ! ! ! ! ! .!!#\ !! ! ! ! ! !! ! ! ! ! .!!#\ !! !!! ! ! !!!!!! ! ! !! .!!#\ !! ! ! ! ! ! !! ! !!! ! ! .!!#\ !! ! ! ! ! ! ! ! ! !! ! ! .!!#\ !! ! ! ! ! ! !! !! !!! !! ! ! ! .!!#\ !! ! ! ! !! ! !!! ! !! ! !.!!#\ !! ! ! ! ! ! !!!!!!! ! ! .!!#\ ! ! ! ! ! ! !!! ! !!!! ! ! . !#\ ! ! ! ! !! ! ! ! !! . !#\ ! !! ! ! ! !!!!!!!!! ! !! ! !!!!. !#\ ! ! ! ! !! !!! !!!!! ! . !#\ ! ! ! !! !!! !!! ! !!!! . !#\ ! ! ! !! !!!! !!!!!!!!!!!! !..+#\ ! ! ! !!!!!! !#\ ! ! ! !#\ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#\ "; match str_to_maze(&maze_str) { Ok(x) => return x, Err(i) => std::process::exit(i), } } ``` To test the larger maze, simply replace the maze string in the `maze_1` function. Make sure to append the correct `#\` characters to each line. **Testing your entry** This script can be used to test entries ``` #!/bin/bash mkfifo /tmp/pipe1 mkfifo /tmp/pipe2 for arg in "$@"; do <path to controller> $arg < /tmp/pipe1 | tee /tmp/pipe2 trascript.txt & ( <path to entry> < /tmp/pipe2 | tee /tmp/pipe1 ) > /dev/null done rm /tmp/pipe1 rm /tmp/pipe2 ``` For example, my script looks like: ``` #!/bin/bash mkfifo /tmp/pipe1 mkfifo /tmp/pipe2 for arg in "$@"; do ./maze/target/release/maze $arg < /tmp/pipe1 | tee /tmp/pipe2 trascript.txt & ( ./maze_test/main < /tmp/pipe2 | tee /tmp/pipe1 ) > /dev/null done rm /tmp/pipe1 rm /tmp/pipe2 ``` It is used in the following way: ``` ./script <mazes to test> ``` For example ``` ./script 1 2 3 4 5 6 ``` It will print everything to the console as well as writing everything to a file called `transcript.txt` For the purpose of developing your entry, you can uncomment the ``` display_maze(&maze, position) ``` line in the `play` function. This will cause the controller to display the maze at each step. [Answer] # Boundary Finding Bot, Java 1.5+, 124 + 37 + 206 + 324 + 248 + 223 = 1172 steps [![enter image description here](https://i.stack.imgur.com/yrVcf.gif)](https://i.stack.imgur.com/yrVcf.gif) This bot attempts to locate and follow the boundaries of the maze knowing that the cheese will always be located on the boundary. It does this by updating its internal view of the maze and constructing current candidates for the north, south, east and west boundary walls. A\* path finding is performed for any unexplored cells in these walls and the shortest path is chosen to follow. However only the candidate boundary walls that do not contain any blank spaces are able to be the "true" boundary wall and thus those that do contain blank cells are not considered for path finding. Unexplored cells within a path are given less desirable score with consecutive unexplored cells compounding the undesirability. In this latest edit, the bot now has a negative weight to cells already visited. This gives a slight improvement. A fail safe movement selection mechanism exists that ensures valid movement is chosen in the event that no paths are able to be found. Note that this implementation is quite inefficient and can take many seconds to solve a maze in the worst case. Deterministic. Run with `java BoundryFindingBot` ``` import java.io.IOException; import java.io.InputStream; public class BoundryFindingBot { private static final char[] DIRECTION = {'n','e','s','w'}; private static final int MAP_SIZE = 102; private static final int PATH_FINDING_MAX_STEPS = 50000; private static final int[][] offsets = new int[][]{{0,-1},{1,0},{0,1},{-1,0}}; public static void main(String[] args) throws Exception { char[][] map = new char[MAP_SIZE][MAP_SIZE]; int[][] visitCount = new int[MAP_SIZE][MAP_SIZE]; int mx=MAP_SIZE/2-1, my=MAP_SIZE/2-1; int direction=0; String line=readLine(System.in); out: while (line!=null && !"0000".equals(line)) { // update map with new information for (int i=0;i<4;i++) { map[mx+offsets[i][0]][my+offsets[i][1]] = line.charAt(i); // immediately move toward cheese if found. if (line.charAt(i) == '+') { System.out.println(DIRECTION[i]); break out; } } // determine the current boundary walls information int currentNorthWallY=-1,currentSouthWallY=-1,currentWestWallX=-1,currentEastWallX=-1; boolean currentNorthWallHasBlanks=false,currentSouthWallHasBlanks=false,currentEastWallHasBlanks=false,currentWestWallHasBlanks=false; for (int y=0;y<MAP_SIZE;y++) { for (int x=0;x<MAP_SIZE;x++) { if (map[x][y]!=0) { if (currentNorthWallY > -1) { if (currentSouthWallY !=y) { currentSouthWallHasBlanks = false; } currentSouthWallY=y; currentSouthWallHasBlanks|=map[x][y]==' '; } else { currentNorthWallY=y; } if (currentNorthWallY == y) { currentNorthWallHasBlanks|=map[x][y]==' '; } } } } for (int x=0;x<MAP_SIZE;x++) { for (int y=0;y<MAP_SIZE;y++) { if (map[x][y]!=0) { if (currentWestWallX > -1) { if (currentEastWallX !=x) { currentEastWallHasBlanks = false; } currentEastWallX=x; currentEastWallHasBlanks|=map[x][y]==' '; } else { currentWestWallX=x; } if (currentWestWallX == x) { currentWestWallHasBlanks|=map[x][y]==' '; } } } } int closestUnvisitedWallCellResult =0xFFFFFF; // attempt to find paths to undiscovered cells in the current north wall, setting the shortest path if shortest of any path if (!currentNorthWallHasBlanks) { for (int x=currentWestWallX;x<=currentEastWallX;x++) { if (map[x][currentNorthWallY] == 0) { int result = pathFind(mx, my, x, currentNorthWallY, map,visitCount,currentWestWallX,currentNorthWallY,currentEastWallX,currentSouthWallY); if ((result &0xFFFFFF) <(closestUnvisitedWallCellResult &0xFFFFFF)) { closestUnvisitedWallCellResult = result; } } } } // attempt to find paths to undiscovered cells in the current south wall, setting the shortest path if shortest of any path if (!currentSouthWallHasBlanks) { for (int x=currentWestWallX;x<=currentEastWallX;x++) { if (map[x][currentSouthWallY] == 0) { int result = pathFind(mx, my, x, currentSouthWallY, map,visitCount,currentWestWallX,currentNorthWallY,currentEastWallX,currentSouthWallY); if ((result &0xFFFFFF) <(closestUnvisitedWallCellResult &0xFFFFFF)) { closestUnvisitedWallCellResult = result; } } } } // attempt to find paths to undiscovered cells in the current east wall, setting the shortest path if shortest of any path if (!currentEastWallHasBlanks) { for (int y=currentNorthWallY;y<=currentSouthWallY;y++) { if (map[currentEastWallX][y] == 0) { int result = pathFind(mx, my, currentEastWallX, y, map,visitCount,currentWestWallX,currentNorthWallY,currentEastWallX,currentSouthWallY); if ((result &0xFFFFFF) <(closestUnvisitedWallCellResult &0xFFFFFF)) { closestUnvisitedWallCellResult = result; } } } } // attempt to find paths to undiscovered cells in the current west wall, setting the shortest path if shortest of any path if (!currentWestWallHasBlanks) { for (int y=currentNorthWallY;y<=currentSouthWallY;y++) { if (map[currentWestWallX][y] == 0 ) { int result = pathFind(mx, my, currentWestWallX, y, map,visitCount,currentWestWallX,currentNorthWallY,currentEastWallX,currentSouthWallY); if ((result &0xFFFFFF) <(closestUnvisitedWallCellResult &0xFFFFFF)) { closestUnvisitedWallCellResult = result; } } } } // fail-safe if we are unable to find a path to a wall (i.e. initial game frame or all current boundary walls are known to have blanks and thus // not wall to head for. Simply tries to go north if possible or failing that try to head east, south, west consecutively if (closestUnvisitedWallCellResult == 0xFFFFFF) { for (int i=0;i<4;i++) { if (map[mx+offsets[i][0]][my+offsets[i][1]] == ' ') { direction = i; break; } } } else { direction = closestUnvisitedWallCellResult >> 24; } mx +=offsets[direction][0]; my +=offsets[direction][1]; visitCount[mx][my]+=5; System.out.println(DIRECTION[direction]); //// uncomment to bot's view of maze solving // System.err.println(); // for (int y=currentNorthWallY;y<=currentSouthWallY;y++) // { // for (int x=currentWestWallX;x<=currentEastWallX;x++) // { // if (x==mx && y==my) // { // System.err.print("O"); // } // else // { // System.err.print(map[x][y]); // } // } // System.err.println(); // } line=readLine(System.in); } System.err.println("Exited"); } /** * returns a result that is the combination of movement direction and path length of a path found from the given start position to the target * position for cells within the given bounding box. Only empty cells and unexplored cells are traversable. Sequential cells of unexplored cells * are given increasing magnitude negative score to reduce desirability. */ static int pathFind(int startX, int startY, int targetX,int targetY,char[][] map,int[][] visitCount,int boundMinX,int boundMinY,int boundMaxX,int boundMaxY) { // A* if (!(startX==targetX && startY==targetY)) { int[] tileX = new int[PATH_FINDING_MAX_STEPS]; int[] tileY = new int[PATH_FINDING_MAX_STEPS]; int[] fscore = new int[PATH_FINDING_MAX_STEPS]; int[] gscore = new int[PATH_FINDING_MAX_STEPS]; int[] openList = new int[PATH_FINDING_MAX_STEPS]; int[] tileParent = new int[PATH_FINDING_MAX_STEPS]; int[] unexploredCellRun = new int[PATH_FINDING_MAX_STEPS]; int[][] tileIsClosed = new int[MAP_SIZE][MAP_SIZE]; int currentIndex = -1; int openListSize=1; int tileId=1; tileX[0]=targetX; tileY[0]=targetY; fscore[0]=1; gscore[0]=1; do { int currentBestIndex=-1; int currentBestScore=Integer.MAX_VALUE; // Look for the lowest F cost square on the open list for (int ii=0;ii<openListSize;ii++) { if (fscore[openList[ii]]<currentBestScore) { currentBestScore=fscore[openList[ii]]; currentBestIndex=ii; } } if (currentBestIndex==-1) { break; } currentIndex=openList[currentBestIndex]; int currentTileX=tileX[currentIndex]; int currentTileY=tileY[currentIndex]; // found path if (startX==currentTileX && startY==currentTileY) { break; } // if not in closed list if (tileIsClosed[currentTileX][currentTileY]==0) { // Switch it to the closed list. tileIsClosed[currentTileX][currentTileY]=1; // remove from openlist openList[currentBestIndex]=openList[--openListSize]; // add neigbours to the open list if necessary for (int i=0;i<4;i++) { int surroundingCurrentTileX=currentTileX+offsets[i][0]; int surroundingCurrentTileY=currentTileY+offsets[i][1]; if (surroundingCurrentTileX>=boundMinX-1 && surroundingCurrentTileX<=boundMaxX+1 && surroundingCurrentTileY>=boundMinY-1 && surroundingCurrentTileY<=boundMaxY+1 ) { tileX[tileId]=surroundingCurrentTileX; tileY[tileId]=surroundingCurrentTileY; if (map[surroundingCurrentTileX][surroundingCurrentTileY]==0) { unexploredCellRun[tileId]=0; } else if (map[surroundingCurrentTileX][surroundingCurrentTileY]=='!') { continue; } else { unexploredCellRun[tileId]=unexploredCellRun[currentIndex]+1; } int surroundingCurrentGscore=gscore[currentIndex]+visitCount[surroundingCurrentTileX][surroundingCurrentTileY]+1+((int) (unexploredCellRun[tileId]*10)); gscore[tileId]=surroundingCurrentGscore; fscore[tileId]=surroundingCurrentGscore+Math.abs( surroundingCurrentTileX-startX)+Math.abs( surroundingCurrentTileY-startY); tileParent[tileId]=currentIndex; openList[openListSize++]=tileId++; } } } else { // remove from openlist openList[currentBestIndex]=openList[--openListSize]; } } while(true); if (tileX[tileParent[currentIndex]]-startX<0) return (3 <<24) + currentIndex; else if (tileX[tileParent[currentIndex]]-startX>0) return (1 <<24) + currentIndex; else if (tileY[tileParent[currentIndex]]-startY<0) return (0 <<24) + currentIndex; else if (tileY[tileParent[currentIndex]]-startY>0) return (2 <<24) + currentIndex; } throw new RuntimeException("Path finding failed"); } /** * Reads a line of text from the input stream. Blocks until a new line character is read. * NOTE: This method should be used in favor of BufferedReader.readLine(...) as BufferedReader buffers data before performing * text line tokenization. This means that BufferedReader.readLine() will block until many game frames have been received. * @param in a InputStream, nominally System.in * @return a line of text or null if end of stream. * @throws IOException */ private static String readLine(InputStream in) throws IOException { StringBuilder sb = new StringBuilder(); int readByte = in.read(); while (readByte>-1 && readByte!= '\n') { sb.append((char) readByte); readByte = in.read(); } return readByte==-1?null:sb.toString(); } } ``` [Answer] # Python, 132 + 23 + 228 + 218 + 764 + 213 = 1578 steps This follows the shortest path that goes through known empty spaces and unknown spaces to the bounding rectangle of the known world, until the cheese becomes visible. Deterministic. Run with `python SCRIPT` or `python3 SCRIPT` (tested in 2.7 and 3.5). ``` import collections, sys def neighbors(p): x, y = p return [("n", (x, y + 1)), ("e", (x + 1, y)), ("s", (x, y - 1)), ("w", (x - 1, y))] ne = sw = loc = 0, 0 maze = {loc: ' '} while True: cells = sys.stdin.readline() if cells == '0000\n': break for (dir1, loc1), cell in zip(neighbors(loc), cells): maze[loc1] = cell if cell == ' ': ne = tuple(map(max, loc1, ne)) sw = tuple(map(min, loc1, sw)) visited = {loc} queue = collections.deque() for dir1, loc1 in neighbors(loc): visited.add(loc1) queue.append((dir1, loc1, loc1)) while True: dir1, loc1, loc2 = queue.popleft() if maze.get(loc2, ' ') == ' ': if loc2 not in maze and \ (any(a >= b for a, b in zip(loc2, ne)) or any(a <= b for a, b in zip(loc2, sw))): break for dir3, loc3 in neighbors(loc2): if loc3 not in visited: visited.add(loc3) queue.append((dir1, loc1, loc3)) elif maze[loc2] == '+': break sys.stdout.write(dir1 + "\n") sys.stdout.flush() loc = loc1 ``` [Answer] # MATLAB, 210 + 23 + 394 + 270 + 1272 + 707 = 2876 steps This approach is a modification of my other [MATLAB submission](https://codegolf.stackexchange.com/a/83654/24877). (They use however the exact same controller.) In this approach, the mouse follows a possible path until it finds a dead end. Then it returns to the previous intersection, where there was a path that was not yet explored. In every step, the mouse does here however check, whether there are enclosed unexplored areas. Within these, the cheese can obviously not be (as it is always on the border). If such an area is found, it is ignored henceforth. It is deterministic. From the available paths it always chooses in the order `NESW`. As I cannot compile matlab scripts, I translated the controller to MATLAB. The "program" is now just a function that accesses global variables for in-between-step-storage. ``` function find_the_cheese_controller() clc;clear; global State; clearvars -global State; %uncomment the maze you want to test %maze=['!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!';'!O ! ! !';'!. ! !!!!!!!!!!!!!!!!!! ! !!!!!!';'!. ! ! ! !';'!. ! !!!!!!!!!!!!!!!!!!!! ! !! !';'!. !........... ! !!.+';'!. !.!!!!!!!!!.!!!!!!!!!!!!!!!.!';'!.!..! ...............!.!';'!.!.!! !!!!!!!!!!!!!!!!!!!!!.!.!';'!.!.!! !!! ! .!.!';'!.!.!! !!! !!!!!!!!!!!!!!!!.!.!';'!...!! !!! .!.!';'! ! !! !!! .!.!';'! ! !! !!! !!!!!!!!! !!!!!!.!.!';'! ! !! !!! ! !! ! .!.!';'! ! !! !!! ! !!!!!!! ! .!.!';'! ! !! !!! ! !! ! .!.!';'! ! !! !!! ! !! ! .!.!';'! ! !! ! ! !! ! .!.!';'! ! !! ! ! !!!!!! !! ! .!.!';'! ! !! ! ! ! !! ! ...!';'! ! !! ! ! ! !! ! !';'! ! !! ! ! ! !! ! ! !';'! ! !! ! ! ! !!!!!! ! ! !';'! ! !! ! ! ! !! ! ! !';'! ! ! ! !! ! ! !';'! !!!!!! !!!!!!!! !! ! ! !';'! ! !! ! ! !';'! !!!!!!!!!!! !!!! !! ! ! !';'! ! ! !';'! !!!!!!!! !!!! ! !';'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!']; %maze=['!!!!!!!!!!!!!!!';'! .......!';'! !!! !.!!!! .!';'! ! !.!!O!!.!';'!!! !....! .!';'! !!!!!!!!!.!';'! !! ..!';'! !!!!!!!!!.!!';'! ..+';'!!!!!!!!!!!!!!!']; %maze=['!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!';'! !!!';'! ! !!! !!!!!!!!!!!!!!!!!! !';'! ! ! !!! !!! ! !';'! ! ! !!!!!!!!!!!!!!!! !! !';'! ! ! !!!! !';'! !! !!!!!!!!!! !! ! !';'! ! ! !!!! !!!!! !!! !';'!! ! ! !!!! ! ! !';'!! ! ! !!!! !!!!!!!!!!!!!! ! !';'!! ! ! !!!! ! ! ! !';'!! ! ! !!!! ! ! !!!! ! ! !';'!! ! ! !!!! ! ! ! !!! ! ! !';'! ! ! !!!! ! ! ! !!! ! ! !';'! ! ! !!!! ! ! !!!!! ! !';'! ! ! !!!! !!! ! !! ! !!!';'! ! ! !!! !! ! !!! ! !!!';'! ! ! ! !! !!!! !! ! !!!';'! ! !! ! !! ! !! ! !!!';'! ! ! !! !! !!! ! !!!';'! !! !!!! !!! !! ! !';'!! ! !! ! !!! !! !!! !';'!! ! ! ! ! !';'!! !!!!!! !! !!!!!!!!!!! !';'! !!!! !!!!!!!!!!! !';'! ..........O!!!! !!!!!!!!!!!.+';'!! .!!!!!! !! !!!!!!!!!!!.!';'!! .! ! ! ! .!';'!!..! !! ! !!! !! !!!.!';'! .!! !!!! !!! !! !...!';'! .! ! !! !! !!! !.!!!';'! .! !! ! !! ! !! !.!!!';'! .! ! ! !! !!!! !! !.!!!';'! .! ! !!! !! ! !!! !.!!!';'! .! ! !!!! !!! ! !! !.!!!';'! .! ! !!!! ! ! !!!!! !...!';'! .! ! !!!! ! ! ! !!! ! !.!';'!!.! ! !!!! ! ! ! !!! ! !.!';'!!.! ! !!!! ! ! !!!! ! !.!';'!!.! ! !!!! ! ! !.!';'!!.! ! !!!! !!!!!!!!!!!!!! !.!';'!!.! ! !!!! ! ! .!';'!..! ! !!!! !!!!! !!!.!';'!.!! !!!!!!!!!! !! !.!';'!.! ! !!!! .!';'!.! ! !!!!!!!!!!!!!!!! !!.!';'!.! ! !!! !!! !.!';'!.! !!! !!!!!!!!!!!!!!!!!!...!';'!............................!!!';'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!']; %maze=['!!!!!!!!!!!!!!!!!+!!!!!!!!!!!!!!';'!................. !!!';'!.! !!! !!!!!!!!!!!!!!!!!! !';'!.! ! !!! !!! ! !';'!.! ! !!!!!!!!!!!!!!!! !! !';'!.! ! !!!! !';'!.!! !!!!!!!!!! !! ! !';'!..! ! !!!! !!!!! !!! !';'!!.! ! !!!! ! ! !';'!!.! ! !!!! !!!!!!!!!!!!!! ! !';'!!.! ! !!!! ! ! ! !';'!!.! ! !!!! ! ! !!!! ! ! !';'!!.! ! !!!! ! ! ! !!! ! ! !';'! .! ! !!!! ! ! ! !!! ! ! !';'! .! ! !!!! ! ! !!!!! ! !';'! .! ! !!!! !!! ! !! ! !!!';'! .! ! !!! !! ! !!! ! !!!';'! .! ! ! !! !!!! !! ! !!!';'! .! !! ! !! ! !! ! !!!';'! .! ! !! !! !!! ! !!!';'! .!! !!!! !!! !! ! !';'!!. ! !! ! !!! !! !!! !';'!!. ! ! ! ! !';'!!. !!!!!! !! !!!!!!!!!!! !';'! ........... !!!! !!!!!!!!!!! !';'! . !!!! !!!!!!!!!!! !';'!! !!!!!! . !! !!!!!!!!!!! !';'!! ! ! . ! ! !';'!! ! !! ! . !!! !! !!! !';'! !! !!!! . !!! !! ! !';'! ! ! !!.!! !!! ! !!!';'! ! !! !.!! ! !! ! !!!';'! ! ! !.!! !!!! !! ! !!!';'! ! ! !!!..!! ! !!! ! !!!';'! ! ! !!!!.!!! ! !! ! !!!';'! ! ! !!!!.! ! !!!!! ! !';'! ! ! !!!!.! ! ! !!! ! ! !';'!! ! ! !!!!.! ! ! !!! ! ! !';'!! ! ! !!!!.! ! !!!! ! ! !';'!! ! ! !!!!.! ! ! !';'!! ! ! !!!!. !!!!!!!!!!!!!! ! !';'!! ! ! !!!!.....O! ! !';'! ! ! !!!! !!!!! !!! !';'! !! !!!!!!!!!! !! ! !';'! ! ! !!!! !';'! ! ! !!!!!!!!!!!!!!!! !! !';'! ! ! !!! !!! ! !';'! ! !!! !!!!!!!!!!!!!!!!!! !';'! !!!';'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!']; %maze=['!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!';'+......!!!! !!! !!! !!!! !!';'! .! !! !!!!!';'! !!!.! !! !!! !!!! !!!!!!!!! !!! !';'! !!...! !!!!! !! ! !! !! !';'!!!..!! ! !! ! ! ! !!';'!! .!!........ !! !!! ! ! ! ! !!';'!!!. !. ! !. ! !!!!! !! ! ! !! !!!';'!!!. !. ! !. ! !!!!! ! !! ! !!!';'!!.. !. ! !.. ! ! ! !! ! ! !!';'!!.! !.! ! ! .. ! !!!!!! ! ! ! ! !!';'!!.! !.! ! !! . ! ! ! ! ! ! !!';'!!.! !.! ! ! . ! !! !! !!!! ! ! ! !!';'!!.! !.!! ! ! . ! !!! !!!! ! ! !! !!';'!!.! !. ! ! ! . ! !! ! ! ! ! !!';'! .!!!. ! ! !!. ! ! ! ! ! ! !';'! .!!!. ! ! !. ! ! ! ! ! ! !';'! .! !. ! ! !. ! ! ! ! ! ! !';'! .! !. ! !! !....!!! ! !! ! ! ! !';'! .! ..! ! ! ...!!!! ! ! ! ! ! !';'! .! .! ! !!!!!!.... !!!!!!! ! ! !';'! .! !!.! !! ! !!!! .! !';'! .!!!!.! !!!! !!! .! !!!!! !!!!!!!!!!! !';'! .. !!.! !!! !! !.!! !';'!!!.. !. ! !!! !..! !!! ! ! !';'!!! .... ! !!!! ! .! ! !!';'!!!!!!!!!!!!!!!!!!!!!!! .! !!!!!!!!!!!!!!!!!!!! !!';'!!! ! .! !!!';'!! ! !!! !! .! !!';'!! ! ! !! !!!!!!.! !!!!!! !!';'!! ! ! !! !!!!!!.! !!!!!!!! ! !!';'!! ! ! !! !!!!!!!.! !!!!!! !! ! ! !!';'!! ! ! ! !!!!!!!!.! !!! ! ! ! !!';'!! ! ! ! !!!!!!!!!.! !!!! ! ! ! ! ! !!';'!! ! ! ! .! !! ! ! ! ! !!';'!! !!! ! ! !!!!!! .! ! !! !!';'!! ! ! ! ! ! !!. ! !!! ! ! !!';'!! ! ! ! ! ! ! . ! ! !! ! ! !!';'!! ! ! ! ! ! !! !!. !!! !! ! ! ! !!';'!! ! ! ! !! ! !!! ! ..... !! ! ! !!';'!! ! ! ! ! ! !!!!!!! . ! ! !!';'! ! ! ! ! ! !!! ! .!!!! ! ! !';'! ! ! ! !! ! ! .! !!.......... !';'! !! ! ! ! !!!!!!!!! .! !! .! !!!!. !';'! ! ! ! !! !!! .!!!!! .. ! . !';'! ! ! !! !!! !!! .......... !!!! . !';'! ! ! !! !!!! !!!!!!!!!!!! !. !';'! ! ! !!!!!! O. !';'! ! !';'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!']; %maze=['!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!';'! !!!! ....!!! !!! !!!! !!';'! ! .!!.......... !!!!!';'! !!! ! !! ...!!! !!!!. !!!!!!!!! !!! !';'! !! ! !!!!!.. !! !. !! !! !';'!!! !! !. !! !..... ! ! !!';'!! !! .. !! !!! . ! ! ! ! !!';'!!! ! ! ! .! !!!!! . !! ! ! !! !!!';'!!! ! ! ! .! !!!!!. ! !! ! !!!';'!! ! ! ! .! ! !. !! ! ! !!';'!! ! ! ! ! ! . ! !!!!!! ! .. ! ! ! !!';'!! ! ! ! ! !! . ! ! ! .....! ! ! !!';'!! ! ! ! ! ! . ! !! !! !!!!.! ! ! !!';'!! ! ! !! ! ! ..! !!! !!!! .! ! !! !!';'!! ! ! ! ! ! .! !! ! .! ! ! !!';'! !!! ! ! !! . ! ! ! .! ! ! !';'! !!! ! ! ! ..! ! ! . ! ! ! !';'! ! ! ! ! ! .! ! ! . ! ! ! !';'! ! ! ! !! ! .!!! ! !! . ! ! ! !';'! ! ! ! ! ...!!!! ! . ! ! ! ! !';'! ! ! ! !!!!!!.... !!!!!!! . ! ! !';'! ! !! ! !! ! !!!! .! . !';'! !!!! ! !!!! !!! .! !!!!! .!!!!!!!!!!! !';'! !! ! !!! !! !.!!.......... !';'!!! ! ! !!! !. !. !!! ! ! !';'!!! ! !!!! !. !. ! !!';'!!!!!!!!!!!!!!!!!!!!!!!. !.!!!!!!!!!!!!!!!!!!!! !!';'!!! ! . !.....................!!!';'!! ! !!! !! O..... ! ..!!';'!! ! ! !! !!!!!! ! !!!!!! .!!';'!! ! ! !! !!!!!! ! !!!!!!!! ! .!!';'!! ! ! !! !!!!!!! ! !!!!!! !! ! ! .!!';'!! ! ! ! !!!!!!!! ! !!! ! ! ! .!!';'!! ! ! ! !!!!!!!!! ! !!!! ! ! ! ! ! .!!';'!! ! ! ! ! !! ! ! ! ! .!!';'!! !!! ! ! !!!!!! ! ! !! .!!';'!! ! ! ! ! ! !! ! !!! ! ! .!!';'!! ! ! ! ! ! ! ! ! !! ! ! .!!';'!! ! ! ! ! ! !! !! !!! !! ! ! ! .!!';'!! ! ! ! !! ! !!! ! !! ! !.!!';'!! ! ! ! ! ! !!!!!!! ! ! .!!';'! ! ! ! ! ! !!! ! !!!! ! ! . !';'! ! ! ! !! ! ! ! !! . !';'! !! ! ! ! !!!!!!!!! ! !! ! !!!!. !';'! ! ! ! !! !!! !!!!! ! . !';'! ! ! !! !!! !!! ! !!!! . !';'! ! ! !! !!!! !!!!!!!!!!!! !..+';'! ! ! !!!!!! !';'! ! ! !';'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'] %replace dot with space maze(maze=='.')=' '; %position of mouse [u,v]=find(maze=='O'); maze(maze=='O') = ' '; step_counter = 0; while true; %game loop %test if mouse found cheese if maze(u,v) == '+'; disp(['mouse found cheese after ', num2str(step_counter), ' steps']); break; end %extract NESW tiles nesw = [maze(u-1,v),maze(u,v+1),maze(u+1,v),maze(u,v-1)]; %get result and move accordingly answer = find_the_cheese(nesw); switch answer; case 'n'; u = u-1; case 'e'; v = v+1; case 's'; u = u+1; otherwise; v = v-1; end %make sure, mouse did not run into wall assert(maze(u,v) ~= '!','mouse ran into wall!'); step_counter = step_counter + 1; end end function step = find_the_cheese(nesw) global State; NESW = 'nesw'; NESW_REVERSE = 'swne'; if all(nesw == '0000'); return; elseif ~isfield(State,'maze'); State = struct('maze', zeros(140)+' ','u',75,'v',75,'state','E'); State.maze(State.u,State.v) = 'S'; end if State.maze(State.u-1,State.v) == ' ' State.maze(State.u-1,State.v) = nesw(1); end if State.maze(State.u,State.v+1) == ' ' State.maze(State.u,State.v+1) = nesw(2); end if State.maze(State.u+1,State.v) == ' ' State.maze(State.u+1,State.v) = nesw(3); end if State.maze(State.u,State.v-1) == ' ' State.maze(State.u,State.v-1) = nesw(4); end current_nesw = [State.maze(State.u-1,State.v),State.maze(State.u,State.v+1),State.maze(State.u+1,State.v),State.maze(State.u,State.v-1)]; if any(current_nesw == '+'); % if there is cheese, go there nesw_index = find(current_nesw == '+',1); elseif any(current_nesw == ' '); % if there is a path that we did not walk, go there nesw_index = find(current_nesw == ' ',1); State.state = 'E'; else % return to previous crossing nesw_index = find(NESW == State.maze(State.u,State.v),1); assert(numel(nesw_index)>0,'not enough indices') State.state = 'R'; end %execute the step if State.state == 'E'; step = NESW(nesw_index); else %State.state = 'R' step = State.maze(State.u, State.v); end switch step; case 'n'; State.u = State.u-1; case 'e'; State.v = State.v+1; case 's'; State.u = State.u+1; otherwise; State.v = State.v-1; end if State.maze(State.u,State.v) == ' '; %if we do not have a reverse poniter yet State.maze(State.u,State.v) = NESW_REVERSE(nesw_index); %reverse pointer end %check whether we have any enclosed areas, where the cheese obviously cannot be M = imfill(State.maze ~= ' ','holes'); %fill those areas with walls State.maze(M & State.maze == ' ') = '!'; %disp_important(State.maze); %uncomment for display end function disp_important(m) %just show the important stuff of the maze if any(m(:) ~= ' '); for k=1:4 m = rot90(m); while all(m(:,1) == ' '); m = m(:,2:end); end end end if numel(m) == 0; m = 'X'; end m = padarray(m,[1,1],35,'both'); disp([m,'']); end ``` [Answer] # Python 3, 156 bytes, 37692 + 715 + 50626 + 27806 + 148596 + 172675 = 438110 steps This isnโ€™t [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), but golf is fun anyway. This steps to the cheese or takes the least traveled outgoing path, similar to [mbomb007โ€™s (not fully implemented) idea](https://codegolf.stackexchange.com/questions/83585/find-the-cheese/83615), but with ties broken by going to the alphabetically latest direction name. Deterministic. Run with `python3 SCRIPT` (tested in 3.5). ``` x=y=0 f={} for l in iter(input,'0000'):c,d,x,y=p=max((f.setdefault(p,0),p)for p in zip(l,'nesw',[x,x+1,x,x-1],[y+1,y,y-1,y])if'!'!=p[0])[1];print(d);f[p]-=1 ``` [Answer] # PHP 362 + 37 + 1638 + 1508 + 6696 + 1613 = 11854 steps Ran benchmark on bug-fixed code: ``` <?php class Maze { public $map, $pos; public $prevPos = FALSE; public $intersections = []; public $n = 75, $e = 75, $w = 75, $s = 75; public function __construct() { // since we don't know where we start, build a 150x150 map and position ourselves at the middle $this->map = array_pad([], 150, array_pad([], 150, 0)); // 0 is unknown $this->pos = ['x'=> 75, 'y'=> 75]; } public function play($input){ $this->updateMap($input); $this->move(); } private function updateField($x, $y, $inData) { if ($inData == '!' || $this->map[$x][$y] >= 1000) { // avoid overwriting our observations $this->map[$x][$y] = 1000; return; } // update our known borders if ($x <= $this->w) { $this->w = $x - 1; } elseif ($x >= $this->e) { $this->e = $x + 1; } elseif ($y <= $this->n) { $this->n = $y - 1; } elseif ($y >= $this->s) { $this->s = $y + 1; } if (!$this->map[$x][$y]) { $this->map[$x][$y] = $inData == '+' ? -1 : 1; } } private function checkForIntersection($input) { if (array_key_exists('x' . $this->pos['x'] . 'y' . $this->pos['y'], $this->intersections)) { if ($this->intersections['x' . $this->pos['x'] . 'y' . $this->pos['y']] > 0) { $this->intersections['x' . $this->pos['x'] . 'y' . $this->pos['y']] --; return TRUE; // intersection already crossed } } elseif ($c = substr_count($input, ' ') > 2) { $this->intersections['x' . $this->pos['x'] . 'y' . $this->pos['y']] = $c - 1; } return FALSE; } private function updateMap($input) { if ($this->checkForIntersection($input)) { // if we're at a known intersection, we know that the path we come from lead nowhere $this->updateField($this->prevPos['x'], $this->prevPos['y'], '!'); } // update discovered information $this->updateField($this->pos['x'], $this->pos['y'] - 1, $input[0]); $this->updateField($this->pos['x'] + 1, $this->pos['y'], $input[1]); $this->updateField($this->pos['x'], $this->pos['y'] + 1, $input[2]); $this->updateField($this->pos['x'] - 1, $this->pos['y'], $input[3]); } private function move() { if ($this->prevPos) { $this->map[$this->prevPos['x']][$this->prevPos['y']] ++; // count times stepped on } $best = ['w' => 1000]; foreach ([ ['x' => $this->pos['x'], 'y' => $this->pos['y'] - 1, 'w' => $this->map[$this->pos['x']][$this->pos['y'] - 1], 'd' => 'n'], ['x' => $this->pos['x'] + 1, 'y' => $this->pos['y'], 'w' => $this->map[$this->pos['x'] + 1][$this->pos['y']], 'd' => 'e'], ['x' => $this->pos['x'], 'y' => $this->pos['y'] + 1, 'w' => $this->map[$this->pos['x']][$this->pos['y'] + 1], 'd' => 's'], ['x' => $this->pos['x'] - 1, 'y' => $this->pos['y'], 'w' => $this->map[$this->pos['x'] - 1][$this->pos['y']], 'd' => 'w']] as $direction) { if ($direction['w'] < $best['w'] || ($direction['w'] == $best['w'] && $best['w'] < 1000 && max($this->e - $direction['x'], $direction['x'] - $this->w, $direction['y'] - $this->n, $this->s - $direction['y']) > max($best['x'] - $this->e, $this->w - $best['x'], $best['y'] - $this->n, $this->s - $best['y']))) { // encourage searching for borders which will later allow to block certain dead end paths without walking them // testing with middle search instead $best = $direction; } } echo $best['d'] . "\n"; $this->prevPos = $this->pos; $this->pos = $best; } } $maze = new Maze(); while (strncmp(($input = fgets(STDIN)), '0000', 4)) { $len = strlen($input); if (($len > 6) || $len < 3) { continue; } $maze->play($input); } ``` [Answer] # MATLAB, 212 + 23 + 416 + 300 + 1806 + 757 = 3514 steps In this approach, the mouse follows a possible path until it finds a dead end. Then it returns to the previous intersection, where there was a path that was not yet explored. It is deterministic. From the available paths it always chooses in the order `NESW` (not `NSFW`, as I was always tempted to write =) As I cannot compile matlab scripts, I translated the controller to MATLAB. The "program" is now just a function that accesses global variables for in-between-step-storage. ``` function find_the_cheese_controller() clc;clear; global State; clearvars -global State; %uncomment the maze you want to test %maze=['!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!';'!O ! ! !';'!. ! !!!!!!!!!!!!!!!!!! ! !!!!!!';'!. ! ! ! !';'!. ! !!!!!!!!!!!!!!!!!!!! ! !! !';'!. !........... ! !!.+';'!. !.!!!!!!!!!.!!!!!!!!!!!!!!!.!';'!.!..! ...............!.!';'!.!.!! !!!!!!!!!!!!!!!!!!!!!.!.!';'!.!.!! !!! ! .!.!';'!.!.!! !!! !!!!!!!!!!!!!!!!.!.!';'!...!! !!! .!.!';'! ! !! !!! .!.!';'! ! !! !!! !!!!!!!!! !!!!!!.!.!';'! ! !! !!! ! !! ! .!.!';'! ! !! !!! ! !!!!!!! ! .!.!';'! ! !! !!! ! !! ! .!.!';'! ! !! !!! ! !! ! .!.!';'! ! !! ! ! !! ! .!.!';'! ! !! ! ! !!!!!! !! ! .!.!';'! ! !! ! ! ! !! ! ...!';'! ! !! ! ! ! !! ! !';'! ! !! ! ! ! !! ! ! !';'! ! !! ! ! ! !!!!!! ! ! !';'! ! !! ! ! ! !! ! ! !';'! ! ! ! !! ! ! !';'! !!!!!! !!!!!!!! !! ! ! !';'! ! !! ! ! !';'! !!!!!!!!!!! !!!! !! ! ! !';'! ! ! !';'! !!!!!!!! !!!! ! !';'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!']; %maze=['!!!!!!!!!!!!!!!';'! .......!';'! !!! !.!!!! .!';'! ! !.!!O!!.!';'!!! !....! .!';'! !!!!!!!!!.!';'! !! ..!';'! !!!!!!!!!.!!';'! ..+';'!!!!!!!!!!!!!!!']; %maze=['!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!';'! !!!';'! ! !!! !!!!!!!!!!!!!!!!!! !';'! ! ! !!! !!! ! !';'! ! ! !!!!!!!!!!!!!!!! !! !';'! ! ! !!!! !';'! !! !!!!!!!!!! !! ! !';'! ! ! !!!! !!!!! !!! !';'!! ! ! !!!! ! ! !';'!! ! ! !!!! !!!!!!!!!!!!!! ! !';'!! ! ! !!!! ! ! ! !';'!! ! ! !!!! ! ! !!!! ! ! !';'!! ! ! !!!! ! ! ! !!! ! ! !';'! ! ! !!!! ! ! ! !!! ! ! !';'! ! ! !!!! ! ! !!!!! ! !';'! ! ! !!!! !!! ! !! ! !!!';'! ! ! !!! !! ! !!! ! !!!';'! ! ! ! !! !!!! !! ! !!!';'! ! !! ! !! ! !! ! !!!';'! ! ! !! !! !!! ! !!!';'! !! !!!! !!! !! ! !';'!! ! !! ! !!! !! !!! !';'!! ! ! ! ! !';'!! !!!!!! !! !!!!!!!!!!! !';'! !!!! !!!!!!!!!!! !';'! ..........O!!!! !!!!!!!!!!!.+';'!! .!!!!!! !! !!!!!!!!!!!.!';'!! .! ! ! ! .!';'!!..! !! ! !!! !! !!!.!';'! .!! !!!! !!! !! !...!';'! .! ! !! !! !!! !.!!!';'! .! !! ! !! ! !! !.!!!';'! .! ! ! !! !!!! !! !.!!!';'! .! ! !!! !! ! !!! !.!!!';'! .! ! !!!! !!! ! !! !.!!!';'! .! ! !!!! ! ! !!!!! !...!';'! .! ! !!!! ! ! ! !!! ! !.!';'!!.! ! !!!! ! ! ! !!! ! !.!';'!!.! ! !!!! ! ! !!!! ! !.!';'!!.! ! !!!! ! ! !.!';'!!.! ! !!!! !!!!!!!!!!!!!! !.!';'!!.! ! !!!! ! ! .!';'!..! ! !!!! !!!!! !!!.!';'!.!! !!!!!!!!!! !! !.!';'!.! ! !!!! .!';'!.! ! !!!!!!!!!!!!!!!! !!.!';'!.! ! !!! !!! !.!';'!.! !!! !!!!!!!!!!!!!!!!!!...!';'!............................!!!';'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!']; %maze=['!!!!!!!!!!!!!!!!!+!!!!!!!!!!!!!!';'!................. !!!';'!.! !!! !!!!!!!!!!!!!!!!!! !';'!.! ! !!! !!! ! !';'!.! ! !!!!!!!!!!!!!!!! !! !';'!.! ! !!!! !';'!.!! !!!!!!!!!! !! ! !';'!..! ! !!!! !!!!! !!! !';'!!.! ! !!!! ! ! !';'!!.! ! !!!! !!!!!!!!!!!!!! ! !';'!!.! ! !!!! ! ! ! !';'!!.! ! !!!! ! ! !!!! ! ! !';'!!.! ! !!!! ! ! ! !!! ! ! !';'! .! ! !!!! ! ! ! !!! ! ! !';'! .! ! !!!! ! ! !!!!! ! !';'! .! ! !!!! !!! ! !! ! !!!';'! .! ! !!! !! ! !!! ! !!!';'! .! ! ! !! !!!! !! ! !!!';'! .! !! ! !! ! !! ! !!!';'! .! ! !! !! !!! ! !!!';'! .!! !!!! !!! !! ! !';'!!. ! !! ! !!! !! !!! !';'!!. ! ! ! ! !';'!!. !!!!!! !! !!!!!!!!!!! !';'! ........... !!!! !!!!!!!!!!! !';'! . !!!! !!!!!!!!!!! !';'!! !!!!!! . !! !!!!!!!!!!! !';'!! ! ! . ! ! !';'!! ! !! ! . !!! !! !!! !';'! !! !!!! . !!! !! ! !';'! ! ! !!.!! !!! ! !!!';'! ! !! !.!! ! !! ! !!!';'! ! ! !.!! !!!! !! ! !!!';'! ! ! !!!..!! ! !!! ! !!!';'! ! ! !!!!.!!! ! !! ! !!!';'! ! ! !!!!.! ! !!!!! ! !';'! ! ! !!!!.! ! ! !!! ! ! !';'!! ! ! !!!!.! ! ! !!! ! ! !';'!! ! ! !!!!.! ! !!!! ! ! !';'!! ! ! !!!!.! ! ! !';'!! ! ! !!!!. !!!!!!!!!!!!!! ! !';'!! ! ! !!!!.....O! ! !';'! ! ! !!!! !!!!! !!! !';'! !! !!!!!!!!!! !! ! !';'! ! ! !!!! !';'! ! ! !!!!!!!!!!!!!!!! !! !';'! ! ! !!! !!! ! !';'! ! !!! !!!!!!!!!!!!!!!!!! !';'! !!!';'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!']; %maze=['!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!';'+......!!!! !!! !!! !!!! !!';'! .! !! !!!!!';'! !!!.! !! !!! !!!! !!!!!!!!! !!! !';'! !!...! !!!!! !! ! !! !! !';'!!!..!! ! !! ! ! ! !!';'!! .!!........ !! !!! ! ! ! ! !!';'!!!. !. ! !. ! !!!!! !! ! ! !! !!!';'!!!. !. ! !. ! !!!!! ! !! ! !!!';'!!.. !. ! !.. ! ! ! !! ! ! !!';'!!.! !.! ! ! .. ! !!!!!! ! ! ! ! !!';'!!.! !.! ! !! . ! ! ! ! ! ! !!';'!!.! !.! ! ! . ! !! !! !!!! ! ! ! !!';'!!.! !.!! ! ! . ! !!! !!!! ! ! !! !!';'!!.! !. ! ! ! . ! !! ! ! ! ! !!';'! .!!!. ! ! !!. ! ! ! ! ! ! !';'! .!!!. ! ! !. ! ! ! ! ! ! !';'! .! !. ! ! !. ! ! ! ! ! ! !';'! .! !. ! !! !....!!! ! !! ! ! ! !';'! .! ..! ! ! ...!!!! ! ! ! ! ! !';'! .! .! ! !!!!!!.... !!!!!!! ! ! !';'! .! !!.! !! ! !!!! .! !';'! .!!!!.! !!!! !!! .! !!!!! !!!!!!!!!!! !';'! .. !!.! !!! !! !.!! !';'!!!.. !. ! !!! !..! !!! ! ! !';'!!! .... ! !!!! ! .! ! !!';'!!!!!!!!!!!!!!!!!!!!!!! .! !!!!!!!!!!!!!!!!!!!! !!';'!!! ! .! !!!';'!! ! !!! !! .! !!';'!! ! ! !! !!!!!!.! !!!!!! !!';'!! ! ! !! !!!!!!.! !!!!!!!! ! !!';'!! ! ! !! !!!!!!!.! !!!!!! !! ! ! !!';'!! ! ! ! !!!!!!!!.! !!! ! ! ! !!';'!! ! ! ! !!!!!!!!!.! !!!! ! ! ! ! ! !!';'!! ! ! ! .! !! ! ! ! ! !!';'!! !!! ! ! !!!!!! .! ! !! !!';'!! ! ! ! ! ! !!. ! !!! ! ! !!';'!! ! ! ! ! ! ! . ! ! !! ! ! !!';'!! ! ! ! ! ! !! !!. !!! !! ! ! ! !!';'!! ! ! ! !! ! !!! ! ..... !! ! ! !!';'!! ! ! ! ! ! !!!!!!! . ! ! !!';'! ! ! ! ! ! !!! ! .!!!! ! ! !';'! ! ! ! !! ! ! .! !!.......... !';'! !! ! ! ! !!!!!!!!! .! !! .! !!!!. !';'! ! ! ! !! !!! .!!!!! .. ! . !';'! ! ! !! !!! !!! .......... !!!! . !';'! ! ! !! !!!! !!!!!!!!!!!! !. !';'! ! ! !!!!!! O. !';'! ! !';'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!']; %maze=['!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!';'! !!!! ....!!! !!! !!!! !!';'! ! .!!.......... !!!!!';'! !!! ! !! ...!!! !!!!. !!!!!!!!! !!! !';'! !! ! !!!!!.. !! !. !! !! !';'!!! !! !. !! !..... ! ! !!';'!! !! .. !! !!! . ! ! ! ! !!';'!!! ! ! ! .! !!!!! . !! ! ! !! !!!';'!!! ! ! ! .! !!!!!. ! !! ! !!!';'!! ! ! ! .! ! !. !! ! ! !!';'!! ! ! ! ! ! . ! !!!!!! ! .. ! ! ! !!';'!! ! ! ! ! !! . ! ! ! .....! ! ! !!';'!! ! ! ! ! ! . ! !! !! !!!!.! ! ! !!';'!! ! ! !! ! ! ..! !!! !!!! .! ! !! !!';'!! ! ! ! ! ! .! !! ! .! ! ! !!';'! !!! ! ! !! . ! ! ! .! ! ! !';'! !!! ! ! ! ..! ! ! . ! ! ! !';'! ! ! ! ! ! .! ! ! . ! ! ! !';'! ! ! ! !! ! .!!! ! !! . ! ! ! !';'! ! ! ! ! ...!!!! ! . ! ! ! ! !';'! ! ! ! !!!!!!.... !!!!!!! . ! ! !';'! ! !! ! !! ! !!!! .! . !';'! !!!! ! !!!! !!! .! !!!!! .!!!!!!!!!!! !';'! !! ! !!! !! !.!!.......... !';'!!! ! ! !!! !. !. !!! ! ! !';'!!! ! !!!! !. !. ! !!';'!!!!!!!!!!!!!!!!!!!!!!!. !.!!!!!!!!!!!!!!!!!!!! !!';'!!! ! . !.....................!!!';'!! ! !!! !! O..... ! ..!!';'!! ! ! !! !!!!!! ! !!!!!! .!!';'!! ! ! !! !!!!!! ! !!!!!!!! ! .!!';'!! ! ! !! !!!!!!! ! !!!!!! !! ! ! .!!';'!! ! ! ! !!!!!!!! ! !!! ! ! ! .!!';'!! ! ! ! !!!!!!!!! ! !!!! ! ! ! ! ! .!!';'!! ! ! ! ! !! ! ! ! ! .!!';'!! !!! ! ! !!!!!! ! ! !! .!!';'!! ! ! ! ! ! !! ! !!! ! ! .!!';'!! ! ! ! ! ! ! ! ! !! ! ! .!!';'!! ! ! ! ! ! !! !! !!! !! ! ! ! .!!';'!! ! ! ! !! ! !!! ! !! ! !.!!';'!! ! ! ! ! ! !!!!!!! ! ! .!!';'! ! ! ! ! ! !!! ! !!!! ! ! . !';'! ! ! ! !! ! ! ! !! . !';'! !! ! ! ! !!!!!!!!! ! !! ! !!!!. !';'! ! ! ! !! !!! !!!!! ! . !';'! ! ! !! !!! !!! ! !!!! . !';'! ! ! !! !!!! !!!!!!!!!!!! !..+';'! ! ! !!!!!! !';'! ! ! !';'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'] ``` ; ``` %replace dot with space maze(maze=='.')=' '; %position of mouse [u,v]=find(maze=='O'); maze(maze=='O') = ' '; step_counter = 0; while true; %game loop %test if mouse found cheese if maze(u,v) == '+'; disp(['mouse found cheese after ', num2str(step_counter), ' steps']); break; end %extract NESW tiles nesw = [maze(u-1,v),maze(u,v+1),maze(u+1,v),maze(u,v-1)]; %get result and move accordingly answer = find_the_cheese(nesw); switch answer; case 'n'; u = u-1; case 'e'; v = v+1; case 's'; u = u+1; otherwise; v = v-1; end %make sure, mouse did not run into wall assert(maze(u,v) ~= '!','mouse ran into wall!'); step_counter = step_counter + 1; end end function step = find_the_cheese(nesw) global State; NESW = 'nesw'; NESW_REVERSE = 'swne'; if all(nesw == '0000'); return; elseif ~isfield(State,'maze'); State = struct('maze', zeros(140)+' ','u',75,'v',75,'state','E'); State.maze(State.u,State.v) = 'S'; end if State.maze(State.u-1,State.v) == ' ' State.maze(State.u-1,State.v) = nesw(1); end if State.maze(State.u,State.v+1) == ' ' State.maze(State.u,State.v+1) = nesw(2); end if State.maze(State.u+1,State.v) == ' ' State.maze(State.u+1,State.v) = nesw(3); end if State.maze(State.u,State.v-1) == ' ' State.maze(State.u,State.v-1) = nesw(4); end current_nesw = [State.maze(State.u-1,State.v),State.maze(State.u,State.v+1),State.maze(State.u+1,State.v),State.maze(State.u,State.v-1)]; if any(current_nesw == '+'); % if there is cheese, go there nesw_index = find(current_nesw == '+',1); elseif any(current_nesw == ' '); % if there is a path that we did not walk, go there nesw_index = find(current_nesw == ' ',1); State.state = 'E'; else % return to previous crossing nesw_index = find(NESW == State.maze(State.u,State.v),1); assert(numel(nesw_index)>0,'not enough indices') State.state = 'R'; end %execute the step if State.state == 'E'; step = NESW(nesw_index); else %State.state = 'R' step = State.maze(State.u, State.v); end switch step; case 'n'; State.u = State.u-1; case 'e'; State.v = State.v+1; case 's'; State.u = State.u+1; otherwise; State.v = State.v-1; end if State.maze(State.u,State.v) == ' '; %if we do not have a reverse poniter yet State.maze(State.u,State.v) = NESW_REVERSE(nesw_index); %reverse pointer end %disp_important(State.maze); %uncomment for display end function disp_important(m) %just show the important stuff of the maze if any(m(:) ~= ' '); for k=1:4 m = rot90(m); while all(m(:,1) == ' '); m = m(:,2:end); end end end if numel(m) == 0; m = 'X'; end m = padarray(m,[1,1],35,'both'); disp([m,'']); end ``` [Answer] # Simple Bot, Java 1.4+, 176 + 25 + 1118 + 486 + 10944 + 1847 = 14596 steps This bot counts and records the number of steps taken to reach each visited cell then, when deciding which direction to move, chooses the direction that has the lowest step count. In the event of a tie, chooses the direction in N,E,S,W order. I do not have rust installed so I had to implement the controller in java and this was the bot i used to test it. I will be attempting a more clever solver soon. Deterministic. Run with `java SimpleBot` ``` import java.io.IOException; import java.io.InputStream; public class SimpleBot { private static final char[] DIRECTION = {'n','e','s','w'}; public static void main(String[] args) throws Exception { int[][] stepMap = new int[100][100]; int mx=49, my=49; int[][] offsets = new int[][]{{0,-1},{1,0},{0,1},{-1,0}}; String line=readLine(System.in); int step=0; while (line!=null && !"0000".equals(line)) { stepMap[mx][my]=step++; int minStep = Integer.MAX_VALUE; int minIndex = -1; for (int i=0;i<4;i++) { if (line.charAt(i) == '+') { minIndex=i; break; } else if (line.charAt(i) == ' ') { if (stepMap[mx+offsets[i][0]][my+offsets[i][1]]<minStep) { minStep = stepMap[mx+offsets[i][0]][my+offsets[i][1]]; minIndex=i; } } } mx +=offsets[minIndex][0]; my +=offsets[minIndex][1]; System.out.println(DIRECTION[minIndex]); line=readLine(System.in); } } /** * Reads a line of text from the input stream. Blocks until a new line character is read. * NOTE: This method is used in favor of BufferedReader.readLine(...) as BufferedReader buffers data before performing * text line tokenization. This means that BufferedReader.readLine() will block until sufficient input have been received. * @param in a InputStream, nominally System.in * @return a line of text or null if end of stream. * @throws IOException */ private static String readLine(InputStream in) throws IOException { StringBuilder sb = new StringBuilder(); int readByte = in.read(); while (readByte>-1 && readByte!= '\n') { sb.append((char) readByte); readByte = in.read(); } return readByte==-1?null:sb.toString(); } } ``` ]
[Question] [ Math has a lot of symbols. Some might say too many symbols. So lets do some math with pictures. Lets have a paper, which we will draw on. To start the paper is empty, we will say that is equivalent to \$\top\$ or \$\textit{true}\$. If we write other things on the paper they will also be true. For example [![P and Q](https://i.stack.imgur.com/d6UrV.png)](https://i.stack.imgur.com/d6UrV.png) Indicates that the claims \$P\$ and \$Q\$ are true. Now let us say that if we draw a circle around some statement that statement is false. This represents logical not. For example: [![not P and Q](https://i.stack.imgur.com/D3EmF.png)](https://i.stack.imgur.com/D3EmF.png) Indicates that \$P\$ is false and \$Q\$ is true. We can even place the circle around multiple sub-statements: [![not (P and Q)](https://i.stack.imgur.com/F7RgN.png)](https://i.stack.imgur.com/F7RgN.png) Since the part inside the circle normally reads as \$P\text{ and }Q\$ by putting a circle around it it means \$\text{not }(P\text{ and }Q)\$. We can even nest circles [![not (not P and Q)](https://i.stack.imgur.com/Cct9N.png)](https://i.stack.imgur.com/Cct9N.png) This reads as \$\text{not }((\text{not }P)\text{ and }Q)\$. If we draw a circle with nothing in it, that represents \$\bot\$ or \$\textit{false}\$. [![False](https://i.stack.imgur.com/9YRJ1.png)](https://i.stack.imgur.com/9YRJ1.png) Since empty space was true, then the negation of true is false. Now using this simple visual method we can actually represent any statement in propositional logic. # Proofs The next step after being able to represent statements is being able to prove them. For proofs we have 4 different rules that can be used to transform a graph. We always start with an empty sheet which as we know is a vacuous truth and then use these different rules to transform our empty sheet of paper into a theorem. Our first inference rule is *Insertion*. ### Insertion We will call the number of negations between a sub-graph and the top level it's "depth". *Insertion* allows us to introduce any statement we wish at an odd depth. Here is an example of us performing insertion: [![Insertion Example](https://i.stack.imgur.com/NNNzs.png)](https://i.stack.imgur.com/NNNzs.png) Here we chose \$P\$, but we could just as well choose any statement we wanted. ### Erasure The next inference rule is *Erasure*. *Erasure* tells us that if we have a statement that is at a even depth we can remove it entirely. Here is an example of erasure being applied: [![Erasure example](https://i.stack.imgur.com/xZwt3.png)](https://i.stack.imgur.com/xZwt3.png) Here we erased the \$Q\$, because it was \$2\$ levels nested. Even if we wanted to we could not have erased \$P\$ because it is \$1\$ level nested. ### Double Cut *Double Cut* is an equivalence. Which means, unlike the previous inferences it can also be reversed. *Double Cut* tells us that we can draw two circles around any sub-graph, and if there are two circles around a sub-graph we can remove them both. Here is an example of the *Double Cut* being used [![Double Cut example](https://i.stack.imgur.com/eouBJ.png)](https://i.stack.imgur.com/eouBJ.png) Here we use *Double Cut* on \$Q\$. ### Iteration *Iteration* is a equivalence as well.1 It's reverse is called *Deiteration* If we have a statement and a cut on the same level, we can copy that statement inside of a cut. For example: [![Iteration example](https://i.stack.imgur.com/5PgO9.png)](https://i.stack.imgur.com/5PgO9.png) *Deiteration* allows us to reverse an *Iteration*. A statement can be removed via *Deiteration* if there exists a copy of it at the next level up. --- This format of representation and proof is not of my own invention. They are a minor modification of a diagrammatic logic are called [Alpha Existential Graphs](https://en.wikipedia.org/wiki/Existential_graph). If you want to read more on this, there is not a ton of literature, but the linked article is a good start. --- # Task Your task will be to prove the following theorem: [![ลukasiewicz - Tarksi Axiom](https://i.stack.imgur.com/d3Pyh.png)](https://i.stack.imgur.com/d3Pyh.png) This, when translated into traditional logic symbolization is \$((A\to(B\to A))\to(((\neg C\to(D\to\neg E))\to((C\to(D\to F))\to((E\to D)\to(E\to F))))\to G))\to(H\to G)\$. Also known as the [ลukasiewicz-Tarski Axiom](https://en.wikipedia.org/wiki/List_of_Hilbert_systems#Implication_and_negation). It may seem involved but existential graphs are *very* efficient when it comes to proof length. I selected this theorem because I do think it is an appropriate length for a fun and challenging puzzle. If you are having trouble with this one I would recommend trying some more basic theorems first to get the hang of the system. A list of these can be found at the bottom of the post. This is [proof-golf](/questions/tagged/proof-golf "show questions tagged 'proof-golf'") so your score will be the total number of steps in your proof from start to finish. The goal is to minimize your score. # Format The format for this challenge is flexible you can submit answers in any format that is clearly readable, including hand-drawn or rendered formats. However for clarity I suggest the following simple format: * We represent a cut with parentheses, whatever we are cutting is put inside of the parens. The empty cut would just be `()` for example. * We represent atoms with just their letters. As an example here is the goal statement in this format: ``` (((A((B(A))))(((((C)((D((E)))))(((C((D(F))))(((E(D))((E(F))))))))(G))))((H(G)))) ``` This format is nice because it is both human and machine readable, so including it in your post would be nice. If you want some nice(ish) diagrams here is some code that converts this format to \$\LaTeX\$: [Try it online!](https://tio.run/##jZJRT8IwEMff9ykuC8naTAhq4sMMJvrmsz6YUGJqV0fD1pGtCGHhs89rN8YQVLa0D9f7/@5/7c15uZBpWtexFCpTWwlRBM/ayEQWMHyAF1MonXjd6QYmoLQyQMp5voYNhTCEaTAKriDlpYEBNPGZ58UFX1vatMXNLO8E3S9iBaXhYgGF5PEcF5CABBBBQO0u8lhSNOAzZnOJb4t31kgnCuHW@fKvxlSoQqSSjK7pPdON4FCmL7mjjg9/2dgbcCl98U3kBPQ42BAbIDH5EgltWg/c78z7rbVYfTWEsJNSy3dNQtflOVVXaggI6FT/XceR@Z@3wU2eXeD6zIOgV42qauBSW44/2F32OI2bd/ynMzsHvud9rtL0Vb7ZQTsZqP1Z2c5MLlaZ1EbgpJYVFtExT3Mtd0wztirlEqvyRFZGLbYu9iETpau9zIXsWXVwijbGiLet7RiTOj5ko7eMKz1ROPEFFwZaN3VN8KP0ERd5ovQb "Haskell โ€“ Try It Online") As for your actual work I recommend pencil and paper when working out. I find that text just isn't as intuitive as paper when it comes to existential graphs. # Example proof In this example proof we will prove the following theorem: [![Law of contra-positives](https://i.stack.imgur.com/u1jdT.png)](https://i.stack.imgur.com/u1jdT.png) Now this may seem alien to you at first but if we translate this into traditional logic notation we get \$(A\rightarrow B)\rightarrow(\neg B\rightarrow \neg A)\$, also known as the law of contra-positives. **Proof:** [![Example Proof 1](https://i.stack.imgur.com/lgPrY.png)](https://i.stack.imgur.com/lgPrY.png) # Practice Theorems Here are some simple theorems you can use to practice the system: ### ลukasiewicz' Second Axiom [![ลukasiewicz' Second Axiom](https://i.stack.imgur.com/9eghU.png)](https://i.stack.imgur.com/9eghU.png) ### Meredith's Axiom [![Meredith's Axiom](https://i.stack.imgur.com/3rpSS.png)](https://i.stack.imgur.com/3rpSS.png) 1: Most sources use a more sophisticated and powerful version of *Iteration*, but to keep this challenge simple I am using this version. They are functionally equivalent. [Answer] # 19 steps 1. `(())` [double cut] 2. `(AB()(((G))))` [insertion] 3. `(AB(A)(((G))))` [iteration] 4. `(((AB(A)))(((G))))` [double cut] 5. `(((AB(A))(((G))))(((G))))` [iteration] 6. `(((AB(A))(((G))))((H(G))))` [insertion] 7. `(((AB(A))(((G)(()))))((H(G))))` [double cut] 8. `(((AB(A))(((DE()(C)(F))(G))))((H(G))))` [insertion] 9. `(((AB(A))(((DE(C)(DE(C))(F))(G))))((H(G))))` [iteration] 10. `(((AB(A))(((DE(CD(F))(DE(C))(F))(G))))((H(G))))` [iteration] 11. `(((AB(A))(((E(CD(F))(DE(C))(F)((D)))(G))))((H(G))))` [double cut] 12. `(((AB(A))(((E(CD(F))(DE(C))(E(D))(F))(G))))((H(G))))` [iteration] 13. `(((AB(A))(((G)((CD(F))(DE(C))(E(D))((E(F)))))))((H(G))))` [double cut] 14. `(((AB(A))(((G)((CD(F))(DE(C))(((E(D))((E(F)))))))))((H(G))))` [double cut] 15. `(((AB(A))(((G)((C((D(F))))(DE(C))(((E(D))((E(F)))))))))((H(G))))` [double cut] 16. `(((AB(A))(((G)((DE(C))(((C((D(F))))(((E(D))((E(F)))))))))))((H(G))))` [double cut] 17. `(((AB(A))(((G)((D(C)((E)))(((C((D(F))))(((E(D))((E(F)))))))))))((H(G))))` [double cut] 18. `(((AB(A))(((G)(((C)((D((E)))))(((C((D(F))))(((E(D))((E(F)))))))))))((H(G))))` [double cut] 19. `(((A((B(A))))(((G)(((C)((D((E)))))(((C((D(F))))(((E(D))((E(F)))))))))))((H(G))))` [double cut] # Practice theorems ### ลukasiewiczโ€™ second axiom: 7 steps 1. `(())` [double cut] 2. `(A()(B)(C))` [insertion] 3. `(A(A(B))(B)(C))` [iteration] 4. `(A(AB(C))(A(B))(C))` [iteration] 5. `((AB(C))(A(B))((A(C))))` [double cut] 6. `((AB(C))(((A(B))((A(C))))))` [double cut] 7. `((A((B(C))))(((A(B))((A(C))))))` [double cut] ### Meredithโ€™s axiom: 11 steps 1. `(())` [double cut] 2. `(()(D(A)(E)))` [insertion] 3. `((D(A)(E))((D(A)(E))))` [iteration] 4. `((D(A)(E))((D(A)(E(A)))))` [iteration] 5. `((D(A)(E))(((E(A))((D(A))))))` [double cut] 6. `(((E)((D(A))))(((E(A))((D(A))))))` [double cut] 7. `(((E)((C)(D(A))))(((E(A))((D(A))))))` [insertion] 8. `(((E)((C)(D(A)(C))))(((E(A))((D(A))))))` [iteration] 9. `(((E)((C)((A)(C)((D)))))(((E(A))((D(A))))))` [double cut] 10. `(((E)((C)((A)(((C)((D)))))))(((E(A))((D(A))))))` [double cut] 11. `(((E)((C)((A(B))(((C)((D)))))))(((E(A))((D(A))))))` [insertion] # Haskell proof searcher (What, you thought I was going to do that by hand? :-P) This only tries insertion, double cut introduction, and iteration. So itโ€™s still possible these solutions could be beaten using erasure, double cut elimination, or deiteration. ``` {-# LANGUAGE ViewPatterns #-} import Control.Applicative hiding (many) import Data.Char import Data.Function hiding ((&)) import qualified Data.Map as M import Data.Maybe import qualified Data.MultiSet as S import qualified Data.PQueue.Prio.Min as Q import System.IO import Text.ParserCombinators.ReadP type Var = Char data Part = Var Var | Not Conj deriving (Eq, Ord) instance Show Part where show (Var s) = [s] show (Not c) = "(" ++ show c ++ ")" newtype Conj = Conj { parts :: S.MultiSet Part } deriving (Eq, Ord) instance Show Conj where show (Conj (S.toAscList -> [])) = "" show (Conj (S.toAscList -> g:gs)) = show g ++ concat ["" ++ show g1 | g1 <- gs] true :: Conj true = Conj S.empty not_ :: Conj -> Conj not_ = Conj . S.singleton . Not (&) :: Conj -> Conj -> Conj Conj as & Conj bs = Conj (S.union as bs) intersect :: Conj -> Conj -> Conj intersect (Conj as) (Conj bs) = Conj (S.intersection as bs) diff :: Conj -> Conj -> Conj diff (Conj as) (Conj bs) = Conj (S.difference as bs) splits :: Conj -> [(Conj, Conj)] splits = S.foldOccur (\a o bcs -> [ (Conj (S.insertMany a o1 bs), Conj (S.insertMany a (o - o1) cs)) | (Conj bs, Conj cs) <- bcs , o1 <- [0 .. o] ]) [(true, true)] . parts moves :: Bool -> Conj -> [(Conj, String)] moves ev a = (do (b, c) <- splits a andMoves ev b c) ++ (do (p, _) <- S.toOccurList (parts a) partMoves ev p (Conj (S.delete p (parts a)))) andMoves :: Bool -> Conj -> Conj -> [(Conj, String)] andMoves ev a b = [(a, "insertion") | not ev] partMoves :: Bool -> Part -> Conj -> [(Conj, String)] partMoves ev (Not a) b = [(a1 & b, why) | (a1, why) <- notMoves ev a] ++ [ (not_ (diff a d) & b, "iteration") | (d, _) <- splits (intersect a b) , d /= true ] partMoves _ (Var _) _ = [] notMoves :: Bool -> Conj -> [(Conj, String)] notMoves ev a = (case S.toList (parts a) of [Not b] -> [(b, "double cut")] _ -> []) ++ [(not_ a1, why) | (a1, why) <- moves (not ev) a] partSat :: Part -> Bool -> M.Map Var Bool -> [M.Map Var Bool] partSat (Var var) b m = case M.lookup var m of Nothing -> [M.insert var b m] Just b1 -> [m | b1 == b] partSat (Not c) b m = conjSat c (not b) m conjSat :: Conj -> Bool -> M.Map Var Bool -> [M.Map Var Bool] conjSat c False m = do (p, _) <- S.toOccurList (parts c) partSat p False m conjSat c True m = S.foldOccur (\p _ -> (partSat p True =<<)) [m] (parts c) readConj :: ReadP Conj readConj = Conj . S.fromList <$> many readPart readPart :: ReadP Part readPart = Var <$> satisfy isAlphaNum <|> Not <$> (char '(' *> readConj <* char ')') parse :: String -> Maybe Conj parse s = listToMaybe [c | (c, "") <- readP_to_S readConj s] partSize :: Part -> Int partSize (Var _) = 1 partSize (Not c) = 1 + conjSize c conjSize :: Conj -> Int conjSize c = sum [partSize p * o | (p, o) <- S.toOccurList (parts c)] data Pri = Pri { dist :: Int , size :: Int } deriving (Eq, Show) instance Ord Pri where compare = compare `on` \(Pri d s) -> (s + d, d) search :: Q.MinPQueue Pri (Conj, [(Conj, String)]) -> M.Map Conj Int -> [[(Conj, String)]] search (Q.minViewWithKey -> Nothing) _ = [] search (Q.minViewWithKey -> Just ((pri, (a, proof)), q)) m = [proof | a == true] ++ uncurry search (foldr (addMove pri a proof) (q, m) (moves True a)) addMove :: Pri -> Conj -> [(Conj, String)] -> (Conj, String) -> (Q.MinPQueue Pri (Conj, [(Conj, String)]), M.Map Conj Int) -> (Q.MinPQueue Pri (Conj, [(Conj, String)]), M.Map Conj Int) addMove pri b proof (a, why) (q, m) = case M.lookup a m of Just d | d <= d1 -> (q, m) _ | null (conjSat a False M.empty) -> ( Q.insert (Pri d1 (conjSize a)) (a, (b, why) : proof) q , M.insert a d1 m) _ -> (q, m) where d1 = dist pri + 1 prove :: Conj -> [[(Conj, String)]] prove c = search (Q.singleton (Pri 0 (conjSize c)) (c, [])) (M.singleton c 0) printProof :: [(Conj, String)] -> IO () printProof proof = do mapM_ (\(i, (a, why)) -> putStrLn (show i ++ ". `" ++ show a ++ "` [" ++ why ++ "]")) (zip [1 ..] proof) putStrLn "" hFlush stdout main :: IO () main = do Just theorem <- parse <$> getLine mapM_ printProof (prove theorem) ``` [Answer] # 22 Steps \$\to\$`(((())(())))` [Double Cut x3] \$\to\$`(((AB())(CDE(F)()))H(G))` [Insertion x3] \$\to\$`(((AB(A))(CDE(F)(CD(F)))(G))H(G))` [Iteration x3] \$\to\$`(((A((B(A))))(((((C))DE(F)(C((D(F)))))(G))))((H(G))))` [Double Cut x5] \$\to\$`(((A((B(A))))(((((C)DE)DE(F)(C((D(F)))))(G))))((H(G))))` [Iteration] \$\to\$`(((A((B(A))))(((((C)((D((E)))))((((((D))E(F)))(C((D(F)))))))(G))))((H(G))))` [Double Cut x5] \$\to\$`(((A((B(A))))(((((C)((D((E)))))((((((D)E)E(F)))(C((D(F)))))))(G))))((H(G))))` [Iteration] \$\to\$`(((A((B(A))))(((((C)((D((E)))))((((((D)E)((E(F)))))(C((D(F)))))(G))))))((H(G))))` [Double Cut] --- A few things I learned from completing this puzzle: * Reduce the provided representation. This involves reversing double cuts and iterations. For example, this axiom reduces to `(((AB(A))(((C)DE)(CD(F))(E(D))(E(F)))(G))H(G))` after reversing double cuts, and `(((AB(A))(()CDE(F)))H(G)))` after reversing iterations. * Look for stray atoms. For example, H is used as a dummy variable, and thus can be inserted at any point. --- # Practice Theorem Solutions: **Solution for ลukasiewicz' Second Axiom:** [8 Steps] \$\to\$`(())` [Double Cut] \$\to\$`(()AB(C))` [Insertion] \$\to\$`((AB(C))AB(C))` [Iteration] \$\to\$`((A((B(C))))A((B))(C))` [Double Cut x2] \$\to\$`((A((B(C))))A(A(B))(C))` [Iteration] \$\to\$`((A((B(C))))(((A(B))((A(C))))))` [Double Cut x2] **Solution for Meredith's Axiom:** [12 Steps] \$\to\$`(())` [Double Cut] \$\to\$`(()(A)D(E))` [Insertion] \$\to\$`(((A)D(E))(A)D(E(A)))` [Iteration x2] \$\to\$`(((((A)D))(E))(A)D(E(A)))` [Double Cut] \$\to\$`(((((A(B))D)(C))(E))(A)D(E(A)))` [Insertion x2] \$\to\$`(((((A(B))(C)D)(C))(E))(A)D(E(A)))` [Iteration] \$\to\$`(((((A(B))(((C)((D)))))(C))(E))(((((A)D))(E(A)))))` [Double Cut x4] ]
[Question] [ ## Rectangle covers Suppose you have a matrix of bits, for example the following. ``` 1 1 0 0 0 1 1 0 1 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 1 1 0 1 1 0 1 1 1 0 1 ``` We would like to find a *rectangle cover* for this matrix. It is a set of rectangular subsets of the matrix that don't contain any 0s, but together contain all the 1s. The subsets are not required to be disjoint. Here is an example of a rectangle cover for the above matrix. ``` +----+ +----+ |1 1| 0 0 0 |1 1| 0 | | | | | +-|-----+ | |+-+ |1 |1| 1 1| 0 |1 1||1| +----+ | | || | | | | || | 0 |1 1 1| 0 |1 1||1| +-------+ | |+-+ +----+ +-----|-+ | |1 1| 0 |1 1 |1| 1| 0 | | | +----+ | | | | +-+ |1 1| 0 |1 1 1| 0 |1| +----+ +-------+ +-+ ``` The number of rectangles in this cover is 7. ## The task Your input is a rectangular matrix of bits, taken in any reasonable format. You can assume it contains at least one 1. Your output is the minimum number of rectangles in a rectangle cover of the matrix. The lowest byte count wins. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test cases ``` [[1]] -> 1 [[1,1]] -> 1 [[1],[1]] -> 1 [[1,0,1]] -> 2 [[1,0],[0,0]] -> 1 [[1,0],[0,1]] -> 2 [[1,0],[1,1]] -> 2 [[1,1,1],[1,0,1]] -> 3 [[0,1,0],[1,1,1],[0,1,0]] -> 2 [[1,1,1],[1,0,1],[1,1,1]] -> 4 [[1,1,0],[1,1,1],[0,1,1]] -> 2 [[1,0,1,0],[1,1,1,1],[1,0,1,0]] -> 3 [[1,1,1,0],[1,0,1,0],[1,1,1,1],[0,0,1,0]] -> 4 [[1,1,1,0],[1,0,1,0],[1,1,1,1],[0,0,1,1]] -> 5 [[1,1,1,0],[1,0,1,0],[1,1,1,1],[0,1,1,1]] -> 4 [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]] -> 3 [[0,1,0,0],[0,1,1,1],[1,1,1,0],[0,0,1,0]] -> 4 [[0,0,1,0,0],[0,1,1,1,0],[1,1,1,1,1],[0,1,1,1,0],[0,0,1,0,0]] -> 3 ``` [Answer] # [Python 2](https://docs.python.org/2/), 318 315 271 bytes Mr.Xcoder, ovs and Jonathan Frech saved a lot of bytes ``` p=range def f(x,i=0,j=-1):z=len(x[0]);j+=1;i+=j/z;j%=z;return i<len(x)and(x[i][j]and-~min([f([[v,v[:j]+[2]*(r-j)+v[r:]][i<=y<=e]for y,v in enumerate(x)],i,j)for e in p(i,len(x))for r in p(j+1,z+1)if all(all(k[j:r])for k in x[i:e+1])]+[f(x,i,j)-1]*(x[i][j]>1))or f(x,i,j)) ``` [Try it online!](https://tio.run/##lZLBbsIwDIbP61NESJOa1WgNsEshe4hdI2vqRrollIDSgoDDXp0laYFSNmk7tIr9f/7ttF7v68@VGR2Pa25z8yGjuSxIEe9A8RQ0HzKaHXgpTbwTKdKpTjibqoTrx8NU3/PD1Mp6Yw1Rs8DQ3MwdqVBodMfh11KZWBSxEFvYikxjIkb4ENuhpslW2AxRqBnfz7jEYmXJHrZEGSLNZiltXktniKBAUy9KL61jBU2nkLNNTicMDgmjqiB5Wcb@WQidWQzQwkNuqEwmDKkbIVzPuQ6Zm6Wd9plR6tiTRI@1rOrX97ySFSciuhNCMERgCM0ZriKEnpoGfXSJHZG69xUTcrcc6@V8DGfPcZt30YkOehP/VnfiECYdvV/fm6VLXLxCl3G3S0vd8umZn/yD91M8/ZH/8VYdKu1QXf/LV0zPFS3X7dHtcvqHLe89Iowiv2HLvLZqB1ZWm7L223ZZHpGxMWYRWVtlajJ4CUg2ALdpTRUFMqg@V5tyTt7kgABpXFzWOTuuoY7f "Python 2 โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` FJโ€˜แนร—โธแบ†Zโ‚ฌแบ†โ‚ฌแบŽล’PFQP$$รแน€Lโ‚ฌแน‚ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/N61HDjIc7Gw9Pf9S44@GutqhHTWuAFJjsOzopwC0wQEXl8ISHOxt8QGI7m/7//x8dbagDhLE6QNoASMcCAA "Jelly โ€“ Try It Online")** A typical golf-complexity solution, don't even bother with larger test cases, they will time out (the power set of all possible rectangles is inspected\*) ### How? Forms all the possible rectangles that may be made. Takes the power-set of those rectangles and inspects them only keeping those sets which both contain no zeros and contain each of the ones at least once. To achieve the "keeping those sets which both contain no zeros and contain each of the ones at least once" part the code first coerces the ones to a set of distinct integers greater than one, leaving the zeros as they are so that it becomes "finding the maxima of the product of the unique values". ``` FJโ€˜แนร—โธแบ†Zโ‚ฌแบ†โ‚ฌแบŽล’PFQP$$รแน€Lโ‚ฌแน‚ - Link: list of lists of ones and zeros, M F - flatten M into a single list J - range of length = [1,2,3,...,len(flattened(M))] โ€˜ - increment = [2,3,4,...,len(flattened(M))+1] แน - mould like M - reshapes it just like M again โธ - chain's left argument, M ร— - multiply (vectorises) - unique integers > 1 at M's 1s and 0s at M's 0s แบ† - non-empty sublists - i.e. row selections Zโ‚ฌ - transpose โ‚ฌach แบ†โ‚ฌ - non-empty sublists of โ‚ฌach - column selections of those แบŽ - tighten - a flat list of all of the rectangles ล’P - power-set - all possible selections of rectangles รแน€ - filter keep those for which the following is maximal: $ - last two links as a monad: F - flatten $ - last two links as a monad: Q - de-duplicate P - product Lโ‚ฌ - length of โ‚ฌach - # of rectangles used by each full-cover แน‚ - minimum ``` --- \* For an **n** by **m** matrix that's **ways(n,m) = 2^(T(n)ร—T(m))**, so... **ways(3,2) = 2^((3+2+1)ร—(2+1)) = 2^18 = 262,144** (the TIO link) **ways(3,3) = 2^((3+2+1)ร—(3+2+1)) = 2^36 = 68,719,476,736** **ways(3,4) = 2^((3+2+1)ร—(4+3+2+1)) = 2^60 = 1,152,921,504,606,846,976** **ways(5,5) = 2^225 ~= 5.4e+67** (the largest test case) **ways(8,5) = 2^540 ~= 3.6e+162** (the example) [Answer] # JavaScript, 434 bytes Code: ``` for(_='),d=...-1||(,Ad<=a,u[o][n]=d, =0,(e,r,C,m))&&()=>.map((h((A,n,on<e|o<r|n>C|o>mf=u=>(q(s=(e>C[e,C]=[C,e]r>m[r,m]=[m,r]lk=1,k&=!!A)kl|=&1,=2k&lh=f=>uA,$ABf(B,$))))(($,Bae=r=C=m=,d=to-Bt=n$&n>$e C=nn+1~ee C=ttn-$t=oB&o>Br m=oo+1~rr m=tq+=sg=[],h((ca||g.push(c)gigb,j(p=1,q+=i<j&&s(b)q)';G=/[-]/.exec(_);)with(_.split(G))_=join(shift());eval(_) ``` Hexdump (because of unprintable characters): ``` 66 6F 72 28 5F 3D 27 29 2C 13 13 64 3D 12 2E 2E 2E 11 2D 31 10 7C 7C 28 0F 2C 41 0F 64 3C 3D 0E 61 2C 0C 75 5B 6F 5D 5B 6E 5D 0B 3D 64 2C 09 3D 30 2C 08 28 65 2C 72 2C 43 2C 6D 07 29 29 13 06 26 26 28 05 29 3D 3E 04 2E 6D 61 70 28 28 03 68 28 28 41 2C 6E 2C 6F 04 02 02 6E 3C 65 7C 6F 3C 72 7C 6E 3E 43 7C 6F 3E 6D 0F 01 66 3D 75 3D 3E 28 71 08 28 73 3D 07 04 28 65 3E 43 05 5B 65 2C 43 5D 3D 5B 43 2C 65 5D 13 72 3E 6D 05 5B 72 2C 6D 5D 3D 5B 6D 2C 72 5D 13 6C 08 6B 3D 31 2C 01 6B 26 3D 21 21 41 29 13 6B 05 01 6C 7C 3D 0B 26 31 2C 0B 3D 32 06 6B 26 6C 13 68 3D 66 3D 3E 75 03 41 2C 24 04 41 03 0C 42 04 66 28 0C 42 2C 24 29 29 29 29 28 28 0C 24 2C 42 04 61 10 0F 65 3D 72 3D 43 3D 6D 3D 10 2C 64 3D 74 08 02 6F 2D 42 0F 74 3D 6E 0E 24 26 6E 3E 24 05 65 09 43 3D 6E 10 12 6E 2B 31 06 7E 65 0F 65 09 43 3D 74 12 74 08 02 6E 2D 24 0F 74 3D 6F 0E 42 26 6F 3E 42 05 72 09 6D 3D 6F 10 12 6F 2B 31 06 7E 72 0F 72 09 6D 3D 74 13 71 2B 3D 73 07 06 67 3D 5B 5D 2C 68 28 28 0C 11 63 04 61 10 7C 7C 67 2E 70 75 73 68 28 63 29 13 67 03 0C 69 04 67 03 62 2C 6A 04 28 70 3D 31 2C 71 2B 3D 69 3C 6A 26 26 73 28 11 0C 11 62 29 06 71 29 27 3B 47 3D 2F 5B 01 2D 13 5D 2F 2E 65 78 65 63 28 5F 29 3B 29 77 69 74 68 28 5F 2E 73 70 6C 69 74 28 47 29 29 5F 3D 6A 6F 69 6E 28 73 68 69 66 74 28 29 29 3B 65 76 61 6C 28 5F 29 ``` [Try it online!](https://tio.run/##lZPfjqIwFMajgn9WIiovsJMQps0cGdlbPSTCxTwEIQ4jVVGhCjizF2Rf3S2zuqK7F7u9aM/X8ztfT9N0E7wH2SKN9vko4SE7nZY8JXN8pKBpIQ5N0xyMrH5REBVmajjFXgDK0eO@l/hdDKGDY2gTBim4ELco1ZqGQWSKtmTGwZ6QxpqQGSTApXo9mbKCT9Misd2C27FaW@IRbXJokwxbEmG2K3sMXB89F5ivpXYseynEQseQ@tquvUULalsDHx5mVNvKtV2BXcOCLn5rbo2dtsYl2sfGDHRp1lAcaUkUB3QqBiGKDo4U9FWGKboYYx9CzNt1PnLUHJOebiS2LrOOi0l/mDxZzR9MLVU@FFAy0gXEe47BbUdOOzHy/pCXUKqWKtcOT5i1miv0fBD3VQYLcVRRrMz9MVuTBdVWDSWSVo032EhkLy4h@Gi6MYyMDJTBG20e6OPkBZ@92kjzn032nS3InE7oR5SvydzM9rsoJy@UznHDo4Rk62iZE0on7D3YCfC0T/mCZZmZ5SE/5uZHGuWMeF88z/J9KBe4BD5c98ZwDcX@WMw38iZ7tYAyhGq9CC7MZ@qX/gt9QX6n7quqvV2TV4cb2zPwJzr@X9T6N/S@@QowrgB3ruduqkjVuep9eYczL8r9z18UoL0kAaVm@fyvX1/p6Sc) It is not very golfy, but at least it works very fast. All test cases can be computed in few milliseconds. ## Ungolfed ``` f=mat=>( iterate=f=>mat.map((A,x)=>A.map((a,y)=>f(a,y,x))), fill=(x1,y1,x2,y2)=>( x1>x2&&([x1,x2]=[x2,x1]), y1>y2&&([y1,y2]=[y2,y1]), isFilled=0, canBeFilled=1, iterate((A,X,Y)=>X<x1|Y<y1|X>x2|Y>y2||( canBeFilled&=!!A )), canBeFilled&&( iterate((A,X,Y)=>X<x1|Y<y1|X>x2|Y>y2||( isFilled|=mat[Y][X]&1, mat[Y][X]=2 )) ), canBeFilled&isFilled ), rectangles=0, iterate((a,x,y)=>a-1||( x1=y1=x2=y2=-1, start=end=0, iterate((A,X,Y)=>Y-y||( end=X, A||( start<=x&X>x&&(x1=start,x2=X-1), start=X+1 ) )), ~x1||(x1=start,x2=end), start=end=0, iterate((A,X,Y)=>X-x||( end=Y, A||( start<=y&Y>y&&(y1=start,y2=Y-1), start=Y+1 ) )), ~y1||(y1=start,y2=end), rectangles+=fill(x1,y1,x2,y2) )), ones=[], iterate((a,...c)=>a-1||ones.push(c)), ones.map((a,i)=>ones.map((b,j)=>( M=1, rectangles+=i<j&&fill(...a,...b) ))), rectangles ) ``` ## Explanation It uses similar algorithm like for solving Karnaugh maps. Firstly it tries to find at least one `1` which can be part of exactly one non-extensible rectangle. By non-extensible I mean if we extend it in any direction (up, left, right, down) it will include at least one `0` (or will go beyond the matrix bounds). When such `1` is found, find the biggest rectangle that includes it and flag all `1`s in that rectangle. Repeat until there is no more non-flagged `1`s that satisfy these conditions. In some cases (like in the 16th test case) there are `1`s that left over after applying the first step. Then enumerate all these `1`s and apply some kind of enhanced brute-force search. This step is rarely applied, and even in these cases, we need to brute-force check only one or two combinations, so it should work very fast even for larger test cases. [Answer] # [Python 3](https://docs.python.org/3/)+[Numpy](https://numpy.org/), 253 bytes ``` from numpy import* from itertools import* R=range P=product def f(A):s=A.shape;r=random.rand(*s);return[N for N in R(1,sum(A)+1)for m in P(*[[(A*r)[a:b+1,c:d+1]for a,c,b,d in P(*[*map(R,s)]*2)]]*N)if len({e*all(b)for b in m for e in b.flat})==sum(A)][0] ``` [Try it online!](https://tio.run/##lZNda9swFIavp19x8C5mOSLYTcfAxRdmMFoYWUh7J0SRbbkx@AtJHgtjvz2TZMdx0w22XDg673ne82Hk/qgPXbs5nUrZNdAOTX@Equk7qQPkpEoLqbuuVrO8TyRvXwTaJb3siiHXqBAllH6KY5Wka3XgvbiTFiq6Zm3//EDhOyn0IFu6hbKTsIWqhb0fETU0xriKsFUbq@78gFI/DSSmPM5WEcnjYhUxm@ckJxkpzlTQ8N7fE4VZcIMZC7a4KqEWrf9TBLyu/cwVzSzeuK7CHrN1WXP9CyfJ2JvRkJ3ew5NQGj5zJRS4ve95/Z3LAu6HphH1BwVPD98Q0oZ6zi2VAEXvKKURYyRiZDyTVxEjV9nQ5W8usSFC83zFOO0tF11pNiZzzc2km@hMu/wY/8135hi5XeSv/VezLIlLLddls@wyUW/5cNbsadz/9j@cdp6P/8j/cb8FFS6oZf3L@wxnx8Qteyy7zBtF004bhhhC7l5zLasfBPJOSpFrewsvF4nGn1iMwPykUEOtITHfEpeSH/3Rh7HLav5iUh7dpY@PzANz1Uc@Sc5lRa2EAb6kD1@Z5zy9rFrtGyeZYAKeOnRDXUAmPJgnMrKZ0yPTpPj0Gw "Python 3 โ€“ Try It Online") This is quite slow due to generating more than the full power set of all rectangles. I also have [an optimized version](https://tio.run/##lVRdT9swFH1efoVVHuYUUzUteynkoZqEQJoYAt4iCzmJCxGOHdkOo5r227trJ81Hy7QtD619fO65H77X1da@KLnc7TZalUjWZbVFRVkpbaeBhwrLtVVKmA4Ocr5BmpfqjT9xmQlleI41z6wJVwGC76Q9RSBt3C@zKFPSskIihuae4/koRqIwFm8KAV4wE4I0OuFYx4FMPgtuQKesBLdcbPeSPEegK5h@5nrA9AqS/9g7SqhHNkqjgiC98EbOOYekuWaWtzmEyWp1FtEmFfcV5ql3FaMrJgzvD6EUi5l5YRVP5hRdogiBhw6KPNRrfaD3qOtejoP2mO0C1pGL1oeXrAo6JrSVAopBtRTFq6uNVSjl4wpByinPWA03oqPZe4QuYxcnLJjMHbTdQ7BIoQukgZsvlISEcq6PfPrMkzmBrJ16K7NIziIC5Wuw40j/VoDhl2rOXoeVlsqOjMfy@8uesariElpyEbatZmstu@MguI819AgP7uJKq7zOrO/oDV67/jXxurm7C@1ouSpn7g9PTXjRKb1bfOtv5tbleY8jYuoS7E@j0KGlQ6FT00IyV0GDD8clweupDhO2Sk8jkq3y04g6Q0YykhJ/XXd4mkxLVuF7YkI6XYQ0JLchFEFwiX/yKQwLTr231NFLHw53y3S2Ecz@CuO4CSrcnaBHbiz6ygxMkJ/qaybemM7RdV2WXHw26PHmexBYYD1ljgXzEnxKEuhfSiJKmjUZ7Sg5OJ3780W/B4ZrjxHHY8e86ABze9JpLlscdnu2P2/2f7Lb8yg5H5wf2h/EMmT0Wt7LcuilZR3z5x3mVk3@5/9h6eL58o/8D/MbsOYD1lC/r@e8s2h5Qx9DL11GUZvTkgY0CHy3M6uLdwINr92AuRbsG2nVjqCphYVZ32CmNdvixqZ95y17hqNJcrd@eKAT/7B4fhzvJd2zCISr9c03OvE2lS6kxWBJWjJBE/OiapHDKzdBXTQAQ4wT0kYZ7n4D) to test the slower test cases, which makes three optimizations: * Uses combinations of N rectangles instead of cartesian product to avoid duplicate rectangles * Uses `next(...)` instead of `[...][0]` to terminate as soon as a single covering is found with minimal number of rectangles * Prunes out rectangles that are subsets of larger rectangles containing only 1s (96% reduction in rectangles for the largest test case) ## Semi-ungolfed ``` from numpy import* from itertools import* R=range # P is the itertools product P=product def f(A): # take input as a numpy array A s = A.shape; # r is a weight matrix that gives a distinct value to each entry in A # (probability 1) # Longer alternative (can be inlined): r=~reshape(range(h*w),(h,w)) r = random.rand(*s); return [ # We're finding number of rectangles N N # In the range [1..sum(A)] where sum(A) is the number of 1s (upper bound for # rectangles) for N in R(1, sum(A)+1) # m is a combination of N possible rectangles for m in P( # (this is Cartesian product instead of combinations, but duplicates # provide no benefit) # P(*[...]*N) === product(..., repeat=N) *[ [ # A*r is modified array such that each 1 is given # a distinct value and all 0s remain 0 # all rectangles in A*r (A*r)[a:b+1, c:d+1] for a,c,b,d in P(*[*map(R,s)]*2) ] ]*N ) # Test that each rectangle contains no 0s and the combination of rectangles covers all 1s: if len({e*all(b) for b in m for e in b.flat})==sum(A) # Get the first N with a valid covering # must be min N because N is generated in order ][0] ``` ]
[Question] [ Write a program or function that takes in a positive integer \$N\$ and a grid of decimal digits (\$0\$ to \$9\$) with width \$W\$ and height \$H\$ (which are also positive integers). You can assume that \$N\$ will be less than or equal to the larger of \$W\$ and \$H\$ (\$N \le \max(W,H)\$). Print or return the largest contiguous \$N\$-digit number that appears horizontally or vertically in the grid, written in normal reading order or in reverse. * Diagonal lines of digits are not considered. * The grid does not wrap around, i.e. it does not have periodic boundary conditions. For example, the \$3\times3\$ grid ``` 928 313 049 ``` would have `9` as the output for \$N = 1\$, `94` as the output for \$N = 2\$, and `940` as the output for \$N = 3\$. The \$4\times3\$ grid ``` 7423 1531 6810 ``` would have `8` as the output for \$N = 1\$, `86` for \$N = 2\$, `854` for \$N = 3\$, and `7423` for \$N = 4\$. The \$3\times3\$ grid ``` 000 010 000 ``` would have output `1` for \$N = 1\$, and `10` for N = 2 and N = 3 (`010` is also valid for N = 3). The \$1\times1\$ grid ``` 0 ``` would have output `0` for \$N = 1\$. You can take the input in any convenient reasonable format. e.g. the grid could be a newline separated string of digits, or a multidimensional array, or a list of lists of digits, etc. Leading zeros are allowed in the output if they were part of the grid. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins, but I'll also award brownie points (i.e. more likely upvotes) for answers that can show that their algorithm is computationally efficient. [Answer] ## CJam, ~~39~~ ~~36~~ ~~35~~ 34 bytes ``` qN/)i\[{zW%_}4*]ff{_,@e<ew:i}e_:e> ``` Just quickly, before @Dennis wakes up :P [Try it online](http://cjam.aditsu.net/#code=qN%2F%29i%5C%5B%7BzW%25_%7D4*%5Dff%7B_%2C%40e%3Cew%3Ai%7De_%3Ae%3E&input=7423%0A1531%0A6810%0A4). ### Explanation The basic algorithm is to take all four rotations of the grid and split each row into chunks of length `N` (or the row length, whichever's smaller). Then convert the chunks to ints and take the largest. ``` qN/ Split input by newlines, giving an array of lines )i\ Drop N from the array and put at bottom [ ] Wrap in array... { }4* Perform 4 times... zW%_ Rotate grid anticlockwise and push a copy Note that this gives an array of 5 grids [CCW1 CCW2 CCW3 CCW4 CCW4] ff{ } For each grid row, mapping with N as an extra parameter... _, Push length of row @e< Take min with N ew Split into chunks :i Convert to ints e_ Flatten that array :e> Take cumulative max ``` [Answer] # Pyth, ~~22~~ 19 bytes *3 bytes thanks to Jakube.* ``` seSs.:RQ.n,L_MdCB.z ``` [Try it online.](https://pyth.herokuapp.com/?code=seSs.%3ARQ.n%2CL_MdCB.z&input=3%0A7423%0A1531%0A6810&debug=0) If we are allowed to print leading zeroes, the code is 18 bytes: ``` eSs.:RQ.n,L_MdCB.z ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ZU$4รยกแบŽแนกโ‚ฌแธŒFแน€ ``` [Try it online!](https://tio.run/##y0rNyan8/z8qVMXk8IRDCx/u6nu4c@GjpjUPd/S4PdzZ8P/w8kcb1yn5HNod5aNyrAso4Q3Ekf//R3NxRkdb6hjpWMTqcHEqRBvrGOoYQ5gGOiY6lrFANkiJOZBjBJMx1DHVASqEcMx0LIB6DGAKDXSAEGaAIYJpgKQkNpYrFgA "Jelly โ€“ Try It Online") This takes the grid as an \$W\times H\$ matrix of single digits. The TIO Footer simply takes each input list and generates the outputs for each \$N = 1, 2, ...\$ up to either \$W\$ or \$H\$, depending on which is larger ## How it works ``` ZU$4รยกแบŽแนกโ‚ฌแธŒFแน€ - Main link. Takes the matrix M on the left and N on the right $ - Group the previous 2 links together as a monad f(M): Z - Transpose U - Reverse 4รยก - 4 times, run f(M) on M, updating M each time, and return all 4 results This yields M, Mแต€ with rows reversed, Mแต€ and M with rows reversed แบŽ - Tighten into a list of lists โ‚ฌ - Over each: แนก - Yield all overlapping sublists of length N แธŒ - Convert back to integers F - Flatten แน€ - Maximum ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` Dร…|ยซโ‚ฌร‚Jโ‚ฌล’หœsรนร  ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f5XBrzaHVj5rWHG7yApJHJ52eU3x45@EF//9HRyuZK@koKJmACCMQYawUq6MQrWQIYptCBICEIUTUDMS2gAgACQOl2FguIwA "05AB1E โ€“ Try It Online") Explanation: ``` D # duplicate matrix ร…| # get column vectors ยซ # join matrix with its column vectors โ‚ฌร‚ # append reversed elements J # join arrays into numbers โ‚ฌล’หœ # Get all substrings sรน # Keep only those of required length ร  # Get the largest value ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` โ–ฒแนXโฐฮฃโ†‘4ยกomโ†”Tยฒ ``` [Try it online!](https://tio.run/##ATUAyv9odXNr/@KCgcK2/@KWsuG5gVjigbDOo@KGkTTCoW9t4oaUVMKy////Mv85MjgKMzEzCjA0OQ "Husk โ€“ Try It Online") The arguments are a bit finicky here. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~13~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes the matrix as an array of lines. Includes leading `0`s in the output, where applicable. ``` 4ร†=z)mรฃVรƒc รฑ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&header=cVI&code=NMY9eilt41bDYyDx&input=IjkyOAozMTMKMDQ5Igox) ``` 4ร†=z)mรฃVรƒc รฑ :Implicit input of array U & integer V 4ร† :Map the range [0,4) = : Reassign to U z : Rotate 90ยฐ clockwise ) : End reassignment m : Map รฃV : Substrings of length V รƒ :End map c :Flatten รฑ :Sort :Implicit output of last element ``` ]
[Question] [ # Introduction Recently, I was skyping with a bunch of friends and we got bored and had nothing to do, so we "invented" a "game" (some people in the comments pointed out that this game is playable online and very popular, so we definetely didn't invent it, although I hadn't seen it before). The reason I put the word "game" in quotation marks is because it's not an actual computer game, but it's played on Wikipedia. It's really easy to play: Someone chooses some Wikipedia article as the goal. Let's assume *[Code Golf](http://en.wikipedia.org/wiki/Code_golf)* for this example. All the players then have to start from a random article (by pressing *Random Article* in the sidebar or going to [this](http://en.wikipedia.org/wiki/Special:Random) URL) and have to get to the "goal" as quick as possible using **only linked articles of the article you are currently at**. Rules include: * The search function is not allowed (obviously) * You may only click links in the article's main text (specifically all text inside `<div id="bodyContent">`) * If your random page or any other page you encounter has no valid links (dead links, loops, etc) or no links at all you may roll again. # The challenge Here's where you come in: unfortunately I'm pretty bad at this game, but I'm also a dirty cheater. So I want you to implement this bot for me. I'm also a programmer, so naturally my hard disk is full of stuff like code, libraries and such and I only have a few bytes of memory to spare. Therefore this challenge is Code Golf, the answer with the least **bytes** wins. ## Implementation Details: * Of course you don't have to implement an intelligent bot that knows connections between topics and automatically detects the optimal route. Brute forcing is more than enough for the purpose of this challenge * In the actual game, time counts. Your program shouldn't take longer than 1 hour to find the article (this is to avoid loopholes like random searchers that will "eventually" find the goal) * If no path to the goal can be found (e.g. dead links or a loop) you can choose what to do from the list below: + Quit (score remains the same) + Get another random article and try again and do nothing on loops (score -= 10) + Get another random article on a dead link or a loop (detect loops automatically) (score -= 50) + (By "score" I mean your byte count here) * Another 20 bonus bytes will be subtracted if you "trace" the route, so you print the title of every individual page you visit. * Standard network libraries may be used (to avoid loopholes like "I crafted my own network library which crawls wikipedia articles") + The only thing network-related your program should do is send a HTTP request to download a wikipedia page * If your program finds the page, it should quit, but somehow signalize that it finished (printing the character "f" or the title of the page is enough) * Standard loopholes are to be avoided **Have fun golfing!** *(This is my first question here, so please point out obvious loopholes and caveats in the comments before exploiting them - thanks :D)* [Answer] ## Python 373 -> 303 It reads the Wikipedia destination from `input()` (user input) and should be in the format of `/wiki/dest`. So, something like `/wiki/Code_golf` or `/wiki/United_States`. It also uses one space for the indents and `http://enwp.org` instead of Wikipedia's full URL to save bytes. * -50 because if it finds a broken [URL](http://en.wikipedia.org/wiki/Uniform_Resource_Locator) it gets a new random URL. * -20 because it prints the title of each URL visited (could change title -> URL, but title is cleaner and actually makes my source larger). It hangs every once and a while, and I can't figure out why. Perhaps because of Wikipedia rate limits? I found the [Boston Red Sox Wikipedia page](https://en.wikipedia.org/wiki/Boston_Red_Sox) in 9 minutes 20 seconds, and the United States page in under 10 seconds, so it shouldn't take *too* long to find Code Golf... ``` from mechanize import*;from lxml.html import*;from random import*;a=Browser();a.set_handle_robots(0);i='http://enwp.org/Special:Random';t=input();d={};k=a.open def f(o): if o!=i:d[o]=o if o in d:f(i) try:v=fromstring(k(o).read()).xpath('//div[@id="content"]//a/@href') except:f(i) print a.title() if t in v:k(t);print 'f';exit() else:f(choice(v)) if v else f(i) f(i) ``` ]
[Question] [ Do you ever look at 3D shapes and think that we have 2 many dimensions. So let's make 3D into 1D! (See what I did there?) # Task Given a 2D representation of a cube (layout below), flatten it into a single string, based on pointers. # The CUBE This is the layout of the cube filled with no-ops (`,`) and pointers at the corners (`<>v^/`). The Navigation Pointer (NP) begins the program where shown. ``` | NP begins here, moving right. V >,,,,,,,,,,,,,,,,,,v , ,, , , , , , , , , , , , , , , , , , , , , , /,,,,,,,,,,,,,,,,,,/ / , , , , , , , , , , , , , , , , , , , , , , ,, ^,,,,,,,,,,,,,,,,,,< ``` The NP continues moving right from the start until it meets a corner. Each corner has a default direction that, unless overridden at the corner by a pointer, will point the NP in a new direction. They are shown on the above diagram. The pointers in the program are `v^<>/` (the `/` points it either down or up, due to the layout there will never be any confusion between the two) The NP stops moving when it reaches the `ยถ` symbol (Yes I know this is a multi-byte character, deal with it). Each character it goes over is added to the final output string except for the pointers, the no-op (`,`) and the `ยถ` symbol. # Input Input will be a multi-line string that matches the layout of the **CUBE** with the non-whitespace characters replaced with any character in the range `0x21` to `0x7E` and **at least** one instance of the EOF. You may take input as: * A multiline string * A list of strings where each line is a new element in the list * A 2D list of strings where each line is broken down into a list # Output The cube, flattened down into a single line string. # Conditional Pointer The NP has a boolean value that is used for something called a "conditional" pointer that begins at `true`. The "conditional" pointer (`?`) is a pointer which will alternate the NP value between `true` and `false` every time it is used. Conditional pointers only take effects when used on the corners where 3 tracks (3-point corner) meet. If the value is `true` when the NP reaches the conditional pointer, the NP moves to the default direction in the CUBE image and, **after** being directed, the NP value is toggled. Therefore, if it is on `false`, the NP follows the non-default direction. There will never be an instance where the NP goes towards a conditional and the default direction is the direction it just came from. Imagine that this is the left corner of the front face and the NP value is currently `true`: ``` NP direction / , , ,,,? , , ``` This will never happen as the default direction will mirror it back to how it was. If the conditional pointer is on an 3-point corner: * It isn't added to the final string * The NP value is toggled between `true` and `false` **after** the NP has been directed. * If the NP value is `true`, the NP is redirected to the **default** direction. Otherwise, it is redirected to the **non-default** direction. If it is on a track or a 2-point corner: * It is added to the final string * the value **is** toggled * The IP **isn't** directed # Something to watch out for If a pointer is on a track and it **doesn't** point into spaces, the NP is directed into the new track, adds the next character to the final string and rotates the NP by 90 degrees to the right. ``` abcd >e g f / NP direction ``` would flatten to ``` (...) gef (...) ``` NOT ``` (...) g>def (...) ``` A `/` pointer doesn't redirect the NP in this instance as it may redirect into a space so ``` f e > ab/d ``` would become `ab/def` # Rules * The width, height and depth of the cube may change * The height and depth of the cube will always be the same and will be half the width, so the width will always be even. * The width will be between (inclusive) 6 and 60. * There will always be an EOF (`ยถ`) that can be reached by the NP. E.g there will never be something like this in the cube: `<ยถ>` as the NP would never be able to reach the cube. * As a space cannot be inserted into the cube's tracks, the final string shouldn't ever have a space in it. * If a pointer is placed in one of the tracks (not on a corner) and it would direct the NP into spaces, the NP stays constant and the character is added to the final string. * However, if the pointer keeps it on the track, the NP is directed and the pointer character isn't added * As no-ops (`,`) aren't added to the final string, the final string shouldn't contain any `,` in it. * You can assume that the input will be correct. * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in *bytes* wins! # Examples ``` Input Output ----- Input Output abcdef ยถ ,g q,,,,, h p ,i onmlkj abcdefghijklmnopq ----- >,,,,,,,,,,,,,,,,,,v ยถ ,, , , , , , , , , , , , , , , , , , , , , , /,,,,,,,,,,,,,,,,,,/ / , , , , , , , , , , , , , , , , , , , , , , ,, ^,,,,,,,,,,,,,,,,,,< nothing ----- Mr/~gm,Vc!r,0cbmPC@Zg9jb)7=m^ppwN*Nuk){r c ยถZ J ; # e j 8 ] b " # ` 4 h $ - p n 2 L S P B ; R @ J D E N < O \ p B y = | 9 ; T x [ 6 o k ! L = E K ~ >mjmz6,?A*Q)^.a:IpGP"^bK}DSXL)2F!BV|"m6/ T a A 6 5 = p 1 i R 4 / ? - Z ( 1 " ` ' 0 { N p M O * K Z J $ " ( d 4 + o f U g i v b U ~ L U M h g ^ D 2 (g 5]u*n<Ldn</9/XQyC444Va\m}W3Rf,rp"a@5cZB0 (Newlines added for readability) Mr/~gmVc!r0cbmPC@Zg9jb)7=m^ppwN*Nuk){rZ#8"4-2PRD<p=;[k=~T 6pR?(`{MK$dogbLhDg0BZc5@a"prfR3W}m\aV444CyQX/9/ndLn*u]52g UUif4"ZON'1-415amjmz6?A*Q)^.a:IpGP"^bK}DSXL)2F!BV|"m6KLox9 y\NJ;Sn$`bj; ----- NEWYORKCITYBABY! ยถ ,, , , , , , , , , , , , , , , , ,,,,,,,,,,,,,,,, , , , , , , , , , , , , , , , , , ,, ,,,,,,,,,,,,,,,, NEWYORKCITYBABY! ----- /{Y!_(=-)s<e!D^<+<+1o30d>QOx9kfu?3X2I:8],t>Ye~,Y9/6;u@ ] >Y ! 1 ) c 7 8 ^ K & f K 9 M } O s _ ? h N e ? u , g = s > Q M a 0 9 b c ( h { c [ m * I R % K E > u 5 n W f ] } | y F E q ) < ; X L S F M | u * Z >XZpJ=L`+8ONRk?T7$qVr6-U^f14{>>ABEEP`Mjx&T[/&o*F=*qq{/ e ยถ < ^ + P C . x m ; ^ > y 4 b 5 v ` Q B c 2 e r a x I 3 1 Y Q v ` w ; o * S h E b S r 6 P M ` l % M A - ` " j \ s } ~ J $ h c % p O I Z Z ] N E ` 3< x^}}SI"-a3[%7U5EV}"UM?Aov|E_yjrMt<HAQ@}QAABO&y//R0$\2p (Newlines added for readability) ]!c^fMsh?g>abh[IKuW}F)XFuXZpJ=L`+8ONRk?T7$qVr6-U^f14{ABEE P`Mjx&T[/&o*F=*qq{*ML<E|f5ERm{c0Q=uN_}KK71Y)8&9O?esM9(c*% >n]yq;S|Ze^Cm>b`crIY`ohSPlA"sJcOZE3NZph~\`M`6bS;;Sb6`M`\~ hpZN3p2\$0R//y&OBAAQ}@QAHtMrjy_E|voA?MU"}VE5U7%[3a-"IS}}^ x`]I%$}j-%MrE*wQ3a2Q5y;.+ ----- %:biv+|? ยถ \+ T c , ?{yX<//v " i [ @ Q Tj U8sUNl.? %:biv+|+"@jT[[T.lNUs8UQi{yXXy{T ----- FCf2hoYA)&*j F ยถ# 3 p ( & ~ w ; * t 39Hq{F'MmmO/ 9 5 \ D - | } 8 c l a 25 GKa"<0/7MG[? FCf2hoYA)&*j#(wt9D}l5[GM7/0"aKGa8-53;&3FFCf2hoYA)&*j#(wt9D}l52c|\*~p ----- #S^[WNk3;9v;e2\h!@CI#Il? G g` $ 2 \ V 9 S m Y b 6 ) * U ' V [ g V I 8 X < T U K ยถ C ?ozMt+xxxxutvQgkx&D9I/<v ' w K p V y h ( R y e P i ] ! x Z / s y w ' # X 4 c ~ W Z E, ~IdXPYS.Lc49lC~vjULUBv.? (Newlines added for readability) #S^[WNk3;9v;e2\h!@CI#Il`\Sb*VVXUC'phyixs'4WE~Xw/!PRyKKyRP!/wX~E .vBULUjv~Cl94cL.SYPXdI~Zc#yZ]e(VwozMt+xxxxutvQgkx&D9I//I9D&xkgQ vtuxxxx+tMzoK<I[U6mV$G#S^[WNk3;9v;e2\h!@CI#Ilg29Y)'g8T ``` [Answer] # [Vim](https://www.vim.org), 971 bytes ``` Go<C-v><C-v><C-v> elsei'<C-v><C-v><C-v><C-r>t'==<Esc>^"zC<C-v><C-v><C-v> let@b=<Esc>^"fC<C-v><C-v><C-v> let@O=<Esc>^"xC:if'<C-v><C-v><C-v><C-r>0'==' '<Esc>^"yC<C-v><C-v><C-v> norm <Esc>^"wC<C-v><C-v><C-v> let@m='<Esc>^"vC'<C-v><C-v><C-r>f0<C-v><C-v><C-v> el<C-v><C-v><C-v> if'<C-v><C-v><C-v><C-r>m'=='<Esc>^"aCyl:if'<C-v><C-v><C-v><C-r>0'!=' '<C-v><C-v><C-v> let@T=<Esc>^"hC457||<C-v><C-v><C-v><C-r>t==147<C-v><C-r>vlk'<Esc>^"iC@n:if<C-v><C-v><C-v><C-r>t==<Esc>^"jC@nlylh<C-r>y<C-r>x'>'<C-r>w@m<C-r>z234568<C-r>wl<C-r>vj'<C-v> el<C-r>wl<C-r>vl'<C-v> en<C-v> <Esc>^"rC@nhyll<C-r>y<C-r>x'<'<C-r>w@m<C-r>z1248<C-r>wh<C-r>vk'<C-v> el<C-r>wh<C-r>vh'<C-v> en<C-v> <Esc>^"lC@nkylj<C-r>y<C-r>x'^'<C-r>w@m<C-r>z234568<C-r>wk<C-r>vl'<C-v> el<C-r>wk<C-r>vk'<C-v> en<C-v> <Esc>^"uC@njylk<C-r>y<C-r>x'v'<C-r>w@m<C-v> el<C-r>wj<C-r>vj'<C-v> en<C-v> <Esc>^"dC<C-r>j<C-r>i<C-r>z38<C-r>vhj'<C-v> el<C-r>x'/'<C-v> en<C-v> <Esc>^"sC<C-r>j178<C-v> if<C-v><C-r>b<C-r>vj<C-r>al'<C-r>vhj'<C-v> el<C-r>vh'<C-v> en<C-r>f1<C-v> en<C-r>z147<C-v> if<C-v><C-r>b<C-r>vlk<C-r>al'<C-r>vj'<C-v> el<C-r>vh'<C-v> en<C-r>f1<C-v> en<C-r>z134<C-v> if<C-v><C-r>b<C-r>vh<C-r>aj'<C-r>vlk'<C-v> el<C-r>vk'<C-v> en<C-r>f1<C-v> en<C-r>z457<C-v> if<C-v><C-r>b<C-r>vlk<C-r>ah'<C-r>vj'<C-v> el<C-r>vl'<C-v> en<C-r>f1<C-v> en<C-v> el<C-r>x'?'<C-r>f(<C-v><C-r>b+1)%2<C-v> en<C-v> <Esc>^"qC"tyl:if'<C-v><C-r>t'=='>'<C-r>w@r<C-r>z'<'<C-r>w@l<C-r>z'v'<C-r>w@d<C-r>z'^'<C-r>w@u<C-r>z'/'<C-r>w@s@e<C-r>z'?'<C-r>w@q@e<C-r>z'โ–ˆ'<C-r>wHdG"op<C-v> k<C-r>z','<C-r>w@e<C-v> el<C-r>w"Oyl@e<C-v> en<C-v> @c<Esc>^"cCma@myl<C-r>y<C-r>w`a@g<C-r>w@m<C-v> en<C-v> <Esc>^"eC<C-r>j58<C-r>vl'<C-r>z178<C-r>vj'<C-r>z38<C-r>vhj'<C-r>z134<C-r>vh'<C-r>z35<C-r>vk'<C-r>z<C-r>i<C-v> en<C-v> <Esc>^"gC:let@t=''<C-v> h<C-r>h1<C-v> en<C-v> <C-v><Esc>k<C-r>h2<C-v> en<C-v> l<C-r>h3<C-v> en<C-v> l<C-r>h4<C-v> en<C-v> j<C-r>h5<C-v> en<C-v> j<C-r>h6<C-v> en<C-v> h<C-r>h7<C-v> en<C-v> h<C-r>h8<C-v> en<C-v> <C-v><Esc>kl<Esc>^"nC1l<Esc>"mx"bxgg @c ``` [Try it online!](https://tio.run/##pZZLc9MwEIDvOeqQSy@pKeOmBPJyHi01cWugQJ@UUphCMzhPx5bTkLZJnD7O/AJ@IH@krGTFjh0zLINnYu@u99uVdmUpo4eHnYtkMplo08t2TwaJXMmqulSXpjoz0/aV1mBqx1cPmTrRN3od7p4Ddzklg83lLv2LoZMCbewDjsrejnRwJ52cl4zdRQCHBQAHQ3dpEHSZBZ1FOGEpTV0pVW5v@RBVNa9UkmREbUb2dK0PpHgDBgsM1KUmcclEfiGTseaQaaGolMpVMqZkZMlsDFykTOwnE0ANgTJdSjm1Kah8QQHGJCNbMCCaAUOBsV1qcaYeyWSL8JSLdkBdA2W51ObUiFOemyXG5rm1dGKRHpkWq5BTjHkiZwOHS3DIV6qslEnSAJYYVA58xUBJJ88fU1azmSsk575/ci0qvqtJDEvmtfZc7bArdCUU1ZyLSuddxfhrMumsgveTfPpxwZ/Kd126Ev3nK9Br25BMvU5QEHihWiDwOl@DkGXCpdYGscbE71z89fMHKG9aO9LFIJmwwZJhL9teiaVDl3IZ8mpNyNzUHUNzXNb28TdD64pueMNqQ4VLVTYRqEmlymbm94NXiVUOLCVWFjIlPZ/s6hts6V6pMtTAJKYoQXLJJqaYNiVm0ZcUT7KIWfKlsicBXfGlqh@HQpa@nqdLkjORGpNuF@bz8JD6nysRZ9wfZu@7Tua0uTzM5JoN50jXzrrrViNdUZ36YDA@WDu4ttM3w1i6iUsMPTuL49/h8OepRzF0GwdbqVR1kT7HwQ34SQv0Ixz8jd2UKG3i4BV@fxqhBzi47z0KYXoPB38Qz6MQvY1tlbiO52kNBwfL4eUc/QoHHwTiZkAf4uCvoRon/m3O7ryizuhbHLweKZ9Hn@DgSVj94tFlHHwR0W1OL@PghbXE541s1e6C5R7oF47lTMuZ2tba@3T9mbHxdrBzJNUbu3cvP3zeSxdeL2@f3kpOubYY7wRoA5d6a8FSZvtiCUerUcOA76p5HN2L6Mfenqzg6GxYrYkd/SmOPgtpq7PzADlyaWFb4zSy5rk5@SY4iw5w9NyWtz93kiE/7LW4RZeIlOPvG9JK6BSVcLSocqoVPoOR/X4S95UmUh0c/ZHfu9Hzv4ejR7OzL0x/xNH3cfsDmt6POyIT0an86arD0RFDF5Ad68b@ayqdX6/1N/da/c3sevbze1dXFOXU@OrcfSoedzLDgWRopebZdg79nwt7/QY) That's a chonker of a Vim program right there. The inputted cube requires a padding of spaces around the sides. Additionally, I used `โ–ˆ` instead of `ยถ` as the stopping point, but that is only because `ยถ` has a special meaning in V. You can replace the `โ–ˆ` with `ยถ` and it will run just fine in Vim. ]
[Question] [ Given an integer `n` output the `n`th iteration of the [Hilbert Curve](https://en.wikipedia.org/wiki/Hilbert_curve) in ASCII using the characters `_` and `|`. Here are the first 4 iterations: ``` n=1 _ | | n=2 _ _ | |_| | |_ _| _| |_ n=3 _ _ _ _ | |_| | | |_| | |_ _| |_ _| _| |_____| |_ | ___ ___ | |_| _| |_ |_| _ |_ _| _ | |___| |___| | n=4 _ _ _ _ _ _ _ _ | |_| | | |_| | | |_| | | |_| | |_ _| |_ _| |_ _| |_ _| _| |_____| |_ _| |_____| |_ | ___ ___ | | ___ ___ | |_| _| |_ |_| |_| _| |_ |_| _ |_ _| _ _ |_ _| _ | |___| |___| |_| |___| |___| | |_ ___ ___ ___ ___ _| _| |_ |_| _| |_ |_| _| |_ | _ | _ |_ _| _ | _ | |_| |_| | |___| |___| | |_| |_| _ _ | ___ ___ | _ _ | |_| | |_| _| |_ |_| | |_| | |_ _| _ |_ _| _ |_ _| _| |___| |___| |___| |___| |_ ``` # Clarifications * My question is similar to [Draw the Hilbert Curve](https://codegolf.stackexchange.com/questions/100335/draw-the-hilbert-curve) and [Draw the Hilbert curve using slashes](https://codegolf.stackexchange.com/questions/34852/draw-the-hilbert-curve-using-slashes). * The conversion between underscores (`_`) and vertical bars (`|`) is `u=2*v-1` where `u` is the number of `_`s and `v` is the number of `|`s. * To maintain consistency with my original post the curve must start and end at the bottom. * You can have a full program or a function. * Output to stdout (or something similar). * You can have leading or trailing white-spaces, the output just needs to line up so that it looks like the examples. * This is code-golf so shortest answer in bytes wins. [Answer] # Befunge, ~~444~~ ~~368~~ 323 bytes ``` &1>\1-:v 0v^*2\<_$00p> _>:10p\:20pv^_@#-*2g00:+1,+55$ ^!-<v*2g000<>$#<0>>-\:v g2*^>>10g20g+v \ ^*84g_$:88+g,89+g,\1+:00 v#*!-1g02!g01_4^2_ >::00g2*-!\1-:10g-\20g-++>v 87+#^\#p01#<<v!`g01/2\+76:_ vv1-^#1-g01:\_$:2/20g`! _ 2/^>:10g#vv#`g02/4*3:\+77 v>0p^^/2:/2_ <^2-1-g02</2`#*3: 0g+10p2*:^*3_1 ! "#%$ %$"#! !!##% |||_ _ __ ``` [Try it online!](http://befunge.tryitonline.net/#code=JjE+XDEtOnYKMHZeKjJcPF8kMDBwPgpfPjoxMHBcOjIwcHZeX0AjLSoyZzAwOisxLCs1NSQKXiEtPHYqMmcwMDA8PiQjPDA+Pi1cOnYKZzIqXj4+MTBnMjBnK3YgXCBeKjg0Z18kOjg4K2csODkrZyxcMSs6MDAKdiMqIS0xZzAyIWcwMV80XjJfCj46OjAwZzIqLSFcMS06MTBnLVwyMGctKys+dgo4NysjXlwjcDAxIzw8diFgZzAxLzJcKzc2Ol8KdnYxLV4jMS1nMDE6XF8kOjIvMjBnYCEKXyAyL14+OjEwZyN2diNgZzAyLzQqMzpcKzc3CnY+MHBeXi8yOi8yXwo8XjItMS1nMDI8LzJgIyozOgowZysxMHAyKjpeKjNfMQohICIjJSQKJSQiIyEKICEhIyMlCnx8fF8KIF8gX18&input=NA) The typical approach to drawing the Hilbert Curve is to follow the path as a series of strokes and turns, rendering the result into a bitmap or some area of memory, and then writing out that rendering when the path is complete. This is just not feasible in Befunge when we only have 2000 bytes of memory to work with, and that includes the source of the program itself. So the approach we've taken here is to come up with a formula that tells us exactly which character to output for a given x,y coordinate. To understand how this works, it's easiest to ignore the ASCII rendering to start with, and just think of the curve as made up of box characters: `โ”Œ`, `โ”`, `โ””`, `โ”˜`, `โ”‚`, and `โ”€`. When we look at the curve like that, we can immediately see that right hand side is an exact mirror of the left hand side. Characters on the right can simply be determined by looking up their partner on the left, and reflecting it horizontally (i.e. occurrences of `โ”Œ` and `โ”` are swapped, as are `โ””` and `โ”˜`). ![Level 3 Hilbert Curve showing the reflection across the vertical axis](https://i.stack.imgur.com/qWv1y.png) Then looking at the bottom left corner, again we can see that the lower half is a reflection of the top half. Thus the characters on the bottom are simply determined by looking up their partner above, and reflecting it vertically (i.e. occurrences of `โ”Œ` and `โ””` are swapped, as are `โ”` and `โ”˜`). ![Level 3 Hilbert Curve showing the reflection across the horizontal axis in the bottom left corner](https://i.stack.imgur.com/O0PDn.png) The remaining half of this corner is a little less obvious. The right hand block can be derived from a vertical reflection of the block diagonally adjacent to it. ![Level 3 Hilbert Curve showing how the top right block of the bottom left corner can be derived](https://i.stack.imgur.com/Jl3HQ.png) And the left hand block can be derived from a vertical reflection of the block in the very top left of the full curve. ![Level 3 Hilbert Curve showing how the top left block of the bottom left corner can be derived](https://i.stack.imgur.com/l5PfW.png) At this point, all we're left with is the top left corner, which is just another Hilbert Curve one iteration lower. In theory, we should now just need to repeat the process again, but there's a bit of a catch - at this level, the left and right halves of the block aren't exact mirrors of each other. So at anything other than the top level, the bottom corner characters need to be handled as a special case, where the `โ”Œ` character is reflected as `โ”€`, and the `โ”‚` character is reflected as `โ””`. ![Level 3 Hilbert Curve showing how the top left block of the bottom left corner can be derived](https://i.stack.imgur.com/Nkf2p.png) But other than that, we really can just repeat this process recursively. At the last level we hardcode the top left character as `โ”Œ`, and the character below it as `โ”‚`. ![Sequence of images showing how the remaining parts of the curve are derived](https://i.stack.imgur.com/NAvsy.png) Now that we have a way to determine the shape of the curve at a particular x,y coordinate, how do we translate that into the ASCII rendering? It's actually just a simple mapping that translates each possible tile into two ASCII characters. * `โ”Œ` becomes `_` (space plus underscore) * `โ”` becomes (two spaces) * `โ””` becomes `|_` (vertical bar plus underscore) * `โ”˜` becomes `|` (vertical bar plus space) * `โ”‚` becomes `|` (again a vertical bar plus space) * `โ”€` becomes `__` (two underscores) This mapping isn't intuitive at first, but you can see how it works when looking at two corresponding renderings side by side. ![Level 2 Hilbert Curve rendered as ASCII art and with box characters](https://i.stack.imgur.com/XPjhZ.png) And that's basically all there is to it. Actually implementing this algorithm in Befunge is another problem altogether, but I'll leave that explanation for another time. [Answer] # C, 267 bytes ``` const n=4,s=1<<n,a[]={1,-s,-1,s};l,p,q; t(d){d&=3;p-q||printf("%.2s",&"__| _| |___ _|_| | | "[l*8+d*2]);p+=a[l=d];} h(d,r,n){n--&&(h(d+r,-r,n),t(d+r),h(d,r,n),t(d),h(d,r,n),t(d-r),h(d-r,-r,n));} main(){for(;p=s*s-s,l=1,q<s*s;++q%s||putchar(10))h(0,1,n),t(3);} ``` [Try it online!](https://tio.run/##VY/NisMgEMdfJQQaNI5LbXtYMD5JCCJKmoJrjVp6SPLq65rt9rAzh/n/5osZTbVV7pqzvruYKicuEAXrOgeqH8TCgEagDOLGLXiYeUIGL6YRZ@7pvK4@3FwaUX34OMUamlrKtfq1d6xWKWWhwrvXvW0/iWlPA@aeCNVbYQa@TchAAIcXR2nToIIkAN0zkHaN4d2x83@iryr9G8B8@1I3h/Ay3gPiXsQ2lh@sYDB3RXNC5kMslz@SnlRA7IjxhI7AXuvOZT7ny7cerbrGTJ8/ "C (clang) โ€“ Try It Online") `h()` uses recursion to generate the strokes of hlibert curve. `t()` only prints out the stroke character if the pen position `p` is equal to the current output position `q`. This is inefficient but simple. If the curve starts at top-left, the code can be reduced to 256 bytes. ]
[Question] [ And in particular the [second law](https://en.wikipedia.org/wiki/Second_law_of_thermodynamics): *the entropy of an isolated system undergoing an irreversible process increases with time*. For this challenge, * An "*isolated system*" will be taken to be a *program or function* (abbreviated as "program" from now on); * The "*irreversible process*" will be *execution* of code; * The passing of "*time*" will correspond to *iterated executions of the program's output*, considered as a new program; * "*Entropy*" will be taken as *Shannon's first-order entropy* (to be defined below), which is a measure of how diverse the characters of the string are. ## The challenge Your program should produce a non-empty string that when executed as a program in the same language produces a string with more entropy than the previous one. Infinitely iterating this execute-the-output process must produce a **strictly increasing sequence of entropy values**. The strings can contain any [Unicode 9.0](http://www.unicode.org/versions/Unicode9.0.0/) characters. The sequence of strings must be deterministic (as opposed to random). The **entropy** for a given string will be defined as follows. Identify its unique characters and their number of occurrences in the string. The frequency *pi* of the *i*-th unique character is the number of occurrences of that character divided by the length of the string. The entropy is then [![enter image description here](https://i.stack.imgur.com/goxXt.gif)](https://i.stack.imgur.com/goxXt.gif) where the sum is over all unique characters of the string. Technically, this corresponds to the [entropy of a discrete random variable](https://en.wikipedia.org/wiki/Entropy_(information_theory)) with distribution given by the frequencies observed in the string. Let *Hk* denote the entropy of the string produced by the *k*-th program, and let *H*0 denote the entropy of the initial program's code. Also, let *L*0 denote the length of the initial program in characters. The sequence {*Hk*} is monotone as per the challenge requirements, and is bounded (because the number of existing characters is finite). Therefore it has a limit, *H*โˆž. The **score** of a submission will be (*H*โˆžโˆ’*H*0)/*L*0: * The numerator, *H*โˆžโˆ’*H*0, reflects to what extent your code "obeys" the law of increasing entropy over an infinite time span. * The denonimator, *L*0, is the length of the initial code in characters (not in bytes). The code with the **highest score wins**. Ties will be resolved in favour of the earliest submission/edit. To compute the entropy of a string, you can use the JavaScript snippet (courtesy of [@flawr](https://codegolf.stackexchange.com/users/24877/flawr) and with corrections by [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) and [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)) at the end of this post. If obtaining the limit *H*โˆž is difficult in your specific case, you can use any lower bound, say *H*20, to compute the score (so you would use (*H*20โˆ’*H*0)/*L*0). But in any case, the infinite sequence of entropies must be strictly increasing. Please include an explanation or short proof that the sequence of entropies is increasing, if that's not evident. ## Example In a fictional language, consider the code `aabcab`, which when run produces the string `cdefgh`, which when run produces `cdefghi`, which ... The unique characters of the original code are `a`, `b` and `c`, with respective frequencies 3/6, 2/6 and 1/6. Its entropy is 1.4591. This is *H*0. The string `cdefgh` has more entropy than `aabcab`. We can know this without computing it because for a given number of characters the entropy is maximized when all the frequencies are equal. Indeed, the entropy *H*1 is 2.5850. The string `cdefghi` again has more entropy than the previous one. We can know without computing because adding a non-existing character always increases the entropy. Indeed, *H*2 is 2.8074. If the next string were `42` the chain would be invalid, because *H*3 would be 1, smaller than 2.8074. If, on the other hand, the sequence went on producing strings of increasing entropy with limit *H*โˆž = 3, the score would be (3โˆ’1.4597)/6 = 0.2567. ## Acknowledgments Thanks to * [@xnor](http://meta.codegolf.stackexchange.com/users/20260/xnor) for his help improving the challenge, and in particular for convincing me that infinite chains of increasing entropy obtained from iterated execution are indeed possible; * [@flawr](http://meta.codegolf.stackexchange.com/users/24877/flawr) for several suggestions, including modifying the score function, and for writing the very useful snippet; * [@Angs](http://meta.codegolf.stackexchange.com/users/60340/angs) for pointing out an essential drawback in a previous definition of the score function; * [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for a correction in the JavaScript snippet; * [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) for another correction in the snippet; * [@PeterTaylor](http://meta.codegolf.stackexchange.com/users/194/peter-taylor) for a correction in the definition of entropy. ## Snippet for calculating the entropy ``` function calculateEntropy() { var input = document.getElementById("input").value; // fetch input as string if (/[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)|([^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/.test(input)) { document.getElementById("output").innerHTML = " invalid (unmatched surrogates)"; return; } var charArray = input.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^]/g); var frequency = {}; for (var ind in charArray) { frequency[charArray[ind]] = 0; } var total = 0; for (var ind in charArray) { frequency[charArray[ind]] ++; total++; } var entropy = 0; for (var key in frequency) { var p = frequency[key] / total; entropy -= p * Math.log2(p); } document.getElementById("output").innerHTML = " " + entropy; }; ``` ``` <button type="button" onClick="javascript:calculateEntropy();">calculate</button>Entropy: <span id="output">NaN</span> <br/> <textarea id="input">asdf asdf</textarea> ``` [Answer] # MATLAB, ~~9.6923e-005~~ 0.005950967872272 ``` H0 = 2.7243140535197345, Hinf = 4.670280547752703, L0 = 327 ``` This new version is an improved version of the first "proof of concept". In this version I get a great score increase from the first iteration. This was achieved by "blowing up" the output of the first program, that is replicated by all the subsequent ones. Then I also tried to find the minimal `H0` by just appending the most common symbol of the code as many times as possible. (This had obviously a limit, since it does not only decrease `H0` but also increases `L0` at the same time. You can see the development of the score plotted against the size of the program where the size is varied by just adding or removing `1`.) The subsequent iterations still are equivalent to the previous version below. ``` a=['ns}z2e1e1116k5;6111gE16:61kGe1116k6111gE16:6ek7;:61gg3E1g6:6ek7;:61gg3E1'];11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111;;disp(['[''',a+1,'''];',0,'a=[''',a,'''];',0,[a-10,']]);'],0,[a-10,']]);']]); ``` ![Score vs Program length](https://i.stack.imgur.com/Cxdxz.jpg) ### Previous version: ``` H0 = 4.22764479010266, Hinf = 4.243346286312808, L0 = 162 ``` The following code is inspired by the [matlab quine](http://blog.garritys.org/2009/10/quines.html). It basically outputs just itself again *twice*. The clue is that for any iteration we have `n` lines of code and `n-1` newline symbols `\n`. So as `n` approaches to infinity, the ratio of lines of code to newlines approaches 1, and at the same time this guarantees that we have a strictly monotonous growth in entropy. That also means we can easily calculate `Hinf` by just considering the zero-th generation code with equally many newlines as lines of code. (Which one can experimentally confirm, as it converges quite quickly.) ``` a=['ns}z2e1kGe1116k6111gE16;:61kGe1116k6111gE16;:6ek7;:61gg3E1g6;:6ek7;:61gg3E1']; disp(['a=[''',a,'''];',10,'a=[''',a,'''];',10,[a-10,']]);'],10,[a-10,']]);']]); ``` [Answer] # Jelly, 0.68220949 ``` โ€œศท6ศท5rแปŒ,ยฎแนพโ‚ฌแนแนพYโพยฉvโธโตโ€ยฉvโต ``` **H90 = 19.779597644909596802, H0 = 4.088779347361360882, L0 = 23** I used long doubles to compute **H90**. Double precision floats incorrectly reported that **H47 < H46** The first program prints ``` โ€œโ€ฆโ€ โ€œศท6ศท5rแปŒ,ยฎแนพโ‚ฌแนแนพYโพยฉvโธโตโ€ยฉv1010 ``` where `โ€ฆ` serves as a placeholder for all Unicode characters with code points between **100,000** and **1,000,000**. The actual length is **900,031** characters. The seconds program prints ``` โ€œโ€ฆโ€ โ€œศท6ศท5rแปŒ,ยฎแนพโ‚ฌแนแนพYโพยฉvโธโตโ€ โ€œโ€ฆโ€ โ€œศท6ศท5rแปŒ,ยฎแนพโ‚ฌแนแนพYโพยฉvโธโตโ€ยฉv101010 ``` which, in turn, prints ``` โ€œโ€ฆโ€ โ€œศท6ศท5rแปŒ,ยฎแนพโ‚ฌแนแนพYโพยฉvโธโตโ€ โ€œโ€ฆโ€ โ€œศท6ศท5rแปŒ,ยฎแนพโ‚ฌแนแนพYโพยฉvโธโตโ€ โ€œโ€ฆโ€ โ€œศท6ศท5rแปŒ,ยฎแนพโ‚ฌแนแนพYโพยฉvโธโตโ€ยฉv10101010 ``` etc. None of these programs works in the online interpreter, which has a **100 KB** output limit. However, if we modify the program to print `0123456789` instead of the aforementioned **900,000** Unicode characters, you can [Try it online!](http://jelly.tryitonline.net/#code=4oCcNTcgNDhy4buMLMKu4bm-4oKs4bmB4bm-WeKBvsKpduKBuOKBteKAncKpduKBtQ&input=) ]
[Question] [ In light of the 2014 Australian Open in Melbourne, and the win by Stanislas Wawrinka against Novak Djokovic, I propose the following code golf challenge! Wawrinka and Djokovic are at it again for the basis of this CGC. Your challenge is to take a string consisting of 1's and 2's and determine the tennis scores based on the tennis scoring system. A "1" indicates that Wawrinka has scored a point, whereas a "2" indicates that Djokovic has scored a point. For the sake of example: `1211222122111122111` will generate a two-line output: ``` Wawrinka 1 - 40 Djokovic 1 - 30 ``` The longer the string, the further into the game the score is. Rules: * Shortest code wins, pure and simple. * The scores when displayed must be right aligned and also column aligned; e.g. * Sample alignment of output: ``` Wawrinka 7 5 3 - 0 Djokovic 6 7 4 - 15 ``` * If a game is in progress, the score must be displayed after the set scores. Game scores must follow set scores with a space-dash-space separator. If this happens to be the first game, a 0-0 set score must be displayed. ``` Wawrinka 0 - 0 Djokovic 0 - 15 ``` * A game will go in order of 0, 15, 30, 40, and game point. If a game reaches 40-40, a deuce is declared, and the score must display the deuce on the player row scoring the point: ``` Wawrinka 7 5 3 - 40 Djokovic 6 7 4 - 40 Deuce ``` * If a deuce is reached, the next point will be an advantage to the player scoring the point: ``` Wawrinka 7 5 3 - Ad Djokovic 6 7 4 - 40 ``` The point after that, if scored by the advantaged player, wins the game, else the game goes back to deuce. * If more than one deuce is scored in between advantage points, the number of the deuce will be indicated by a number in parentheses: ``` Wawrinka 7 5 3 - 40 Djokovic 6 7 4 - 40 Deuce (2) ``` * A set is won if a player reaches 6 games or more and with a two game margin in lead, e.g. 7-5, 6-4... 9-7 (In the case of last night's fifth set) * Consecutive sets must be separated with a space. * There are tie breaks in the Australian Open, therefore if a 6-6 set is reached, a tie-break is established by the first player reaching seven points with a two point margin lead. Display of tie breaks are shown within square brackets as follows: ``` Wawrinka 7 6 [6] Djokovic 6 6 [4] ``` The winner of the tie-break is said to have won the previous set 7-6. * If the fifth set reaches 6-6, play is continued without tie-break until a two game margin is reached with one player, that player being the winner of that set. There are NO tie-breaks in the fifth set. * If a player has won three sets, a third line will be displayed saying `Wawrinka wins` or `Djokovic wins` depending on who has won and the code then terminates. ``` Wawrinka 2 6 6 3 9 Djokovic 6 4 2 6 7 Wawrinka wins ``` * If the string ends such that the last point has won a game, set or match, the game score is not displayed... ``` Wawrinka 7 5 3 Djokovic 6 7 4 ``` * If the string goes beyond a match being won, the rest of the string is ignored, the score displayed and the winner declared. [Answer] ## Perl - 424 bytes ``` *1=a;*2=b;@1=(Wawrinka,0);@2=(Djokovic,0); $$_++>${$o=S^$_}&&$$_>3and$1=$2=0, $w=$w[$_]+=($$_[$.]++>$$o[$.]||(($t=$$_[$.]==$$o[$.])&&!$%&&$.<5))&& $$_[$.]>5+$%&&!($1[$.]=$2[$.+=!$%]=$w<2&&0,$$_[$.-1]+=$%,$%=$t)for<>=~/./g; @s=(' 0',15,30,(40)x($e=$$o<3||$$o-2),Ad); $%and$_="[$_]"for@1[-1],@2[-1];$d[$&]=$1>2&&$1==$2&&' Deuce'.($1>3&&" ($e)"); print"@1",$w<3&&" - $s[$1]$d[1]","\n@2",$w<3&&" - $s[$2]$d[2]",$w>2&&"\n${$&}[0] wins" ``` *Newlines have been added for ~~readability~~ horizontal sanity.* I believe this to be a complete solution, according to the scoring of the [Australian Open](http://www.ausopen.com/en_AU/event_guide/a_z_guide.html): * Best of five sets (a.k.a. race to three). * Sets 1-4 are played as a 6-6 tie-breaker. * Set 5 is played as an advantage set. ### Test Cases --- ``` 1211222122111122111 ``` # ``` Wawrinka 1 - 40 Djokovic 1 - 30 ``` --- ``` 12112221221111221112 ``` # ``` Wawrinka 1 - 40 Djokovic 1 - 40 Deuce ``` --- ``` 121122212211112211122 ``` # ``` Wawrinka 1 - 40 Djokovic 1 - Ad ``` --- ``` 1211222122111122111221 ``` # ``` Wawrinka 1 - 40 Deuce (2) Djokovic 1 - 40 ``` --- ``` 22111111212122221122111212212112121221212211221121222222112112221121121122221122221211111222121222122211212122111212112211222121211212211212211122121211112222222212211121122 ``` # ``` Wawrinka 6 [5] - 30 Djokovic 6 [6] - 40 ``` --- ``` 221111112121222211221112122121121212212122112211212222221121122211211211222211222212111112221212221222112121221112121122112221212112122112122111221212111122222222122111211222 ``` # ``` Wawrinka 6 0 - 0 Djokovic 7 0 - 0 ``` --- ``` 1122222211121211121211111121111211221222212212112221211222211222112212211121122122212122212222122212212211221111121222111221211111211112222212122122112111212121221221212211112122212211111111112111212222221112212121122212121111122111222222111212221121221111222122122222111212111111221121122111122122111222222121122221112221221122221121211212111122111121212112112121222122 ``` # ``` Wawrinka 5 4 6 6 5 - 15 Djokovic 7 6 4 4 6 - 40 ``` --- ``` 11222222111212111212111111211112112212222122121122212112222112221122122111211221222121222122221222122122112211111212221112212111112111122222121221221121112121212212212122111121222122111111111121112122222211122121211222121211111221112222221112122211212211112221221222221112121111112211211221111221221112222221211222211122212211222211212112121111221111212121121121212221222 ``` # ``` Wawrinka 5 4 6 6 5 Djokovic 7 6 4 4 7 Djokovic wins ``` --- ``` 222221112112212212222111222211111111121111121112211221221211212121122211222112111112122122212222211112122212221111121111121211212112112112221221121122121121112221221222122122211222212121212112112111221221121112222212122222221111112222222221221122211221121111221121222222111111122221122111211121222112112122212122221121222221222121212111121221221112111212212222122212212212112111112112112121112221111221221221121222122211221212211111111222222121221112221212 ``` # ``` Wawrinka 6 7 6 4 7 - 40 Djokovic 3 5 7 6 8 - Ad ``` --- ``` 2222211121122122122221112222111111111211111211122112212212112121211222112221121111121221222122222111121222122211111211111212112121121121122212211211221211211122212212221221222112222121212121121121112212211211122222121222222211111122222222212211222112211211112211212222221111111222211221112111212221121121222121222211212222212221212121111212212211121112122122221222122122121121111121121121211122211112212212211212221222112212122111111112222221212211122212122 ``` # ``` Wawrinka 6 7 6 4 7 Djokovic 3 5 7 6 9 Djokovic wins ``` All intermediate scores for the last test case can be seen here: <http://codepad.org/FzDIcf0W> [Answer] **ECMAScript 6 - 635 Characters** ``` f=(p,q,C)=>{B='';T=' ';L=(x)=>(B+x).length;M=(x,y)=>x>y?x:y;E=(a)=>{var x=L(a[0]),y=L(a[1]),q=M(x,y);for(;x++<q;)a[0]=T+a[0];for(;y++<q;)a[1]=T+a[1]};E(a=[p,q]);g=[m=n=o=i=t=z=0,0];s=[0,0];S=[0,0];w=2;O=(i)=>a[i]+(n+o>0?T+s[i]:B)+(o>0?(t?' ['+g[i]+']':' - '+[' 0',15,30,40,'Ad'][g[i]]+(z>0&&g[0]+g[1]==6&&i==w?' Deuce'+(z>1?' ('+z+')':B):B)):B)+'\n';while(W=C[i++]){w=--W;++o;if((d=++g[w])>M(t?6:3,(e=g[l=1-w])+1)){g=[o=z=0,0];j=++s[w];k=s[l];t=++n>11;if(j>M(5,m>4||k<6?k+1:6)){E(s);a[0]+=T+s[0];a[1]+=T+s[1];s=[n=0,0];++m;if(++S[w]>2)break}}else if(!t&&d+e>7){--g[w];--g[l];++z}}E(s);E(g);return O(0)+O(1)+(S[w]>2?(w?q:p)+' wins':B)} ``` **With comments:** ``` // Function f takes arguments: // p - Player 1 name // q - Player 2 name // C - String of 1s and 2s representing points won by players. f=(p,q,C)=>{ /* Empty String */ B=''; /* Space */ T=' '; /* String Length Func. */ L=(x)=>(B+x).length; /* Max Function */ M=(x,y)=>x>y?x:y; /* Equalize Length Func. */ E=(a)=>{var x=L(a[0]),y=L(a[1]),q=M(x,y);for(;x++<q;)a[0]=T+a[0];for(;y++<q;)a[1]=T+a[1]}; /* No. of sets */ m=0; /* No. games in set */ n=0; /* No. points in game */ o=0; /* Input Index */ i=0; /* Output String */ E(a=[p,q]); /* Current Game's Points */ g=[0,0]; /* Current Set's Games */ s=[0,0]; /* No. sets won */ S=[0,0]; /* Is a tiebreaker */ t=0; /* No. of deuces */ z=0; /* Current match result */ w=2; /* Output Fnctn */ O=(i)=>a[i]+(n+o>0?T+s[i]:B)+(o>0?(t?' ['+g[i]+']':' - '+[' 0',15,30,40,'Ad'][g[i]]+(z>0&&g[0]+g[1]==6&&i==w?' Deuce'+(z>1?' ('+z+')':B):B)):B)+'\n'; while(W=C[i++]){ w=--W; // w - index of winner of current game // l - index of loser of current game // d - winner of current point's game score // e - loser of current point's game score ++o; if((d=++g[w])>M(t?6:3,(e=g[l=1-w])+1)){ g=[0,0]; // Reset the game score. o=z=0; j=++s[w]; // j = Increment the winner's set score k=s[l]; // k = Loser's set score t=++n>11; // Is a tiebreak? if(j>M(5,m>4||k<6?k+1:6)){ E(s); a[0]+=T+s[0]; // Add to output a[1]+=T+s[1]; // Add to output s=[n=0,0]; // Reset current set's no. of games & no. of deuces. ++m; // Increment no. of sets. if(++S[w]>2)break; // Increment winners no. sets won and check if match won. } } else if(!t&&d+e>7){--g[w];--g[l];++z}// Check if deuces increased. } E(s); // Format sets strings. E(g); // Format games strings. return O(0)+O(1)+(S[w]>2?(w?q:p)+' wins':B); } ``` **Testing** ``` var tests=[ '', '1', '2', '11', '222', '1111', '2222', '1112221', '11122212', '121212121', '1212121212', '1211222122111122111', '12112221221111221112', '121122212211112211122', '1211222122111122111221', '1111222211112222111122221111222211112222111122221212121212121212121', '11111111111111111111111111111111111111111111111111111111111111111111111', '111111111111111111111111111111111111111111111111111111111111111111111111', '1111111111111111111111111111111111111111111111111111111111111111111111111' ]; for(var ex in tests) console.log('Test '+ex+'\n'+tests[ex]+'\n'+f('Wawrinka','Djokovic',tests[ex])); ``` **Test Outputs** ``` Test 0 Wawrinka Djokovic Test 1 1 Wawrinka 0 - 15 Djokovic 0 - 0 Test 2 2 Wawrinka 0 - 0 Djokovic 0 - 15 Test 3 11 Wawrinka 0 - 30 Djokovic 0 - 0 Test 4 222 Wawrinka 0 - 0 Djokovic 0 - 40 Test 5 1111 Wawrinka 1 Djokovic 0 Test 6 2222 Wawrinka 0 Djokovic 1 Test 7 1112221 Wawrinka 0 - Ad Djokovic 0 - 40 Test 8 11122212 Wawrinka 0 - 40 Djokovic 0 - 40 Deuce Test 9 121212121 Wawrinka 0 - Ad Djokovic 0 - 40 Test 10 1212121212 Wawrinka 0 - 40 Djokovic 0 - 40 Deuce (2) Test 11 1211222122111122111 Wawrinka 1 - 40 Djokovic 1 - 30 Test 12 12112221221111221112 Wawrinka 1 - 40 Djokovic 1 - 40 Test 13 121122212211112211122 Wawrinka 1 - 40 Djokovic 1 - Ad Test 14 1211222122111122111221 Wawrinka 1 - 40 Deuce Djokovic 1 - 40 Test 15 1111222211112222111122221111222211112222111122221212121212121212121 Wawrinka 6 [10] Djokovic 6 [ 9] Test 16 11111111111111111111111111111111111111111111111111111111111111111111111 Wawrinka 6 6 5 - 40 Djokovic 0 0 0 - 0 Test 17 111111111111111111111111111111111111111111111111111111111111111111111111 Wawrinka 6 6 6 Djokovic 0 0 0 Wawrinka wins Test 18 1111111111111111111111111111111111111111111111111111111111111111111111111 Wawrinka 6 6 6 Djokovic 0 0 0 Wawrinka wins ``` [Answer] # Javascript - 743 bytes ``` var b=process.argv[2],c=[0,0],e=[],g=[0,0],h=[0,0],k=["0","15","30","40"],l=["Wawrinka","Djokovic"];function m(a){var d="",f;for(f in e)d+=e[f][a]+" ";3<=c[0]||3<=c[1]||(d+=g[a]+" - ",f=h[a],a=h[(a+1)%2],d=n()?d+("["+f+"]"):3>f||3>a?d+k[f]:f>a?d+"Ad":d+k[3]);return d}function n(){return 6<=g[0]&&6<=g[1]}function p(){var a=q;g[a]++;h=[0,0];7<=g[a]?(e.push(g),g=[0,0],c[a]++):6<=g[a]&&g[a]>g[(a+1)%2]+1&&(e.push(g),g=[0,0],c[a]++)} for(var r in b){var q=parseInt(b[r])-1,s=++h[q];n()?7<=s&&(4>e.length?p():s>h[(q+1)%2]+1&&p()):4<=s&&s>h[(q+1)%2]+1&&p()}console.log(l[0]," ",m(0));console.log(l[1]," ",m(1),n()?"":2<h[0]&&2<h[1]&&h[0]==h[1]?"Deuce"+(3<h[0]?" ("+(h[0]-2)+")":""):"");console.log(3<=c[0]||3<=c[1]?(3<=c[0]?l[0]:l[1])+" wins":""); ``` Without closure compiler: ``` var input = process.argv[2]; var score = [0,0]; var match = []; var set = [0,0]; var game = [0,0]; var gameScore = [ '0', '15', '30', '40' ]; var names = ['Wawrinka', 'Djokovic']; function printScores(who) { var out = ''; for (var i in match) { out += match[i][who] + ' '; } if (!isDone()) { out += set[who] + ' - '; var point = game[who], otherPoint = game[(who+1)%2]; if (isTieBreaker()) { // Tie breaker out += '['+point+']'; } else { if (point < 3 || otherPoint < 3) { out += gameScore[point]; } else if (point > otherPoint) { out += 'Ad'; } else { out+= gameScore[3]; } } } return out; } function printDeuce() { if (isTieBreaker()) { return ''; } else { return (game[0] > 2 && game[1] > 2 && game[0] == game[1]) ? ('Deuce' + (game[0] > 3 ? ' (' + (game[0] - 2) + ')' : '')) : ''; } } function isDone() { return score[0] >= 3 || score[1] >= 3; } function isTieBreaker() { return set[0] >= 6 && set[1] >= 6; } function getOther(who) { return (who + 1) % 2; } function addPoint(who) { var points = ++game[who]; if (isTieBreaker()) { if (points >= 7) { if (match.length < 4) { addGame(who); } else if (points > (game[getOther(who)]+ 1)) { addGame(who); } } } else { if (points >= 4 && points > (game[getOther(who)] + 1)) { addGame(who); } } } function addGame(who) { set[who]++; game = [0,0]; if (set[who] >= 7) { // Won Tiebreaker addSet(who); } else if (set[who] >= 6 && set[who] > (set[getOther(who)] + 1)) { addSet(who); } } function addSet(who) { match.push(set); set = [0,0]; score[who]++; } // Play game for(var i in input) { addPoint(parseInt(input[i]) - 1); } console.log(names[0], ' ', printScores(0)); console.log(names[1], ' ', printScores(1), printDeuce()); console.log(isDone() ? ((score[0] >= 3 ? names[0] : names[1]) + ' wins') : ''); ``` ]
[Question] [ Given a sequence of the bases Adenine, Cytosine, Guanine and Thymine (encoded as `ACGT`), you're to produce an ASCII art representation of a corresponding double strand of DNA. The strand will extend vertically. The left-hand strand is the one you are given as input. The right-hand strand will be its complement. For those not familiar with DNA, `A` is paired with `T` and `C` is paired with `G`. Furthermore, there is backbone structure on either side of the double strand which is identical for all bases. So if you were given the input `TAGCAT` the large-scale structure of the ASCII art would be: ``` BTAB BATB BGCB BCGB BATB BTAB ``` where `B` represents the backbone. Now each of these letters stands for an entire molecule and you're to reproduce the [actual molecular structure](http://en.wikipedia.org/wiki/DNA#mediaviewer/File:DNA_chemical_structure.svg). ## The Bases Use the following templates1 for each of the bases (each one is displayed together with its complementary base and the two backbone molecules): 1Credits to Peter Taylor for helping out with the ASCII layout. **Adenine** ``` O O \\ / P / \ --O O / | < N NH2 ..... O * | \ // \ / \\ / | +--O // ---- ---- | | \ | // \\ / \\ | | >--N--< N ...... HN > ---+ | / \ / \ / / | +--- N=== ---N--< | | // \ | | O O--+ | \ | > | / O O-- \ / P / \\ O O ``` **Cytosine** ``` O ย  ย O \\ / P / \ --O ย  O NH2 ..... Oย  ย  ย  N / / ย  ย  ย  ย \\ ย  / \\ ย  ย  ย | < ย  ย  ย  ย  ---- ย  ย  ย  ---- ย  \\ ย ---+ \ ย  ย  ย  // \\ ย  ย  ย  ย  ย / ย \\ ย  | ย / ย  | +--O ย <ย  ย  N ...... HN ย  ย  >--N--< ย  ย | | ย  \ ย \ ย  / ย  ย  ย  ย  ย \ย  ย  / ย  ย  ย \ ย  | | ย  ย >--N---ย  ย  ย  ===N ย  ย  ย  ย  O--+ | ย  / ย  ย  ย \\ ย  ย  ย  ย  ย  / ย  ย  ย  ย  ย  ย  ย  ย  \ +--- ย  ย  ย  ย  O .....ย H2Nย  ย  ย  ย  ย  ย  ย  ย  ย  ย > | ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  / ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย O ย  O-- ย  ย  ย  ย  ย  ย  ย  ย  ย  ย ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  \ / ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย P ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  / \\ ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย O ย  ย O ``` **Guanine** ``` O O \\ / P / \ --O O / | < N O ..... H2N | \ // \ // \ | +--O // ---- ---- | | \ | // \ // \\ | | >--N--< NH ...... N > ---+ | / \ / \ / / | +--- N=== ---N--< | | \ // \ | | NH2 ..... O O--+ | \ | > | / O O-- \ / P / \\ O O ``` **Thymine** ``` O ย  ย O \\ / P / \ --O ย  O * O ..... H2Nย  ย  ย  N / \ // ย  ย  ย  ย \ ย  / \\ ย  ย  ย | < ย  ย  ย  ย  ---- ย  ย  ย  ---- ย  \\ ย ---+ \ ย  ย  ย  // \ ย  ย  ย  ย  ย // ย \\ ย  | ย / ย  | +--O ย <ย  ย  NH ...... N ย  ย  >--N--< ย  ย | | ย  \ ย \ ย  / ย  ย  ย  ย  ย \ย  ย  / ย  ย  ย \ ย  | | ย  ย >--N---ย  ย  ย  ===N ย  ย  ย  ย  O--+ | ย  / ย  ย  ย \\ ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  \ +--- ย  ย  ย  ย  O ย  ย  ย  ย  ย  ย  ย  ย  ย > | ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  / ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย O ย  O-- ย  ย  ย  ย  ย  ย  ย  ย  ย  ย ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  \ / ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย P ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  / \\ ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย O ย  ย O ``` ## Constructing the Double Strand These repeat vertically, such that there are no gaps in the backbone structure. This means that the bounding boxes of these four templates will overlap. The bottom end of the left and top end of the right backbone will connect to the `O` of an `OH`. The free `O` at the top end of the left and bottom end of the right backbone will have a free bond going inwards, indicated by `--`. **Example** `ATG` ``` O O-- \\ / P / \ --O O OH / | < N NH2 ..... O * | \ // \ / \\ / | +--O // ---- ---- | | \ | // \\ / \\ | | >--N--< N ...... HN > ---+ | / \ / \ / / | +--- N=== ---N--< | | // \ | | O O--+ | \ | > | / O ย  ย O O O-- \\ / \ / P P / \ / \\ --O ย  O * O ..... H2Nย  ย  ย  N O O / \ // ย  ย  ย  ย \ ย  / \\ ย  ย  ย | < ย  ย  ย  ย  ---- ย  ย  ย  ---- ย  \\ ย ---+ \ ย  ย  ย  // \ ย  ย  ย  ย  ย // ย \\ ย  | ย / ย  | +--O ย <ย  ย  NH ...... N ย  ย  >--N--< ย  ย | | ย  \ ย \ ย  / ย  ย  ย  ย  ย \ย  ย  / ย  ย  ย \ ย  | | ย  ย >--N---ย  ย  ย  ===N ย  ย  ย  ย  O--+ | ย  / ย  ย  ย \\ ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  \ +--- ย  ย  ย  ย  O ย  ย  ย  ย  ย  ย  ย  ย  ย > | ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  / O O ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย O ย  O-- \\ / ย  ย  ย  ย  ย  ย  ย  ย  ย  ย ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  \ / P ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย P / \ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  / \\ --O O ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  ย O ย  ย O / | < N O ..... H2N | \ // \ // \ | +--O // ---- ---- | | \ | // \ // \\ | | >--N--< NH ...... N > ---+ | / \ / \ / / | +--- N=== ---N--< | | \ // \ | | NH2 ..... O O--+ | \ | > | / OH O O-- \ / P / \\ --O O ``` **More Examples:** Here are the MD5 hashes of several more examples (without extraneous leading or trailing spaces): ``` ATG 2e4a906c44a96fe84134bf4346adf11c (this is the above example) C e3648b8960967463784818c3eee57246 TTT 6028a90b05775905ef1a00e7a45463c5 TAGCAT 3b834d2b7b9adc4113ffabd52d354c41 GATTACA a19463f965c641d071e07da59d64a418 ``` Let me know if you think any of these are wrong. If you're unsure how to check your results' hashes reliably, try [this online MD5 generator](http://onlinemd5.com/). Make sure that there is no trailing line break. ## Further Notes You *may* use leading or trailing spaces as you see fit. Of course, if you use leading spaces it has to be the same amount in each line. If I have made any mistakes in copying the chemical structure, the above templates are still normative for the purposes of this challenge. You may write a function or a program which takes the input *string* as a parameter, command-line argument via STDIN or expects it to be stored in a variable. Write the resulting ASCII art to STDOUT. This is code golf, so the shortest answer (in bytes) wins. [Answer] # [Python 3](https://docs.python.org/3/), 1008 bytes Decomposite to smaller blocks and then compress using python's zlib and encode the binary data with asii85 encoding. Before compressing, the size is 629 and after compression and encoding, the size is 260. Smaller blocks: ``` N NH2 NH2 ... * O ..... N O .. O O ---+ // \ / / \ // // \ // \\ / / | // ---- ---- ---- // ---- P --< | | // \\ // \\ // \ | // \ / \ \ | N--< N .. < N ..... < NH .... N--< NH . --O O O--+ \ / \ / \ / \ / / \ N=== N--- N--- N=== < > \\ \\ \ \ / O ..... O NH2 +--O O O-- | \ \ / | >-- P | / / \\ +--- O O ``` The program reads from STDIN. It may have trailing spaces at the end of each line and may have empty lines at the end. ``` import zlib,base64 D=input() B=b'GasbU3tfFR$q,H5@dA9CAl@Bd?/ZcRUN$!!66MJ3&IN+RbL6[r)7K,3-8;3.^a\'7XZD_Lh;(7`.g>%[1,o(<9L\\neaPK"9^lCg7teknAd\\HXFNbL!)l/pG]YNpRS-C]sXR5A[A[#C&pnT;I-Q$Bj@n$L"ODZk8M_YcM#\\5PaLq3@UfJmfm[)$+#H,A\\B+b`mL9^OQ/cET-@`YRD_DJ6mXMD">9HHep\\%LnL8&\\G?fDdbs20%[J\'jMG[Qp' B=[b.split('\n')for b in zlib.decompress(base64.a85decode(B)).decode().split('\n\n')] C=dict(zip('/\\<>', '\\/><')) a=[(6,14),(6,28),(10,40)] b=[(4,12),(4,26),(6,40)] P=[a,b,b,a] H=[18,14,14,18] J=''.join R=range L=len F=[[' ']*54 for _ in R(5+18*L(D))] e=enumerate y=0 def t(b,p): for i,r in e(b): for j,c in e(r): if' '!=c:F[y+p[0]+i][p[1]+j]=c O=['OH'] U=['--'] t(O,(4,47)) t(U,(0,7)) for i in map('ACTG'.index,D): a,b,c=P[i];t(B[4],(0,0));t(B[i],a);q=B[(i+2)%4];t([J(C.get(z,z)for z in l[::-1]).replace('2HN', 'H2N')for l in[r+' '*(max(map(L,q))-L(r))for r in q]],b);t(B[5],c) for j in R(y+13,y+H[i]):F[j][6]='|' for j in R(y+5,y+c[0]):F[j][47]='|' y+=H[i] t(O,(0,6)) t(U,(4,45)) for l in F:print(J(l)) ``` Checksum matched using [this script](http://pastebin.com/VmbBapnF) And here's the ungolfed version: ``` import zlib, base64 flip_char_map = dict(zip('/\\<>', '\\/><')) def flip_char(c): return flip_char_map.get(c, c) def pad(block): w = max(map(len, block)) return [line + ' ' * (w - len(line)) for line in block] def flip(block): return [''.join(map(flip_char, line[::-1])).replace('2HN', 'H2N') for line in pad(block)] blocks = b'GasbU3tfFR$q,H5@dA9CAl@Bd?/ZcRUN$!!66MJ3&IN+RbL6[r)7K,3-8;3.^a\'7XZD_Lh;(7`.g>%[1,o(<9L\\neaPK"9^lCg7teknAd\\HXFNbL!)l/pG]YNpRS-C]sXR5A[A[#C&pnT;I-Q$Bj@n$L"ODZk8M_YcM#\\5PaLq3@UfJmfm[)$+#H,A\\B+b`mL9^OQ/cET-@`YRD_DJ6mXMD">9HHep\\%LnL8&\\G?fDdbs20%[J\'jMG[Qp' blocks = [b.split('\n') for b in zlib.decompress(base64.a85decode(blocks)).decode().split('\n\n')] poss = [ [(6, 14), (6, 28), (10, 40)], [(4, 12), (4, 26), (6, 40)], [(4, 12), (4, 26), (6, 40)], [(6, 14), (6, 28), (10, 40)], ] heights = [18, 14, 14, 18] get_id = 'ACTG'.index dna = input() height = sum(heights[get_id(x)] for x in dna) field = [[' '] * 54 for _ in range(height + 5)] def put(block, pos): i, j = pos for di, row in enumerate(block): for dj, c in enumerate(row): if c != ' ': field[y + i + di][j + dj] = c y = 0 put(['OH'], (4, 47)) put(['--'], (0, 7)) for p in dna: i = get_id(p) h = heights[i] pos = poss[i] put(blocks[4], (0, 0)) put(blocks[i], pos[0]) put(flip(blocks[(i + 2) % 4]), pos[1]) put(blocks[5], pos[2]) for j in range(y + 13, y + h): field[j][6] = '|' for j in range(y + 5, y + pos[2][0]): field[j][47] = '|' y += h put(['OH'], (0, 6)) put(['--'], (4, 45)) for line in field: print(''.join(line).rstrip()) from hashlib import md5 import sys result = '\n'.join(map(str.rstrip, map(''.join, field))).encode() print(md5(result).hexdigest(), file=sys.stderr) ``` [Answer] # Perl 5 (510) Perl's fine with null bytes, so please use the hexdump provided for running this. This works by printing out different parts of the DNA strand, with parts being one or more lines. An O or H is appended to the top line of each component to ensure valid output. Assumes input is in the variable `$_`. Golfed version: ``` use Compress::Zlib;@f=(eval uncompress q+xล“รUร‹nรƒ ยผรณ{ยณโ€โ€ยฌโ€slqรครน |xลกร…< Mร”vยค(1bยผ;รŒโ€ž]8ร— `?Cรร‹ร—ร‚รœ/ยฅร€รฎยบยคร‚โ€”ยผรƒร"6p!ร‡vDรฟ@k โ€˜ยฎ^รร€ ยฒ>รˆB$รฌยกรŒHBรฝi`รฃ\qรพห†Rn^โ€šยข6WรฉJยฑรญRCXร€\Cj[ยญรซzร–Kg-ยตโ‚ฌหœ*Rtยฎabลก3โ€˜ยชยคยฐรˆโ€ "]ร–SXโ€ฐG2รดล“ร‚V<<#9_รลฝGยด8Oa3uE'ร‡C%โ€ฆยนโ€”tLยบลกร‚BCQโ€นยกNรˆยป*/ Vร—Aร›Vร”ร–ArยฉKรปรŠhรกtยฐDรƒรZรฟร>; kMโ€š2(9รกรฝIP t'Aโ€ยฟลพg qยญ= ล [~yรŒยฒรนNร‡sNsลฝลฝGร—ล“:Iรqล ร™l)หœรนรฐ รฌโ€ฆรงรŽรยซ:eรดu?<(- รฉย รฆ ลฝRxNSรœAM1ร‚โ€ขย โ€”)ลกโ€”%+);s/./$y.=$f[$u?8:9].$f[$q=(-65+ord$&)%15].($u++?" O":H).$f[$q+1]/ge;($y.=$f[10])=~s/@/\\/g;print$y ``` Ungolfed version: ``` use Compress::Zlib; # load parts to @f; see below for list of parts @f=(eval uncompress q+ .... +); # for each chracater in input ($_) s/./ # append either the one or two backbone molecules # then append most of the first line of the base, followed by an O or H # then append the rest of the base $y .= $f[$u?8:9] . $f[$q = (-65+ord$&)%15] . ($u++?" O":H) . $f[$q+1] /ge; # append the last backbone molecule, then replace # @ with \ ($y .= $f[10])=~s/@/\\/g; print $y ``` `(-65+ord$&)%15` conveniently results in `A=>0, C=>2, T=>4, G=>6`, which is perfect as the program needs two elements in the array for each letter. The center part, top part, and bottom part are stored in indices `8-10` in that order. List of Parts (uses @ instead of \ to avoid a ton of escaping): ``` '--O O O', ' / | < N NH2 ..... O * | @ // @ / @@ / | +--O // ---- ---- | | @ | // @@ / @@ | | >--N--< N ...... HN > ---+ | / @ / @ / / | +--- N=== ---N--< | | // @ | | O O--+ | @ | > ', '--O O NH2 ..... O N O', ' / / @@ / @@ | < ---- ---- @@ ---+ @ // @@ / @@ | / | +--O < N ...... HN >--N--< | | @ @ / @ / @ | | >--N--- ===N O--+ | / @@ / @ +--- O ..... H2N > ', '--O O * O ..... H2N N O', ' / @ // @ / @@ | < ---- ---- @@ ---+ @ // @ // @@ | / | +--O < NH ...... N >--N--< | | @ @ / @ / @ | | >--N--- ===N O--+ | / @@ @ +--- O > ', '--O O O', ' / | < N O ..... H2N | @ // @ // @ | +--O // ---- ---- | | @ | // @ // @@ | | >--N--< NH ...... N > ---+ | / @ / @ / / | +--- N=== ---N--< | | @ // @ | | NH2 ..... O O--+ | @ | > ', ' | / O O O O-- @@ / @ / P P / @ / @@ ', ' O O-- @@ / P / @ ', ' | / OH O O-- @ / P / @@ --O O' ``` Hexdump: ``` 0000000 7375 2065 6f43 706d 6572 7373 3a3a 6c5a 0000010 6269 403b 3d66 6528 6176 206c 6e75 6f63 0000020 706d 6572 7373 7120 782b cd9c cb55 c36e 0000030 1020 f3bc 7b15 94b3 ac94 7394 716c 04e4 0000040 20f9 7c7f 9a78 3cc5 4d0a 76d4 28a4 6231 0000050 3bbc 84cc 385d 00d7 3f60 d043 d7cb dcc2 0000060 1c2f c0a5 08ee ba0f c2a4 bc97 cdc3 3622 0000070 2170 1004 76c7 ff44 6b40 910a 0216 ae01 0000080 8d5e 0fdd 0dc0 3eb2 42c8 ec24 cca1 481e 0000090 9042 08fd 8169 6012 5ce3 fe71 5288 5e6e 00000a0 0c82 36a2 e957 084a edb1 4352 c058 435c 00000b0 5b6a ebad d67a 4b10 2d67 80b5 2a98 108d 00000c0 1052 ae74 0c61 9a62 1b01 9133 a4aa c8b0 00000d0 2286 d65d 5853 4789 f432 c29c 3c56 233c 00000e0 1839 d05f 478e 38b4 614f 1e33 0775 2745 00000f0 c71e 2543 b985 1306 7497 ba4c c29a 4342 0000100 510e a18b 4e0e bbc8 082a 0715 0d2f d756 0000110 db41 5616 7fd4 41d6 a972 4b10 0efb 68ca 0000120 7fe1 b074 c344 1ec1 ff5a 1ec1 3b3e 1a09 0000130 6b09 824d 2832 e139 49fd 0f50 740a 4127 0000140 9411 9ebf 6704 710d 3dad 8a09 175b 797e 0000150 cc12 90b2 4ef9 73c7 4e0b 7311 8e8e d747 0000160 1b9c 493a 71cf d98a 296c f998 0df0 85ec 0000170 cee7 abc1 1a3a f465 3f75 283c 2d07 0907 0000180 a0e9 20e6 528e 7813 534e 41dc 314d 95c2 0000190 97a0 2917 979a 2b25 3b29 2f73 2f2e 7924 00001a0 3d2e 6624 245b 3f75 3a38 5d39 242e 5b66 00001b0 7124 283d 362d 2b35 726f 2464 2926 3125 00001c0 5d35 282e 7524 2b2b 223f 2020 2020 224f 00001d0 483a 2e29 6624 245b 2b71 5d31 672f 3b65 00001e0 2428 2e79 243d 5b66 3031 295d 7e3d 2f73 00001f0 2f40 5c5c 672f 703b 6972 746e 7924 00001fe ``` ]
[Question] [ Your goal is to print the lyrics to the song "Twinkle Twinkle Little Star" as each note is played. The computer's microphone will hear notes. If the pitch (but not necessarily the length) of the note is correct, print the appropriate syllable. Otherwise, do nothing. Each note will be at least half a second long, and there will be a break of at least a quarter of a second between notes. Use the musical notes provided [here](http://en.wikipedia.org/wiki/File:Twinkle_Twinkle_Little_Star.png), and the following lyrics: (Vertical lines represent syllable breaks.) > > Twin|kle, twin|kle, lit|tle star, > > > How I won|der what you are. > > > Up a|bove the world so high, > > > Like a dia|mond in the sky. > > > Twin|kle, twin|kle, lit|tle star, > > > How I won|der what you are. > > > A recording of the music can be found [here](https://en.wikipedia.org/wiki/File:Twinkle_Twinkle_Little_Star_plain.ogg). # Example The computer hears a middle C and prints "Twin" It hears another middle C and prints "kle," Then it hears another middle C (wrong note) and does nothing. Then it hears the G above middle C and prints "twin" and so on. # Rules * Punctuation must be as shown. * Spacing must be as shown (with spaces and newlines). * The whitespace may be printed along with either the previous or the next syllable. [Answer] ## Python 3 - Partial solution (~~760~~ ~~742~~ ~~734~~ ~~710~~ ~~705~~ 657 characters) *(Last edit; I promise)* This seems like a really, pretty, very hard problem (especially recognizing where the notes start or end). Automatic transcription of music seems like an open research topic (not that I know anything about it). So here's a partial solution that doesn't do any note segmentation (eg it prints "Twinkle" all at once when it hears the frequency) and probably only works for that specific ogg file: ``` A=-52 F=44100 C=4096 import pyaudio as P import array import scipy.signal as G import numpy as N import math L=math.log i=0 j=[9,2,0,2,4,5,7,9] k=[2,4,5,7] n=j+k+k+j w="Twinkle, |twinkle, |little |star,\n|How I |wonder |what you |are.\n|Up a|bove the |world so |high,\n|Like a |diamond |in the |sky.\n".split('|') w+=w[:8] e=P.PyAudio().open(F,1,8,1,0,None,0,C) while i<24: g=array.array('h',e.read(C));b=sum(map(abs,g))/C if b>0 and 20*L(b/32768,10)>A: f=G.fftconvolve(g,g[::-1])[C:];d=N.diff(f);s=0 while d[s]<=0:s+=1 x=N.argmax(f[s:])+s;u=f[x-1];v=f[x+1] if int(12*L(((u-v)/2/(u-2*f[x]+v)+x)*F/C/440,2))==n[i]+15:print(w[i],end='',flush=1);i+=1 ``` This requires... * Python 3 (tested with 3.3 on Windows 64 bit... *should* work on Mac/Linux in theroy) * [PyAudio](http://people.csail.mit.edu/hubert/pyaudio/) (I used the [windows binary package from here](http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#pyaudio), since the windows binary packages from the PyAudio page didn't work) * SciPy and NumPy (I used [scipy-stack from the same site](http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#scipy-stack)) Change the A=-52 (minimum amplitude) on the top line depending on your microphone, ammount of ambient sound, how loud the song is playing, etc. On my microphone, less than -57 seems to pick up a lot of extraneous noise and more than -49 requires you play it very loud. This could be golfed a LOT more; I'm sure there are ways to save a bunch of characters on the words array in particular. This is my first non-trivial program in python, so I'm not very familiar with the language yet. I stole the code for frequency detection via autocorrelation from <https://gist.github.com/endolith/255291> Ungolfed: ``` import pyaudio from array import array import scipy.signal import numpy import math import sys MIN_AMPLITUDE = -52 FRAMERATE = 44100 def first(list): for i in range(len(list)): if(list[i] > 0): return i return 0 # Based on: https://en.wikipedia.org/wiki/Decibel#Acoustics def getAmplitude(sig): total = 0; elems = float(len(sig)) for x in sig: total += numpy.abs(x) / elems if(total == 0): return -99 else: return 20 * math.log(total / 32768., 10) # Based on: https://en.wikipedia.org/wiki/Piano_key_frequencies def getNote(freq): return int(12 * math.log(freq / 440, 2) + 49) # -------------------------------------------------------------------------- # This is stolen straight from here w/ very slight modifications: https://gist.github.com/endolith/255291 def parabolic(f, x): return 1/2. * (f[x-1] - f[x+1]) / (f[x-1] - 2 * f[x] + f[x+1]) + x def getFrequency(sig): # Calculate autocorrelation (same thing as convolution, but with # one input reversed in time), and throw away the negative lags corr = scipy.signal.fftconvolve(sig, sig[::-1], mode='full') corr = corr[len(corr)/2:] # Find the first low point diffs = numpy.diff(corr) # Find the next peak after the low point (other than 0 lag). This bit is # not reliable for long signals, due to the desired peak occurring between # samples, and other peaks appearing higher. # Should use a weighting function to de-emphasize the peaks at longer lags. start = first(diffs) peak = numpy.argmax(corr[start:]) + start return parabolic(corr, peak) * (FRAMERATE / len(sig)) # -------------------------------------------------------------------------- # These are the wrong keys (ie it is detecting middle C as an A), but I'm far too lazy to figure out why. # Anyway, these are what are detected from the Wikipedia .ogg file: notes = [73, 66, 64, 66, 68, 69, 71, 73, 66, 68, 69, 71, 66, 68, 69, 71 ] words = ["Twinkle, ", "twinkle, ", "little ", "star,\n", "How I ", "wonder ", "what you ", "are.\n", "Up a", "bove the ", "world so ", "high,\n", "Like a ", "diamond ", "in the ", "sky.\n"] notes += notes[:8] words += words[:8] pa = pyaudio.PyAudio() stream = pa.open(format=pyaudio.paInt16, channels = 1, rate = FRAMERATE, input = True, frames_per_buffer = 4096) idx = 0 while(idx < len(notes)): # Read signal sig = array('h', stream.read(4096)) if(getAmplitude(sig) > MIN_AMPLITUDE): note = getNote(getFrequency(sig)) if(note == notes[idx]): sys.stdout.write(words[idx]) sys.stdout.flush() idx += 1 ``` ]
[Question] [ ### Background As noted in the PPCG challenge [Compress a maximal discrepancy-2 sequence](https://codegolf.stackexchange.com/q/122304/12012) โ€“ which inspired this challenge โ€“ the authors of the paper [Computer-Aided Proof of Erdล‘s Discrepancy Properties](https://arxiv.org/pdf/1405.3097v2.pdf) found a maximal discrepancy-2 sequence, namely ``` -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, -1, 1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, -1, -1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, -1, -1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, 1 ``` However, this is not the the only discrepancy-2 sequence of the length 1160; apart from the obvious variation of negating every term of the sequence, the are many valid variations that involve negating a pair of terms, and possibly entirely unrelated approaches that also lead to maximal sequences. The papers's authors made several design decisions that sped up their algorithm, but would a different set of decisions lead to a more compressible sequence? Let's find out! ### Definitions Let \$k\$ and \$n\$ be positive integers. A finite sequence \$x\_1, \dots, x\_n\$ over \$\{-1, 1\}\$ is of discrepancy \$d\$ if $$ \max\_{1\leq k\leq m\leq n} \left| \sum\_{1\leq jk\leq m} x\_{jk} \right| \leq d $$ In other words, the partial sums of the subsequences resulting of taking every \$k\$th term of \$x\$ all lie in the interval \$[-d, d]\$. The sequence provided by the authors is of discrepancy **2**, as can be verified programmatically. For the first three values of \$k\$, we get the following subsequences and partial sums. ``` k = 1: -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, ... (sums) -1, 0, 1, 0, 1, 0, -1, 0, 1, 0, 1, 2, 1, 2, 1, 0, 1, 0, ... k = 2: 1, -1, -1, 1, -1, 1, 1, -1, -1, ... (sums) 1, 0, -1, 0, -1, 0, 1, 0, -1, ... k = 3: 1, -1, 1, 1, -1, -1, ... (sums) 1, 0, 1, 2, 1, 0, ... ``` Later terms of the sequences of partial sums never reach **-3** or **3**. In contrast, **1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1** is *not* a discrepancy-2 sequence. ``` k = 1: 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1 (sums) 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, -1, 0 k = 2: -1, 1, -1, 1, -1, 1 (sums) -1, 0, -1, 0, -1, 0 k = 3: -1, -1, 1, 1 (sums) -1, -2, -1, 0 k = 4: 1, 1, 1 (sums) 1, 2, 3 ``` ### Task Write a full program or a function that takes no input, prints or returns a single discrepancy-2 sequence with 1160 terms, and abides to the following rules. * You can use any kind of iterable (arrays, strings, etc.) that consists of exactly two different symbols: one representing **-1** and one representing **1**. * Your output must be consistent, i.e., every time your code is run, it must output the same sequence. * You must include the output of your program in your answer. * Hardcoding your output sequence is allowed. * To prevent trivial brute-force solutions, your code must finish in under a minute. For borderline-compliant solutions, I'll determine the official run time on my own machine (Intel Core i7-3770, 16 GiB RAM, openSUSE 13.2) or a sufficiently similar one if I cannot test your code on mine. * Any built-in that is itself a valid submission to this challenge or a variation that takes the discrepancy as input (e.g., `FindMaximalDiscrepancySequence`) may not be in your answer. All other built-ins โ€“ including built-ins that calculate the discrepancy of a sequence โ€“ are allowed. While finding a suitable sequence is a big part of the task, only your implementation contributes to your score. In other words, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), and may the shortest code in bytes win! ### Validation You can use [this Python script](https://tio.run/nexus/python3#dZDNbsIwEITP5ClGXGKrRMIcekCltz5BDz1UFTLpQiwFk3qd/qrPTteQQJCKkhy8nvkmO3umt5Z8SViA3m2tnG/aqLTOMreG30UwRdWLNO4W@CnMBOZ3no2a4HxU44cQdmGOWBF6Yc5wkbaMbcsRKwI5uQ4oDHYBZqyzEX26qMwxpyY/zIAxt9MTP3@ywTu/uUxAZRlr@hBorKw/WI6ZuTDXksKRmiW7b4LzCNZvSMmPX0TpFGJDdLZecruVDqbZKHkTKNl65fMZVsBgLs9p8iKQC8rN4uCXqaxmV6wGlxr3mCVDv9ygvE4Gkclq3QZIEfnkHDdBHsiWlcyG3IQ8VdqxH9uyJOZ/int1XAZqrC@/MMv1fi/NFN13fK@c/gA "Python 3 โ€“ TIO Nexus") to verify the output of your submission. It expects a string of comma-separated **-1**'s and **1**'s. [Answer] # [C (gcc)](https://gcc.gnu.org/), 416 bytes ``` f(i){for(i=1160;i--;)putchar(L"\x72ca563b\xd24f18ad\xa70acd36\x59a6b345\xd669d0cb\x729b4962\xcd34ba65\x6359a2d2\x2e5c6936\x592ad729\xda652af1\xe69b4934\xc70adb50\xcc3b30dc\x96934dac\x69b1c6c3\x5b49369c\x3692ed26\xc9c6d329\xda4cf493\xa6716962\x6d349b43\xf26d349a\xa6934f22\xab14f235\xa569a4d5\xb4d26996\xd1a652e9\x9a6d2671\xa4e54bb4\x750e938d\xd369369a\x469b4d22\x69b0dacd\xb345a4f2\xb49a4d36i"[i/32]>>i%32&1?43:45);} ``` *-a ton of bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!* [Try it online!](https://tio.run/##JVHLTgMxDPyXSqDtoSKJHW9DRfkB/oDl4DgbyIGHKpAiIb69TNrLatYzHo8d272anc91atvf@nma2oP34g5ttztsv36@7U1P09Nm6XMwjUJ56SVw9XstS9fZqRWSpcekkokjWJFUnOXRkTInCUuHhrMKWCEoQ0EtrNEkXXuDFojRC03Q6pe@yuglRi9mlBwdkFEmV2zpCY1cFAgyb2IEl6GXhBq@YS0BzpZMCl2d2SoEyCyzl0sqUIwpqNVwwTpYONcAVrMHIGTG2km5AGWGbUpwLn5EXeGMxVGckVl5jZwzMs/RrYn2uBCOM1LBmcdGZTgDOIQHOy6mmDKcxwiStnludxRejsd2Q@HWPzLdc9we/s7v2j4mPNE0fv4B "C (gcc) โ€“ Try It Online") # [C (gcc)](https://gcc.gnu.org/), 416 bytes ``` f(i){for(i=1160;i--;)putchar(L"\x72ca563b\xd24f18ad\xa70acd36\x59a6b345\xd669d0cb\x729b4962\xcd34ba65\x6359a2d2\x2e5c6936\x592ad729\xda652af1\xe69b4934\xc70adb50\xcc3b30dc\x96934dac\x69b1c6c3\x5b49369c\x3692ed26\xc9c6d329\xda4cf493\xa6716962\x6d349b43\xf26d349a\xa6934f22\xab14f235\xa569a4d5\xb4d26996\xd1a652e9\x9a6d2671\xa4e54bb4\x750e938d\xd369369a\x469b4d22\x69b0dacd\xb345a4f2\xb49a4d36i"[i/32]>>i%32&1?45:43);} ``` [Try it online!](https://tio.run/##JVHLTgMxDPyXSqDtoSKJHW9DRfkB/oDl4DgbyIGHKpAiIb69TNrLatYzHo8d272anc91atvf@nma2oP34g5ttztsv36@7U1P09Nm6XMwjUJ56SVw9XstS9fZqRWSpcekkokjWJFUnOXRkTInCUuHhrMKWCEoQ0EtrNEkXXuDFojRC03Q6pe@yuglRi9mlBwdkFEmV2zpCY1cFAgyb2IEl6GXhBq@YS0BzpZMCl2d2SoEyCyzl0sqUIwpqNVwwTpYONcAVrMHIGTG2km5AGWGbUpwLn5EXeGMxVGckVl5jZwzMs/RrYn2uBCOM1LBmcdGZTgDOIQHOy6mmDKcxwiStnludxRejsd2Q@HWP3K8Z9oe/s7v2j4mPNE0fv4B "C (gcc) โ€“ Try It Online") # [C (gcc)](https://gcc.gnu.org/), 1148 bytes, non-competing ``` #include <limits.h> #include <stdint.h> #include <stdio.h> #define DISCREPANCY 2 #define NTERMS 1160 #define NBITS(x) (sizeof(x) * CHAR_BIT) static int terms[NTERMS]; /* non-branching abs */ static inline int abs_(int x) { return (x ^ (x >> (NBITS(x) - 1))) - (x >> (NBITS(x) - 1)); } /* generate and print terms */ int main(void) { register int result = 0, iter, incr; for(iter = 0; iter < NTERMS; iter++) terms[iter] = 1; for(incr = NTERMS; incr > 0; incr--) { result = 0; for(iter = incr - 1; iter < NTERMS; iter += incr) { result += terms[iter]; if(abs_(result) > DISCREPANCY) { /* undo change */ /* result -= terms[iter]; */ /* change term to fit requirements */ terms[iter] = -terms[iter]; /* do correct change */ result += 2 * terms[iter]; } } } for(iter = 0; iter < NTERMS; iter++) { if(iter == NTERMS-1) printf("%d\n", terms[iter]); else printf("%d, ", terms[iter]); } } ``` This is my half-brute-force half-calculating solution but it breaks when you check every third term. I hope to improve it to the point where it generates a correct solution. Replace the `1` with `-1` on line 24 to negate the sequence. Please feel free to help me make this correct. [Try it online!](https://tio.run/##lVPBbtswDL3rK4gWA@QkXusedkkXoMsKrIcFQ9LLsLWFK8uOAEfeJHkIVvjbU9L2LHt1ClQHWSIfH59IWoSZEIfDqdIiLxMJl7naKWffbxfM26xLlHYvbQWZ2GkiU6UlfL7ZLNfX365Wy@9w0VlXt9frrxuIog/nHrr6dHO74fsAuFV/ZZHScQLLL1frB/QEjFkXOyUAs4KTZmd/NDR3c8bOJqALHT6aWIut0hnEjxYmZz4kpwwUiY4HTod9wJ4Y4DLSlUYD38M9bYsF8E5KCFEQ0GfUMWdVnTqTWprYSYh1Ar9MJ5AU0GUXK83/FCrxKTNlEVIrMtKWuYOPcD4DhUbctTD4KEKmheFkJPe8dsNlW77mOp0GNZBWUxWy3iE@6lMgI5q6QLouakY8hWFD8dQReUktx39S6ngswagimDYAr8sT98gR1dM7H0BUyus@NdAApfbmKBhAh9y0sCGlTgoQ21hnknowgmhFhEMRR8AtEyHBFZAqatrvUhm5k9rZsahhK8KjL20zkNzCGCncK7J94S7wxzhKWbHhqXrjJPmKYhuaiH@TE0bD4teznvKTd8lPfTLrSwq8JplbeSRqBqNRFasOh2c "C (gcc) โ€“ Try It Online") ]
[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. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. You are to write a program that does one of the following. 1. Only displays "Hello World" does nothing else 2. Quits and nothing else (no output, no errors.) 3. Takes one line of input, parses it as an integer, displays the first that many primes (or gives a nice error if it is given input that can't be parsed as an integer, or is less than 0.) 4. Given one line of input, it parses it has a stock symbol, and checks online for the current stock value and its change. The catch, it should not be apparent which function it performs. Namely, for someone looking at your code, it should not be apparent which function it will do. Also, it may only perform and be able to perform one function (it can not pick and choose.) How good a program is is determined by how uncertain someone is that looks at it as to what its function is, and also how familiar that person is with that language. BONUS: If you in a clever way make it so although for any one compiler/intrpreter and platform, the program will also perform the same function, different compilers/interpreters or platforms, it will perform a different function. This bonus may only be collected if done cleverly. BONUS: If your program only contains code that is capable of one function (save nothing, as empty code is capable of that), and it is not possible to make a simple modification unrelated to the function to allow it to perform a different function. For example: if you did ``` obfuscatedBool = 1g8uhad'l8fygrcetdu8y4fd/,.oe87fy4d --Magic if obfuscatedBool: print "Hello World" ``` Would not count as obfuscatedBool could be made True or False to make it print "Hello World" or do nothing respectively. INFINITY BONUS: If you realize both bonuses simultaneously, you are magic. NEGATIVE BONUS: Using libraries with specific abilities to do the functions. Voters, take the bonuses in to consideration, because the program with the most votes wins! Note: If you say what your program does, make sure to use spoiler syntax! [Answer] # Whitespace/Brainfuck/Python ``` '''begin''''''''''''ย ย  main(args){ย ย ย  ย ย  ย ย ย  parseArgs=args.Find('^++++++++^[<++++[<++<+++<+++<+>>>>a-z]<+<+<A-Z[>]>0-9]<<.<---.*$'); ย ย ย ย for(intย i=0; Range(GetLength(parseArgs)); i++){validateArg(parseArgs(i));}ย ย  ย  //name ย ย ย ย stringย stockName=""; ย  ย ย  //loop ย ย ย ย for(intย i=0;Range(GetLength(parseArgs));i++){ ย  ย ย  //validate ย ย ย ย ย  if(matchFound=Find('a+z+A+.Z.0+9+_+.<<*$'){ ย  //found ย ย ย ย ย  parseArgs(i).Split('>-.>.+');}ย ย ย ย ย  ย ย ย ย ย  for(intย j=0;Range(GetLength(parseArgs(i)));j++){ ย  //download ย ย ย ย data=ConvertTo.String(eval("curlย -get http://some-stock-ticker-source-url-here.com")); ย  print; ย ย ย ย printย data; ย ย  ย  ย ย ย ย //lineย separator ย  ย ย  ย ย ย ย printย "--------."; ย ย  ย ย  }} }ย ย  ''finish''''''''''''''' ``` [Wikipedia: Whitespace (programming language)](http://en.wikipedia.org/wiki/Whitespace_(programming_language)) [Online Whitespace Interpreter to Test Answer](http://whitespace.kauaveel.ee/) [Online Brainfuck Interpreter to Test Answer](http://esoteric.sange.fi/brainfuck/impl/interp/i.html) > > Output (Whitespace/Brainfuck): > > ``` > Hello World > ``` > > > Ouput (Python): > > Nothing, but runs successfully. > > > [Answer] **JS** ``` ๏พŸฯ‰๏พŸ๏พ‰=/๏ฝ€๏ฝยด๏ผ‰๏พ‰~โ”ปโ”โ”ป//*ยดโˆ‡๏ฝ€*/['_'];o=(๏พŸ๏ฝฐ๏พŸ)=_=3;c=(๏พŸฮ˜๏พŸ)=(๏พŸ๏ฝฐ๏พŸ)-(๏พŸ๏ฝฐ๏พŸ);(๏พŸะ”๏พŸ)=(๏พŸฮ˜๏พŸ)=(o^_^o)/(o^_^o);(๏พŸะ”๏พŸ)={๏พŸฮ˜๏พŸ:'_',๏พŸฯ‰๏พŸ๏พ‰:((๏พŸฯ‰๏พŸ๏พ‰==3)+'_')[๏พŸฮ˜๏พŸ],๏พŸ๏ฝฐ๏พŸ๏พ‰:(๏พŸฯ‰๏พŸ๏พ‰+'_')[o^_^o-(๏พŸฮ˜๏พŸ)],๏พŸะ”๏พŸ๏พ‰:((๏พŸ๏ฝฐ๏พŸ==3)+'_')[๏พŸ๏ฝฐ๏พŸ]};(๏พŸะ”๏พŸ)[๏พŸฮ˜๏พŸ]=((๏พŸฯ‰๏พŸ๏พ‰==3)+'_')[c^_^o];(๏พŸะ”๏พŸ)['c']=((๏พŸะ”๏พŸ)+'_')[(๏พŸ๏ฝฐ๏พŸ)+(๏พŸ๏ฝฐ๏พŸ)-(๏พŸฮ˜๏พŸ)];(๏พŸะ”๏พŸ)['o']=((๏พŸะ”๏พŸ)+'_')[๏พŸฮ˜๏พŸ];(๏พŸo๏พŸ)=(๏พŸะ”๏พŸ)['c']+(๏พŸะ”๏พŸ)['o']+(๏พŸฯ‰๏พŸ๏พ‰+'_')[๏พŸฮ˜๏พŸ]+((๏พŸฯ‰๏พŸ๏พ‰==3)+'_')[๏พŸ๏ฝฐ๏พŸ]+((๏พŸะ”๏พŸ)+'_')[(๏พŸ๏ฝฐ๏พŸ)+(๏พŸ๏ฝฐ๏พŸ)]+((๏พŸ๏ฝฐ๏พŸ==3)+'_')[๏พŸฮ˜๏พŸ]+((๏พŸ๏ฝฐ๏พŸ==3)+'_')[(๏พŸ๏ฝฐ๏พŸ)-(๏พŸฮ˜๏พŸ)]+(๏พŸะ”๏พŸ)['c']+((๏พŸะ”๏พŸ)+'_')[(๏พŸ๏ฝฐ๏พŸ)+(๏พŸ๏ฝฐ๏พŸ)]+(๏พŸะ”๏พŸ)['o']+((๏พŸ๏ฝฐ๏พŸ==3)+'_')[๏พŸฮ˜๏พŸ];(๏พŸะ”๏พŸ)['_']=(o^_^o)[๏พŸo๏พŸ][๏พŸo๏พŸ];(๏พŸฮต๏พŸ)=((๏พŸ๏ฝฐ๏พŸ==3)+'_')[๏พŸฮ˜๏พŸ]+(๏พŸะ”๏พŸ).๏พŸะ”๏พŸ๏พ‰+((๏พŸะ”๏พŸ)+'_')[(๏พŸ๏ฝฐ๏พŸ)+(๏พŸ๏ฝฐ๏พŸ)]+((๏พŸ๏ฝฐ๏พŸ==3)+'_')[o^_^o-๏พŸฮ˜๏พŸ]+((๏พŸ๏ฝฐ๏พŸ==3)+'_')[๏พŸฮ˜๏พŸ]+(๏พŸฯ‰๏พŸ๏พ‰+'_')[๏พŸฮ˜๏พŸ];(๏พŸ๏ฝฐ๏พŸ)+=(๏พŸฮ˜๏พŸ);(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]='\\';(๏พŸะ”๏พŸ).๏พŸฮ˜๏พŸ๏พ‰=(๏พŸะ”๏พŸ+๏พŸ๏ฝฐ๏พŸ)[o^_^o-(๏พŸฮ˜๏พŸ)];(o๏พŸ๏ฝฐ๏พŸo)=(๏พŸฯ‰๏พŸ๏พ‰+'_')[c^_^o];(๏พŸะ”๏พŸ)[๏พŸo๏พŸ]='\"';(๏พŸะ”๏พŸ)['_']((๏พŸะ”๏พŸ)['_'](๏พŸฮต๏พŸ+(๏พŸะ”๏พŸ)[๏พŸo๏พŸ]+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+(๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ)+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+((๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ))+(๏พŸ๏ฝฐ๏พŸ)+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+(๏พŸ๏ฝฐ๏พŸ)+((๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ))+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+((o^_^o)+(o^_^o))+((o^_^o)-(๏พŸฮ˜๏พŸ))+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+((o^_^o)+(o^_^o))+(๏พŸ๏ฝฐ๏พŸ)+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+((๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ))+(c^_^o)+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸ๏ฝฐ๏พŸ)+((o^_^o)-(๏พŸฮ˜๏พŸ))+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+(๏พŸฮ˜๏พŸ)+(c^_^o)+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+(๏พŸ๏ฝฐ๏พŸ)+((๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ))+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+((๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ))+(๏พŸ๏ฝฐ๏พŸ)+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+((๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ))+(๏พŸ๏ฝฐ๏พŸ)+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+((๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ))+((๏พŸ๏ฝฐ๏พŸ)+(o^_^o))+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸ๏ฝฐ๏พŸ)+(c^_^o)+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+((o^_^o)-(๏พŸฮ˜๏พŸ))+((๏พŸ๏ฝฐ๏พŸ)+(o^_^o))+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+((๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ))+((๏พŸ๏ฝฐ๏พŸ)+(o^_^o))+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+((o^_^o)+(o^_^o))+((o^_^o)-(๏พŸฮ˜๏พŸ))+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+((๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ))+(๏พŸ๏ฝฐ๏พŸ)+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸฮ˜๏พŸ)+(๏พŸ๏ฝฐ๏พŸ)+(๏พŸ๏ฝฐ๏พŸ)+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+(๏พŸ๏ฝฐ๏พŸ)+((o^_^o)-(๏พŸฮ˜๏พŸ))+(๏พŸะ”๏พŸ)[๏พŸฮต๏พŸ]+((๏พŸ๏ฝฐ๏พŸ)+(๏พŸฮ˜๏พŸ))+(๏พŸฮ˜๏พŸ)+(๏พŸะ”๏พŸ)[๏พŸo๏พŸ])(๏พŸฮ˜๏พŸ))('_'); ``` > > Alerts "Hello World" > > > Was answered at <https://codegolf.stackexchange.com/a/3946/803> > > Since I did not come up with this answer, making it a community wiki > > > [Answer] ## MS-DOS x86 Assembly Because it isn't already obfuscated when it's in assembly, let's make it even worse! This SHOULD work with any assembler that can assemble to a COM file, but I've only tested with TASM for DOS using `tasm obfuse`, `tlink /t obfuse` ``` .286 CODE SEGMENT ASSUME CS:code, DS:code ORG 0100h start: .586 xor eax, eax xor ecx, ecx xor edx, edx xor ebx, ebx xor edi, edi xor esi, esi stc pushfd rcr di, 8 mov cx, 35 cli push edi xor word ptr [di + 8], 2720 pushfd sub bx, 64512 rcr ebx, 11 sub word ptr [di + 125], 61702 pop eax dec dx and word ptr [di + 4], cx mov ecx, eax sub byte ptr [di + 124], 21 xor eax, ebx push eax xor byte ptr [di + 127], 240 popfd xor dword ptr [di], 179066414 pushfd xor byte ptr [di + 11], dl pop eax mov bp, 8268 xor byte ptr [di + 123], 110 pop edx add byte ptr [di + 10], 49 popfd sti and ecx, ebx or word ptr [di + 4], bp and eax, ebx xor word ptr [di + 6], 23601 cmp eax, ecx db 'u', 5 dec cl movsx dx, cl int 32 CODE ENDS END start ``` > > This is self-modifying code that does several things: > > 1) It modifies the first 12 bytes to 'Hello World[dollar sign]' > > 2) It modifies the seemingly out of place 'dec cl' and 'movsx dx cl' to 'nop', 'mov ah, 9', 'int 021h' > > 3) Everything is highly interspersed within each other. This is also doing a flags test to see if your CPU supports CPUID > > > > [Answer] ## C ``` int puts(const char *s) { char error[] = "Error: invalid number\n"; int a, b=0, c=0, i, j; scanf("%d", &b); if (b<1) { printf(error); } for (i=2; c<b; i++) { int z=1; for (j=2; j<i; j++) { z = z&&(i%j); } if (z) { printf("%d\n", i); c++; } } } int main () { printf("Hello World\n"); } ``` > > On `gcc`, with default settings, this does the prime thing. Using `tcc`, you get `Hello World`. A C compiler *may* rewrite a `printf("String\n")` call into a `puts("String")` call. This is more efficient, but it does assume nobody wrote their own `puts`. A compiler does not *have* to do this, so depending on your compiler and your compiler settings, you will get either `Hello World` or a bunch of primes. The `printf` calls in `puts` are not affected, because they don't match the exact template. I think I qualify for the bonus. > > > [Answer] # LOLCODE This language is already obfuscated by itself. Here is my code: ``` HAI I HAS A CATURDAY CATURDAY IS NOW A TROOF I HAS A LOLZ ITZ 32907 I HAS A CHEEZBURGER MAEK CHEEZBURGER A NUMBR CHEEZBURGER R QUOSHUNT OF LOLZ AN LOLZ CHEEZBURGER BIGGR THAN 1?, O RLY? YA RLY BTW RLY LOLZ CATURDAY R WIN OBTW EVERYDAY IS CATURDAY ME LIKEZ CATURDAY!!1! TLDR CHEEZBURGER R QUOSHUNT OF LOLZ AN CHEEZBURGER NO WAI CATURDAY R FAIL BTW LOLZ!!1! I HAS A LIMIT ITZ 10 CHEEZBURGER R 0 OIC IM IN YR LOOP CHEEZBURGER, WTF? OMG 1 VISIBLE "Hello World!" OMGWTF CATURDAY R FAIL OIC GTFO IM OUTTA YR LOOP KTHXBYE ``` > > This code quits and does nothing else (no output, no errors). But although it does absolutely nothing, it runs like a charm (tested with version that contained a `VISIBLE "test"` statement before the last statement `KTHXBYE`, proving that all is fine). Basically it declares variables, changes their types, enters in loops and ifs and cases constructs, even has a line that would print "Hello World!" if ever reached (if only reached...). A total waste of computation :) > > > [Answer] # JavaScript (ES6) Using pragma `black magic` to reveal JavaScript true power: ``` var WKRBD=''; var DIJqZ=(gFJLA=WKRBD,i=29)=>( "use black magic", gFJLA=WKRBD.concat(gFJLA), [String.fromCharCode((c.charCodeAt()-61)^gFJLA[i++].charCodeAt())for(c of gFJLA.substr(1,11))].join('') ); DIJqZ(DIJqZ); ``` **Output:** ``` Hello World ``` **Explanations:** This program is actually quite simple and could be summarize as bellow. Everything else if syntactic sugar! ``` var dummy = function() { var output = ''; var a = 'gFJLA=WKRBD'; var b = 'black magic'; for (var i = 0; i < a.length; i++) { output += String.fromCharCode((a[i].charCodeAt(0) - 61) ^ b[i].charCodeAt(0)); } return output; }; dummy(); ``` Here is the annotated version: ``` // Nothing special here. var WKRBD=''; // Define a new function. Its name doesn't matter. // But its arguments do! // * gFJLA=WKRBD: encoded "Hello World" // * i=29: number of characters before "black magic" var DIJqZ=(gFJLA=WKRBD,i=29)=>( // Store the XOR key using a fancy pragma name! "use black magic", // Convert gFJLA to String thus it is possible to read // its body and extract the encoded "Hello World". gFJLA=WKRBD.concat(gFJLA), // Use a generator to decode the message. [ // Generate the decoded character String.fromCharCode( // Decode the character. // gFJLA[i++] retrieves a character from "black magic". (c.charCodeAt() - 61) ^ gFJLA[i++].charCodeAt() ) // Iterates over the function body. // The extracted part is "gFJLA=WKRBD". for(c of gFJLA.substr(1,11)) // Build the message. Since it is the last expression of // the arrow function, its result is returned. ].join('') ); // Invoke the function and pass itself as the first argument. DIJqZ(DIJqZ); ``` [Answer] COBOL (IBM Enterprise COBOL) ``` ID ``` If shown that, very close to 100% of IBM Mainframe COBOL programmers would say "that's not even a program, that won't compile!". The more experience they have, the less likely they are to think it will compile (as older Mainframe COBOLs were much more strict). Then ask "if it does compile, what does it do?" They would say, "it won't compile, but if it did, it would give some sort of error, probably Language Environment would give a U4038 or something like that". Managed to shorten it. There are four DIVISIONs in a COBOL program. IDENTIFICATION/ID, ENVIRONMENT, DATA, PROCEDURE. It turns out that PROCEDURE *requires* the word DIVISION and the others don't. Guess which one I removed first and assumed that the other words DIVISION were mandatory... further puzzling revealed otherwise. Pity it's not Golf. A two-character COBOL program... > > OK, yes, the compiler does moan, and indeed gives it a Return Code of > eight. Usually people don't even generate the object code for, let > alone try to execute, programs with a Return Code of eight. > > However, this is a case where none of the E-level errors affect the > code generated. So the code runs without a problem at all, if you generate it. > > > The above source is effectively the equivalent of this: > > > ID DIVISION. > > PROCEDURE DIVISION. > > GOBACK > > . > > > Which simply returns to whence it came. > > > [Answer] # Java,C++-11 1 Bonus claimed Not sure about if i got both bonuses but it was already a headache to intermingle 2 programming languages... ``` /* *??/ / #include <iostream> using namespace std; int main() { return 0; } /* *\u002F class D_arvit{static int a=0,b=a++,e=a++,f=a/a;static char p(String s){return(char)Byte.parseByte(s,a);}public static void main(String[]z){//\u000Along x=e,y=b;String c=((Long)x).toString(),d=((Long)y).toString();char u=p(c+c+d+c+c+d+d),m=p(c+c+d+d+c+d+c),o=(char)(u+a+f);char _=p(c+d+d+d+d+d),$=_++;System.out.print(new char[]{p(c+d+d+c+d+d+d),m,u,u,o,$,p(c+d+c+d+c+c+c),o,(char)(o+a+f),u,(char)(m-f),_});\u000A}} /\u002A*/ ``` > > Getting the C++ inbetween the java code which i already used on another Hello World answer was a Pain in the ass. Took me a while to find a fitting second language where i was able to juggle around comments as needed so they disable/enable differently at different languages > > > [Answer] # Python - 1 Bonus Claimed ``` import base64 try: a=1/(1/2) eval(compile(base64.b64decode("IyBUaGlzIGlzIGEgc2FtcGxlIFB5dGhvbiBzY3JpcHQKcHJpbnQgIkhlbGxvIiwKcHJpbnQgIldvcmxkISIK"),'<string>','exec')) except: pass ``` In Python 2, `1` divided by `2` equals `0`. `1` divided by `0` can't be evaluated and throws a division by zero error. Nothing is printed, and still the program terminates without error. In Python 3, `1/2` => `0.5`, and `1/0.5` => `2.0`. No error. `Hello, World!` is printed. [Answer] ### Batch ``` @echo off&setLocal enableDelayedExpansion&for /L %%a in (2,1,%1)do (set/aa=%%a-1&set c=&for /L %%b in (2,1,!a!)do (set/ab=%%a%%%%b&if !b!==0 set c=1) if !c! NEQ 1 set l=!l!%%a,) echo !l:~0,-1! ``` > > This will return a list of prime numbers less than the inputted value. > > H:\uprof>obf.bat 12 > > 2,3,5,7,11 > > > I don't know that convoluted counts as obfuscated, though there are definitely some aspects of obfuscation present. [Answer] # Ruby - or is it Whitespace? Well, can anyone guess what I do? ~~Small hint: if you want to run it, please copy **all of the code** in the code box ;)~~ Update: Copying the code doesn't seem to work due to Unicode-related problems? Forking the online version and then copying the code seems to work! Look out for the whitespace ;) [Online version](http://ideone.com/NnrbJK) ``` # encoding: utf-8 def method_missing(m, *a) $* << (m.to_s.size-1).to_s end at_exit do eval ($**'').scan(/.../).map(&:to_i).pack('C*') end ย ย ย ย ย ย ย ย ย ย  ย ย ย ย  ย  ย ย ย ย  ย ย ย ย  ย  ย  ย  ย ย  ย ย ย ย ย ย ย ย ย  ย  ย ย  ย ย ย ย ย  ย ย  ย ย  ย ย  ย ย  ย ย  ย ย ย ย ย ย ย ย ย ย  ย ย  ย ย  ย ย ย  ย ย ย ย  ย  ย ย  ย ย  ย ย  ย ย ย ย ย ย ย ย ย  ย  ย ย  ย ย ย ย ย ย ย ย ย  ย  ย ย  ย ย  ย  ย ย  ย ย ย  ย ย ย ย ย ย ย ย  ย  ย ย ย ย ย ย ย ย ย ย  ย ย ย ย  ย  ย ย ย  ย ย ย ย  ย  ย ย ย ย ย ย  ย ย  ย ย  ย ย ย ย ย ย ย  ย ย  ย ย  ย ย ย ย ย ย ย ย  ย ย  ย ย  ย ย ย  ย ย  ย ย  ``` ### Output: ``` Hello world! ``` ### Explanation: * The last line consists of quite a few chunks of no-break-spaces (UTF-8: 160dec) separated by regular spaces. * Ruby handles the chunks as though they were methods - since no such methods are defined, `method_missing` is called, which saves the lengths of the chunks * Each chunk represents one digit of a three digit number, which represents a character * in `at_exit` the characters are formed by concatenating the digits etc. and the expression is evaluated, in this case `puts 'Hello world!'` * Instead of using UTF-8 whitespaces, you could also use underscores for better visibility: ``` def method_missing(m, *a) $* << (m.to_s.size-1).to_s end at_exit do eval ($**'').scan(/.../).map(&:to_i).pack('C*') end __________ ____ _ ____ ____ _ _ _ __ _________ _ __ _____ __ __ __ __ __ __________ __ __ ___ ____ _ __ __ __ _________ _ __ _________ _ __ __ _ __ ___ ________ _ __________ ____ _ ___ ____ _ ______ __ __ _______ __ __ ________ __ __ ___ __ __ ``` [Answer] # Forth Let's create a new TASK. ``` FORTH ok : TASK [ HEX ] 3A91224B. 1F836AFE. 4A BASE ! D. D. ; TASK Hello World ok ``` > > It displays two 32-bits numbers in base 74 (4Ah). > 74 because it is the difference between ASCII "z" and ASCII "0" plus one, so I can use it to display a small words starting from a number. > The first number is "Hello" (1F836AFEh) and the second number is "World" (3A91224Bh). > It really prints a trailing space after the number "World". > > > ![Real execution](https://i.stack.imgur.com/ClQhx.jpg) [Answer] # PHP: ~~$words=array('Heart','eagle','low','lonely','over',' SPACE ','Window','optimus','rotting','list','done','!done');~~ ``` $words=array('Hated','ever','lonely','lover','oposed',' to','Witness','our','rare','long','discover'); $find='l'; foreach($words as $word)echo($find^(($find&$word)^($find|$word))); ``` > > Prints 'Hello World'. > > It takes off the 1st letter from each word in the array. > > The var `$find` can have any single-byte string of 1 byte. > > Using a longer value for the var `$find` will give weird outputs. > > > > [Answer] # Brainfuck ``` print("Hello World") ``` ### Explanation > > At least if your compiler ignores invalid instructions, this program does nothing. > > > [Answer] # C++11 I claim the bonus for compiler dependence - for example, this will exhibit different beahviour between gcc 4.8 and gcc 4.9. ``` #include <iostream> #include <list> #include <type_traits> #include <utility> // Type-agnostic & efficient output template <class T> void write(T data) { std::cout.write((char*)&data, sizeof data); } // Helper for automatic output to simplify exception handling struct PrimeList : std::list<unsigned int> { ~PrimeList() { while (!empty()) { write(front()); pop_front(); } } }; // Basic brute-force handler struct BasicHandler { template <class C> static void handle(C &primes) { std::cin.clear(std::ios_base::failbit); // remove possible non-fatal errors std::cin.exceptions(std::ios_base::failbit); // easier error handling unsigned int count; // unsigned so that negatives error out immediately std::cin >> count; unsigned long long candidate = 1; for (unsigned int p = 0; p < count; ++p) { bool isPrime; do { ++candidate; isPrime = true; for (auto prime : primes) { if (candidate % prime == 0) { isPrime = false; break; } } } while (!isPrime); primes.push_back(candidate); } } }; // Smart handler using known accelerating divisors struct SmartHandler : BasicHandler { template <class C> static void handle(C &primes) { // Pre-fill with accelerating divisors primes.push_back(1819043144u); primes.push_back(1867980911u); primes.push_back(560229490u); BasicHandler::handle(primes); // Remove divisors, as they are not primes primes.pop_front(); primes.pop_front(); primes.pop_front(); } }; // Choose handler appropriate for container template <class Container> struct PrimeHandler { template <class PrimePointer> static char selector(PrimePointer p, decltype(Container().insert(p, *p))); static double selector(...); typedef typename std::conditional< sizeof selector( typename Container::const_iterator(), typename Container::iterator() ) == 1 , SmartHandler, BasicHandler >::type Selection; }; int main() { try { PrimeList primes; PrimeHandler<decltype(primes)>::Selection::handle(primes); } catch (std::ios_base::failure &) { std::cout.clear(std::ios_base::failbit); // remove possible non-fatal errors std::cout << "You need to enter a positive number" << std::endl; } } ``` Compiler dependency explanation: > > C++11 changed the requirements for insert() and erase() functions in standard containers so that they now accept constant iterators, where previously they required mutable iterators. That's what PrimeHandler tests. gcc only changed its standard library to be compliant in 4.9; MSVC 2013 is not compliant yet; I don't know about clang. > > > General behaviour explanation: > > The clear(x) function of streams does not *clear* flag **x**, it **sets** it. Therefore, the handle() function actually puts the stream in error state, so any attempt to read fails (and helpfully throws an exception). In the same way, the error output is avoided. > The auto-output destructor of PrimeList makes sure any data in it is written - as binary, not as numbers. Of course, the "smart divisors" are actually "Hello World!" encoded in little-endian ASCII. And because an exception is thrown, nothing gets added in BasicHandler, and only the "smart divisors" are added in SmartHandler (and never removed, because of said exception). > > > [Answer] # Delphi Not sure if this counts but I will tell you how I saw this challenge. My thought was to write code that wouldnt execute what you expected it to. ``` program Project1; {$APPTYPE CONSOLE} {$R *.res} uses System.sysutils,Generics.Collections; type TMyIntList= TList<integer>; function SieveOfEratosthenes(upperLimit:integer):TMyIntList;overload; var i,j: integer; a:array of boolean; upperSqrt,sieveBound:integer; begin Result:=TMyIntList.Create; sieveBound:=Round((upperLimit-1)/2); upperSqrt:=Round((Sqrt(upperLimit)-1)/2); SetLength(a,sieveBound); for I:=0to sieveBound-1 do a[I]:=true; for I:=1to upperSqrt do begin if a[I] then begin J:=i*2*(i+1); while J<=sieveBound do begin a[J]:=false; J:=J+2*i+1; end end end;//end for loop Result.Add(2); for I:=1to sieveBound-1do if a[i]then Result.Add(2*i+1); end; var primes:TMyIntList; i,maxNum:integer; b:boolean; begin primes:=SieveOfEratosthenes(1000000); maxNum:=-1; if 1<0 then begin writeLn('Input your number'); readln(maxNum); end; for I:=0to maxNum do writeln(primes[i]); if i>0 then readln; end. ``` > > What I did was write a program that implies to execute function 3 but actually runs function 2 and simply exits as soon as its started. > > The hints are: **SieveOfEratosthenes** Algorithm for generating primes > > Var **primes** and **maxNum** > > code: `WriteLn('Input your number');readln(maxNum);` > > Which is code that will never be reached since booleans are `False` by default > > > [Answer] # Haskell ``` import Control.Concurrent import System.Exit import System.Time import Control.Monad hw = putStrLn "Hello World" busyWait = do (TOD s p) <- getClockTime go (TOD (succ s) p) exitWith ExitSuccess where go t = do t' <- getClockTime unless (t' > t) (go t) main :: IO () main = forkIO hw >> busyWait ``` > > Run with GHC and it will print hello World. With Hugs (which implements > cooperative multitasking) It will always quit without printing anything. > > > [Answer] JS ``` [][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]+!+[]]+(+(+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+[+[]])))() ``` > > Does nothing. No Error. No Output > > > [Answer] # Matlab Here is code that can roughly perform various operations, can you predict the flow? ``` six=input('input your number or ticker?','s') six=six(six==6) if six 'Hello World!' elseif ~six try primes(str2num(six)) catch urlread(['http://finance.yahoo.com/q?s=' six]) end end ``` Here is a hint: > > Regardless of which number or ticker you input, you will always end up on the same spot > > > [Answer] This one does both bonuses. Have a look at the spoilers in the end to see what it does. **Java / Brainf\*ck** ``` //[ import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; //] public class Something { private static String magicNumber="1000"; public static void primes(int nr) { int ct = 0; int val = 1+2+3+4+5+6+7+8+9+10+1+2-57; int primes[ /*(*|*>) (+|+) (+|+) (+|+) (+|*>) (+|+) (+|+) (+|+) (+|+) (+|+> (+|+) (+|*> (+|*) <*|*< <*|*< (-|*) SMILEY STAMPEDE! */ ]; //I probably won't use that array anyways... Whatever. while (nr > ct) { val++; boolean isPrime = true; for (int i = 2; System.out!=null && val > i; i+=1) { if (val % i == Integer.parseInt("0")) { isPrime = false; break; } } if (isPrime) { println(val); ct++;//>*|*> (*|*> } } } public static void main(String[] args) throws IOException {//<*|*< <*|*) I like smileys! new Something(); setMagicNumber(1+(getMagicNumber()+7+9+12+4)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine(); try { setMagicNumber(getMagicNumber()+3+1+2); System.gc(); setMagicNumber(getMagicNumber()>5 ?getMagicNumber() : getMagicNumber()+1+2); magicNumber = input; primes(getMagicNumber()); } catch (Exception ex) { magicNumber = "1000"; println(getStockValueString(input)); } } public static String getStockValueString(String stockname) throws IOException { URL url = new URL("http://marketwatch.com/investing/stock/"+stockname); setMagicNumber(getMagicNumber2()<7 ? (getMagicNumber2()<9+3) ? 5+3+5+7+6+3 : 2+9+6+9 : 7+6+1+2+5+2+4); HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); boolean setOutput = getMagicNumber2()>2; httpConnection.setDoOutput(setOutput); setMagicNumber(getMagicNumber2()+2+3+4); DataOutputStream wr = new DataOutputStream(httpConnection.getOutputStream()); setMagicNumber(getMagicNumber2()-1-2-3-4-5-6); wr.flush(); setMagicNumber(getMagicNumber2()-5-3-1-8-9-5-5-4); BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); String line; while ((line = readLine(in)) == null == (getMagicNumber2()>100000)) { line = line.trim(); setContainsTxt(line); if (contains("p "+"class"+"=\"data "+"bgLast\"")) { setSubstringTxt(line); setIndexOfTxt(line); line = substringL(indexOf("p class=\"data bgLast\"")+22); setIndexOfTxt(line); setSubstringTxt(line); line = substringR(indexOf("/p")-1); return line; } } return ""; } //>*|*> [*|*> public Something() { } public static int getMagicNumber2() { try { return Integer.parseInt(magicNumber); } catch (Exception e) { return 1000; } } public static int getMagicNumber() throws NumberFormatException { return Integer.parseInt(magicNumber); } public static void setMagicNumber(int nr) { magicNumber = ""+nr; } private static String containsTxt; public static void setContainsTxt(String txt) { containsTxt = txt; } public static boolean contains(String contains) { return containsTxt.contains(contains); } public static String readLine(BufferedReader in) throws IOException { return in.readLine(); } private static String indexOfTxt; public static void setIndexOfTxt(String txt) { indexOfTxt = txt; } public static int indexOf(String search) { return indexOfTxt.indexOf(search); } public static void println(Object txt) { System.out.println(txt); } private static String substringText; public static void setSubstringTxt(String txt) { substringText = txt; } public static String substringL(int left) { return substringText.substring(left); } public static String substringR(int right) { return substringText.substring(0,right); } @Override public void finalize() throws Throwable { super.finalize(); magicNumber = "NaN"; }//<*|*] } ``` **Brainfuck** > > In Brainfuck this just returns "Hello World". > > > **Java** > > In Java this either returns the first x prime numbers (depending on the input number) or the stock value of the given stock market symbol (e.g. GOOG for Google). Which one is chosen depends on the implementation of the currently used JavaVM, but with the Oracle JavaVM it should get the stock market value. You can also force the prime number calculator (2nd bonus) by commenting out the System.gc()-line, which in turn stops the finalize() call so the magicNumber never becomes NaN and thus no exception is thrown that would cause the stock market value getter to run instead of the prime numbers generator. > > > [Answer] ## C, 346 chars ``` #include <stdio.h> int main(int O, char **o) { int l4, l0, l, I, lO[]= { 444,131131,13031,12721,17871,20202,1111, 20102,18781,666,85558,66066,2222,0 }; for(l4=0;l4<14;++l4){ for((l=l0=lO[l4])&&(l0=-7); l>4&&(I=2-((l|l>>O)&O));l=l&O?l+(l<<O)+O:l>>I,l0+=I);{ putchar(10+l0); } } return 0; } ``` This is an old program I created 10+ years ago. It actually prints "Hello, world!" The code uses palindromic numbers in base 10 and is slightly obfuscated. > > Don't trust the indentation. Also, see: <http://oeis.org/A006577> > > > Oh, I almost forgot... The program only works when started without command line arguments. Also, if you start it with 11 command line arguments it seems to enter an infinite loop. 12 is fine though. [Answer] **Malbolge** I'd say that it can't get anymore obfuscated than Malbolge ;) ``` (=<`:9876Z4321UT.-Q+*)M'&%$H"!~}|Bzy?=|{z]KwZY44Eq0/{mlk** hKs_dG5[m_BA{?-Y;;Vb'rR5431M}/.zHGwEDCBA@98\6543W10/.R,+O< ``` > > It just prints "Hello, world." All credits go to Wikipedia since I am still not getting this language... > > > [Answer] ## bash/sh, python ``` set -e exec 2>/dev/null main() { eval $(eval base64 -d<<<"cHl0aG9uIC1jICIkQCI=") } while read -r foo; do main "$foo" done < <(echo "exec'import __\x68e\x6c\x6co__'") ``` This would produce: ``` Hello world... ``` when executed with `bash`. When the same code is executed with `sh` or with `bash` in posix mode, i.e. by saying `bash --posix filename`, it doesn't produce any output. > > Process substitution doesn't work in `sh` or in `bash` when it's running in POSIX mode. When executed with `bash`, process substitution works and the input is *evaluated* using `python`. Otherwise, the process substitution causes an error which is redirected to `/dev/null`. > > > [Answer] Now, according to the comments and by reading it, this will do 1 of 3 things. * It will do the primes objective if you pass it a number. * It will lookup stocks if you pass it a non-number. * It will print "Hello World" if you do something silly However, this program does not follow its documentation very well, because no matter what you give it... it will always print the FOURTH objective, which is nothing. ``` /** * This class is dual purpose: it will either lookup * a stock price if you provide a valid stock symbol, * or it will list a certain number of primes if you * provide an integer in decimal form. Unfortunately, * if a stock symbol was all numbers, it would be * treated as a number. Sorry for the inconvenience. * * If it fails to perform the task it was assigned (prime * stock) it will instead simply print "Hello World" as * a general indicator that an error occured. * * Usage: java StocksOrPrimes 5 * 2 3 5 7 11 * Usage: java StocksOrPrimes MSFT * 37.70 */ import java.util.*; import java.io.*; import java.net.*; class StocksOrPrimes { public static void main(String...args) { try { if(args.length != 1) { System.out.println("Please only enter one argument."); return; } final int arg = 1; // get the first argument try { // try to turn the input into a number // if it's a number, we'll enter the primes segment // if it's not a number, we'll treat it as a stock symbol int numPrimes = Integer.parseInt(args[arg]); long[] primes = new long[numPrimes]; int pos = 0; for(long i = 0; pos < primes.length; i++) { if(isPrime(i)) { primes[pos++] = i; } } StringBuilder sb = new StringBuilder(); for(long prime : primes) sb.append(prime).append(" "); System.out.println(sb); } catch(Exception e) { // clearly we're dealing with a stock symbol, so print // the stock's price Scanner sc = new Scanner(new URL("http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=" + args[arg]).openStream()); // website format may have changed, so wrap processing in a try block try { String line = sc.nextLine(); line = sc.nextLine(); int start = line.indexOf("&lt;Last&gt;") + "&lt;Last&gt;".length(); int end = line.indexOf("&lt;/Last&gt;"); String last = line.substring(start,end); if(last.equals("0.00")) throw new IllegalStateException("invalid return code"); System.out.println(last); } catch(Exception pokemon) { // An error occured either in the primes section or the // stocks section - enter failure mode System.out.println("Hello World"); } } } catch(Exception ex) {} } static boolean isPrime(long n) { if(n < 2) return false; if(n == 2 || n == 3) return true; if(n%2 == 0 || n%3 == 0) return false; long sqrtN = (long)Math.sqrt(n)+1; for(long i = 6L; i <= sqrtN; i += 6) { if(n%(i-1) == 0 || n%(i+1) == 0) return false; } return true; } } ``` > > This program works (or rather fails) because Java has 0 indexed arrays. So it should be trying to access `args[0]`. However, the `final int arg = 1` value says we're accessing the first value. Java developers know that `args[1]` is actually the second value. Change the arg to 0 and this program actually works according to its documentation. > > > [Answer] # Javascript I don't even understand this ``` var ________________ = [] + []; var _ = day() - day(); _++; var _____ = _ + _; var ___ = _____ + _____; var __ = ___ + ___; var ____ = __ + __; var ______ = ____ + ____; var _______ = ______ + _; var ___________ = ______ + ______ + __; var ______________ = ___________ + ____ - _; var ____________ = _ + _____; var ________ = _______ * ____________ + _; var _________ = ________ + _; var _____________ = ______________ + ______ - ___ - _; var __________ = _____________ - ____________; var _______________ = __________ - ____________; println(________________ + String.fromCharCode(___________, _________, _______________, _______________, __________, ______, ______________, __________, _____________, _______________, ________, _______)); ``` Note the script is not mine: [original source](https://codegolf.stackexchange.com/a/22746/12291) [Answer] ## **Perl** This is my first attempt to write obfuscated code. I hope you'll like it. ``` #!/usr/bin/env perl {$i=$s=-!$v>>~!!$a<<!$l,$e=<>,!$e||$e<=$!?last:$!;{$_.=!(!$!+$#{[grep{$i==$_||!($i%$_)}$s..$i/$s]})&&$e--?"$i+!":'',$i++,$e>$!?redo:y.+!.,\x20.,s.,\s$.\n.,print}exit} $_="Hello World\n",s#\w(.)(.){5}(.)(.)\w*#$1$4$4$3$4#,print and die ``` > > This program asks for a number and then prints that many primes. In case of error it will simply print `error`. > > > [Answer] C++: ``` #include <iostream> int main() { std::cout<<"Hello world!"<<std::endl; std::cout<<"\b\b\b\b\b\b\b\b\b\b\b\b\b";//backspace, delete the hello world return 0; } ``` > > std::endl prevents the backspace from working. This outputs Hello World! > > > [Answer] ## Ruby 2.0.0 + 1 Bonus Okay, so I'll explain the bonus in the spoiler. But this is pretty much just a roundabout way to print "Hello World!" in Ruby. ``` require "base64" eval(Base64.decode64(DATA.read)) _________ = $$/$$ _ = _________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________ #H __ = _________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________ #e ___ = _________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________ #l ____ = _________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________ #o _____ = _________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________ # ______ = _________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________ #W _______ = _________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________ #r ________ = _________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________+_________ #d $> << ('' << _ << __ << ___ << ___ << ____ << _____ << ______ << ____ << _______ << ___ << ________) #$$/$$ references the DATA after it's been "eval"'d, as the "eval" changes the division symbol, and the rest of it is just a fancy way of printing it __END__ Y2xhc3MgSU8NCglkZWYgPDwob2JqKQ0KCWVuZA0KZW5k ``` And the output: > > > > > What? > > Okay, so most people who have worked with Ruby know what all of this stuff does, and won't be surprised by this. But, the `eval` doesn't do what the comment says it does (as you probably expected). Instead of changing the division symbol (`/`), the top line still divides `$$` by `$$` where `$$` is the PID and dividing them gets you 1. Instead, the `eval` changes how the shovel symbol (`<<`) works. After it is `eval`'d, the shovel symbol does absolutely nothing. You can see how I did this by Base64 decoding the stuff after the `__END__` > > > And the bonus: > > Comment out the second line, it prints "Hello World!". Maybe this doesn't count, because it still prints one space. > > > [Answer] # Matlab Very simple small code, could probably easily be expanded to make it more obfuscated, but I've left it smaller as a proof of principle, because the approach is a bit lame. Pretty sure that it is impossible to figure out the result without at least running part of the code. ``` str = '''''d nrtnWlr)\ifpflHnrut(e!rloeo;'; rng(42); [~,I] = sort(rand(size(str))); eval(str(I)); ``` [Answer] # C++ or C & Bonus No. 1 ``` ??=include <stdio.h> ??=define P_ putchar; ??=define _defined 0 #define if(c) Cb(le,whi) (c) ??=define G_ 0x48; ??=define r return #define SS 0 ??=define E S ??=define NL ??=define _defjned v #define while(c) Cb(f,i) (c) ??=define C(d,...) d##__VA_ARGS__ %:define Cb(a,...) __VA_ARGS__##a ??=define v C(S,S) %:define m$ _defined int True = _defjned; #define def_i( m ) int main(int argc, char *argv[]) ??< while(argc == m$ + !True)??< return m$; ??> if(True) { while(True){} } else { return 1; } ??> ??=ifndef __cplusplus ??=undef _defined ??=define _void int ??=define i _void ??=define m$ void %:define _defined 1 ??=undef _defined ??=undef SS ??=define SS 1 ??=define c_ char ??=define Z$ ; ??=define Z$$ ) ??=define _T typedef ??=define u unsigned ??=define jakjf c_ ??=define jaofhouwa u jakjf _T jaofhouwa z_;i a;c_ c;i (*p)(i c); ??=undef i ??=undef def_i ??=ifndef i ``` I claim Bonus No. 1. `clang/gcc` vs. `clang++/g++`. ### With C++ ``` clang++ -trigraphs obfuscate.c ``` > > Compiled as C++, it exits. > > > ### With C ``` gcc -trigraphs obfuscate.c ``` > > Compiled as C, it prints "Hello, world!" > > > ]
[Question] [ This is the robbers' thread. The cops' thread [goes here](https://codegolf.stackexchange.com/questions/99546/code-ladder-cops). Write a code that has the same number of bytes as the cop post and where the revealed characters are identical. The code must produce `1` in its initial state, and produce the numbers `2, 3 ..` when single alterations are made. The winner will be the robber that cracked the most posts. **Example post:** # MyLang, 9 bytes, 8 numbers (including link to answer), Cop's username. Original code: ``` abc1efghi ``` Code that produces 1 - 8: ``` 1: abc1efghi 2: abc2efghi 3: abc2efghij 4: kbc2efghij 5: kbc23fghij 6: kbc23fghi 7: kbc63fghi 8: kbc63fhi ``` Explanations are encouraged. The exact format of the robber post is optional. [Answer] # Retina, 2 bytes, 10 numbers, by [Martin Ender](https://codegolf.stackexchange.com/a/99549/31625). Original code: ``` 1 ``` This replaces the empty input by the number 1. Code that produces 1 - 10 (showing newlines as `\n` for convenience): ``` 1 : \n1 2 : \n1\n 3 : \n11\n 4 : \n111\n 5 : \n1111\n 6 : \n11111\n 7 : \n111111\n 8 : \n1111111\n 9 : \n11111111\n 10: \n111111111\n ``` For 2 and onwards, we count the number of empty strings in the previous stage. For 2, there is an empty string before and after the 1. For 3 there is an empty string before the ones, in between the ones and after the ones. This works all the way up to 10. [Try it online](http://retina.tryitonline.net/#code=CjExMTExMTExMQo&input=) [Answer] # Perl, 12 bytes, 10 numbers, by [ais523](https://codegolf.stackexchange.com/a/99623/57100) Original code: ``` ____;say__-9 ``` Code that produces 1 - 10: ``` wait;say$!-9 wait;say$!-8 wait;say$!-7 wait;say$!-6 wait;say$!-5 wait;say$!-4 wait;say$!-3 wait;say$!-2 wait;say$!-1 wait;say$!-0 ``` Explanation: ``` wait; # waits for a child process to end (there is no child so it just returns) say # put the following on the screen: $! # current value of the C errno. In this case, ECHILD (No child processes) # which has a value of 10 -9 # minus 9 ``` [Answer] # JavaScript, 30 bytes, 10 numbers, by [ETHproductions](https://codegolf.stackexchange.com/a/99565/41805). Original code: ``` 1: alert(Array(2).join(3).length) ``` Other numbers ``` 2: alert(Array(2).join(31).length) 3: alert(Array(2).join(314).length) 4: alert(Array(2).join(3141).length) 5: alert(Array(2).join(31415).length) 6: alert(Array(2).join(314159).length) 7: alert(Array(2).join(3141592).length) 8: alert(Array(2).join(31415926).length) 9: alert(Array(2).join(314159265).length) 10: alert(Array(2).join(3141592653).length) ``` ### Explanation `Array(2)` creates an Array with two empty cells. The `.join` method joins all the elements in an Array using a delimiter, which converts it into a String. In the Original Code, the delimiter was `3`. This meant that the two empty cells in the Array are joined together used `3` as their delimiter. This evaluates `"3"`, without anything on either side of the `3` because the Array is empty. And since the `length` of `"3"` is `1`, this value is outputted to the console. For the other numbers, I add 1 more digit to the delimiter that is joining the elements of the Array. Hence, this increases its length, thus `alert`ing with increasing values. Note that the numerical value of the delimiter is not important, only its length is. ## Snack Snippet! **Note:** I used `console.log` instead of `alert` in my Snack Snippet for obvious reasons. Also, output from the console is display in the snippet. ``` console.log(Array(2).join(3).length) console.log(Array(2).join(31).length) console.log(Array(2).join(314).length) console.log(Array(2).join(3141).length) console.log(Array(2).join(31415).length) console.log(Array(2).join(314159).length) console.log(Array(2).join(3141592).length) console.log(Array(2).join(31415926).length) console.log(Array(2).join(314159265).length) console.log(Array(2).join(3141592653).length) ``` [Answer] # Octave, 17 bytes, 10 numbers, by [Stewie Griffin](https://codegolf.stackexchange.com/a/99604/24877) ``` original: _i_(__i__(2_5_)) solution: fix( 'i'-(2*52)) fix( 'j'-(2*52)) fix( 'k'-(2*52)) fix( 'l'-(2*52)) fix( 'm'-(2*52)) fix( 'n'-(2*52)) fix( 'o'-(2*52)) fix( 'p'-(2*52)) fix( 'q'-(2*52)) fix( 'r'-(2*52)) ``` [Answer] # Python 2, 17 bytes, 10 numbers, by [xnor](https://codegolf.stackexchange.com/a/99681/53748) ``` print len([' ']) print len(*[' ']) print len(*[' ']) print len(*[' ']) print len(*[' ']) print len(*[' ']) print len(*[' ']) print len(*[' ']) print len(*[' ']) print len(*[' ']) ``` **[repl.it](https://repl.it/EWpb)** [Answer] ## Python 2, 9 bytes, 10 numbers, [xnor](https://codegolf.stackexchange.com/a/100036/21487) ``` print 8/8 print 18/8 print 28/8 print 38/8 print 38/7 print 38&7 print 31&7 print 31&72 print 31&73 print 31&74 ``` [Answer] # Perl, 14 bytes, 10 numbers, by [Dada](https://codegolf.stackexchange.com/a/99569/62131) Original code: ``` say_!"___"%""_ ``` Code that produces 1 - 10: 1. `say"!"+1#"%""r` 2. `say"!"+2#"%""r` 3. `say"!"+3#"%""r` 4. `say"!"+4#"%""r` 5. `say"!"+5#"%""r` 6. `say"!"+6#"%""r` 7. `say"!"+7#"%""r` 8. `say"!"+8#"%""r` 9. `say"!"+9#"%""r` 10. `say"1"+9#"%""r` I have a feeling this isn't what you were going for. [Answer] # JavaScript, 22 bytes, 10 numbers, by [Arnauld](https://codegolf.stackexchange.com/a/99665/62131) Original program: ``` alert(0_6_4_>_0_2_0_7) ``` Cracked: 1. `alert(0+6^42>101210^7)` 2. `alert(0+5^42>101210^7)` 3. `alert(0+4^42>101210^7)` 4. `alert(0+3^42>101210^7)` 5. `alert(0+2^42>101210^7)` 6. `alert(0+1^42>101210^7)` 7. `alert(0+0^42>101210^7)` 8. `alert(0+0^42>101210^8)` 9. `alert(0+0^42>101210^9)` 10. `alert(0+3^42>101210^9)` The hard part is to deal with the `>`, which has a very low precedence. I tried changing it to an `>>`, but it's easiest to just absorb it by making it uselessly calculate a boolean false (the `42>101210` section) which is numerically 0, and just generate the numbers from 1 to 10 with operators with an even lower precedence than `>`. I used `^`, bitwise xor, because it can generate the numbers from 1 to 10 fairly easily (conveniently, the 6 and 7 in the original input let me simplify the expression down to `6^7` which is 1). [Answer] # JavaScript, 9 bytes, [Hedi](https://codegolf.stackexchange.com/a/99611/42545) Original code: ``` alert(+1) ``` Modifications: ``` alert(1+1) // 2 alert(2+1) // 3 alert(3+1) // 4 alert(4+1) // 5 alert(5+1) // 6 alert(6+1) // 7 alert(7+1) // 8 alert(8+1) // 9 alert(9+1) // 10 ``` [Answer] ## Octave, 55 bytes, 10 numbers, [flawr](https://codegolf.stackexchange.com/a/99669/30688) ``` (o=@(O,o)(@(O,o)o{2-O} ) (0<O,{ (yo=O-1)+1,@()1}))(1,o) ``` The final `1` can be cycled up to 9, and then change the `+1` to `+2`. [Answer] ## Python 3, 16 bytes, 10 numbers, by [Sp3000](https://codegolf.stackexchange.com/a/99869/16766) This was fun. ``` print(?%??f?r?t) print(1%0xfor t) print(2%0xfor t) ... print(8%0xfor t) print(84%0xfor t) print(85%0xfor t) ``` Exploits the fact (which I didn't know till now) that a hex literal ends as soon as a character that isn't `0-9a-fA-F` is encountered--thus `0xfor` is a very sneaky way to write `15 or`. After that, it was a matter of finding the right value congruent to 10 modulo 15. [Answer] ## JavaScript, 22 bytes, 10 numbers by [Arnauld](https://codegolf.stackexchange.com/a/99643/9365) **Original code**: ``` alert(__14_337__xc_de) ``` **Modified**: ``` alert(00140337-0xc0de) // 1 alert(00140337-0xc0dd) // 2 alert(00140337-0xc0dc) // 3 alert(00140337-0xc0db) // 4 alert(00140337-0xc0da) // 5 alert(00140337-0xc0d9) // 6 alert(00140337-0xc0d8) // 7 alert(00140337-0xc0d7) // 8 alert(00140337-0xc0d6) // 9 alert(00140337-0xc0d5) // 10 ``` I'm guessing this isn't the intended solution, but I'm hoping it's not too far off... [Answer] # Octave, 32 bytes, 10 numbers, by [Luis Mendo](https://codegolf.stackexchange.com/a/99567/31516) Original code: ``` nnz(isprime(floor(s=3):i*-2i))+1 ``` Modified codes: ``` 2: nnz(isprime(floor(s=3):i*-3i))+1 3: nnz(isprime(floor(s=3):i*-5i))+1 4: nnz(isprime(floor(s=3):i*-9i))+1 5: nnz(isprime(floor(s=3):i*-9i))+2 6: nnz(isprime(floor(s=3):i*-9i))+3 7: nnz(isprime(floor(s=3):i*-9i))+4 8: nnz(isprime(floor(s=3):i*-9i))+5 9: nnz(isprime(floor(s=3):i*-9i))+6 10: nnz(isprime(floor(s=3):i*-9i))+7 ``` There are many ways to make modifications here (for instance `s=2` and `+0` in the beginning). Edit: A more probable alternative: ``` nnz(isprime(floor(s=2):i*-2i))+0 nnz(isprime(floor(s=2):i*-2i))+1 nnz(isprime(floor(s=2):i*-2i))+2 nnz(isprime(floor(s=2):i*-2i))+3 nnz(isprime(floor(s=2):i*-2i))+4 nnz(isprime(floor(s=2):i*-2i))+5 nnz(isprime(floor(s=2):i*-2i))+6 nnz(isprime(floor(s=2):i*-2i))+7 nnz(isprime(floor(s=2):i*-2i))+8 nnz(isprime(floor(s=2):i*-2i))+9 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/), 11 bytes, 10 numbers, by [Oliver](https://codegolf.stackexchange.com/a/99579/41805) Original code: ``` 1: 3628801zรฏ0> ``` Other numbers ``` 2: 3628801zรฏ0>> 3: 3628801zรฏ0>>> 4: 3628801zรฏ0>>>> 5: 3628801zรฏ0>>>>> 6: 3628801zรฏ0>>>>>> 7: 3628801zรฏ0>>>>>>> 8: 3628801zรฏ0>>>>>>>> 9: 3628801zรฏ0>>>>>>>>> 10: 3628801zรฏ0>>>>>>>>>> ``` ### Explanation ``` 3628801 # push this number z # find its reciprocal รฏ # round it to the nearest integer (becomes 0) 0 # push 0 >>>> # increment by 1 for each `>` present (this is for 4) # implicit output ``` To summarise it, push `3628801`, take its reciprocal and round that to the nearest integer (evaluates to `0`). Then increment the stack. TADA! [Try it online!](http://05ab1e.tryitonline.net/#code=MzYyODgwMXrDrzA-&input=) For output = 1 Then add as many `>`s as you want depending on what number you want to output. [Answer] # JavaScript, 12 bytes, 10 numbers, [Hedi](https://codegolf.stackexchange.com/a/99617/42545) Original code: ``` alert(+[+1]) ``` 2 through 10: ``` alert(+[1+1]) alert(+[2+1]) alert(+[3+1]) alert(+[4+1]) alert(+[5+1]) alert(+[6+1]) alert(+[7+1]) alert(+[8+1]) alert(+[9+1]) ``` There's only so much you can do with this much code... [Answer] # Jelly, 7 bytes, 10 numbers, [Jonathan Allan](https://codegolf.stackexchange.com/a/99636/58765) Original code: ``` โ€œ1โ€˜แปŒศฎแธŠโ€˜ ``` Then: ``` โ€œ1โ€˜โ€˜แปŒศฎแธŠโ€˜ โ€œ1โ€˜โ€˜โ€˜แปŒศฎแธŠโ€˜ โ€œ1โ€˜โ€˜โ€˜โ€˜แปŒศฎแธŠโ€˜ โ€œ1โ€˜โ€˜โ€˜โ€˜โ€˜แปŒศฎแธŠโ€˜ โ€œ1โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜แปŒศฎแธŠโ€˜ โ€œ1โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜แปŒศฎแธŠโ€˜ โ€œ1โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜แปŒศฎแธŠโ€˜ โ€œ1โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜แปŒศฎแธŠโ€˜ โ€œ1โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜โ€˜แปŒvแธŠโ€˜ ``` You can check the last one on [TryItOnline!](http://jelly.tryitonline.net/#code=4oCcMeKAmOKAmOKAmOKAmOKAmOKAmOKAmOKAmOKAmOG7jHbhuIrigJg&input=) --- Another way would be ``` โ€œ2โ€˜แปŒศฎแธŠโ€˜ โ€œ3โ€˜แปŒศฎแธŠโ€˜ ... โ€œ9โ€˜แปŒศฎแธŠโ€˜ โ€œ9โ€˜แปŒvแธŠโ€˜ ``` [Answer] # Octave, 21 bytes, 10 numbers, by [Stewie Griffin](https://codegolf.stackexchange.com/a/99654/24877) The `fpr` was a nice misguidance=) But I love the `(1') -> 2(1') -> 2+(1')` sequence! ``` original: disp(fpr___f__e_(_'_) % original disp(fprintf= e=(1')) % my solution disp(fprintf= e=2(1')) disp(fprintf= e=2+(1')) disp(fprintf= e=3+(1')) disp(fprintf= e=4+(1')) disp(fprintf= e=5+(1')) disp(fprintf= e=6+(1')) disp(fprintf= e=7+(1')) disp(fprintf= e=8+(1')) disp(fprintf= e=9+(1')) ``` [Answer] # Hexagony, 7 bytes, 10 numbers, by [Martin Ender](https://codegolf.stackexchange.com/a/99771/57100) Original: ``` 1<@|!__ ``` Code that produces 1 - 10: ``` 1<@|!). 2<@|!). 3<@|!). 4<@|!). 5<@|!). 6<@|!). 7<@|!). 8<@|!). 9<@|!). 9<@|!).! ``` 1: [Try it Online!](http://hexagony.tryitonline.net/#code=MTxAfCEpLg&input=) 9: [Try it Online!](http://hexagony.tryitonline.net/#code=OTxAfCEpLg&input=) 10: [Try it Online!](http://hexagony.tryitonline.net/#code=OTxAfCEpLiE&input=) Here is the hex for the first 9 programs (where # is the number that you want to print): ``` # < @ | ! ) . ``` The memory edge is just set to the value you want to print, deflected to the SE and printed. And the hex for 10: ``` 9 < @ | ! ) . ! . . . . . . . . . . . ``` Here, I added a character to the end which increased the hex size. First, the memory edge is set to 9, the pointer is deflected to the SE, memory is incremented, wraps around, the pointer is deflected to the SW, the value is printed and the program ends. --- Here is a second solution: ``` 1<@|!$) 2<@|!$) 3<@|!$) ... 8<@|!$) 9<@|!$) 9#@|!$) ``` 1: [Try it Online!](http://hexagony.tryitonline.net/#code=MTxAfCEkKQ&input=) 9: [Try it Online!](http://hexagony.tryitonline.net/#code=OTxAfCEkKQ&input=) 10: [Try it Online!](http://hexagony.tryitonline.net/#code=OSNAfCEkKQ&input=) The hex for 1 - 9 (this time `*` is the number to print): ``` * < @ | ! $ ) ``` This works the same as 1 - 9 above. The hex for 10: ``` 9 # @ | ! $ ) ``` This hits `9` then `#` switched the instruction pointer to the lower right one, memory is incremented to 10, `$` jumps over the `!`, the pointer is reversed back east where it jumps over `)` and ends. [Answer] # C#, 90 bytes, 10 numbers, [Scepheo](https://codegolf.stackexchange.com/a/99738/58765) Original: ``` using ______________________________________________;class C{static void Main(){_______;}} ``` First: ``` using System;class D{public D(){Console.Write(+1);}};class C{static void Main(){new D();}} ``` Then: ``` using System;class D{public D(){Console.Write(1+1);}};class C{static void Main(){new D();}} using System;class D{public D(){Console.Write(2+1);}};class C{static void Main(){new D();}} using System;class D{public D(){Console.Write(3+1);}};class C{static void Main(){new D();}} using System;class D{public D(){Console.Write(4+1);}};class C{static void Main(){new D();}} using System;class D{public D(){Console.Write(5+1);}};class C{static void Main(){new D();}} using System;class D{public D(){Console.Write(6+1);}};class C{static void Main(){new D();}} using System;class D{public D(){Console.Write(7+1);}};class C{static void Main(){new D();}} using System;class D{public D(){Console.Write(8+1);}};class C{static void Main(){new D();}} using System;class D{public D(){Console.Write(9+1);}};class C{static void Main(){new D();}} ``` [Answer] # Ruby, 81 bytes, 10 numbers, [histocrat](https://codegolf.stackexchange.com/a/99944/45268) Original code: ``` x=##/=#%# ) ###x ``` Cracked: ``` x=/$/=~%q ) p x ``` This was a tricky one. Many characters that were revealed turned out to be red herrings! `/` isn't division but part of a regex literal. `%` isn't mod but part of an uncommon string literal syntax. This program simply prints the length of a string delimited by newlines. The subsequent programs can be obtained by inserting additional characters in the second line. [Answer] # Octave, 25 bytes, 10 numbers, by [Luis Mendo](https://codegolf.stackexchange.com/a/99582/24877) ``` mean(repmat(1,ones(1,1))) mean(repmat(2,ones(1,1))) mean(repmat(3,ones(1,1))) mean(repmat(4,ones(1,1))) mean(repmat(5,ones(1,1))) mean(repmat(6,ones(1,1))) mean(repmat(7,ones(1,1))) mean(repmat(8,ones(1,1))) mean(repmat(9,ones(1,1))) ``` [Answer] # ์•„ํฌ(Aheui), 19 bytes, 10 numbers, by [JHM](https://codegolf.stackexchange.com/a/99581/25180) Original code: ``` ๋ดƒๆณ•ํฌ ๋ฐ˜์ž๋ญ‰ ``` Modified: ``` 2 ๋ดƒๆณ•ํฌ ๋ฐ˜๋ฐ˜๋ญ‰ 3 ๋ดƒๆณ•ํฌ ๋ฐ˜๋ฐฌ๋ญ‰ 4 ๋ดƒๆณ•ํฌ ๋ฐ˜๋ฐญ๋ญ‰ 5 ๋ดƒๆณ•ํฌ ๋ฐ˜๋ฐœ๋ญ‰ 6 ๋ดƒๆณ•ํฌ ๋ฐ˜ํƒ€๋ญ‰ 7 ๋ดƒๆณ•ํฌ ๋ฐ˜๋ฐ๋ญ‰ 8 ๋ดƒๆณ•ํฌ ๋ฐ˜๋ฐฃ๋ญ‰ 9 ๋ดƒๆณ•ํฌ ๋ฐ˜๋ฐข๋ญ‰ 10 ๋ดƒๆณ•ํฌ ๋ฐ˜๋‹ค๋ญ‰ ``` [Answer] # Octave, 24 bytes, 9 numbers, [by flawr](https://codegolf.stackexchange.com/a/99605/31516) ``` max(repmat(1,ones(),1))% max(repmat(2,ones(),1))% max(repmat(3,ones(),1))% max(repmat(4,ones(),1))% max(repmat(5,ones(),1))% max(repmat(6,ones(),1))% max(repmat(7,ones(),1))% max(repmat(8,ones(),1))% max(repmat(9,ones(),1))% ``` **Octave, 24 bytes ~~9~~ 10 numbers** Note: This crack is for the first version of the cop post (posted the wrong snippet), with the revealed code looking like this: `___a__repmat(__one__),__)`. The correct version is above. Original code: ``` +mean(repmat(1,ones(),1)) ``` Modified versions that print 2-10 ``` 1+mean(repmat(1,ones(),1)) 2+mean(repmat(1,ones(),1)) 3+mean(repmat(1,ones(),1)) 4+mean(repmat(1,ones(),1)) 5+mean(repmat(1,ones(),1)) 6+mean(repmat(1,ones(),1)) 7+mean(repmat(1,ones(),1)) 8+mean(repmat(1,ones(),1)) 9+mean(repmat(1,ones(),1)) ``` [Answer] # JavaScript, 15 bytes, 10 numbers, [ETHProductions](https://codegolf.stackexchange.com/a/99614/34388) Original code: ``` alert( +"+1"+0) // Prints 1 ``` Programs: ``` alert( +"+1"+1) // Prints 2 alert( +"+1"+2) // Prints 3 alert( +"+1"+3) // Prints 4 alert( +"+1"+4) // Prints 5 alert( +"+1"+5) // Prints 6 alert( +"+1"+6) // Prints 7 alert( +"+1"+7) // Prints 8 alert( +"+1"+8) // Prints 9 alert( +"+1"+9) // Prints 10 ``` [Answer] # Octave, 21 bytes, 9 numbers, [by flawr](https://codegolf.stackexchange.com/a/99608/31516) I really enjoyed this one... Clever :) ``` a='repmat(1one'(1,8) a='repmat(2one'(1,8) a='repmat(3one'(1,8) a='repmat(4one'(1,8) a='repmat(5one'(1,8) a='repmat(6one'(1,8) a='repmat(7one'(1,8) a='repmat(8one'(1,8) a='repmat(9one'(1,8) ``` [Answer] ## *Acc!!*, 10 bytes, 9 numbers, by [DLosc](https://codegolf.stackexchange.com/a/99570/55508) Original code : ``` Write 49+_ ``` To produce the numbers 1 to 9 : ``` Write 49+_ Write 49+1 Write 49+2 Write 49+3 Write 49+4 Write 49+5 Write 49+6 Write 49+7 Write 49+8 ``` 49 is the ascii code of `1`. `_` contains 0 by default (so `49+_ = 1`). And `Write` prints the character corresponding to the ascii code of its argument. Pretty straight forward. [Answer] # Python 2, 49 bytes, 10 numbers, [AlexRacer](https://codegolf.stackexchange.com/questions/99546/code-ladder-cops/99622#99622) Maybe (just maybe) the intended solution, but if so, plenty of bytes could have been golfed off: ``` y=10-6;s='0901100000';print int(s[8-8+y-2+0+0:y]) y=10-6;s='0902100000';print int(s[8-8+y-2+0+0:y]) y=10-6;s='0903100000';print int(s[8-8+y-2+0+0:y]) y=10-6;s='0904100000';print int(s[8-8+y-2+0+0:y]) y=10-6;s='0905100000';print int(s[8-8+y-2+0+0:y]) y=10-6;s='0906100000';print int(s[8-8+y-2+0+0:y]) y=10-6;s='0907100000';print int(s[8-8+y-2+0+0:y]) y=10-6;s='0908100000';print int(s[8-8+y-2+0+0:y]) y=10-6;s='0909100000';print int(s[8-8+y-2+0+0:y]) y=10-4;s='0909100000';print int(s[8-8+y-2+0+0:y]) ``` [Answer] ## [Befunge-93](http://esolangs.org/wiki/Befunge), 11 bytes, 10 numbers, [James Holderness](https://codegolf.stackexchange.com/a/99648/8478) ``` 905:**-8-.@ 905:**-7-.@ 905:**-6-.@ 905:**-5-.@ 905:**-4-.@ 905:**-3-.@ 905:**-2-.@ 905:**-1-.@ 905:**-0-.@ 905:**-~-.@ ``` [Try it online!](http://befunge.tryitonline.net/#code=OTA1OioqLX4tLkA&input=) Probably not the intended solution. What I did was get rid of the pesky 25 (`5:*`) by multiplying it by `0`. If we then put a `9` at the beginning then the outputs will be `9 - N` where need to generate `N` from a single command. The only issue is `-1` to get `10`, but trying to read an integer if there's no input conveniently pushes a `-1`. [Answer] # 05AB1E, 5 bytes, 10 numbers, by [Adnan](https://codegolf.stackexchange.com/a/99656/56258). Original code: ``` โ€ฆ[==1 ``` 1-10: ``` โ€ฆ[==1 โ€ฆ[==2 โ€ฆ[==3 โ€ฆ[==4 โ€ฆ[==5 โ€ฆ[==6 โ€ฆ[==7 โ€ฆ[==8 โ€ฆ[==9 โ€ฆ[==T ``` **Explanation:** ``` โ€ฆ[== 3 char string 1 Push number ``` [Answer] # 05AB1E, 6 bytes, 10 numbers, [Adnan](https://codegolf.stackexchange.com/a/99667/58106) Original code: ``` ยผ [==q ``` Keep adding `ยผ`'s to output up to 10: ``` ยผยผ [==q ยผยผยผ [==q ยผยผยผยผ [==q ยผยผยผยผยผ [==q ยผยผยผยผยผยผ [==q ยผยผยผยผยผยผยผ [==q ยผยผยผยผยผยผยผยผ [==q ยผยผยผยผยผยผยผยผยผ [==q ยผยผยผยผยผยผยผยผยผยผ [==q ``` [Try it online](http://05ab1e.tryitonline.net/#code=wrzCvMK8wrzCvMK8wrzCvMK8wrwgWz09cQ&input=) How it works: ``` ยผ # Increment counter_variable to count_of(ยผ), it's printed at some point... [ # Infinite loop start == # Print nothing because stack is empty q # Quit ``` ]
[Question] [ Your challenge is to find the file extension of a provided filename: ``` hi.txt -> txt or .txt carrot.meme -> meme or .meme lol (undefined behavior) what..is..this..file -> file or .file .bashrc -> bashrc or .bashrc [[emailย protected]](/cdn-cgi/l/email-protection)[]h -> h0wC[]h or .h0wC[]h agent.000 -> 000 or .000 ``` **You must get the text from the last `.` or after the last `.` to the end of the string.** The first capturing group match of the regular expression `/\.([^.]+)$/` works, and so does splitting the input on `.`s and returning the last one. The file name will always contain at least one `.`, but it may contain multiple `.`. (see examples) The input will always match [`^[.a-zA-Z0-9^!\[\]{}@$%+=]+$`](https://regex101.com/r/KW4sF3/2). [Answer] # [Retina](https://github.com/m-ender/retina), 5 bytes ``` .*\. ``` Replaces everything and a dot with nothing at all. [Try it online!](https://tio.run/nexus/retina#@6@nFaPH9f9/RmpOTr5eeX5RTopeSWpxiV5WQbpeakUqAA "Retina โ€“ TIO Nexus") [Answer] ## JavaScript (ES6), 19 bytes Returns the full filename when there's no file extension. I suppose this is an acceptable *undefined behavior*. ``` let f = s=>s.split`.`.pop() console.log(f("hi.txt")) // -> txt console.log(f("carrot.meme")) // -> meme console.log(f("lol")) // -> undefined behavior console.log(f("what..is..this..file")) // -> file console.log(f("[[emailย protected]](/cdn-cgi/l/email-protection)[]h")) // -> h0wC[]h console.log(f(".bashrc")) // -> bashrc ``` [Answer] ## Mathematica, 13 22 bytes *Edit: Not sure how I missed the `".bashrc"` test case. Thanks to Artyer for keeping me honest.* ``` FileExtension["a"<>#]& ``` If the input matches `\.[^.]+`, then `FileExtension` just returns the empty string, so we prepend the letter `a`. In any other case, prepending `a` doesn't affect output of `FileExtension`. [Answer] # POSIX Shell, 13 ``` echo ${1##*.} ``` [Try it online](https://tio.run/nexus/bash#NYzNCsIwEITvPsWwrRchC54F3yW0GxJIs5IsKEifPY1C5/DB/DBBK0yaLb4JUgHFxPYxAi2@VjXeZJPhsubBd/TGnBqzxR9DykIPrHrB0KumYgF0bXBPEObv@bz/@yYG5zCfaZcl6ljdp@nGe1@1SD8A). [Answer] # c function, 21 * 1 byte saved thanks to @Dennis. * 3 bytes saved thanks to @JohanduToit. * 2 bytes saved thanks to @Neil. * 1 byte saved thanks to @algmyr. ``` f(s){s=rindex(s,46);} ``` [Try it online](https://tio.run/nexus/c-gcc#XZDBboMwDIbvPIUVqVJCWehh2oV1L9JxiLKkWIJQxWarVvHsLMA00HxIfv2Of33O5CWpB50jhg93l1Q8v6hqnDAwdAYDyFmZeLUF2D4Qg21MhDw5nwoeGaRaHXbE1pCjSw3n385cokHNdxbF5lgTY8@6c53b2WUp2r4VRVI5WDOkKDBA7urN0DLk5Rbw1RjWGklrbubTY@vE0h6r5ZqhscoW7fuYtkhMpwoQXkESfrveyz9gBSX89y6nWqn0/nhUu11u6ZfYS3EgeHqDA72HhLvNYF3APgPnjBVrRYmOhxgSSDZOPw). [Answer] # [Japt](https://github.com/ETHproductions/japt), 3 bytes 2 bytes of code, +1 for the `h` flag. ``` q. ``` ### Explanation: ``` q. Split the input by `.` -h Return the last item ``` [Try it online!](https://tio.run/nexus/japt#@1@o9/@/UnlGYomeXmaxnl5JBohMy8xJVdLNAAA "Japt โ€“ TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` '.ยกยค ``` [Try it online!](https://tio.run/nexus/05ab1e#@6@ud2jhoSX//5dnJJbo6WUW6@mVZIDItMycVAA "05AB1E โ€“ TIO Nexus") or [Try All Tests](https://tio.run/nexus/05ab1e#qymr/K@ud2jhoSX/K5UO77dSULLX@Z@RqVdSUcKVnFhUlF@il5uam8qVk5/DVZ6RWKKnl1msp1eSASLTMnNSufSSEoszipK5QgwMfB3yjL0TA6L0MgzKnaNjMwA "05AB1E โ€“ TIO Nexus") ``` '. # Push '.' ยก # Split on occurrences of '.' ยค # Tail ``` [Answer] # [Neo4j Cypher](http://neo4j.com/docs/developer-manual/current/cypher), 24 bytes ``` return split($i,".")[-1] ``` Input is in a param (`i`), probably the only way for cypher to take input. Pretty straightforward. [Cypher has never been used on PPCG before](https://codegolf.stackexchange.com/search?q=Cypher) [Answer] # PHP, 21 Bytes ``` <?=pathinfo($argn,4); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVcrI1CupKFGy5rK3@29jb1uQWJKRmZeWrwGW1jHRtP7/HwA "PHP โ€“ TIO Nexus") is a shorter expression for ``` <?=pathinfo($argn)[extension]; ``` [pathinfo](http://php.net/manual/en/function.pathinfo.php) # PHP, 27 Bytes ``` <?=end(explode(".",$argn)); ``` [explode](http://php.net/manual/en/function.explode.php) [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVcrI1CupKFGy5rK3@29jb5ual6KRWlGQk5@SqqGkp6QDVqWpaf3/PwA "PHP โ€“ TIO Nexus") ## PHP <7.0, 26 Bytes ``` <?=end(split("\.",$argn)); ``` deprecated [split](http://php.net/manual/en/function.split.php) [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), 1397 bytes ``` Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[a]Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan "b" if no one is waiting.Switch to plan "a".[b]Go to The Babelfishery:n 1 l 1 l.[c]Go to Fueler Up:n.Go to Joyless Park:n 2 r.Go to Narrow Path Park:w 1 r 3 l.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 l 1 r 2 l.Pickup a passenger going to Crime Lab.Pickup a passenger going to Joyless Park.'.' is waiting at Writer's Depot.Go to Writer's Depot:s.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 1 r 2 r 2 l.Switch to plan "c" if no one is waiting.Go to Narrow Path Park:n 5 l.[d]Pickup a passenger going to Chop Suey.Go to Chop Suey:e 1 r 1 l 1 r.Go to Narrow Path Park:n 1 l 1 r 1 l.Switch to plan "e" if no one is waiting.Switch to plan "d".[e]Go to Joyless Park:e 1 r 3 l.Switch to plan "f" if no one is waiting.Pickup a passenger going to Narrow Path Park.Go to Fueler Up:w 1 l.Go to Narrow Path Park:n 4 l.Switch to plan "e".[f]Go to Narrow Path Park:w 1 r 3 l.[g]Switch to plan "h" if no one is waiting.Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to KonKat's.Go to Narrow Path Park:n 2 l.Switch to plan "g".[h]Go to KonKat's:e 1 r.Pickup a passenger going to Post Office.Go to Post Office:s 3 r 1 l. ``` [Try it online!](https://tio.run/##nVTLboMwEPyVVS65WWqaXji2VSs1VRsprXpAHAxZsBVqI9sR5eupCYYQAnkdbGutfczsjm3oHy/LVwlGwlJqA59xzCP0criD1C5VnWTJo802AwoZ1RpFggoSyUVSRT0xmcFqiwWps7S2J5p4mLs8Pg1OpfqgSskcltQwu6mNy9i/3iXeg@uXxbasPckq5yZilUeWUgGTcAI8BiFBCgSuIafc2PJHfnRC/DCoc38xhEcaYhpzzVAVLQDLKHI@L1tMLZfvzBMO0ZssUtS6gTyzYEb45DvE9@caXUSpBd3wra3OoGbn4hX/RXin4UmvLmoyJdNOj4Aa@FHcoJpqeMZMGofl8NLTF8JwRBrb6WXmqPQHEo0MblQjD9V41sFt2j0U0UU67APGC5W2tkrDYEAz2MqiHxKPpL7hce11m3de0wDV@SBF4sfBWVX7SdCPZDcwWEixoGaqHcbGrPt0TeQAuyHFJZYdC64u1vlGyfHHqm1Har2UZc6oIYRrQgyr9pin@A8 "Taxi โ€“ Try It Online") Taxi doesn't have a reverse function so this ballooned pretty quickly. The logic is: 1. Break the string into characters 2. Reverse the array 3. Iterate through each until a period is found, storing each in a FIFO array 4. Empty the array (because there's only one LIFO array available) 5. Dump the FIFO array into the LIFO array 6. Concatenate the LIFO array and output [Answer] # [GNU Make](https://www.gnu.org/software/make/), 12 bytes ``` $(suffix $1) ``` Not using a builtin, 27 bytes: ``` $(lastword $(subst ., ,$1)) ``` [Answer] ## Batch, 10 bytes ``` @echo %~x1 ``` Strangely competitive for once. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~5~~, 3 bytes Since more of this answer is unprintable than printable, here is a hexdump: ``` 00000000: cd81 ae ... ``` [Try it online!](https://tio.run/nexus/v#@3@491DjoXX//2dk6pVUlHAlJxYV5Zfo5abmpnLl5OdwlWcklujpZRbr6ZVkgMi0zJxUAA "V โ€“ TIO Nexus") This uses [Jan Dvorak's algorithm](https://codegolf.stackexchange.com/a/120937/31716), it just happens to be a more efficient encoding of it. Explanation: ``` ร " Remove all occurrences of: 0x81 " Anything (greedy) ยฎ " Followed by a dot ``` Old solution: ``` $T.d| ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 22 bytes ``` s=>s.Split('.').Last() ``` Implicit `using System.Linq;` FTW! [Try it online!](https://tio.run/##NctNawIxEIDhc/MrggibgB0CvflFQVoorlBUKLR6mMasGdidlWR0BfG3bymll/c5vT4/@kz965n9NEsiPo70n3Nd6Znu82yeYXOqSUwBhYUSsxjbT1TVpoA@anPBpEkT6zeGdcDDtn3hg7H/044La9XDRyIJJXEww8GN7uOd3CpD9j6wkz4SyFWUx5RagSY0QXURBYAygMTfVlQHBd@YY/Jq69zqmZ@W@P4J0XWLr31UeAws4Jz7AQ "C# (Visual C# Interactive Compiler) โ€“ Try It Online") [Answer] # Vim, 5 bytes ``` $F.d0 ``` Explanation: find last `.` in line, delete everything before it Another, longer, but in my opinion still interesting approach with 9 bytes (notice the trailing new line) ``` d/.*\./e ``` This one works similarly, 5 bytes (again, trailing new line): ``` d?\. ``` [Answer] # PowerShell, ~~34~~ 26 bytes -8 bytes thanks to @mazzy ``` (Read-Host).Split('.')[-1] ``` Takes input from STDIN. Actually managed to golf it down shorter than the built-in. # PowerShell, 20 bytes ``` ($args-split'.')[-1] ``` Takes input from commandline arguments. Big thanks to @mazzy again! # PowerShell (with built-in), 36 bytes ``` [IO.Path]::GetExtension((Read-Host)) ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 45 bytes ``` : f begin 1 -1 d+ s" ."search 0= until type ; ``` [Try it online!](https://tio.run/##NYzBCsIwEETvfsWQq3RJ9WZRBI8iePCkeIht2gTStCRbql9fU6yX2Xm7s1N3gU3W1POYph1qvHRjPXJkOao1ogCJqFUoDeQeg2frwJ9eo0jpHptq6H9MAsgOEKmiDChW6dNY4jcL9DOUKoSOqdWtXjauc4sbjWIiG4nYzFpb9w/RS0UTyoVuUl6OfntW1zsZOZ4eT7NcVKM9k5Qy8fQF "Forth (gforth) โ€“ Try It Online") ### Code Explanation ``` : f \ start a new word definition begin \ start an indefinite loop 1 -1 d+ \ remove the first character from the string s" ."search \ find the length and starting address of the first substring that starts with '.' 0= \ check if '.' was found in the string until \ end the loop if not type \ output the result ; \ end the word definition ``` [Answer] # Python 3, 29 bytes ``` print(input().split(".")[-1]) ``` [Answer] # [Rust](https://www.rust-lang.org/), 34 bytes ``` |p|p.extension().or(p.file_stem()) ``` Usable as a `fn(&std::path::Path) -> Option<&std::ffi::OsStr>`. [Try it online!](https://tio.run/##jY5NCsIwEIX3PUXsQiagOcD4s3NdwQOUVic0YJOYmWJFPXstulB04@Yx8L75eKljGaxXbeU8aHXNjiTKovUwZTkgxkoaxO2Yer4uorjgl6/GWodY8E7SWq2GW7xFQ72Q5xEBbUKCaKw7UslCLWg9LLKOST1/AyN23vWflk0vi6xipiQlnSZgfxYgejpD3jgjveRaz9QutARfa8Y7hbasL0IMdf5C9X9qU1fcpP2/7jc@@u/DAw "Rust โ€“ Try It Online") [Answer] # [sed](https://www.gnu.org/software/sed/), 8 bytes ``` s:.*\.:: ``` [Try it online!](https://tio.run/nexus/sed#@19spacVo2dl9f9/RqZeSUUJV3JiUVF@iV5uam4qV05@Dld5RmKJnl5msZ5eSQaITMvMSQUA "sed โ€“ TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แนฃโ€.แนช ``` A monadic link taking the file name and returning the extension with no leading `.`. **[Try it online!](https://tio.run/nexus/jelly#@/9w5@JHDXP1Hu5c9f////KMxBI9vcxiPb2SDBCZlpmTCgA "Jelly โ€“ TIO Nexus")** ### How? Literally does what was asked... ``` แนฃโ€.แนช - Main link: list of characters, f โ€. - literal '.' แนฃ - split f at occurrences of '.' แนช - tail (get the last chunk) ``` [Answer] # [Go](https://golang.org/), 85 bytes Go is... troublesome. ``` import(."fmt" ."os" ."strings") func main(){s:=Split(Args[1],".");Print(s[len(s)-1])} ``` [Try it online!](https://tio.run/nexus/go#K0hMzk5MT1XITczM@5@ZW5BfVKKhp5SWW6LEpaeUXwwii0uKMvPSi5U0udJK85LBKjU0q4utbIMLcjJLNByL0oujDWN1lPSUNK0DgEpLNIqjc1LzNIo1dQ1jNWv///@fkalXUlECAA "Go โ€“ TIO Nexus") A sample of parentheses from the code: ``` ()(){([])([()])} ``` [Answer] # JavaScript (ES6), ~~33~~ ~~31~~ 28 bytes ``` s=>s.slice(s.lastIndexOf`.`) ``` Spec change in comments removes the need for `+1`. -3 bytes thanks to nderscore [Answer] # Common Lisp, 57 bytes ``` (lambda(s)(#1=reverse(subseq #2=(#1# s)0(search"."#2#)))) ``` [Try it online](https://tio.run/nexus/clisp#DcixDkBADADQX5Hr0i4NdqNgQQ6D8dCEBOEafv944wt4@e2cEXd3TItDJYQk8/KKV0F9JpU7gjT7FyKlGFWcn1fDBlKgn2mHnnlsBsvc9baqC@Yyt7khCuED) (added some bytes to call this anonymous function and display returned string) ### Explanation ``` (#1=reverse ...) ;reverse is now accessible with #1# - saves 1 byte. I ;also need to reverse output of function inside to ;get extension in correct order #2=(#1# s) ;reverse of input string is now accessible with #2# (search"."#2#) ;I take reversed string and search for "." to get position of ;first instance of "." in string from the end of it (subseq ... 0 ...) ;get part of reversed string, ;starting from first character and ending just ;before first occurance of "." ;this gives reversed extension ``` I get substring of reversed string, starting from 0, ending on this [Answer] # Gema, 3 characters ``` *.= ``` Sample run: ``` bash-4.4$ gema '*.=' <<< 'what..is..this..file' file ``` [Answer] # Javascript (ES5), 38 bytes ``` function(s){return s.split(".").pop()} ``` [Answer] # C#, ~~33~~ 41 bytes ``` a=>a.Split('.').Last(); ``` Edit as suggested: ``` using System.Linq;a=>a.Split('.').Last(); ``` [Answer] # Awk, ~~14~~ 13 characters (~~10~~ 9 characters code + 4 characters command line option.) ``` {$0=$NF}1 ``` Thanks to: * [Robert Benson](https://codegolf.stackexchange.com/users/45724/robert-benson) for spotting the unnecessary semicolon (-1 character) Sample run: ``` bash-4.4$ awk -F. '{$0=$NF}1' <<< $'hi.txt\ncarrot.meme\nlol\nwhat..is..this..file\n.bashrc\[[emailย protected]](/cdn-cgi/l/email-protection)[]h' txt meme lol file bashrc h0wC[]h ``` [Answer] # [Lua](https://www.lua.org), ~~53~~ 30 bytes Replaces everything upto the last `.` with the empty string `''`. Double parenthesis to select only the first return value of `gsub`. Any golfing tips are welcome, I'm rusty in lua... ``` print(((...):gsub('.*%.',''))) ``` [Try it online!](https://tio.run/nexus/lua#@19QlJlXoqGhoaenp2mVXlyapKGup6Wqp66jrq6pqfn///@kxDwg1EtMSkxOLEnVS61IBQA "Lua โ€“ TIO Nexus") [Answer] # JS (ES6), ~~26~~ 25 bytes ``` x=>/\.([^.]+)$/.exec(x)[1] ``` -1 byte thanks to Shaggy ``` document.querySelector('pre').innerText = (x=>/\.([^.]+)$/.exec(x)[1])("example.txt") ``` ``` <input oninput = "document.querySelector('pre').innerText = (x=>x.match(/\.([^.]+)$/)[1])(this.value)" value = "example.txt"> <pre></pre> ``` Alternate, 29 bytes: ``` x=>(y=x.split`.`)[y.length-1] ``` ]
[Question] [ Rearrange a given list such that all the odd numbers appear before all the even numbers. Besides for this requirement, the output list may be in any order. The input will only contain integers, but they may be negative and there may be duplicates, and they may appear in any order. Shortest solution wins. ### Test cases `[1,2]` โ†’ `[1,2]` `[2,1]` โ†’ `[1,2]` `[1,0,0]` โ†’ `[1,0,0]` `[0,0,-1]` โ†’ `[-1,0,0]` `[3,4,3]` โ†’ `[3,3,4]` `[-4,3,3]` โ†’ `[3,3,-4]` `[2,2,2,3]` โ†’ `[3,2,2,2]` `[3,2,2,2,1,2]` โ†’ `[1,3,2,2,2,2]` or `[3,1,2,2,2,2]` `[-2,-2,-2,-1,-2,-3]` โ†’ `[-1,-3,-2,-2,-2,-2,]` or `[-3,-1,-2,-2,-2,-2,]` `[]` โ†’ `[]` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` ฮฃร‰ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OLDnf//RxvqGOkY65jomOqY6ZjrWOhYxgIA "05AB1E โ€“ Try It Online") [Answer] # C++, ~~79~~ ~~76~~ 64 bytes ``` [](auto a,auto b){while(a<--b)*a%2?*++a:(*a^=*b,*b^=*a,*a^=*b);} ``` This function accepts a pair of iterators (which must be random access iterators), and steadily moves them towards each other. When `a` points to an odd number, it is advanced. Otherwise, `a` points to an even number; `b` is decremented, and `iter_swap`'ed with `a`. (We use XOR swap, which saves us having to include `<algorithm>` - or `<utility>` for `std::swap`). There are unnecessary swaps when `b` points to an even number, but we're golfing, not squeezing efficiency! ## Demo ``` auto f=[](auto a,auto b){while(a<--b)*a%2?*++a:(*a^=*b,*b^=*a,*a^=*b);}; #include <array> #include <iostream> int main() { auto a = std::array{ 3,2,2,5,2,1,2 }; f(a.begin(),a.end()); for (auto i: a) std::cout << i << " "; std::cout << std::endl; } ``` --- ## Non-competitive answer The natural C++ method is `std::partition`, but that comes out at **83** bytes: ``` #include<algorithm> [](auto a,auto b){std::partition(a,b,[](auto x){return x&1;});} ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~4~~ 3 bytes -1 byte thanks to isaacg ``` iD2 ``` [Try it online!](https://tio.run/##K6gsyfj/P9PF6P//aEMdIx1jHRMdcx1TMMtSx9hEx9AoFgA "Pyth โ€“ Try It Online") crossed out 4 is still regular 4 [Answer] # [R](https://www.r-project.org/), ~~30~~ 24 bytes ``` (x=scan())[order(!x%%2)] ``` [Try it online!](https://tio.run/##K/r/X6PCtjg5MU9DUzM6vygltUhDsUJV1Ugz9r@hgpGCqYKlgpmCsYKJgjmYbQHmGSoYGvwHAA "R โ€“ Try It Online") *-6 bytes thanks to JayCe* [Answer] # [J](http://jsoftware.com/), 5 bytes ``` \:2&| ``` [Try it online!](https://tio.run/##y/r/P83WKsbKSK0GyFIwUjBXMFSwANIWYNqYK03BGMgyAWJTBUuguJmCKQA "J โ€“ Try It Online") `\:`โ€ƒsort descending by `2&|`โ€ƒmod-2 [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 bytes ``` รฑv ``` [Try it online!](https://tio.run/##Dci5DYBADEXBhp4lvne9Ry2IgJSIANEXNVCYYcI59vPKfJ87c7XAKlYwx8SCcAqVoNEZTPSnkKOCKgrUUEcDze0D "Japt โ€“ Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 12 bytes ``` *.sort(*%%2) ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0uvOL@oRENLVdVI8781V3FipUKaRrShjpGOsY5JrCZcxFjHVMdcx9AASchIx0THTMcSKPIfAA "Perl 6 โ€“ Try It Online") Some Whatever code that sorts the input by parity, with odd numbers first. You can remove a `%` to get even numbers first instead. Note that 'Whatever' is the name of this sort of anonymous function. [Answer] # MATL, 6 bytes ``` tog&)v ``` [Try it on MATL Online](https://matl.io/?code=tog%26%29v&inputs=%5B5%2C2%2C3%2C4%2C19%2C7%2C8%2C1%2C20%5D&version=20.9.1) Alternately: ``` to_2$S ``` [Try it on MATL Online](https://matl.io/?code=to_2%24S&inputs=%5B5%2C2%2C3%2C4%2C19%2C7%2C8%2C1%2C20%5D&version=20.9.1) [Answer] # [Haskell](https://www.haskell.org/), ~~23~~ 22 bytes ``` f odd<>f even f=filter ``` [Try it online!](https://tio.run/##DY2xDoIwFEV3vuIOjtJI4uAgLpjoSOJiog4VXsuLpcVH4fOtnc5wz80Z9Pwh5xKPU5CIs45a3WhkK2GZUJbwAS54SwJP1FMP9rhcGxzUXlUIgoHtQLLFe4kQ@i4sWTJ5iAOhW0TIR6wkMwePbBIyI4fCosYzGYS@P54MaCVfmNqwiyRp1LlTYxLO7w0sHpVS1e6Vfp1x2s6pvDdt@wc "Haskell โ€“ Try It Online") This is equivalent to ``` g x = filter odd x ++ filter even x ``` *-1 byte thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)* --- Other approaches: ``` (<>).($odd)<*>($even)$filter import Data.List;sortOn even g x=[i|m<-[0,1],i<-x,odd$m+i] g x=[i|m<-[1,0],i<-x,mod i 2==m] g x=id=<<filter<$>[odd,even]<*>[x] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~37~~ 36 bytes ``` lambda a:sorted(a,key=lambda x:~x%2) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHRqji/qCQ1RSNRJzu10hYqWmFVV6FqpPm/oCgzr0QhTSNa11DHRMdYR9dYx0hH1yhW8z8A "Python 2 โ€“ Try It Online") 1 byte tip o' the hat to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder). [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 bytes ``` {|eom ``` [Run and debug it](https://staxlang.xyz/#c=%7B%7Ceom&i=[1,2,3,4,5,6]%0A[3,57,26,36823435,0]&a=1&m=2) Explanation: ``` {|eom Full program, implicit input { o Sort by key: |e Is odd? m Map over result: Implicit output with newline ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 11 bytes ``` SortBy!Even ``` [Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@z84v6jEqVLRtSw1779fampKcbRKQUFyeixXQFFmXklIanGJc2JxanF0mo5CNJcCEEQb6igY6SgY6yiY6CiYxupABC3BIhY6CoYGQGwI5hkbgrhAvhFMlS5Ery5QpzFMLJYrNvY/AA "Attache โ€“ Try It Online") ## Explanation `Even` returns `true` for even numbers and `false` otherwise. `SortBy` ranks `false < true` (by a numerical cast to `0 < 1`), thus placing odd numbers before even ones. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 29 bytes ``` a=>a.sort((a,b)=>(b&1)-(a&1)) ``` [Try it online!](https://tio.run/##DcpBCoAgEADA38QKu0LZLfQj0WEtjULc0Oj75mVOc/PHdS/X81KWI7RoG1vHukp5ARi9sg78MCoC7qq27JKrpKCTnBBhpRFnNEgGJ6Rp6@MH "JavaScript (Node.js) โ€“ Try It Online") Save 4 bytes by only supporting positive values using `b%2-a%2`. If you write this as: ``` function(a){return a.sort((a,b)=>(b&1)-(a&1))} ``` then it will work on all sorts of old JavaScript implementations that didn't sort stably. [Answer] # T-SQL, 26 bytes ``` SELECT*FROM t ORDER BY~i&1 ``` Uses the bitwise AND operator "&" to compare the last digit with 1. EDIT: Bitwise NOT then shorter than adding 1. EDIT2: Reorder to allow removal of the space. [Answer] # [PHP](https://php.net/), 55 bytes ~14 months later and I'm a little bit better at golfing now: ``` for(;''<$n=$argv[++$i];$s=$n%2?"$n $s":"$s $n");echo$s; ``` [Try it online!](https://tio.run/##DcTRCkAwAAXQX9G6QksxtbDJh8iDhHnZlpXfv5yHE12kneP/GZ7SFIWFn7A917tIiXs1SBN8rmYBnyGJUSBl8KIyx@4CkiGp2LBl3bJjTzWw1lp/ "PHP โ€“ Try It Online") --- # [PHP](https://php.net/) (>=5.4), ~~84~~ 82 bytes (-2 bytes, thanks to [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel)) ``` <?array_shift($a=&$argv);usort($a,function($i){return$i%2==0;});echo join(' ',$a); ``` To run it: ``` php -n <filename> <number_1> <number_2> ... <number_n> ``` Example: ``` php -n sort_odds_first.php 2 0 1 -1 3 8 29 -666 ``` Or [Try it online!](https://tio.run/##FczRCsIgGAbQV9mFNYUJm4EUTnqUkLGlXaj8ajCiV@@L3Z6Lk30G5rsjcvuj@LBVzpw9M0fPtzCtJDpg2FpcakiRsyA@tNZGkYWTsnY0X2HWxafulULkfdcPzAkDQGHEBDnhgivUDVJr/Uv5WApk/AM "PHP โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แธ‚รžแนš ``` **[Try it online!](https://tio.run/##y0rNyan8///hjqbD8x7unPX//38LHSMdYx0DHV0THV1DHTMgNAQA "Jelly โ€“ Try It Online")** One of the more oft-wanted atoms seems to be an is-even one (which would make this 2 bytes), without it we must reverse I believe... ``` แธ‚รžแนš - Link: list of integers รž - sort by: แธ‚ - bit (least significant bit - i.e. 1 if odd 0 if even) แนš - reverse ``` [Answer] **JavaScript, ~~22~~ 20 bytes** `a=>a.sort(a=>!(a%2))` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5Rrzi/qEQDyFLUSFQ10tT8b52cn1ecn5Oql5OfrpGmEW2oY6RjrGOiY6pjpqNrqKNrpKNrrKNrEgtUCgA) [Answer] # [Python](https://docs.python.org/2/), 35 bytes ``` lambda l:sorted(l,key=(-1).__pow__) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHqji/qCQ1RSNHJzu10lZD11BTLz6@IL88Pl7zf46CrUK0rqGOiY6xjq6xjpGOrlEsV0FRZl6JQppGjuZ/AA "Python 2 โ€“ Try It Online") Sorts by the function `x -> (-1)**x`, which gives `-1` for odd and `1` for even. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 50 bytes ``` A+S:-predsort([X,Y,Z]>>(Y/\1>Z/\1,X= <;X= >),A,S). ``` [Try it online!](https://tio.run/##FcpLCoAgAEXRrTg0fBZGEvQRXIOTvrMigkgxoeWbTQ5cuM7byx78ec8YNTMNd37fHusDnQeMmFal6FgsQk0JDD3p2oTKoGGyPDaczAIlJJIVZAXxR52yhlyZAXH@vAP95w8 "Prolog (SWI) โ€“ Try It Online") -8 thanks to Jo King [Answer] # [Red](http://www.red-lang.org), 42 bytes ``` func[a][sort/compare a func[n][n % 2 = 1]] ``` [Try it online!](https://tio.run/##HcixCoAgFEbhvaf4l@bwqhRBL9F6uYOUQkMqZs9v2HCG7xR/tt2fLENYW3jjwU74SaVOR7qzKx4O/47CESMIG5RIy@WKFQGsoAikYXqaDKwm2A5L0FgwS/sA "Red โ€“ Try It Online") If we need to account for negative values: # [Red](http://www.red-lang.org), 43 bytes ``` func[a][sort/compare a func[n][n // 2 = 1]] ``` [Try it online!](https://tio.run/##HchBCoAgEEbhfaf4LxDiqBRBl2g7zEJKoUUWVuefsMVbfK@mTZe0sXR50vyWlaPwfdbHrOdxxZoQ8e8iXGAMCDOsiF51Lw8y2MISyMG3HHkER@hDUyA4jBhEPw "Red โ€“ Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` โ†”ร–%2 ``` [Try it online!](https://tio.run/##yygtzv7//1HblMPTVI3@//8fbaljoWOuY6ZjqGOkY6xjomMaCwA "Husk โ€“ Try It Online") **Explanation** ``` ร– sort input according to the result of the following function %2 modulo 2 โ†” reverse result to get odd numbers to the front ``` [Answer] # [Scala](http://scala-lang.org), 18 bytes ``` _.sortBy(_.+(1)%2) ``` [Answer] # C#, 23 bytes ``` i=>i.OrderBy(u=>u%2==0) ``` Quite straigt forward really: This basically converts the numbers to booleans, whilst `true` means that the number is even and `false` that it's odd. Because `true` is higher than `false` the even numbers appear first. The formatted version looks like that: ``` i => i.OrderBy (u => u % 2 == 0) ``` And you can test it like that: ``` Console.WriteLine (string.Join (",", new Func <IEnumerable <int>, IEnumerable <int>> ( i => i.OrderBy (u => u % 2 == 0) ).Invoke (new [] {3, 2, 2, 2, 1, 2, 5, 5}))); ``` Which results in the following: ``` 3,1,5,5,2,2,2,2 ``` [Answer] # JavaScript, 23 bytes 6 bytes shorter than [@Neil's answer](https://codegolf.stackexchange.com/a/168782/81748) using the same language :D ``` a=>a.sort(n=>-(n&1)||1) ``` **Explanation:** The function passed to `sort` only cares about the first parameter. If it is odd it returns `-1` (the result of `-(n&1)`). Otherwise (when `-(n&1)` yields `0`) it returns `1`. [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9Wmpds@z/R1i5Rrzi/qEQjz9ZOVyNPzVCzpsZQ8791cn5ecX5Oql5OfroGSKlGtKGOgomOgq6xjoKpjoIRkAXimYGZEDFzIB@ELXQULHUUDHQUDEHYEEQbxGpq/gcA) [Answer] # JavaScript (Chrome v67) - ~~24~~ ~~19~~ 23 bytes ``` a=>a.sort(a=>!(a&1)-.5) ``` The use of `&1` rather than `Math.abs()%2` was stolen from @Neil. Thanks! Thanks to @Shaggy for showing my hacky 19 byte solution wasn't valid. If anyone wants it: ~~Depends on how the browser handles a hacky return value of `0`. Chrome v67, after 100000 iterations of random arrays never sorted it wrong. I'm very sure it works -- and it relies on the specific sort algorithm Chrome uses too, I believe. (It might work in other browsers, that's not the point)~~ `a=>a.sort(a=>++a&1)` [Answer] # JavaScript, 21 bytes ``` a=>a.sort(n=>(-1)**n) ``` [Try it online](https://tio.run/##LUxbDoMwDPvnJC1yK0J5fsBFGBIVgwnEWgRo12ctoESx48Se9U/v/TathzD2PZxjdeqq1nK328FMVTNBPAwNP3trdrsMcrEf1gQNIW4RNDHIAyFC5IkDiEtSSKA8EQ5vFsOXuq/38sSIGE/TNW9jCucV6tEj/wwfmyJDjgIlyIkEcjkKlIBSUAbKQQWobINWfvXKRi5nO5nuZTp@/gE) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~22~~ 19 bytes ``` $args|sort{!($_%2)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL24pji/qKRaUUMlXtVIs/b///@6RlBk8F/XEMw0/m/y3xQA "PowerShell โ€“ Try It Online") Takes input via splatting, e.g., `$a=(3,4,3); .\sort-odd-numbers-first.ps1 @a`, which on TIO manifests as separate arguments for each entry. Like some other answers here, `Sort-Object` can compare based on an expression. Here the expression is `!($_%2)`, i.e., odds get sorted to `$false` and evens get sorted to `$true`. Thanks to how Boolean values are compared, falsey values are sorted first. This moves the odds to the beginning of the output, and the evens to the end. `Sort-Object` is stable, so the ordering of the individual items in their respective categories doesn't change (as in the TIO example). *-3 bytes thanks to mazzy.* [Answer] # [Ruby](https://www.ruby-lang.org/), 23 bytes ``` ->a{a.sort_by{|i|~i%2}} ``` [Try it online!](https://tio.run/##LcjLCkBAFADQva@4jSzdsKP4EaQr1JRX81hM4/r1QVmdOsqOLix1SBvyhPpQZhidv@R1y6RgDgQ15Bkauc0aNzrBK9onSEvEkqPTGg1C7q8VQGdiTyz@VbO269vfLi31LMID "Ruby โ€“ Try It Online") Explanation: `sort_by` sorts every number as if its value were the result of the block (`~i%2`) `~x` is equivalent to `-x-1` and takes precedence over `%2` Odd numbers will evaluate to `0` and even numbers will evaluate to `1` so odd numbers will be sorted first. ### Barely related: this works on ruby from homebrew 2.5.1p57 (because it's based on a small bug) but only for non-negative integers, 20 bytes ``` ->a{a.sort{|i|i%-2}} ``` Explanation: This uses `sort` which expects a block that takes 2 values and returns `-1`, `0` or `1` depending on whether the first one is bigger, they're equal or the second one is bigger. The block given here ignores the second value and returns `-1` if the first number is odd or `0` if it's even. It's not guaranteed to work but it does in some (I think buggy) implementations. [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine, 47 bytes ``` A0 00 84 FE B1 FB 4A 90 07 C8 C4 FD F0 20 D0 F4 2A 85 02 84 FE A4 FD 88 C4 FE F0 12 B1 FB 4A 90 F6 2A AA A5 02 91 FB A4 FE 8A 91 FB 90 D6 60 ``` Expects a pointer to an array of numbers in `$fb`/`$fc` and the length of this array in `$fd`. Manipulates the array in place to have all odd numbers in front. This is position independent code, so no load address is needed. As the 6502 is an 8bit chip (so the instructions only deal with 8bit values, optionally signed), the valid number range is `[-128 .. 127]` and the maximum array size is `256`. ### Commented disassembly ``` ; function to "partially sort" array, so all odd numbers come before all ; even numbers. ; ; input: ; $fb/$fc: address of array to sort ; $fd: length of array to sort, 0 means 256 (maximum size) ; ; clobbers: ; $fd/$fe: position from back/front of array ; $2: temporary for exchanging two values ; A, X, Y .oddfirst: A0 00 LDY #$00 ; initialize index from front 84 FE STY $FE ; to 0 .search_front: B1 FB LDA ($FB),Y ; load number from front 4A LSR A ; check for even/odd by shifting 90 07 BCC .search_back ; if odd -> to searching from back C8 INY ; next position from front C4 FD CPY $FD ; same as position searching from back? F0 20 BEQ .done ; then we're finished D0 F4 BNE .search_front ; else check next from front .search_back: 2A ROL A ; shift carry back in 85 02 STA $02 ; and save number to temp 84 FE STY $FE ; save index from front A4 FD LDY $FD ; load index from back .sb_loop: 88 DEY ; previous position from back C4 FE CPY $FE ; same as position searching from front? F0 12 BEQ .done ; then we're finished B1 FB LDA ($FB),Y ; load number from back 4A LSR A ; check for even/odd by shifting 90 F6 BCC .sb_loop ; if odd -> check previous position 2A ROL A ; shift carry back in AA TAX ; remember in X A5 02 LDA $02 ; load temporary from front 91 FB STA ($FB),Y ; store at current position A4 FE LDY $FE ; load index from front 8A TXA ; load remembered number 91 FB STA ($FB),Y ; store at current position 90 D6 BCC .search_front ; and back to searching from front .done: 60 RTS ``` --- ### Example C64 assembler program using the routine: **[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22oddfirst.prg%22:%22data:;base64,AQgLCOIHnjIwNjEAAACpF40Y0KkAhSqFUqnnoAkgHqup5KAJIB6rqU+gCqIFIHsIrU8K8B+pT6AKIAgJkAmpLaAKIB6rsNmi/4ZSpiqdVwrmKtDMpVLwI6lXhfupCoX8pSqF/SC1CakAhVKkUrlXCiDuCOZSpVLFKtDwYMqG+4X8hP2gAITMhP4gQvHw+4UCKX/JILAOyQ3wEMkU0Oul/vDn0Aal/sX78N94pNOx0Sl/kdGlAiAW56bP8Aqk07HRCYCR0aUCWMkU8CDJDfAJpP6R/MiE/tCxqQCk/pH8eKTTsdEpf5HR5sxYYMb+sJoQDUn/hQLmAqktIBbnpQKqqQAgzb2pIEwW54X7hPygAIT9hP6MVAqMVQqMVgqx+/AjyMkg8PfJLfAMyTCQFMk6sBDm/ZDnpf3QCKX+0ATm/tDbOGCIMPuiArH7yTCQC8k6sAc46TCdVArKiBDsqQCF+6IITlQKrVUKkAIJEEqNVQqtVgqQAgkQSo1WCmb7yvAmrVQKyQgwBekDjVQKrVUKyQgwBekDjVUKrVYKyQgww+kDjVYKsLyl/vAIqf9F+4X75vul+xhgoACE/rH7SpAHyMT98CDQ9CqFAoT+pP2IxP7wErH7SpD2KqqlApH7pP6KkfuQ1mA+IAANDcVOVEVSIE9ORSBOVU1CRVIgUEVSIExJTkUuDUpVU1QgUFJFU1MgRU5URVIgKEVNUFRZIExJTkUpIFdIRU4gRE9ORS4AxVJST1IgUEFSU0lORyBOVU1CRVIsIFRSWSBBR0FJTi4NAA==%22%7D,%22vice%22:%7B%22-autostart%22:%22oddfirst.prg%22%7D%7D)** [![screenshot](https://i.stack.imgur.com/wDVrX.png)](https://i.stack.imgur.com/wDVrX.png) **Code in [ca65](http://cc65.github.io/doc/ca65.html) syntax:** ``` .import oddfirst ; link with routine above .segment "BHDR" ; BASIC header .word $0801 ; load address .word $080b ; pointer next BASIC line .word 2018 ; line number .byte $9e ; BASIC token "SYS" .byte "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes .bss linebuf: .res 5 ; maximum length of a valid signed ; 8-bit number input convbuf: .res 3 ; 3 BCD digits for signed 8-bit ; number conversion numbers: .res $100 ; maximum array size that can be ; directly handled with indexing ; instructions .data prompt: .byte "> ", $0 message: .byte $d, $d, "Enter one number per line.", $d .byte "just press enter (empty line) when done.", $0 errmsg: .byte "Error parsing number, try again.", $d, $0 .code lda #$17 ; set upper/lower mode sta $d018 lda #0 sta $2a ; index for number array sta $52 ; flag that at least one number was ; entered lda #<message ; display message ldy #>message jsr $ab1e inputloop: lda #<prompt ; display prompt ldy #>prompt jsr $ab1e lda #<linebuf ; read string into buffer ldy #>linebuf ldx #5 jsr readline lda linebuf ; empty line? beq process ; -> start processing lda #<linebuf ; convert input to int8 ldy #>linebuf jsr toint8 bcc numok ; successful -> store number lda #<errmsg ; else show error message and repeat ldy #>errmsg jsr $ab1e bcs inputloop numok: ldx #$ff ; set flag that we have a number stx $52 ldx $2a sta numbers,x inc $2a ; next index bne inputloop ; if array not full, next input process: lda $52 ; check we have some numbers beq exit ; otherwise exit program lda #<numbers ; address of array to $fb/fc sta $fb lda #>numbers sta $fc lda $2a ; length of array to $fd sta $fd jsr oddfirst ; call "sorting" function lda #$0 ; index variable for output loop sta $52 outloop: ldy $52 ; load current index lda numbers,y ; load current number jsr printnum ; -> output inc $52 ; next index lda $52 ; compare with ... cmp $2a ; ... array size bne outloop ; not reached yet -> repeat exit: rts ; done, exit program ; read a line of input from keyboard, terminate it with 0 ; expects pointer to input buffer in A/Y, buffer length in X .proc readline dex stx $fb sta $fc sty $fd ldy #$0 sty $cc ; enable cursor blinking sty $fe ; temporary for loop variable getkey: jsr $f142 ; get character from keyboard beq getkey sta $2 ; save to temporary and #$7f cmp #$20 ; check for control character bcs checkout ; no -> check buffer size cmp #$d ; was it enter/return? beq prepout ; -> normal flow cmp #$14 ; was it backspace/delete? bne getkey ; if not, get next char lda $fe ; check current index beq getkey ; zero -> backspace not possible bne prepout ; skip checking buffer size for bs checkout: lda $fe ; buffer index cmp $fb ; check against buffer size beq getkey ; if it would overflow, loop again prepout: sei ; no interrupts ldy $d3 ; get current screen column lda ($d1),y ; and clear and #$7f ; cursor in sta ($d1),y ; current row output: lda $2 ; load character jsr $e716 ; and output ldx $cf ; check cursor phase beq store ; invisible -> to store ldy $d3 ; get current screen column lda ($d1),y ; and show ora #$80 ; cursor in sta ($d1),y ; current row lda $2 ; load character store: cli ; enable interrupts cmp #$14 ; was it backspace/delete? beq backspace ; to backspace handling code cmp #$d ; was it enter/return? beq done ; then we're done. ldy $fe ; load buffer index sta ($fc),y ; store character in buffer iny ; advance buffer index sty $fe bne getkey ; not zero -> ok done: lda #$0 ; terminate string in buffer with zero ldy $fe ; get buffer index sta ($fc),y ; store terminator in buffer sei ; no interrupts ldy $d3 ; get current screen column lda ($d1),y ; and clear and #$7f ; cursor in sta ($d1),y ; current row inc $cc ; disable cursor blinking cli ; enable interrupts rts ; return backspace: dec $fe ; decrement buffer index bcs getkey ; and get next key .endproc ; print an int8 number to the screen ; input: ; A - the number to print ; clobbers: ; X, Y .proc printnum bpl doprint ; positive? -> direct number output eor #$ff ; else invert, sta $2 ; ... inc $2 ; add one, lda #'-' ; output a minus sign jsr $e716 lda $2 doprint: tax ; number to X reg lda #$0 ; set A to 0 jsr $bdcd ; routine for uint16 in X/A output lda #' ' jmp $e716 ; and print a space .endproc ; parse / convert int8 number using a BCD representation and double-dabble, ; handle negative numbers. .proc toint8 sta $fb sty $fc ldy #$0 sty $fd sty $fe sty convbuf sty convbuf+1 sty convbuf+2 scanloop: lda ($fb),y beq copy iny cmp #$20 beq scanloop cmp #$2d beq minus cmp #$30 bcc error cmp #$3a bcs error inc $fd bcc scanloop minus: lda $fd bne error lda $fe bne error inc $fe bne scanloop error: sec rts copy: dey bmi error ldx #$2 copyloop: lda ($fb),y cmp #$30 bcc copynext cmp #$3a bcs copynext sec sbc #$30 sta convbuf,x dex copynext: dey bpl copyloop lda #$0 sta $fb ldx #$8 loop: lsr convbuf lda convbuf+1 bcc skipbit1 ora #$10 skipbit1: lsr a sta convbuf+1 lda convbuf+2 bcc skipbit2 ora #$10 skipbit2: lsr a sta convbuf+2 ror $fb dex beq done lda convbuf cmp #$8 bmi nosub1 sbc #$3 sta convbuf nosub1: lda convbuf+1 cmp #$8 bmi nosub2 sbc #$3 sta convbuf+1 nosub2: lda convbuf+2 cmp #$8 bmi loop sbc #$3 sta convbuf+2 bcs loop done: lda $fe beq positive lda #$ff eor $fb sta $fb inc $fb positive: lda $fb clc rts .endproc ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes -7 thanks to @rak1507. ``` {โต[โ’2|โต]} ``` Explanation: ``` {โต[โ’2|โต]} 2|โต โ โต mod 2, return 1 for each odd element and 0 for each even element โ’ โ pick the indices that produce the array sorted in descending order [ ] โ pick elements corresponding to indices in provided order... โต โ from โต ``` For example: ``` 2|6 7 8 9 => 0 1 0 1 โ’0 1 0 1 => 2 4 1 3 6 7 8 9[2 4 1 3] => 7 9 6 8 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24TqR71box/1TjKqATJia/8/6psKFE1TMFQwUjBWMOGC8Q@tNwHyjf8DAA "APL (Dyalog Extended) โ€“ Try It Online") ]
[Question] [ Create a window that says hello world inside and nothing else. You can not have any ok or cancel buttons inside. It must be just a plain window that says hello world. I do not care about the contents of the window frame or how the window looks, but inside it must say hello world only. Example: ![enter image description here](https://i.stack.imgur.com/2W7co.png) **Shortest code wins.** EDIT: I am sorry Johannes Kuhn the window has to actually stay there, it may not close right away. I didn't think of this scenario and as such didn't account for this. EDIT 2: We currently have 3 tied answers (20 characters). Any suggestions of who should be the winner is welcome. [Answer] ## Windows Command Prompt, 26 ``` echo Hello World>.hta&.hta ``` ![enter image description here](https://i.stack.imgur.com/ISJBE.png) [Answer] # R, 23 ``` plot(1,m="Hello World") ``` This opens a plot window. [Answer] ## Dyalog APL (20) ``` โŽ•SMโ†'Hello World'1 1 ``` Picture: ![Picture](https://i.stack.imgur.com/Z8G55.png) [Answer] ### bash ~~20~~ 19 chars Thanks @manatwork for the useless space after `-p`! ``` read -pHello\ World ``` In action: ``` echo 'read -pHello\ World' >/tmp/helloworld.sh chmod +x /tmp/helloworld.sh ``` Than double click from file manager: ![enter image description here](https://i.stack.imgur.com/XByY5.png) And see: ![enter image description here](https://i.stack.imgur.com/1Uf9y.png) Having [bash](/questions/tagged/bash "show questions tagged 'bash'") as default shell. ### ~~19~~ 16 As question stand for *only Hello World* and *Nothing else*, *the window have to stay* but nothing like *print text only once* or so on, I think this match requirement too! ``` yes Hello\ World ``` There is only 16 chars. ``` echo >/tmp/helloworld.sh 'yes Hello\ World' ``` With same procedure this give: ![enter image description here](https://i.stack.imgur.com/m5NYF.png) [Answer] ### HTML (kinda), 17 ``` data:,Hello World ``` Paste that into your browser's address bar. ### Javascript, 25 ``` open("data:,Hello World") ``` This uses your browser's `window.open` and a data uri. A Data URIs's mime-type and charset default to `text/plain;charset=US-ASCII` when omitted. ### Javascript, 19 ``` eval($("s").text()) ``` This one only works when this answer is the top (or accepted) answer and it is run on THIS stackoverflow page (via your JavaScript console). :-) ~~open("data:,Hello World");~~ [Answer] ## Powershell, 23 ``` 'Hello World'>.hta;.hta ``` ![enter image description here](https://i.stack.imgur.com/r3B7J.png) [Answer] # Matlab, 30 27 20 ``` title('Hello World') ``` Are plot windows allowed? It does not have any buttons inside. [Answer] # Java, 117 chars ``` import java.awt.*;class C{public static void main(String[]a){new Frame(){{add(new Label("Hello World"));show();}};}} ``` With formatting: ``` import java.awt.*; class C { public static void main(String[] a) { new Frame() { { add(new Label("Hello World")); show(); } }; } } ``` We can avoid having to explicitly declare a variable by using [initializer blocks](http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html) inside an anonymous subclass of Frame. Interestingly, using awt, it's just as many characters to `import java.awt.*;` as it is to just fully qualify both classnames. [Answer] # Mathematica ~~29 27~~ 25 With 1 byte saved thanks to CatsAreFluffy. ``` DialogInput@"hello world" ``` ![hello world](https://i.stack.imgur.com/hk57q.png) [Answer] # Shell, 32 ``` xmessage -buttons '' Hello World ``` [Answer] # Ruby with [Shoes](http://shoesrb.com/), 28 ``` Shoes.app{para'Hello World'} ``` Result: ![screenshot](https://i.stack.imgur.com/TvR8G.png) [Answer] # Rebol 2, 29 ``` view layout[txt{Hello World}] ``` ![enter image description here](https://i.stack.imgur.com/GJyeb.png) [Answer] # Python 2/3, 54 characters Capitalize the t in tkinter to make it work on Python 2. ``` __import__("tkinter").Label(text="Hello World").pack() ``` [Answer] ## Windows Batch, 23 ``` @pause|echo Hello World ``` * Opens a black window that shows `Hello World`, nothing else. * Now the windows stays open * There are no buttons in the window. [Answer] ### ExtJS (Javascript) 44 ``` new Ext.Window({html:'Hello world',}).show() ``` ``` new Ext.Window({html:'Hello world',}).show() ``` ``` <link rel="stylesheet" type="text/css" href="http://dev.sencha.com/deploy/dev/resources/css/ext-all.css"/> <script type='text/javascript' src="http://dev.sencha.com/deploy/dev/adapter/ext/ext-base.js"></script> <script type='text/javascript' src="http://dev.sencha.com/deploy/dev/ext-all.js"></script> ``` [Answer] ## Processing, 23 Based on my answer here: [Make a PNG image with "Hello World!" with programming APIs, in the shortest code possible](https://codegolf.stackexchange.com/questions/19801/make-a-png-image-with-hello-world-with-programming-apis-in-the-shortest-code/19856#19856) ``` text("Heฮ o World!",9,8); ``` ![enter image description here](https://i.stack.imgur.com/11AqF.png) --- 24 char non-cheating solution: ``` text("Hello World!",9,9); ``` ![enter image description here](https://i.stack.imgur.com/oxVAX.png) [Answer] ## Tcl/Tk, 34 ``` pack [label .l -text Hello\ World] ``` [Answer] # **AutoHotkey, 26** ``` GUI,Add,Text,,Hello World! ``` [Answer] **AutoIt v3, 32** ``` ToolTip("Hello World") Sleep(9^9) ``` [Answer] # HTML, 11 ``` Hello World ``` Screenshot: ![HTML Hello World](https://i.stack.imgur.com/TzLgF.png) I guess this shouldn't count, but I think it would be interesting to see such an answer here. [Answer] ## PowerShell: 162 124 114 or 20 --- ## The Long Way Around ``` ($t=($a='New-Object Windows.Forms')+".Label"|iex).Text='Hello World';($x=iex $a".Form").Controls.Add($t);$x.Show() ``` Since PowerShell really doesn't have any built-in GUI functionality, I'm having a hard time coming up with anything shorter than this which I feel really fits the original spirit of the challenge. (Or, at least, fits within the parameters several of us have assumed were implied.) ![enter image description here](https://i.stack.imgur.com/m3Nrv.jpg) > > **Changes from original:** > > > * Removed window size definition. Apparently, it's optional and the default is plenty large enough. > * Incorporated changes provided by SpellingD in comments. **Note: The window which spawns will hang - you'll need to kill PowerShell via Task Manager.** > > > --- ## Alternative 20-Character Approach Removing some assumed-implied requirements, we can also meet this challenge a-la [Johannes Kuhn](https://codegolf.stackexchange.com/a/15427/9387) with this: ``` 'Hello World';for(){} ``` Save as a .ps1 file. Make sure the system's ExecutionPolicy allows unsigned scripts. Right-click and select "Run with PowerShell". ![enter image description here](https://i.stack.imgur.com/dSR2E.jpg) [Answer] # Factor, 36 code + 23 imports = 59 ``` USING: ui ui.gadgets ; "Hello World" <label> "" open-window ``` When this is run inside the listener, the imports will be brought in automatically. You only need them to deploy a standalone executable. [Answer] ## Groovy, 68 27 Using console. ``` print"Hello World";for(;;); ``` Using Frame. ``` new java.awt.Frame(){{add new java.awt.Label("Hello World")}}.show() ``` Inspired by @swilliams Java answer. [Answer] # Processing, 37 chars: ``` void draw(){text("Hello World",0,9);} ``` Various things used to reduce strokes: * Sketch window is spawned by default; no need to manually create it * Using `draw` is shorter than `setup` (although the text is then redrawn each frame) * Uses default size, background, fill, font, and font size * You don't actually need all 10 pixels height for the text [Answer] **Bash** (36 chars) `xmessage -buttons "" "Hello World!"` Looks like crap, but works as requested. ![enter image description here](https://i.stack.imgur.com/69Fa4.png) [Answer] # Ghostscript 50 ``` 0 0 moveto/Courier 20 selectfont(Hello World)show ``` Could make it 49 by using a 9-point font, but it's a little hard to read. Can make a smaller window by invoking gs with a geometry argument for an additional 8 chars. ``` gs -g200x30 hello.ps ``` [Answer] # C#, 72 ``` class P{static int Main(){System.Console.Write("hello world");for(;;);}} ``` Based on the answer by @Noctis. I would have suggested it as a comment if I had enough Rep. [Answer] ## Delphi - 73 62 ``` uses Dialogs;begin MessageDlg('Hello World',mtCustom,[],0)end. ``` Edit after @manatwork and @Gareth 's suggestions. Which actually brings me to a character count of 62. [Answer] # Shell script: 56 character ``` convert -size 99x9 xc: -draw 'text 0,10 Hello\ World' x: ``` Sample output: ![Hello World](https://i.stack.imgur.com/pgV2l.png) [Answer] ## Ti84-Basic, 25 ``` ClrHome Disp "HELLO WORLD ``` ## Arduino, 27 ``` Serial.print("Hello World") ``` Place this in `void setup()` ## Game Maker Language, 40 ``` show_message_ext("Hello World","","","") ``` I'm pretty sure this is the shortest way without adding any extension packages. ]
[Question] [ With roughly one second (plus or minus 10 ms) between outputs, output anything. The first output must be at most one second after the start of the program, but can be as soon as right when the program starts. So, the first output can be up to a second after the program starts, the second exactly one second after that, the third a second after that, and so on to infinity. The outputs do not need to be consistent, nor have any sort of delimiter. However, they must be visible (even if it's only visible when highlighted). [Answer] # MacOS shell, 3 ``` top ``` On the Mac, `top`'s default refresh period is 1 sec. --- # Linux shell, 7 ``` top -d1 ``` Unfortunately on Linux, `top`'s default refresh period is more like 2 secs, so we need an extra 4 bytes. Since this is just one command, both variants are shell-agnostic. [Answer] # [Bash](https://www.gnu.org/software/bash/) + `iputils`, 6 bytes ``` ping 0 ``` send `ICMP ECHO_REQUEST` to 0 (127.0.0.1) once per second. --- # [Bash](https://www.gnu.org/software/bash/) + `procps-ng`, 8 bytes ``` free -s1 ``` Display amount of free and used memory in the system with one second between outputs. [Answer] # [Python 3](https://docs.python.org/3/), ~~40~~ 39 bytes ``` import time while[help()]:time.sleep(1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEkMzeVqzwjMyc1OiM1p0BDM9YKJKRXnJOaWqBhqPn/PwA "Python 3 โ€šร„รฌ Try It Online") Improved by [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus) [Answer] # [Desmos](https://desmos.com/calculator), 5+3+3+2=13 bytes Ticker expression (5 bytes) ``` a->-a ``` Ticker repeat delay (3 bytes) ``` 999 ``` Main expressions (3 bytes) ``` a=1 ``` 2 bytes for "file boundaries" (treat each expression as a separate "file"; there are 3 "files", so there are two "file boundaries", as per this [comment](https://codegolf.meta.stackexchange.com/questions/19316/scoring-desmos-equations#comment74833_19317)) [Try It On Desmos!](https://www.desmos.com/calculator/b0oevnbpmy) To run, click the ticker icon (the metronome) near the top left of the screen. This switches the variable `a` between the values `1` and `-1` every 999 milliseconds. While this isn't outputting onto the console or stdin in the traditional sense, you can still clearly see the code switching between the `1` and the `-1`, which hopefully emulates outputting close enough. [Answer] # [C (gcc)](https://gcc.gnu.org/), 30 bytes Prints a newline every second. ``` main(){main(sleep(puts("")));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7MaTBXnpKYWaBSUlhRrKClpampa1/7/DwA "C (gcc) โ€šร„รฌ Try It Online") [Answer] # [Factor](https://factorcode.org/), 18 bytes ``` [ .s ] 1e9 every . ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqVQkpmbWlSsUFCUWlJSWVCUmVeiYP0/WkGvWCFWwTDVUiG1LLWoUkHv/38A "Factor โ€šร„รฌ Try It Online") `every` calls a function each time a duration has passed. If `every` is not given a duration such as `1 seconds`, and instead given a number, it defaults to nanoseconds. Thus, one billion (or 1e9) means one second. `.s` simply prints the contents of the data stack without consuming them, which in this case will print the timer object `every` uses to do its thing. The `.` at the end is necessary to satisfy the stack effect checker by removing the item on the data stack (because Factor programs must end with an empty stack), even though it will never be reached. [Answer] # Javascript, ~~22~~ ~~20~~ 19 Bytes Thanks to @Kaiido for -2 Bytes Thanks to @Elias Holzmann for -1 Bytes ``` setInterval({},1e3) ``` <https://jsfiddle.net/ry2sgkz7/> [Answer] # shell + GNU/Linux core utils, 11 bytes `watch -n1 w` A bit of a boring answer. [Answer] # [\*><>](https://github.com/redstarcoder/go-starfish), 4 bytes Prints "10" on startup, and once every second ``` a:nS ``` [Try it online!](https://tio.run/##Ky5JLErLLM74/z/RKi/4/38A "*><> โ€šร„รฌ Try It Online") ## Explanation ``` a # Push 10 onto the stack : # Duplicate it n # Pop a value off the stack, and print it as a decimal number S # Pop a value off the stack, and sleep for 100ms * the popped value ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 5 bytes ``` โ€šร…ฮฉkNยทโˆรปU ``` Don't [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJqIiwiIiwi4oG9a07huJ5VIiwiIiwiIl0=) - it doesn't work there. This one's kind of hilarious. It creates an infinite list of times, and then uniquifies them. The `j` flag is necessary due to how Vyxal handles printing infinite lists. ``` ยทโˆรป # Generate an infinite list from... โ€šร…ฮฉ # A function that returns kN # The current time of day (hh:mm:ss) U # Get unique values ``` [![enter image description here](https://i.stack.imgur.com/6zJUc.png)](https://i.stack.imgur.com/6zJUc.png) [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` `@D1Y.T ``` This displays the natural numbers in order. Try at [MATL online](https://matl.io/?code=%60%40D1Y.T&inputs=&version=22.7.4)! ### How it works ``` ` % Do...while @ % Push iteration index, starting at 1 D % Display 1 % Push 1 Y. % Pause for that many seconds T % Push true. This is used as loop condition, causing an infinite loop % End (implicit) ``` [Answer] # [(,)](https://esolangs.org/wiki/(,)), ~~60~~ ~~62~~ 61 Chars or \$61\log\_{256}(3)\approx\$ 12.09 Bytes ``` ((),((()))((())))((()),((())))(,((()),(),(),,((())),()),,,()) ``` ``` ((),((()))((()))) Sets variable 1 to -2. ((()),((()))) sets variable -2 (time) to itself. (AKA setting the current time to 0) (, Start of loop ((()),(),(),,((())),()) If variable -2 (time) is at least 1, reduce it by 1 and output 1\n ,,,()) Loop forever ``` First solution sometimes had the second output less than a second after the first. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 1โ‰ˆรฌSยทฯ€ร‘ยฌรธ ``` A full program which prints `1` and a newline and then after (just over) one second has elapsed prints another, then repeats this step forever. It's "just over" as it takes some time to do the work. The first pause could take more than 1 second on slow hardware as Jelly has to initialise Python, and itself (create an interpreter, import some cruft, etc.) and parse the code. Subsequent pauses are unlikely to be over the 1.01 second threshold however as it just needs to check that the result is truthy and print to STDOUT. **[Try it online!](https://tio.run/##y0rNyan8/9/w4c6Wo5ODD@3//x8A "Jelly โ€šร„รฌ Try It Online")** (TIO does not output anything as a program runs, but kill it while in flight and take a look; killing within a second should give a single `1` in the "Output" section, leaving it running longer should give more outputted `1`s for each second that passed.) ### How? ``` 1โ‰ˆรฌSยทฯ€ร‘ยฌรธ - Main Link: no arguments 1 - set the left argument to one ยฌรธ - while... ยทฯ€ร‘ - ...condition: print {left=1} and a newline, and yield {left=1} โ‰ˆรฌS - ...action: sleep for {implicit right=left=1} seconds and yield {left=1} ``` --- Replace `ยทฯ€ร‘` with `ยปร†` for no newlines. [Answer] # [PHP](https://php.net/), ~~22~~ ~~21~~ 17 bytes ``` for(;;a)sleep(1); ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKytEzWLc1JTCzQMNa3//wcA "PHP โ€šร„รฌ Try It Online") I think the naive approach will be the shortest here. On TIO the output will be visible only when stopping the program of course EDIT: saved 1 byte by echoing the falsey result of `sleep`, it works because `sleep` returns zero instead of `false` which would have lead to an empty string EDIT 2: stole the suggestion from [this JS answer](https://codegolf.stackexchange.com/a/262209/90841) by triggering a warning instead of an echo [Answer] # TI-Basic (TI-84+), 22 bytes ``` startTmr While 1 If checkTmr(Ans:Then Disp Ans startTmr End End ``` [Answer] # [Racket](https://racket-lang.org), ~~43~~ ~~37~~ ~~28~~ 26 bytes ## Changelog 1. Thanks to [@Dadsdy](https://codegolf.stackexchange.com/users/118038/dadsdy) for the `-2` bytes. 2. The `-4` bytes comes from converting `#lang racket` to `#!racket`. 3. Another `-9` as I found out that language statements may go into the header of TIO, and as such, don't contribute to number of bytes. 4. I just learnt about Racket's `do` loop! `-2` bytes! ๏ฃฟรผรฉรข ## Code ``` (do()(#f)(write(sleep 1))) ``` [Try it online!](https://tio.run/##K0pMzk4t@a@ck5iXrlAE4Wik5GtoaiinaWqUF2WWpGoU56SmFigYampq/v8PAA "Racket โ€šร„รฌ Try It Online") --- ## Explanation We create a [*do*](https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._do%29%29) loop that runs infinitely. Since we used `#f` (false) in `do`s second argument, the loop won't terminate as it will only terminate if there is a `#t` value. If we were to expand this out and make it more readable, it would look like this: ``` (do () (#f) ; (sleep 1) doesn't return anything, so #<void> will be printed. (write (sleep 1))) ``` The `do` loop acts a bit similar to JavaScript's `while` loop: ``` while (!false) { // ... } ``` [Answer] # [GFA-Basic](https://en.wikipedia.org/wiki/GFA_BASIC) 3.51 (Atari ST), 15 bytes A manually edited listing in .LST format. All lines end with `CR`, including the last one. ``` DO ?0 PA 50 LO ``` which expands to: ``` DO PRINT 0 PAUSE 50 LOOP ``` We could use `DELAY 1` instead of `PAUSE 50`. Unfortunately, the shortest unambiguous abbreviation of `DELAY` is `DELA`. ### Output After 5 seconds: [![output](https://i.stack.imgur.com/GbvB4.png)](https://i.stack.imgur.com/GbvB4.png) [Answer] # x86-16 machine code, PC DOS, 14 bytes ``` 00000000: b42c cd21 3ac6 74fa 8ac6 cd29 ebf4 .,.!:.t....).. ``` **Listing** ``` B4 2C MOV AH, 2CH ; DOS API get system time function SEC_LOOP: CD 21 INT 21H ; Read time: DH = seconds 3A C6 CMP AL, DH ; second changed? 74 FA JE SEC_LOOP ; continue polling if not 8A C6 MOV AL, DH ; save new second CD 29 INT 29H ; write AL to console EB F4 JMP SEC_LOOP ; loop indefinitely ``` A standalone executable DOS COM program. Spams the DOS time function and writes the corresponding ASCII codepoint for the number of seconds. *Several minutes later...* [![enter image description here](https://i.stack.imgur.com/TtcIH.png)](https://i.stack.imgur.com/TtcIH.png) [Answer] ## Batch, ~~15~~ ~~13~~ 9 bytes ``` ping -t 0 ``` After some initial output, outputs the following every second: ``` PING: transmit failed. General failure. ``` Edit: Saved 4 bytes thanks to @c--. Previous 15-byte solution: ``` timeout/t 1 %0 ``` Repeatedly outputs the following: ``` C:\Users\Neil>timeout/t 1 Waiting for 1 seconds, press a key to continue ...0 C:\Users\Neil>262205.bat ``` When output is to the screen, the cursor is moved so that the `0` overwrites the `1`. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 45 bytes Nothing special ``` for(;;){Thread.Sleep(1000);Console.Write(1);} ``` [Try it online!](https://tio.run/##Sy7WTS7O/F9anJmXrhBcWVySmqsXklGUmpgCFLD@n5ZfpGFtrVkNEdILzklNLdAwNDAw0LR2zs8rzs9J1QsvyixJ1TDUtK79/x8A "C# (Visual C# Interactive Compiler) โ€šร„รฌ Try It Online") [Answer] # [Nim](https://nim-lang.org/), 36 bytes ``` import os while 0<1:echo 1;sleep 999 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3VTJzC_KLShTyi7nKMzJzUhUMbAytUpMz8hUMrYtzUlMLFCwtLSFqoVpgWgE) [Answer] # [Perl 5](https://www.perl.org/), 19 bytes ``` say 2 while sleep 1 ``` [Try it online!](https://tio.run/##K0gtyjH9r1Jja2itoFxckl@gEOLpr1uSmZuaX1qikFaUn6tQUJRalppXkpmXrgAUKygt@V@cWKlgpFCekZmTqlCck5paoGD4//@//IKSzPy84v@6vmWmeoYGAA "Perl 5 โ€šร„รฌ Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~24~~ 21 bytes ``` !x=!show(sleep(1)) !0 ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/X7HCVrE4I79cozgnNbVAw1BTk0vR4P9/AA "Julia 1.0 โ€šร„รฌ Try It Online") -3 bytes thanks to ovs: improve recursion, and redefine an operator (An argument has to be passed to it, but this can be ignored by the function) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~7~~ 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs a `ReferenceError`. Any lowercase letter word work instead of the second `i`. ``` Aยฌโ‰ฅii ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JGNvbnNvbGUuY2xlYXIoKSQ&code=QbNpaQ) (Open your browser's console) [Answer] # [ELF (x86/x64, Linux)](https://refspecs.linuxfoundation.org/elf/elf.pdf), 112 bytes Prints 'A' about once per second, indefinitely. ``` 00000000: 7f45 4c46 fec0 505f e81b 0000 0000 0000 .ELF..P_........ 00000010: 0200 3e00 0000 0000 0400 0000 4100 0000 ..>.........A... 00000020: 3800 0000 0000 0000 5e40 80c6 3f50 5a0f 8.......^@..?PZ. 00000030: 0504 2256 eb32 3800 0100 0000 0500 0000 .."V.28......... 00000040: 0000 0000 0000 0000 0000 0000 4100 0000 ............A... 00000050: 0100 0000 0000 0000 7000 0000 0000 0000 ........p....... 00000060: 7000 0000 0000 0000 5faf 0f05 eb96 0000 p......._....... ``` [Try it online!](https://tio.run/##bZG7DsIwDEV3vsLiAyzn4TQw8BhgYujEwAAqVTwx8P9LSUTSUNoMViL7ntwrh5cMA@WzhUYsg@2tAwk9ARMLBK@ekNo/BfB0OSO2D8xn9SWoyCAdB0yYzJMtN6sqA3dFjsfK0JFh/FSeCgdL4Kl3YITjsyMB8Fl/PyDu21thmOSDyYLW7CA8jc7I8ffYrT7WV9Qe/7LYxKC5j1omWXApCyeGmiubBdrIeE99uLSXhXmWToCEOObbuMwo2rKYYfgA "ELF (x86/x64, Linux) โ€šร„รฌ Try It Online") (Prints 60 `A`'s before TIO kills the process) ## Explanation The file abuses a lot of undefined behavior within the Linux ELF loader; the kernel is able to make a lot of (correct) assumptions when certain fields are not the right value. [Here](https://tio.run/##jVRNc5swEL3zK3bSziSZxI0/sOshpx7aU/9BppMRaGXUAYQlYeP8eXdXQGyTZBoOQuxKb6X33iKcwzItDpNKuPJ4fEq1d7CK/0TRk7EbmNLkEZQuENJGF1JXG8BCgbKmBJdZ4bOcV/BusGJPuW88nZjuAyYq1VUU0fQ5lzaJgB6ZwrT9ru5pjJdhzMK4gseQgKufv39dMexsDunBo4McLYI3kIsdgjMlgmqqCCtvDwkEUF1lIApC6LeEYN24nI7VUngWwl3U1GClvgxmoiigwtZTeNlDhITXJR1gEU5NuaZqHMouJfd03jkFscWs8SIt8BRfICVEKaFdryar@AwrHmGFLVsosXxOhcO7cC1GDe/a6MoPa2prNkwkZXlqRUnUCIkWjFIOfSAtPidNGQulsR1hfL/kxIEbcSCkBKcLFmOhKBV/kspR0B1cYPNSCwYXhL2I3xVpfJa/ZQ0uN9ZDIZw/23LG8PotDU6/YDSwlLzNk4cKIyRzq5kUdjbxa5h9uLHtLQj/qsSp1IyQvhDHIzgHDwGOlQeHmxJ7qTqh55dCf7SYiJm2y9OyG6wk1@L@oVvc0j5L5e7YZYMR@oaiTZ3wdIlwmbGZLhbstA2XM2SrB2poFVbbra8T3jM7PylHBzAGZmIpH159rf@v6mqxKde9J9mOSlfUqeTHQFPE@iYfNyZ5ycnPGOzkmKGBXi1DvbRDKpebZpPTC4mYYCu/N/3BiG@Kj@0iyCMvaM09Jw/8SVjO6/CvQNk377tqc9WgAJOfZkw3yajYNGQ3rkW/vBlc/7iOBrESwG0TwtP@iaKB1S73FSaD9MfjPw) is the full NASM source. Basically, the executable is just an ELF header, a program header (partially merged into the ELF header), and the actual program (which is spread throughout the two headers so that it doesn't take up any additional space). The full program calls `sys_write(stdout, "A", 1)`, then `sys_nanosleep({tv_sec=1, tv_nsec=112}, <nonsense valid pointer>)`, and then loops back to the start. [Answer] # [R](https://www.r-project.org/), ~~27~~ 25 bytes *Edit: -2 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` repeat show(Sys.sleep(1)) ``` [Try it online!](https://tio.run/##K/r/vyi1IDWxRKE4I79cI7iyWK84JzW1QMNQU/P/fwA "R โ€šร„รฌ Try It Online") This works well on my local machine, but TIO accumulates output until it finishes execution, so you don't see the progress. [Answer] # [Arturo](https://arturo-lang.io), 23 bytes ``` whileโˆšโˆ[1:s>>{a}1pause] ``` ``` whileโˆšโˆ[ ; start infinite loop (while loop with null for condition) 1:s ; push duration of 1 second to stack >>{a}1 ; create/overwrite file named a pause ; pause execution for one second (which we left on the stack earlier) ] ; end while ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` #.d .j ``` [Try it online!](https://tio.run/##K6gsyfj/X1kvhUsv6/9/AA "Pyth โ€šร„รฌ Try It Online") ### Explanation ``` # # loop forever until error (no error will occur) .j # imaginary number i, printed .d # sleep for abs(i) seconds ``` It may seem weird that I have to sleep for \$|i|\$ seconds, why not just 1? While that would save a byte, unfortunately `.d1` is a predefined macro which returns the amount of time which has passed since the program started, which is not really useful for this challenge. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` ร”ยบโ‰คร”ยบโˆ‘ล“รœล“ร ร”ยบโˆžร”ยบยฉยฌยจล’ยฃร”ยบยดร”ยบยด ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8oNa0otTgjPCMzJ1UjTUehUlPBtzSnJLOgKDOvRMM5sbhEwy@/RCO4NFcjIDU1W0MTBKz///@vW5YDAA "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. Uses control codes to toggle the top left corner between `1` and `0`, so on TIO you need to let it run for a few seconds and then interrupt it to see the control codes and `1`s and `0`s. Explanation: ``` ร”ยบโ‰คร”ยบโˆ‘ล“รœล“ร  ``` Repeat indefinitely, showing the current canvas with a 1000ms delay on each repeat. ``` ร”ยบโˆžร”ยบยฉยฌยจล’ยฃร”ยบยดร”ยบยด ``` Toggle the current character between `1` and `0`. [Answer] # [Lua](https://www.lua.org/), 50 bytes ``` o=os.time::a::t=o()repeat until t<o()print()goto a ``` [Try it online!](https://tio.run/##yylN/P8/3za/WK8kMzfVyirRyqrENl9Dsyi1IDWxRKE0ryQzR6HEBihSUJSZV6KhmZ5fkq8A1AMA "Lua โ€šร„รฌ Try It Online") A platform independent solution. You *can* make this shorter by using `os.execute`, but that solution is both platform dependent and not very interesting. ]
[Question] [ Draw an ASCII-art rainbow! # Input An integer between 0 and 1000, inclusive. # Examples Input 0: ``` /\ || ``` Input 1: ``` _ / \ | | ``` Input 2: ``` __ / \ | | ``` Input 3: ``` ___ / \ | | ``` The first row is a space followed by *n* underscores. The second row is a slash followed by *n* spaces, and a backslash. The third row is a pipe followed by *n* spaces, and a pipe. Trailing spaces are allowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code wins. [Answer] # i386 (16-bit mode) Bootsector, 512 bytes All i386 bootsectors have to be 512 bytes, so... Without the padding required by i386, it is 137 bytes. Since I can't easily post a TIO link, here's a screenshot of it running: [![enter image description here](https://i.stack.imgur.com/TEUjh.png)](https://i.stack.imgur.com/TEUjh.png) This code registers the BIOS interrupt `int 0x69` to take the number in the `bx` register and use it as input. Thus, doing ``` mov bx, 3 int 0x69 ``` is equivalent to the last test case. The disassembled, Intel-syntax source is: ``` [org 0x7c00] xor ax, ax mov es, ax cli mov dx, interrupt mov [es:0x69*4], dx mov ax, cs mov [es:0x69*4+2], ax sti xor bx, bx int 0x69 call newline mov bx, 1 int 0x69 call newline mov bx, 2 int 0x69 call newline mov bx, 3 int 0x69 cli hlt interrupt: or bx, bx jz special push bx mov ax, 0x0e20 int 0x10 mov al, '_' .loop1: int 0x10 dec bx jnz .loop1 call newline mov al, '/' int 0x10 mov al, ' ' pop bx push bx .loop2: int 0x10 dec bx jnz .loop2 mov al, '\' int 0x10 call newline mov al, '|' int 0x10 pop bx mov al, ' ' .loop3: int 0x10 dec bx jnz .loop3 mov al, '|' int 0x10 iret newline: mov ax, 0x0e0d int 0x10 mov al, 0x0a int 0x10 ret special: mov si, s mov ah, 0x0e .sloop: lodsb int 0x10 or al, al jnz .sloop iret s: db '/', '\', 10, 13, '|', '|' times 510-($-$$) db 0 dw 0xaa55 ``` (Bit verbose, I know, but hey, it's assembly.) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` โ†‘|โ†—/ร—_๏ผฎยถ\ยถ| ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMqtEBHQalGSdOaCy4QlJmeUQIU1UeIhmTmphZrKMUr6Sh45hWUlviV5ialFmloasJVKMXkxcTE5IFM@v/f0OC/blkOAA "Charcoal โ€“ Try It Online") Link is to verbose version of code. This shape is too simple to tax Charcoal's drawing primitives, so this is just basically printing strings to the canvas. Explanation: ``` โ†‘| ``` Print the left `|` and move the cursor up a line. ``` โ†—/ ``` Print the `/` and move the cursor to the start of the `_`s. ``` ร—_๏ผฎ ``` Print the desired number of `_`s. This leaves the cursor just to the right of the last `_`. ``` ยถ\ยถ| ``` Move down a line, print a `\`, and print a `|` directly beneath. Just for fun I thought I'd write a 25-byte version which allows you to vary the height and thickness too: ``` ๏ผฎฮธ๏ผฎฮท๏ผต๏ผฏฮท๏ผฎ|โ†‘๏ผงโ†’โ†‘ฮท/โ†—๏ผต๏ผฏฮธฮท_โ€–๏ผข๏ผฏฮธ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5Psn5eTnpWtk6Cggy2jqKCjVKAGlffPLUjWsQguAzID8nMr0/DwNq6DM9IwSHQWgqI4CUJ@SPrJCsCTC3EKIkniQkqDUtJzU5BKn0pKS1KK0nEr/stSinMQCkLP@/zc0UDBXMPmvW5YDAA "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes input as inner width, thickness and inner height. Note that Charcoal does not support zero-sized boxes, so all of the inputs need to be at least `1`. [Answer] # [Rust](https://www.rust-lang.org/), ~~76~~ ~~57~~ ~~53~~ ~~51~~ 45 bytes -4 bytes thanks to madlaina ``` |n|print!(" {:_<1$} /{0:1$}\\ |{0:1$}|","",n) ``` [Try it online](https://tio.run/##JY7BCoMwEETv@xVj6GED1tpDLyoe/Qqh9BBpoN2WGCnU5NvTaE8zs7Bvxi2zT5PgebPCGisB3syeU5DwdlZ8wQprc@3Oh0intW6yjiOFvwuqVKoUnQDdUiTKpO29G3qeGgyaPnfjTIYOOQkvs/0ajWMP1rR1TS8HgRXUVXXZ2/ONJcM2tw94SMF7jhTTDw) --- Old answer (76 bytes): ``` |n|format!(" ")+&"_".repeat(n)+" /"+&" ".repeat(n)+"\\ |"+&" ".repeat(n)+"|" ``` [Try it online](https://tio.run/##dc49DsIwDAXg3acwHpCt8j8C6tgLsFZCHRKoRNMqdYVE07OHdETAZn/De88PvUbrsKlqx4IjIKrplWNwwba@qXTBhCTZkq608aYzlbKTjGBLyfDDyhLCtwaKiHKCCSAVzennImd7xELgeTfepM4ifY6Hvn4ZwXWOF/W1u8E8p0uXPlyaMU60Qss7SWE/fP/HD7NP8Q0) Just the boring answer. Borrows are needed [to satisfy the type checker](https://doc.rust-lang.org/std/string/struct.String.html#impl-Add%3C%26%27_%20str%3E), unfortunately. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 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")) Full program, prompting for `n` from stdin. ``` ' /|',' \|',โจ3โ†‘1โŽ•โด'_' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@6gn6Nuo66QgyQfNS7wvhR20TDR31TH/VuUY9XByn5rwAGBVwGXDCWIZxlBGcZI2QNDAy4AA "APL (Dyalog Unicode) โ€“ Try It Online") `'_'`โ€ƒan underscore `1โŽ•โด'_'`โ€ƒcyclically reshaped into a matrix with one row and *n* columns `3โ†‘`โ€ƒtake the first three rows, padding with spaces `' \|',โจ`โ€ƒappend this character-list as a trailing column `' /|',`โ€ƒprepend this character-list as a leading column [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` lambda n:" %s\n/%s\\\n|%s|"%("_"*n," "*n," "*n) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSklBtTgmTx9IxMTk1agW1yipaijFK2nl6SgpwEnN/2n5RQp5Cpl5CgY6hjpGOsZWXAoFRZl5JQppGkBZAA "Python 2 โ€“ Try It Online") Inserting the `n`-dependent components into a template using string formatting. --- **48 bytes** ``` lambda n:" "+"_"*n+"\n/"+" "*n+"\\\n|"+" "*n+"|" ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSklBSVspXkkrT1spJk8fyFaAsGNi8mrgvBql/2n5RQp5Cpl5CgY6hjpGOsZWXAoFRZl5JQppGnma/wE "Python 2 โ€“ Try It Online") Straight up concatenation. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26~~ 21 bytes ### My original 26 bytes approach: ``` " 0 /1\|1|"3รดโ€ž_ vyยนะธJNs:}ยป ``` Explanation: ``` " 0 /1\|1|"3รดโ€ž_ vyยนะธJNs:}ยป " 0 /1\|1|" push string template (the idea is to replace 0 and 1 with _ and space respectively using loop count index 3รด split by chunks of 3 โ€ž_ push 2 chars _ and space v } for each character in the previous string yยนะธ repeat it by the number in input J join the new string Ns push the index before that string to easily replace : replace in the string template ยป join by new lines ``` [Try It Online](https://tio.run/##yy9OTMpM/f9fScFAQd8wpsawRsn48JZHDfPiFcoqD@28sMPLr9iq9tDu//9NAA) ### 21 bytes (@KevinCruijssen comments): ``` โ€ž_ Sร—ฤ" 1/2|2"2รด.ยบยปrโ€ก ``` [Try It Online](https://tio.run/##ASkA1v9vc2FiaWX//@KAnl8gU8OXxIEiIDEvMnwyIjLDtC7CusK7cuKAof//NA) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~72~~ 70 bytes -2 bytes thanks to ceilingcat! ``` f(n){printf(" %s\n/%*c\n|%*2$c",memset(calloc(n,2),95,n),n+1,92,'|');} ``` [Try it online!](https://tio.run/##FYtBCoMwEEXX5hRDqDhjR0oDLUjoTdzIYEpAR1G7Us@e6urz3uNL9RVJKaDSNs1R14AW8qXRR15Ko3teuptYHrph6VaUtu9HQWVHXL9YifX@5NpxsRfkj3T@YWijIpnNZGGcAS8V4QNvD7GqPJDJzpQFjOTPnX7rgrZRe9FhjvQH "C (gcc) โ€“ Try It Online") [Answer] # [MAWP 1.1](https://esolangs.org/wiki/MAWP), 95 bytes ``` %@~52WWM52WWM52WWM84W;![1A99M1M5W;]%52W;68W1A;![1A84W;]%68W2W4A;52W;56W1M4W;![1A84W;]%56W1M4W;. ``` [Try it!](https://8dion8.github.io/?code=%25%40%7E52WWM52WWM52WWM84W%3B!%5B1A99M1M5W%3B%5D%2552W%3B68W1A%3B!%5B1A84W%3B%5D%2568W2W4A%3B52W%3B56W1M4W%3B!%5B1A84W%3B%5D%2556W1M4W%3B.&input=0012) Explanation: ``` % Remove initial 1 from stack @~ Push input as integers and reverse stack 52WWM Add top of stack multiplied by 10 to second stack element [5,4,3,2] ==> [5,4,23] 52WWM52WWM Two more times [5,4,3,2] ==> [2345] 84W; Print a space (8*4=32) ! Duplicate top of stack [ Start of loop 1A Subtract 1 99M1M5W; Print an underscore ((9+9+1)*5=95) ] End of loop. If result from subtraction doesn't equal to 0 jump to start of loop % Remove 0 52W; Print a newline (5*2=10) 68W1A; Print a slash (6*8-1=47) ![1A84W;]% Do the same loop as before but printing spaces instead 68W2W4A; Print a backslash (6*8*2-4=92) 52W; Print a newline 56W1M4W; Print a pipe ((5*6+1)*4=124) ![1A84W;]% Same loop as second 56W1M4W; Print a pipe . ``` [Answer] # [Integral](https://github.com/nph278/integral), ~~37~~ 31 Bytes ``` โ™‚8โ™ฆโŒก_โŒกgโ–บโŒก/โŒกโ€ข8gโ–บโŒก\โŒกโ–บโ€ขโŒก|โŒกโ™ฆ8gโ–บโŒก|โŒกโ–บ ``` First real answer in my new language! [Try it](https://nph278.github.io/integral?code=CzgE9V/1ZxD1L/UHOGcQ9Vz1EAf1fPUEOGcQ9Xz1EA&input=0%250A%250A1%250A%250A2%250A%250A3) Explanation: ``` (Implicit input) โ™‚ Triplicate top of stack 8 Push space โ™ฆ Swap โŒก_โŒก Push underscore g Repeat string โ–บ Concatenate โŒก/โŒก Push slash โ€ข Stack: ...abc -> ...bca 8 Push space g Repeat string โ–บ Concatenate โŒก\โŒก Push backslash โ€ข Stack: ...abc -> ...bca โŒก|โŒก Push pipe โ™ฆ Swap 8 Push space g Repeat string โ–บ Concatenate โŒก|โŒก Push pipe โ–บ Concatenate ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` โ€ฆ_ ฮตร—โ€ฆ /|NรจยบSsรฝ, ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcOyeAWFc1sPTweyFPRr/A6vOLQruPjwXp3//43/6@rm5evmJFZVAgA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/W96bJKSZ15BaYmVgpK936GVtlxK/qUlEL7O/0cNy@IVFM5tPbTu8HQgW0G/xu/wikO7gosP79X5X3tom/3//7q6efm6OYlVlQA). **Explanation:** ``` โ€ฆ_ # Push string "_ " ฮต # Map over each character in this string: ร— # Repeat it the (implicit) input amount of times as string โ€ฆ /| # Push string " /|" Nรจ # Use the map-index to index into this string ยบ # Mirror the character (" "โ†’" "; "/"โ†’"/\"; "|"โ†’"||") S # Convert the string to a pair of characters s # Swap so the "_"/" "-string is at the top of the stack รฝ # Join the pair with this string as delimiter , # And output it with trailing newline ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` ' /|'4i:)B95*' \|'v! ``` [Try it online!](https://tio.run/##y00syfn/X11Bv0bdJNNK08nSVEtdIaZGvUzx/39zAA "MATL โ€“ Try It Online") ### How it works ``` ' /|' % Push this string: first column of the output, but as a row (*) 4 % Push 4 i:) % Implicitly input n; range; modular indexing. This gives a row vector % [4 4 ... 4] of length n B % Convert to binary. Each number gives a row in the output. So this % produces the matrix [1 0 0; 1 0 0; ...; 1 0 0] with n rows 95* % Multiply each entry by 95 (ASCII code of '_'). This gives the central % columns of the output, but transposed, as an nร—3 matrix (**) ' \|' % Push this string: last column of the output, but as a row (***) v % Concatenate (*), (**) and (***) vertically ! % Transpose. Implicitly display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` โ€œ_ โ€ร—โ€œ โ€œ/\โ€œ||โ€j"Y ``` A full program accepting a non-negative integer which prints the resulting ASCII art. **[Try it online!](https://tio.run/##y0rNyan8//9Rw5x4BYVHDXMPTwcyQaw5@jFAoqYGKJalFPn//39TAA "Jelly โ€“ Try It Online")** ### How? ``` โ€œ_ โ€ร—โ€œ โ€œ/\โ€œ||โ€j"Y - Main Link: integer, n (e.g. 3) โ€œ_ โ€ - list of characters = ['_', ' ', ' '] ร— - multiply -> ['___', ' ', ' '] (now strings, a bit of a hack in Jelly) โ€œ โ€œ/\โ€œ||โ€ - list of lists of characters = [[' ', ' '], ['/', '\'], ['|', '|']] " - zip together applying: j - join -> [[' ', '___', ' '], ['/', ' ', '\'], ['|', ' ', '|']] Y - join with newlines -> [' ', '___', ' ', '\n', '/', ' ', '\', '\n', '|', ' ', '|'] - implicit, smashing print >>> ___ >>>/ \ >>>| | ``` [Answer] # JavaScript (ES8), 50 bytes ``` n=>` ${'_'.repeat(n)} /${s=''.padEnd(n)}\\ |${s}|` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5BQaVaPV5dryi1IDWxRCNPs5ZLX6W62FZdXa8gMcU1LwUkFBPDVQMUrK1J@J@cn1ecn5Oql5OfrpGmYaCpyYUqYoghYoQhYqyp@R8A "JavaScript (Node.js) โ€“ Try It Online") --- # JavaScript (ES6), 50 bytes ``` n=>' '+`_ / \\ | |`.replace(/_| /g,c=>c.repeat(n)) ``` [Try it online!](https://tio.run/##Zcy7CoAgFADQ3a9wS6m0x2xfIpjcblGIhkWT/241RusZzmYve0Bc97P2YcI8q@zVUNCiHA2RVGuSaBpFxN1ZQCZNonKpQA3wGtqTec4zBH8Eh8KFhc2s4Zx8pf1J95P@eW4 "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 24 bytes ``` %" %s /%s\\ |%s|"*RQ"_ ``` [Try it online!](https://tio.run/##K6gsyfj/X1VJQbWYS1@1OCaGq0a1uEZJKyhQKV5B4f9/43/5BSWZ@XnF/3VTAA "Pyth โ€“ Try It Online") ## Explanation ``` %"..."*RQ"_ "_ : The string literal "_ " *RQ : Multiply each element of the string by input (["___", " ", " "]) %"..." : Do string formating on string with args from previous comamnd ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` " {รง'_} /{รง}\\ |{รง}| ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IiB75ydffQove%2bd9XFwKfHvnfXw&input=Mw) `รง` is one of Japt's `repeat` methods for integers; you can probably figure the rest out from there! [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~43~~ 41 bytes -2 bytes thanks to mazzy ``` param($n)' '+'_'*$n ' '*$n|%{"/$_\ |$_|"} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0MlT1NdQV1bPV5dSyWPC8gEUjWq1Ur6KvExXDUq8TVKtf9ruQz09AwNgMIq8dZqKmkKQEpdvfY/AA "PowerShell โ€“ Try It Online") Eh, it's ~~okay~~slightly better [Alternative 41 byte solution offered by mazzy](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V8lsSi9uEa1Wl1BXVs9Xl1LJZ4LyARSQDElfZX4GK4aIFuptvZ/LZeBnp6hAVBcJd5aTSVNAUipq9f@BwA "PowerShell โ€“ Try It Online") [Answer] # Java 11, 61 bytes ``` n->" "+"_".repeat(n)+"\n/x\\\n|x|".replace("x"," ".repeat(n)) ``` [Try it online.](https://tio.run/##dY9NDoJADIX3nKKZ1UwQdOMK8QaycekYM8JoBqEQGAhGODuWn8SVmybte339mqpWeWnyGuNM1TWclMGPA2DQ6uqhYg3R1AKcbWXwCTEnBVAENBwcKrVV1sQQAUI4ondkwFx2Y36lS60sR@EyidtOSol918/zjGI569iGvD@fGIMpr2zuGeWtsW1hEsiJiS/3L1dQYgF6FNXMYsJdAOYQ7qm67ioS77u2OveLxvolbdoMOfpEL2b0P45VG@bnhvEL) **Explanation:** ``` n-> // Method with integer parameter and String return-type " " // Return a space +"_".repeat(n) // Appended with the input amount of "_" +"\n/x\\\n|x|" // Appended with " // /x\ // |x|", .replace("x", // of which the "x" are replaced with: " ".repeat(n)) // The input amount of spaces ``` [Answer] # [Python 3](https://docs.python.org/3/), 41 bytes ``` lambda n:(f" /|{'_ '*n} \\|\n\n"*3)[::3] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSiNNSUG/plo9XkFBXSuvViEmpiYmLyZPSctYM9rKyjj2f0FRZl6JRpqGhabmfwA "Python 3 โ€“ Try It Online") How could I forget about f-strings? --- # [Python 3](https://docs.python.org/3/), 43 bytes ``` lambda n:(" /|%s \\|\n\n"%("_ "*n)*3)[::3] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSkNJQb9GtVghJqYmJi8mT0lVQyleQUFJK09Ty1gz2srKOPZ/QVFmXolGmoaFpuZ/AA "Python 3 โ€“ Try It Online") Constructs the string transposed, then transposes it using modular arithmetic. [Answer] # [COW](https://bigzaphod.github.io/COW/), 420 bytes ``` MoOMoOMoOMoOMoOMoOMoOMMMMoOMoOMoOmoOMMMMOOMMMMOOmoOMoOmOoMOomooMMMMOomoooommoOMoOMoOMoOMoOMooMMMmoOMMMMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMMMMOOmoOMoOMoOMOOmoOMoOmOoMOomoomOoMOomooMMMmoOmoOMMMmOoMMMMoOmOomOomOoMMMMOOmoOmoOmoOMoomOomOomOoMOomooMMMmOoMoomoOmoOmoOMoomOomOoMMMMOOmoOMoomOoMOomoomoOmoOmoOMOoMOoMOoMoomOomOomOomOoMoomoOMMMmoOMMMMOOmoOmoOMoOmOomOoMOomooMMMmoOmoOMMMMoomOomOomOoMOOmoOMoomOoMOomooMMMMoo ``` [Try it online!](https://tio.run/##jVBbDsAgCDvUzmE4xL5JP3d8xkMFdR8zxNRaWvTGI9JAH6VrYI4j9Z2DJDQCA04aAJh3H7vl1e1XlSCrI7Sm85jQSA9SEDV9ugbIq9muWPlDU2ZIfcqcadFLxdY1@WqatrTnzo9dptoTQyByvQ "COW โ€“ Try It Online") Pretty happy with 140 instructions (3 bytes per instruction) considering that the ASCII values of the six required characters sum to 400. ### Commented ``` MoOMoOMoOMoOMoOMoOMoO # push 7 to 1st memory block blocks: [[7]], register: nil MMM # copy to register blocks: [[7]], register: 7 MoOMoOMoO # add 3 to 1st block blocks: [[10]], register: 7 moOMMM # paste 7 to 2nd block blocks: [10, [7]], register: nil MOOMMMMOOmoOMoOmOoMOomooMMMMOomoo # set 3rd block to 28 = 7 + 6 + 5 + 4 + 3 + 2 + 1 blocks: [10, [0], 28], register: nil oom # read input n (e.g. 3) into 2nd block blocks: [10, [3], 28], register: nil moOMoOMoOMoOMoO # add 4 to 3rd block blocks: [10, 3, [32]], register: nil Moo # print ASCII character 32 (space) blocks: [10, 3, [32]], register: nil MMMmoOMMM # copy and paste 32 to 4th block blocks: [10, 3, 32, [32]], register: nil MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoO # add 15 to 4th block blocks: [10, 3, 32, [47]], register: nil MMMMOOmoOMoOMoOMOOmoOMoOmOoMOomoomOoMOomooMMM # add 2 to 6th block 47 times blocks: [10, 3, 32, [47], 0, 94], register: nil moOmoOMMMmOoMMM # copy and paste 94 to 5th block blocks: [10, 3, 32, 47, [94], 94], register: nil MoO # add 1 to 5th block blocks: [10, 3, 32, 47, [95], 94], register: nil mOomOomOoMMMMOOmoOmoOmoOMoomOomOomOoMOomooMMM # print ASCII character 95 (underscore) n times blocks: [10, [3], 32, 47, 95, 94], register: nil mOoMoo # print ASCII character 10 (newline) blocks: [[10], 3, 32, 47, 95, 94], register: nil moOmoOmoOMoo # print ASCII character 47 (forward slash) blocks: [10, 3, 32, [47], 95, 94], register: nil mOomOoMMMMOOmoOMoomOoMOomoo # print n spaces blocks: [10, [0], 32, 47, 95, 94], register: 3 moOmoOmoOMOoMOoMOo # subtract 3 from 5th block blocks: [10, 0, 32, 47, [92], 94], register: 3 Moo # print ASCII character 92 (backslash) blocks: [10, 0, 32, 47, [92], 94], register: 3 mOomOomOomOoMoo # print newline blocks: [[10], 0, 32, 47, 92, 94], register: 3 moOMMMmoOMMMMOOmoOmoOMoOmOomOoMOomooMMM # add 32 to 5th block blocks: [10, 3, [32], 47, 124, 94], register: nil moOmoOMMM # copy 124 to register blocks: [10, 3, 32, 47, [124], 94], register: 124 Moo # print ASCII character 124 (pipe) blocks: [10, 3, 32, 47, [124], 94], register: 124 mOomOomOoMOOmoOMoomOoMOomoo # print n spaces blocks: [10, [0], 32, 47, 124, 94], register: 124 MMMMoo # paste 124 to 2nd block and print as ASCII character blocks: [10, [124], 32, 47, 124, 94], register: nil ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 36 bytes ``` ->n{" #{?_*n} /#{a=" "*n}\\ |#{a}|"} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWklBudo@XiuvlktfuTrRVklBCciOieGqAfJqa5Rq/2sY6OkZa@qlJiZnKFQr1OTVKBSUlhQrpEXnxSrU/gcA "Ruby โ€“ Try It Online") [Answer] # Scala, 47 bytes ``` n=>print(s" ${"_"*n}\n/${" "*n}\\\n|${" "*n}|") ``` ## Longer version, 94 bytes ``` n=>print(Seq((' ',' ',"_"),('/','\\'," "),('|','|'," "))map(t=>t._1+t._3*n+t._2)mkString "\n") ``` [Try them in Scastie](https://scastie.scala-lang.org/GRW7wRwySaSQNaN7MrBcDA) [Answer] # [Haskell](https://www.haskell.org/), 58 bytes ``` f n|x<-' '<$[1..n]=' ':('_'<$x)++"\n/"++x++"\\\n|"++x++"|" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hr6bCRlddQd1GJdpQTy8v1hbIttJQjwcKVGhqayvF5OkraWtXgFgxMXk1UHaN0v/cxMw8BVuF3MQC33gFjYLSkuCSIp88BT2FNE2FaAM9PePY/wA "Haskell โ€“ Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~109~~ 91 bytes Saved a whopping 18 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` #define p printf(L"| |\\ / _ "+i) i;j;f(n){for(i=9;i--;i--,p,puts(""))for(i-=p,j=n;j--;)p;} ``` [Try it online!](https://tio.run/##LYxBCsIwEEX3OcUQNzO0QRduZMwNPEJBpG10CsZQKy7anD2mqQMDf97/f1pzb9uUdl3vxPcQIIziJ4cXvcDSNLCHK@hKSAkP7NDT7F4jij2xGLNuHerwmd6oNVGxjA31YD0P2afAMeV/8LyJR1Kzgjw5BrjSr3TTAywc@C/PcGSoqnIQbOnSwA1xIVHF9AM "C (gcc) โ€“ Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 40 bytes ``` say$"._ x$_,$/,$_='/'.$"x$_.'\\';y/ /|/c ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJFSS9eoUIlXkdFX0cl3lZdX11PRQnI11OPiVG3rtRX0K/RT/7/3/BffkFJZn5e8X9dX1M9A0OD/7oFAA "Perl 5 โ€“ Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 17 bytes ``` TJRโฐ"_ "ยฝ" /| ยฆ| ``` [Try it online!](https://tio.run/##yygtzv7/P8Qr6FHjBqV4BQWlQ3uVFPRrFA4tq/n//78pAA "Husk โ€“ Try It Online") ## Explanation ``` TJRโฐ"_ "ยฝ" /| ยฆ| Input is a number, say n = 3, accessed via โฐ. " /| ยฆ| String literal " /| \|". The parser replaces ยฆ by \ and the closing " is implicit. ยฝ Split in half: x = [" /|", " \|"] "_ " String literal. Rโฐ Repeat n times: y = ["_ ", "_ ", "_ "] J Join x by this list: [" /|", "_ ", "_ ", "_ ", " \|"] Since x and y are lists of strings, y is inserted between each pair of elements in x and the result is flattened to keep the types consistent. T Transpose: [" ___ ", "/ \", "| |"] Implicitly print, separated by newlines. ``` [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 17 bytes ``` ร€รฉ_>>o/\ร€รฉ ร™ร“ร“/| ``` ``` Explain ร€ # @arg times รฉ_ # <M-i>nsert a '_' >> # indent by one space o/\ # insert '/\' on the next line (cursor stays at '\') ร€รฉ # @arg times insert ' ' ร™ # Duplicate this line down ร“ / # Find and replace ... ร“ # all Non-whitespace (\S == <M-S>) | # with a '|' ``` Haven't done one of these in a while. [Try it online!](https://tio.run/##K/v//3DD4ZXxdnb5@jHSIKbC4ZmHJx@erF/z//9/YwA "V (vim) โ€“ Try It Online") [Answer] # [MAWP v1.1](https://esolangs.org/wiki/MAWP), 92 bytes ``` %@_1A84W;[1A~25WWM~]%!![1A92W1M5W;]%67M;85W7M;[1A84W;]%45W3M4W;67M;65W1M4W;[1A84W;]65W1M4W;. ``` [Try it!](https://8dion8.github.io/?code=%25%40_1A84W%3B%5B1A%7E25WWM%7E%5D%25!!%5B1A92W1M5W%3B%5D%2567M%3B85W7M%3B%5B1A84W%3B%5D%2545W3M4W%3B67M%3B65W1M4W%3B%5B1A84W%3B%5D65W1M4W%3B.&input=0) [Answer] # 1+, 174 bytes ``` ."11+""*"**;1^<#[#(?|11##11+"1+""*""*+++;1+"\"/<1+1<1+#)]11+"""**+;11+"1+""""*++*+;1^<11++#(|?)[#(|11##11+""*"**;1+"\"/<1+1<1+#)]11+"1+"*""*++;11+"""**+;11+"*""1+""*+*+";()/; ``` Don't ask me how this work, I don't know at all! I didn't yet try to golf it down (although I probably can offer a 50% discount on the bytecount when I have time), and there's still a lot of repetitions. But at least I made it. 1+ 174 vs 92 MAWP v1.1. Fiasco. [Answer] # [Pepe](https://github.com/Soaku/Pepe), 118 bytes ``` REeEeEEEEErEeErREEeeeEReREEEEEEeRREeeEeeeeeReeereeEreeeEeEEEEREEEEeeEREEeeeEReeereeEeEEEeereeERrEeEEEEEeerreEeReeereEe ``` [Try it online!](https://soaku.github.io/Pepe/#!bzQ@_b.E5-!8hHIV2Dv_bHXkI-!dk@KHK%5D) [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~36~~ 32 bytes ``` @(n)[' /|';'_ '+~(1:n)';' \|']' ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI08zWl1Bv0bdWj1eQUFdu07D0CpPE8hTiKlRj1X/n5ZfpJBpa2BlaMClAAQpmcUFGmkamZqaXKl5Kf8B "Octave โ€“ Try It Online") Simple anonymous function that stitches together the first column ( `/|`), `n` middle columns (`_` ), and the final column ( `\|`), then returns the result. Because the strings are rows rather than columns, everything is stitched together vertically, and then the result is transposed to get the desired orientation. This works as trailing spaces are allowed, so a fully populated matrix can be formed. If trailing spaces were disallowed, the code would be 6 bytes longer by wrapping the result in `trim(...)`. --- * Saved 4 bytes by duplicating the string literal using array expansion rather than with `repmat`. Thanks @LuisMendo. ]
[Question] [ It is common to start countdowns 100 days prior to an event, probably because of our base 10 system. Examples of this can be found everywhere: * 100 days until your birthday * 100 days until the wedding * 100 days until the election * 100 days until our graduation * 100 days until her due date * 100 days until football season * 100 days until you get the Fanatic badge You get the picture. It seems that the 100th day before an event is second place only to the actual event. So for this challenge, I need to know what the date will be in 100 days, so that I can determine what I should start counting down too. ## Input No input ## Output The date 100 days from the current date based on the standard [Gregorian Calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) (Make sure to account for leap years). Output is flexible as long as the date format is human read-able (eg `2016-10-8`, `10-8-16`, `[ 2016, 10, 8 ]`, `10/8/16 12:00:00 AM`). ## Winning Code golf: shortest code in bytes --- ### Examples 100 days from today (Apr 5th, 2017) is Friday, July 14 2017. ``` Current Future ------- ------ 01/01/2001 +100 04/11/2001 01/01/2004 +100 04/10/2004 01/01/1900 +100 04/11/1900 01/01/2000 +100 04/10/2000 07/04/2017 +100 10/12/2017 10/31/2017 +100 02/08/2018 12/25/2017 +100 04/04/2018 08/29/1941 +100 12/07/1941 06/03/2001 +100 09/11/2001 ``` [Answer] # Excel, 10 ``` =NOW()+100 ``` ### Demonstration [![enter image description here](https://i.stack.imgur.com/KQSSQ.gif)](https://i.stack.imgur.com/KQSSQ.gif) [Answer] # Bash, ~~17~~ ~~16~~ ~~15~~ ~~14~~ 13 bytes ``` date -d100day ``` It turns out the `date` command takes some pretty flexible input for relative timings. You can also do things like `1 year`, `1 week ago`, `yesterday`, etc. It's pretty cool. -1 byte by realizing that bash does not care about grammar. -1 byte because the space between `100` and `day` is unnecessary. -1 byte because I don't need quotes anymore because I don't have a space in the string. -1 byte by removing the space after `-d` (thanks ASCII-only!) [Answer] # PowerShell, 10 bytes ``` (date)+1e2 ``` Thanks to ConnorLSW for the +1e2 trick. It appears that doubles (`1e2` is a double) are also added as days. ### Previous version, 12 bytes: ``` (date)+"100" ``` Apparently you can add strings to dates in PowerShell. The string `"100"` is converted into a 100 days-`TimeSpan`. [Answer] # Mediawiki, 19bytes ``` {{#time:r|+100day}} ``` You may try it with [wikipedia's sandbox](https://en.wikipedia.org/w/index.php?title=Wikipedia:Sandbox&action=edit) [Answer] # PHP, 28 bytes ``` <?=date(Y_m_d,time()+864e4); ``` human readable version, 35 bytes: ``` <?=date(Y_m_d,strtotime("100day")); ``` almost readable, 34 bytes: ``` <?=date(Y_m_d,strtotime(1e2.day)); ``` -4 bytes if also printing the time is accepted: replace `Y_m_d` with `r` or `c`. Itยดs National Holiday in France in 100 days. [Answer] # [Ruby](https://www.ruby-lang.org/), 16 bytes ``` p Time.now+864e4 ``` [Try it online!](https://tio.run/nexus/ruby#@1@gEJKZm6qXl1@ubWFmkmry/z8A "Ruby โ€“ TIO Nexus") [Answer] # Javascript, ~~29~~ ~~26~~ 25 bytes Saved 3 bytes thanks to @ASCII-only! Saved 1 byte thanks to @JohanKarlsson ``` new Date(+new Date+864e7) ``` ``` document.body.innerHTML=new Date(+new Date+864e7) ``` [Answer] ## SQL (PostgreSQL), 19 Bytes ``` SELECT now()+'100d' ``` [Answer] # Vim, 27 bytes ``` :r!date "+\%F" -d"+100 day" ``` [try it online!](https://tio.run/nexus/v#@29VpJiSWJKqoKQdo@qmpKCbAmQZGhgopCRWKv3/DwA "Try it Online!") [![enter image description here](https://i.stack.imgur.com/AkClj.png)](https://i.stack.imgur.com/AkClj.png) Edit: Removed unnecessary space char. [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` Z'100+1XO ``` Output format is `15-Jul-2017` (which I find most readable). Change `1XO` to `2XO` to get the format used in the examples, `07/15/17`. [Try it online!](https://tio.run/nexus/matl#@x@lbmhgoG0Y4f///9e8fN3kxOSMVAA "MATL โ€“ TIO Nexus") ### Explanation ``` Z' % Push current date and time as a serial date number 100+ % Add 100 1XO % Convert to string with format 'dd-mmm-yyyy'. Implicitly display ``` [Answer] **SQL (Microsoft), 35 31 bytes** ``` SELECT DATEADD(D,100,GETDATE()) ``` [Answer] # Java 8, ~~77~~, 61 bytes ``` ()->System.out.print(java.time.LocalDate.now().plusDays(100)) ``` [Try it online!](https://tio.run/nexus/java-openjdk#DcmtDsIwEABgv6eobAWXobGToCYJ4jiaUdK/7K4ly7LHRpeqT3zkkVnd0MV9yOXpHSkWlE5N7qVCDz3L6uJyfyhcl2r2Nm8sNkAqArmP6A9WBHHBwjUR@gnFQkxfbSD7whNurM/jaMylHcPRfjGdCOlt/w "Java (OpenJDK 8) โ€“ TIO Nexus") [Answer] # C#, 103 97 bytes *Thanks to [raznagul](https://codegolf.stackexchange.com/users/42502/raznagul) for saving 6 bytes!* ``` using System;class P{static void Main(){Console.Write(DateTime.Now.AddDays(100).ToString("d"));}} ``` Full program which reads the current date, adds 100 days and displays the result in `M/d/YYYY` format. You can change the date format by adding a few more bytes: ``` using System;class P{static void Main(){Console.Write(DateTime.Now.AddDays(100).ToString("d-M-yyyy"));}} ``` --- To eliminate boilerplate code - C# isn't exactly known to be very compact - an anonymous function can be used: # C# lambda, 49 43 bytes ``` ()=>DateTime.Now.AddDays(100).ToString("d") ``` Full program: ``` using System; class P { static void Main() { Func<string> f = ()=>DateTime.Now.AddDays(100).ToString("d"); Console.WriteLine(f()); } } ``` [Answer] # [Noodel](https://tkellehe.github.io/noodel), 8 [bytes](https://tkellehe.github.io/noodel/docs/code_page.html) ``` ]5@Laฦ‡โบฦˆ ``` [Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%5D5%40La%C6%87%E2%81%BA%C6%88&input=&run=false) --- ## How it works ``` ]5@Laฦ‡โบฦˆ ]5@La # The string "]5@La" gets pushed onto the stack which in base 98 represents 8,640,000,000. ฦ‡ # Pushes an integer that represents the current time where highest resolution is milliseconds. โบ # Add the time and the string which will be interpreted as 8,640,000,000ms. ฦˆ # Convert the integer to human readable time. # Implicitly output to the screen. ``` ``` <div id="noodel" code="]5@Laฦ‡โบฦˆ" input="" cols="80" rows="2"/> <script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script> <script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script> ``` [Answer] # Mathematica, ~~26~~ 21 bytes -5 bytes thanks to @KiranLinsuain! ``` Today+Quantity@"100d" ``` If including the time is permitted, then we can save 2 bytes: ``` Now+Quantity@"100d" ``` [Answer] # C, ~~87~~ ~~46~~ 44 bytes *saved 2 bytes thanks to [Albert Renshaw](https://codegolf.stackexchange.com/users/16513/albert-renshaw)* ``` f(){time_t t=time(0)+864e4;puts(ctime(&t));} ``` I realized the output is flexible enough to allow for day of week and time, so there's no need to use `localtime` or the `tm` structure at all. ### Old answer ``` f(){time_t t=time(0)+8640000;char b[9];strftime(b,9,"%d-%m-%y",localtime(&t));puts(b);} ``` Based on [Khaled.K's answer](https://codegolf.stackexchange.com/a/115517/67236), but instead of messing with the `tm` structure, adds the number of seconds equivalent to 100 days directly to the `time_t` value. It also prints only the date, without time or day of week. As it should happen on a golfed program, some ugly warnings are generated on compilation. [Try it online!](https://ideone.com/ZFJc7k) ### Ungolfed: ``` f(){ // Current time + 100 days time_t t=time(0)+8640000; // Buffer for printing formatted time char b[9]; // Print the time in format dd-mm-yy to buffer strftime(b,9,"%d-%m-%y",localtime(&t)); // print buffer puts(b); } ``` [Answer] # JavaScript, 42 bytes ``` (d=new Date()).setDate(d.getDate()+100)&&d ``` ``` setInterval(_=>document.body.innerHTML=(d=new Date()).setDate(d.getDate()+100)&&d,1000) ``` [Answer] # IBM/Lotus Notes Formula, 29 bytes ``` @Adjust(@Today;0;0;100;0;0;0) ``` Unfortunately `@Adjust` requires the trailing `0's` for the missing `hh:mm:ss`. If we were allowed to display the time as well then changing `@Today` to `@Now` would save 2 bytes for 27. [Answer] ## JavaScript (ES6), 44 bytes ``` _=>new Date(Date.now()+864e7).toDateString() ``` 25 bytes if returning a date with the time is acceptable: ``` _=>Date(Date.now()+864e7) ``` [Answer] # 30 bytes **Mysql!** ``` select NOW()+INTERVAL 100 DAY; ``` **SQLite** ``` SELECT date('now','+100 day'); ``` [Answer] # F# (53 bytes) ``` printf"%s"(DateTime.Now.AddDays(100.0).ToString("d")) ``` [Answer] ## Swift 3, 39 bytes ``` print(Date(timeIntervalSinceNow:864E4)) ``` [Answer] # C, ~~120~~ 113 bytes ``` #include <time.h> f(){time_t t=time(0);struct tm*tm=localtime(&t);tm->tm_mday+=100;t=mktime(tm);printf("%s",ctime(&t));} ``` [**Live Demo**](http://ideone.com/O15P4q) ``` #include <stdio.h> #include <time.h> void PrintDatePlus100days() { // obtain current time time_t t = time( 0 ); // convert to datetime struct struct tm *tm = localtime( &t ); // add 100 days tm->tm_mday += 100; // convert to time_t t = mktime( tm ); // print time in readable format puts( ctime( &t ) ); } ``` [Answer] **PowerShell, 23** ``` (get-date).adddays(100) ``` This is my first ever try, so please give me constructive feedback. Thanks! [Answer] # R (REPL), 14 bytes ``` Sys.Date()+100 ``` Try it on [Ideone](http://ideone.com/27USzq). [Answer] # Python, 63 bytes ``` from datetime import* print(datetime.now()+timedelta(days=100)) ``` Very simple solution really. Because the `datetime.now()` result is the same `type` as the result of `timedelta`, it happily adds the two together. [Answer] # JavaScript, 38 Bytes ``` d=new Date;d.setDate(d.getDate()+100);d ``` A little bit shorter than [ASCII-only answer](https://codegolf.stackexchange.com/a/115441/65663). ``` document.write(eval("d=new Date;d.setDate(d.getDate()+100);d")) ``` [Answer] # Golang, 58 bytes ``` import ."time" func f(){Println(Now().AddDate(0, 0, 100))} ``` Full Program ``` package main import . "time" import . "fmt" func main() { Println(Now().AddDate(0, 0, 100)) } ``` [try it online!](https://tio.run/nexus/go#K0hMzk5MT1XITczM48rMLcgvKlHQU1BKyy1R@g/jKpVk5qYqcaWV5iUrpGloVgcUZeaV5ORp@OWXa2jqOaakuCSWpGoY6CgAkaGBgaZm7X@wWpCZGpoK1VycQF1ctf8B) [Answer] **Oracle, 34 bytes** ``` SELECT CURRENT_DATE+100 FROM DUAL; ``` [Answer] # Python 2 + Pandas 0.19.1, 56 51 bytes ``` from pandas import* print Timestamp('now','D')+100 ``` ]
[Question] [ **This question already has an answer here**: [Find the square root, BUT [closed]](/questions/71477/find-the-square-root-but) (1 answer) Closed 8 years ago. Define a function, s, which takes a number and returns the square root. No use of library functions, such as Java's Math.sqrt() or PHP's built in sqrt(), allowed. [Answer] ## Python - 11 chars Technically not a library function :) ``` input()**.5 ``` As a function it's 16 chars ``` f=lambda x:x**.5 ``` [Answer] ## Python (13 chars) `f=.5.__rpow__` This is equivalent to `f=lambda x:x**.5`, but 3 bytes shorter. [Answer] ## Python - 41 chars Takes a while to run for large numbers :) ``` n=input() i=0 while i*i<n:i+=1e-9 print i ``` [Answer] ## Java (163) Implementing a double precision square root calculator by making use of the fast invert square root stuff from quake and a new constant for the 64bit floats. In java. Yay for verbosity. ``` public double i(double a){double b=a/2;long c=0x5fe6ec85e7de30daL-(Double.doubleToRawLongBits(a)>>1);a=Double.longBitsToDouble(c);return a*(1.5-b*a*a);};s=1/i(x); ``` [Answer] ## **J, ~~6~~, 5** Using power: ``` ^&0.5 ``` Or, perhaps more mnemonically: ``` ^&1r2 ``` Using the slightly less "cheaty" method, `exp(log(x)/2)`. ``` -:&.^. ``` Except since `exp` is the inverse of `log`, we simply "**halve** (`-:`) **under** (`&.`) **log** (`^.`)" Not that normally a J programmer would not name a method this short; he'd simply embed in in a larger program. [Answer] # Haskell, 9 characters ``` s=(**0.5) ``` Similar to [@gnibbler's Python solution](https://codegolf.stackexchange.com/questions/73/reimplementing-square-root/83#83). [Answer] **LISP (66)** Using Babylonian method. ``` (defun s(A) (do((x 1(*(+ x(/ A x)).5))(n 100(1- n)))((zerop n)x))) ``` [Answer] Naive solution, accepts only positive integer inputs. ``` s n=foldr (\x a->x*x==n||a) False [1..] ``` Haskell, 39 characters. [Answer] ## Python - 65 A simple solution using Newton's method. ``` def s(x): t=1.0 while 1e-9<abs(x-t*t):t-=(t*t-x)/2/t return t ``` [Answer] C with some bad form and deprecated features: ``` s(int n,int g){return g*g-n?s(n,random()%n):g;} ``` If your compiler is enough of a liberal hippie, it should be possible to call s(n) and (eventually) receive the desired value. [Answer] ``` return 1.f/InvSqrt(x); ``` InvSqrt of [course courtesy of Quake](http://www.beyond3d.com/content/articles/8/). What, you mean you wanted an accurate result? [Answer] ``` def sqrt_newton(x): f,g,w,d=lambda a:a*a-x,lambda a:2.0*a,x/2.0,1e-4 while abs(f(w))>d:w-=(f(w)/2.0/w) return w ``` reduced version of <https://gist.github.com/713104> [Answer] ## C++ (61) *Uses [Heron's Method](http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method):* ``` f64 s(f64*x,u64 n=9){*x=(x[1]/*x+*x)/2;return n?s(x,--n):*x;} ``` Recursion, pointers, optional arguments, and ternary operators FTW! --- Usage: ``` f64 x[2] = {12.0, 12.0}; std::cout << s(x); ``` [Answer] ## C++ (35) ``` f64 s(f64 x){return exp(log(x)/2);} ``` I promise I didn't use `sqrt()`! [Answer] ## ActionScript3 (53) Using Newton's method. (Hooray 4 IEEE 754) ``` function s(b,d=2){return b==d*d?d:s(b,d-(d*d-b)/2/d)} ``` I know I'm TOO late but I just wanted to write something I did :( [Answer] # GolfScript - 21 It uses the Babylonian method and works only with integers. According to my tests, it's good for up to 56 digits. ``` {1{.2$\/+2/}99*\;}:s; ``` Usage: `1000 s` -> `31` I think this is the shortest solution so far that doesn't call some kind of power function or external library. [Answer] # k (17 chars) Iterative (implementation of [Babylonian method](http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)): ``` {{.5*y+x%y}[x]/x} ``` Iterates until two successive values are *equal* Example: ``` sqrt[1234] = {{0.5*y+x%y}[x]/x}1234 1b ``` Also the mandatory `xexp[;0.5]` for 10. [Answer] # JavaScript, 121 No, it doesn't even come close, but it is more optimal than other solutions and doesn't use `Math.pow` with fractions. ``` s=n=>{for(var c=Math.pow(10,(''+Math.floor(n)).length),v=0,l;(l=v*v<n),c>1e-10;l!=v*v<n?c/=10:0)v*v<n?v+=c:v-=c;return v} ``` [Answer] **Mathematica 27** ``` f@x_:=Nest[(#+x/#)/2&,1.,9] ``` [Answer] ## Golf-Basic 84, 9 characters ``` i`Ad`A^.5 ``` As a function, **15** characters: ``` i`A:Return A^.5 ``` [Answer] ## JavaScript, 36 (or 14 without the function) ``` function s(n){return Math.pow(n,.5)} ``` [Answer] **AWK, 8** ``` 1,$0^=.5 ``` Following solution can handle all values except 0 **AWK, 6** ``` $0^=.5 ``` [Answer] # Befunge 98 - 18 ``` &00pv 0*::<+1vj!`g0 ``` This **program** takes an input number from the user, and ends by pushing the integer square root on the stack (note that you said square root, but didn't specify whether floating point was necessary). Here is a function (well, closest thing to one) (requiring free access to cell `00`) (**15** chars): ``` 00p::*00g`!jv1+ ``` [Answer] In these I expect the byte to be squared is in the current cell. It needs 8 cells to the right empty and it will have answers in the 4 cells starting from where the number was. These are: 1. integer result 2. a alternative result (would be the same or one higher if those multiplied is closer to the argument) 3. remainder 4. flag for negative remainder # [Extended BrainFuck](http://sylwester.no/ebf/): 310 ``` >+4>15+4<[>>+<+<[->[->->>+<<]>[-<+>>]<+<<]>[-]>[-]3<[->+>>+3<]>[-<+>]4>[-<+3<+4>]<<[->-[>+>>]>[+[-<+>]>+>>]5<]3>[-3<+3>]<[->>+>+3<]<[->+4>+5<]>+[>>[-<]<[>]<-]3>+<[[-]>[-]>[-4<+4>]5<+<+4>]>[->[-]<[-3<+3>]]3<[->+<]<<[->>+4<->>]<+<[-[+3>[-]>>[-]4<-]>[-5>+4<]<]>[->]<<]<[-]5>[-4<+<+5>]>>[-6<+6>]<[-3<+3>]<<[-<<+>>] ``` It turns into the following: # BrainFuck: 390 (the same as above run through the compiler) ``` >+>>>>+++++++++++++++<<<<[>>+<+<[->[->->>+<<]>[-<+>>]<+<<]>[-]>[-]<<<[->+>>+<<<]>[-<+>]>>>>[-<+<<<+>>>>]<<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>>[-<<<+>>>]<[->>+>+<<<]<[->+>>>>+<<<<<]>+[>>[-<]<[>]<-]>>>+<[[-]>[-]>[-<<<<+>>>>]<<<<<+<+>>>>]>[->[-]<[-<<<+>>>]]<<<[->+<]<<[->>+<<<<->>]<+<[-[+>>>[-]>>[-]<<<<-]>[->>>>>+<<<<]<]>[->]<<]<[-]>>>>>[-<<<<+<+>>>>>]>>[-<<<<<<+>>>>>>]<[-<<<+>>>]<<[-<<+>>] ``` It's Newtons method starting at guess 16 and goes downwards. It stops when the last iteration didn't make a different integer result. This is actualy from the `sqrt` macro of EBF since I use it to implement print-string operator `|`. Here's the part from EBF source ungolfed: ``` ; sqrt ^0 uses 9 cells that need to be empty ; will be fuzzy after calling because of divmod ; returns ^0 result ; ^1 same as ^0 or it increased by 1. typically will ^2*^3 be closerto the requested argument than ^2*^2 ; ^2 remainder ; ^3 indicates if remainder is negative {sqrt check for wrong usage !diff:diff :in:guess:temp:cur:div:mod:res:indicator @in $guess+ ;initial guess is 16, but $mod 15+ ; its in mod and incremented (rounded up) $guess( ; worst case is 1 with 5 iterations $cur+$temp+ $guess(-$temp[->-$mod+$cur]>[@cur-$temp+$div]$cur+) $temp(-)$cur(-) $in(-$guess+$cur+) $guess(-$in+) $mod(-$div+$guess+) $cur &roundivmod ; remainder wil now be in mod $mod(-$res+) $cur(-$mod+$guess-) $temp+ $guess[-[+$div(-)$res(-)$temp-]>[-@temp$indicator+$cur]$temp]>[-@temp>] ) $in(-) $mod(-$guess+$in+) $indicator(-$guess+) $res(-$cur+) $div(-$temp+) $in !indicator!res!mod!div!cur!temp!guess!in } ;; helper macros ; roundivmod uses divmod and puts the rounded result in ^0 and indication of rounded in ^1 ; and a remainder (which ^1 is an indication is either reduction or inrement) in ^2 {roundivmod &divmod @cur ; *0|n-rem|rem|res| >>>(-<<<+) <(->>+>+) make double copy of remainder ; res|n-rem|0|0|rem|rem <(->+>>>>+) ; res|0|n-rem|0|rem|rem|n-rem >+[>>[-<]<[>]<-] >>>+<( [-]>[-] >(-<<<<+) <<<<<+<+ ) >(- >[-] <(-<<<+) ) end divide } ; this does the divmod. compiler is fuzzy after so caller must fix position to calling {divmod[->-[>+>>]>[+[-<+>]>+>>]<<<<<]} ``` [Answer] ### Scala 78 chars: ``` type D=Double def q(x:D,g:D=9):D=if(math.abs(g*g-x)<.001)g else q(x,(g+x/g)/2) ``` invocation: ``` scala> q(12345) res36: D = 111.10805572305925 ``` [Answer] # Python, 44 ``` def s(x):t=1.;exec"t=(t+x/t)/2;"*99;return t ``` Tested with: ``` for x in [0, (3+5**0.5)/2, 1000, 10**5, 10**11]: print x, '->', s(x) ``` Output: ``` 0 -> 1.57772181044e-30 2.61803398875 -> 1.61803398875 1000 -> 31.6227766017 100000 -> 316.227766017 100000000000 -> 316227.766017 ``` # Python, 50 49 In case you like recursion: ``` s=lambda x,t=1.,r=99:r and s(x,t/2+x/t/2,r-1)or t ``` Same testing code, same output. [Answer] # Postscript ~~94~~ 89 Babylonian method. Iterates until successive values are equal. ``` s{dup 2 div{2 copy div 1 index add .5 mul 2 copy eq{exit}if exch pop}loop pop exch pop}def ``` Commented: ``` /s{ dup 2 div % S x { % S x 2 copy div % S x S/x 1 index add .5 mul % S x (S/x+x)/2 2 copy eq { exit } if % S x (S/x+x)/2 exch pop % S (S/x+x)/2:->x }loop pop exch pop }def ``` [Answer] ## [bash](/questions/tagged/bash "show questions tagged 'bash'") 228 ( a lot but **pure** bash only! ;) For the count: ``` x=(600000 200000);z=${x[$(($1&1))]} y=1;while [ $y -ne $z ] ;do y=$z;printf -v z "%u" $(((${y}000+${1}00000000000/${y})/2));printf -v z "%.0f" ${z:0:${#z}-3}.${z:${#z}-3};done;z=0000$z;printf "%.3f\n" ${z:0:${#z}-4}.${z:${#z}-4} ``` As a function: ``` sqrt() { local -a xx=(600000 200000) local x1=${xx[$(($1&1))]} x0=1 while [ $x0 -ne $x1 ] ;do x0=$x1 printf -v x1 "%u" $(( (${x0}000 + ${1}00000000000/${x0} )/2 )) printf -v x1 "%.0f" ${x1:0:${#x1}-3}.${x1:${#x1}-3} done x1=0000$x1 printf "%.3f\n" ${x1:0:${#x1}-4}.${x1:${#x1}-4} } sqrt 2000000 1414.214 sqrt 1414214 1189.207 echo $((1189207000/1414214)) 840 ``` (Nota: **840 x 1189** is A0 paper size in milimeters ;-) ## The same, but working under [zsh](/questions/tagged/zsh "show questions tagged 'zsh'"), [dash](/questions/tagged/dash "show questions tagged 'dash'"), [ksh](/questions/tagged/ksh "show questions tagged 'ksh'"), [bash](/questions/tagged/bash "show questions tagged 'bash'") and [ash](/questions/tagged/ash "show questions tagged 'ash'") (busybox): ``` sqrt() { _val=$1 set -- 6 2 x1=$(eval echo \$$((1+(_val&1))))00000 x0=1 while [ $x0 -ne $x1 ] ;do x0=$x1 x1=000$(( (${x0}000 + ${_val}000000000/${x0} )/2 )) x1=$(printf "%.0f" $(echo $x1|sed 's/\(...\)$/.\1/')) done printf "%.3f\n" $(echo $x1|sed 's/\(...\)$/.\1/') } ``` [Answer] # dc, 46 chars ## [Babylonian method](http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) - iterative with given precision: ``` Fk?sp?sn1[ddstlnr/+2/pdlt-[0r-]sbd0>blp<a]dsax ``` Takes precision and `N` from stdin. Example invocation (first number is the precision, second number is N: ``` { echo 0.0000001 ; echo 489 ; } | dc -e'Fk?sp?sn1[ddstlnr/+2/pdlt-[0r-]sbd0>blp<a]dsax' ``` It prints all the iterations, just for fun. Printing only last one is trivial change - just move the `p` behind `/+2/` at the end of the program. Explanation: * `Fk` sets precision to 15 (see the [hexa trick here](https://codegolf.stackexchange.com/a/17050/2800)) * `?sp` and `?sn` asks for input and stores it to the registers * `1` is the original seed * the iteration is computed by `ddstlnr/+2/`. Then, `dlt-` computes difference from previous iteration. `[0r-]sbd0>b` performs absolute value of the difference, and if it is greater than the specified precision, loop continues - `lp<a`. [Answer] # CoffeeScript (12) ``` s=(n)->n**.5 ``` Thanks to [gnibbler](https://codegolf.stackexchange.com/users/95/gnibbler)'s post for the `.5` idea, I wouldn't have remembered that by myself. ]
[Question] [ [`zipwith`](http://zvon.org/other/haskell/Outputprelude/zipWith_f.html) is a functional construct that takes three arguments: one binary function and two lists of the same length, and returns a single list where each element is constructed by applying the binary function to each pair of elements from the two lists: ``` zipwith (a+b) [1,2,3] [4,5,6] = [5,7,9] ``` You are to take a [black-box function](https://codegolf.meta.stackexchange.com/a/13706/66833) which takes exactly two arguments and two non-empty arrays of the same length consisting of positive integers, and output the result of applying `zipwith` to this function and arrays. For the sake of simplicity, you can assume that the black-box function will always input and output integers within your language's integer domain. If your answer consists solely of a builtin which does this (for example Haskell's `zipWith`), please edit into [this](https://codegolf.stackexchange.com/a/218018/66833) Community Wiki answer. You may input and output in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins ### Test Cases ``` function, array, array -> output a = b, [1, 2, 3], [3, 2, 1] -> [0, 1, 0] a - b, [8, 3], [3, 8] -> [5, -5] aยฒ + b/2, [6, 8, 1, 3], [5, 3, 6, 2] -> [38, 65, 4, 10] a ร— ฯ†(b), [4, 2, 5, 8, 3], [7, 6, 10, 2, 1] -> [24, 4, 20, 8, 3] ``` The third test case uses integer (floor) division. The fourth uses the [Euler Totient function](https://en.wikipedia.org/wiki/Euler%27s_totient_function) [Answer] # [Haskell](https://www.haskell.org/), 22 bytes ``` (.zip).(.).map.uncurry ``` [Try it online!](https://tio.run/##jZFNb4JAEIbv@yvegwdQdiP4WRN6bNJDb02alG7iClvdFJAgtNqmv50O@FFNNMphZnd553l3dhZq9aHjuEqWURlrPCmT4muhc81@eGWJb5PZwhK2SFQmyjQs83xT8V@WbF5N9mKKBSYTWAr8HrM6hHYdAyWbNNumUB7pfZynMlYsC6PToiY@UqJKSofTNVXGOp0TooV3Exc6h2X5vmtDYB5GWNsIXCHWkrGk7sJHtGRAlhuqbuH/BlanVjrwHPQkgr6DgYOhxPWPcwSkHTm4k@fRvn/C7jUrV96GflDxSjt4zkuKzeaCCyeT8cFhfMvVTxrggwvgN7Udo2ordGg5jcznFB7ZDcmHOtmaEoJ86ciTR@AeCYb0ix7U7V4zQBv7yc7sZgheM4ddW6MG73YP71cbeP0G7nV3suoP "Haskell โ€“ Try It Online") Not particularly interesting, just a reimplementation of `zipWith` converted to pointfree form: ``` \f x y -> map (uncurry f) (zip x y) \f x -> map (uncurry f) . zip x \f x -> (map (uncurry f) .) zip x \f -> (map (uncurry f) .) . zip \f -> (. zip) (map (uncurry f) .) \f -> (. zip) ((.) (map (uncurry f))) \f -> (. zip) ((.) ((map . uncurry) f)) \f -> (. zip) ((.) . (map . uncurry) $ f) \f -> (. zip) . ((.) . (map . uncurry)) $ f (. zip) . ((.) . (map . uncurry)) ``` [Answer] # Trivial builtin answers Edit your answer into this post if it consists of a builtin which does the entire task by itself --- # [HBL](https://github.com/dloscutoff/hbl), 0.5 [bytes](https://github.com/dloscutoff/hbl/blob/main/docs/codepage.md) ``` 2 ``` (Not implemented in the online version at the time of this writing.) # [Fig](https://github.com/Seggan/Fig), \$1\log\_{256}(96)\approx\$ 0.823 bytes ``` z ``` [Try it online!](https://fig.fly.dev/#WyJ6IiwiIl0=) Same as Husk. # [APL (Dyalog Unicode)](https://www.dyalog.com/), 1 byte ``` ยจ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSF6ke9uxRsFR71bq1VeNTdovCobypIWMNQR8FIR8FYUyHt0AoFDWMwz1CTC6FHF1OPBYoGC5hqDaByLSNNBW2FRz1dQE2Htxuh6jMDKgaajtBtCmTqKACFjTS5Du8AqdHWN7R91LXoUceKR72bgTbPVXAtzUktUi9WKMkvyUzNK1FIK81LLsnMz0Ny4uHpCod3YDrTBOwZU7ClMBvNwdYZGkD9@f8/AA "APL (Dyalog Unicode) โ€“ Try It Online") # [BQN](https://mlochbaum.github.io/BQN/), 1 byte ``` ยจ ``` Same as APL. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=4oCiU2hvdyAx4oC/MuKAvzMgPcKoIDPigL8y4oC/MQrigKJTaG93IDjigL8zIC3CqCAz4oC/OArigKJTaG93IDbigL844oC/MeKAvzMgeyjwnZWo4ouGMikr4oyKKPCdlanDtzIpfcKoIDXigL8z4oC/NuKAvzIKQA==) # [Husk](https://github.com/barbuz/Husk), 1 byte ``` z ``` [Try it online!](https://tio.run/##yygtzv7/v0r7////0YY6RjrGOiaxQJaBjpGBjrGBjolBLAA "Husk โ€“ Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` " ``` [Try it online!](https://tio.run/##y0rNyan8/19b6f///9GGOkY6xjomsf@jTXXMdMx1LGIB "Jelly โ€“ Try It Online") # [J](http://jsoftware.com/), 2 bytes ``` "0 ``` [Try it online!](https://tio.run/##ZY89C8IwFEX3/IqLg/2wCUlsaw0KBcHJyVUcWimog0VoJ8W/Hl@bQisG8kHuOXkvdzsTXoutgYcIEoYmF9gdD3s7kzZgrOjCEyu77cyaurlVj4bOPsfHBHPxNIxVl2sNBY0lxuGTiTJoJ1eUayiHZz9wj/N/PHNwSriaCH5o8gILbETOTe6shPIU2gkxFUomNej1EEPzA48V4UqOHbkPxOSllJEj8UKBt6AlGlpb91bSc9p@AQ "J โ€“ Try It Online") Not technically a builtin, but close enough. # [C#](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip), 3 bytes ``` Zip ``` [Try it online!](https://tio.run/##VY47C8IwFIX3/IqDU4sx4HMJdekmOnUQFIdYgwRqUpO0IqW/vV7UQS8X7uPA@U4ZJqXzemiCsVcUzxD1TbLfS2yNvUvG6uZcmRIhqkijrFQIyFnHgH@ldeaCnTI2SUnrBlC1ysPr0FQRGax@HE/ophwzjnkvDqZOvr8Fx5Jj1XMkiuOcIltDYUybfPvkzgZXabH3JmrKpZMieooqNo54Iw7qDydNJdF71g8v "C# (.NET Core) โ€“ Try It Online") # [Julia](http://julialang.org/), 3 bytes ``` map ``` [Try it online!](https://tio.run/##VY1RCsIwEET/9xTzmWAaaIvSn3iREiHFBiI1ljaCN/MAHixuiiDdn5l9O8PenlNw9St7k@9uzmlc0wqDnoQxCn2t0Ci0lm272dpKEhWv3R93hQmnBonqDHdpcMDweXO6P/GVS7/skVWBWcMNS@QfC8pHhLjpSuCZlxDTFEUhckf8xrTWcs8ljfGavw "Julia 1.0 โ€“ Try It Online") # [Python 2](https://docs.python.org/2/), 3 bytes ``` map ``` [Try it online!](https://tio.run/##bY7BCsIwEETv@Yo9NnGLNEUphXxJ3MMGLQq2DU0ufn3cFMGD7mWW4c0w8ZXv62LL5C5l5ljyLeUEDrwCOf/kOVwZGMMIjyU37FzQCL5DsAg9ydvvb0eEvxFugxDDlxz@Y8ZYOEA4SpE/CyV9n8xJFEE8S6RIqWndoG6UNbumUeriVrdNjamO1uUN "Python 2 โ€“ Try It Online") # [R](https://www.r-project.org/), 3 bytes ``` Map ``` [Try it online!](https://tio.run/##K/pflVlQnlmSYfvfN7Hgf2leTmZxiQZUTCPB1jZBx9DKWMfYylBTkwtdVjdBJ1nDQsdYE0gZ61hoYipJK81LLsnMz9NI1EnSrE7Lyc8v0kiMM9JO0jfSrAXqMtNRsNBRMNRRAJthCqR1FIBiRkCj/gMA "R โ€“ Try It Online") The canonical [R](https://www.r-project.org/) built-in function is [mapply](https://tio.run/##K/pflVlQnlmSYfs/N7GgIKcSxtdIsLVN0DG0MtYxtjLU5IKL6iboJGtY6BhrAiljHQtNhFRaaV5ySWZ@nkaiTpJmdVpOfn6RRmKckXaSvpFmLVC1mY6ChY6CoY4CWK8pkNZRAIoZaWr@BwA) (6 bytes). However, the [R](https://www.r-project.org/) documentation for `Map` reads *"Map is a simple wrapper to mapply which does not attempt to simplify the result"* (meaning that `Map` leaves its output as a list, rather than a vector, of results), so this seems to be a perfectly-acceptable 3-byte alternative here. # [Factor](https://factorcode.org/), 4 bytes ``` 2map ``` [Try it online!](https://tio.run/##VY29DoJAEIR7nmJ6IwYQQjTWxsbGWBGLCy6RyP1wdxTG@OzncqGh2Z3MfDvbidZrG@63y/V8wJusogGOxolUSw5S@FccaTep1vdaOSghyRkxx8aS9x9je@VxTELAFxlyFPix2qNExarBBg/kUhikyYooWGWROK2IOuaIRB1Vg@2KqNjPlpaSd8VNc08DNzL47A0bO3SD1ja@X27DHw "Factor โ€“ Try It Online") # [Raku](https://github.com/nxadm/rakudo-pkg), 4 bytes ``` &zip ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfrSqz4L81V3FipUKahlV5ZkmGhtahTQraCloKKZllCkaaOgoaZjoKFjoKhjoKxiCeKZDWUQCKGWlqWv8HAA "Perl 6 โ€“ Try It Online") # [Haskell](https://www.haskell.org/), 7 bytes ``` zipWith ``` [Try it online!](https://tio.run/##bcuxDoIwFIXhvU9xEhxAbmPaStOF53AgHUjU0IhAgKFofPbaGAaHTmf4v9O1y@PW9@HNw8tNF7d2gX8Y89mGGv7oUeLej@OMfDvJgrFn64ZYriMDptkNKw7Yj8jLAo0gScqiOVNF2qZUXf8xFVckGY/K7MYkRRaFJkPipypSpEna8AU "Haskell โ€“ Try It Online") # [Prolog (SWI)](http://www.swi-prolog.org), 7 bytes ``` maplist ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/xvr5ucmJOj8T83sSAns7jkv45CQU5psY5CtKGOkY5xLJBhomOqYwZkRGnqKJQXZZak5uRpRGnq/QcA "Prolog (SWI) โ€“ Try It Online") # MATLAB / Octave, 8 bytes ``` arrayfun ``` [Try it online!](https://tio.run/##y08uSSxL/Z9m6xDzP7GoKLEyrTTvf5qGQ0FOabGOQrShjoKRjoJxLJBpoqNgqqNgFqvJBZROLUSVBDJNQEzN/wA "Octave โ€“ Try It Online") # Elm, 9 bytes ``` List.map2 ``` # [PHP](https://php.net/), 9 bytes ``` array_map ``` [Try it online!](https://tio.run/##hc5BCoMwEAXQvaeYRRaJjSTGKoJNexAJkrSIi6ohYKGnT4dAcdNiVkP@8P74ycfLzU8@I@O23EFDtCHY9zBbH7sse9kwPLbZ0xRTGBdKLCeO6SuxWhPHoS85KA6VwbFKY2mAsQ5@PCF6iTkHaQ7sItHt7rZ/0d2uORT1kZzn6jQ@1zVQ4oRiqDeop6tSFyJYh3/q24hyhQsNJmfckyZ@AA "PHP โ€“ Try It Online") (PHP's `array_map` can take any number of array arguments) # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 9 bytes ``` MapThread ``` [Try it online!](https://tio.run/##Vc29CsIwFAXgvU8RCHTxFk1qa5dKF92Egm6lwqWmpNAfCXUK6avHWIPgWc7ycc6AsxQDzl2Dts3tBZ83qQQ@bKm6ca5odGyLgtbhcm1wXHSgaZ5THpJfgGjNgENsQMeumTEGHIv@1MoyjzJP7nxz7qdJVZRveR1@SAoZsJUlEEMK3FNyevVClbJztiYr3buzBL6bB0fZzr8Hxr4B "Wolfram Language (Mathematica) โ€“ Try It Online") # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 18 bytes Not exactly a builtin, but a library function: ``` map* ``` 4 bytes for the function, 14 bytes for `(load library)`. [Try it online!](https://tio.run/##TYzBDoIwEETvfsUctyYeWiLhZsqfLFkOTbaKCCZ8fVmTih5n5s1b0n3T9JpKIX2wQNMw87ydKPN0xvhcWW8gIxZ4BDSuhsaCd65yl9p2/0B3zKScB2FQRG87iwRQXjUgIloh6R3QIzj3fbem8j/Z1XTtZy9lBw) [Answer] # [C (gcc)](https://gcc.gnu.org/), 49 bytes ``` z(f,a,b,n)int*a,*b,(*f)();{for(;n--;f(a++,b++));} ``` [Try it online!](https://tio.run/##PU/LTsMwELz7K0ZFlbz2hkcJCMktP1L1YDsYLIGDSttDI3972LSEPXhWOzPrndi8xziOZ53Yc@BCuRyMZxNYm0Sa3JD6vXalaVzS3loO1hK5Ot7kEj@P3RvWP4cu97cfr0qd@twhHUvUsgWyBhcMpAYFKeOxgZbXSEuw0gfcYUVOVaUm7ZfPRc/yaeC37U5MA54ZL4wHxiOq@6fDTD8JwZNoNdMSSS5hyBWB0dJ1KmlwuS6L7d4JrNEKSCpcf53qey@SpBfLjrGQFdu8@/NXVcdf) Loops for `0-n`, applying `f` on `&a[i], &b[i]`. Fairly simple. Ungolfed signature: ``` void zipwith(void (*blackbox)(int *, int *), int *a, int *b, int length); ``` This version expects a function like this: ``` void func(int *a, int *b) { *a = *a OP *b; } ``` It overwrites the contents in `a`. Since this is a pretty loose interpretation of the rules, I have also provided a more strict version which acts like a normal `zipwith`. # [C (gcc)](https://gcc.gnu.org/) strict, ~~61~~ 54 bytes ``` z(f,a,b,n)int*a,*b,(*f)();{for(;n--;*a++=f(*a,*b++));} ``` [Try it online!](https://tio.run/##PU/LTsMwELz7K0ZFSH5seJSAkNzyI1UPdlIXS62LQnIh8reHdULYy1iex@401blppulHBnLkKamYeu1Ie5I6KKnsGG6dtKmqrHbG7IOcWWOUsnm6i6m5DO0Ju@@@jbeHzw8hOABhSI0sD0co4JUYBXi6Uz90CdJBwykYSI9HbJUVeXFeXUxyVc8Jh/qIPUa8Ed4Jz4QXZPtP@5V@ZYKKaLvS3InPoHKDJ9Rq@eU6mE@LbHuyDDvUDNwIy9YyXx1Lgtzct4QNRxzi8c@fRZ5@AQ "C (gcc) โ€“ Try It Online") Loops for `0-n`, storing the result of `f` on `a[i], b[i]` to `a[i]`. Fairly simple. Degolfed signature: ``` void zipwith(int (*blackbox)(int, int), int *a, int *b, int length); ``` Thanks to @att for reminding me I don't need a separate output array, saving 7 bytes. [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` ฮดm ``` [Try it online!](https://tio.run/##AS0A0v9odXNr/@KCgeKCgv/OtG3/fivilqHDtzL//1s2LDgsMSwzXf9bNSwzLDYsMl0 "Husk โ€“ Try It Online") (Implement the function in the footer, the header passes it to the main code) Sure, Husk has a trivial builtin solution for this (`z`), but here's the shortest interesting solution :) `ฮด` is a higher order function that turns something using an unary function on elements of one list into one using a binary function on elements from two lists. Here, we turn the map function `m` that applies the (unary) input function to each element of the input list into one that applies the (binary) input function to each pair of elements from the two input lists: exactly what zipWith should do! [Answer] # x86-16 machine code, ~~15~~ 14 bytes Saved 1 byte thanks to @Joshua! ``` AD 50 87 F3 AD 50 87 F3-FF D2 AB E2 F3 C3 ``` Callable function. Inputs: * `CX` = lengths of both lists * `[SI]` = address of first list * `[BX]` = address of second list * `[DX]` = address of function Outputs towards `[DI]` = address of output list (buffer needs to be large enough). Disassembly: ``` LoopTop: AD LODSW ; AX = [SI], SI+=2 50 PUSH AX ; push AX onto stack 87 F3 XCHG SI, BX ; swap SI and BX AD LODSW ; AX = [SI], SI+=2 50 PUSH AX ; push AX onto stack 87 F3 XCHG SI, BX ; swap SI and BX FF D2 CALL DX ; call function at [DX] ; the function should take two items on the stack ; and AX = the return value (stock calling convention) AB STOSW ; [DI] = AX, DI+=2 E2 F3 LOOP LoopTop ; --CX; jump to top of loop while CX >= 0 C3 RET ; return to caller ``` ## Example run Tested with DOS debug: ``` -r AX=0000 BX=0040 CX=0003 DX=0060 SP=FFFE BP=0000 SI=0030 DI=0050 DS=1000 ES=1000 SS=0B17 CS=1000 IP=0000 NV UP EI PL NZ NA PO NC 1000:0000 AD LODSW -u1000:0060 1000:0060 58 POP AX 1000:0061 A37600 MOV [0076],AX 1000:0064 58 POP AX 1000:0065 A37800 MOV [0078],AX 1000:0068 58 POP AX 1000:0069 01067800 ADD [0078],AX 1000:006D A17600 MOV AX,[0076] 1000:0070 50 PUSH AX 1000:0071 A17800 MOV AX,[0078] 1000:0074 C3 RET -t AX=0004 BX=0030 CX=0003 DX=0060 SP=FFFF BP=0000 SI=0042 DI=0050 DS=1000 ES=1000 SS=0B17 CS=1000 IP=0001 NV UP EI PL NZ NA PO NC 1000:0001 50 PUSH AX -t AX=0004 BX=0030 CX=0003 DX=0060 SP=FFFD BP=0000 SI=0042 DI=0050 DS=1000 ES=1000 SS=0B17 CS=1000 IP=0002 NV UP EI PL NZ NA PO NC 1000:0002 87F3 XCHG SI,BX ... -t AX=0009 BX=0036 CX=0000 DX=0060 SP=FFFF BP=0000 SI=0046 DI=0056 DS=1000 ES=1000 SS=0B17 CS=1000 IP=000D NV UP EI PL NZ NA PE NC 1000:000D C3 RET -d1000:0000 1000:0000 AD 50 87 F3 AD 50 87 F3-FF D2 AB E2 F3 C3 00 19 .P...P.......... 1000:0010 00 00 00 00 00 00 00 20-20 20 20 20 20 20 20 20 ....... 1000:0020 20 20 20 20 20 20 20 20-20 20 00 00 00 00 00 00 ...... 1000:0030 01 00 02 00 03 00 00 00-00 00 00 00 00 00 00 00 ................ 1000:0040 04 00 05 00 06 00 00 00-00 00 00 00 00 00 00 00 ................ 1000:0050 05 00 07 00 09 00 00 00-00 00 00 00 00 00 00 00 ................ 1000:0060 58 A3 76 00 58 A3 78 00-58 01 06 78 00 A1 76 00 X.v.X.x.X..x..v. 1000:0070 50 A1 78 00 C3 00 0A 00-09 00 00 00 00 00 00 00 P.x............. ``` [Answer] # [Rust](https://www.rust-lang.org/), 34 bytes ``` |f,a,b|a.into_iter().zip(b).map(f) ``` [Try it online!](https://tio.run/##PY1BCoMwEEX3PUV0NQMxi7qRqOktuikiMSQQiFFs2kWNZ7cJhcIM83h8/myvZziNJ7O0HnB3OhDDjYc0YOsrTYtYiYx3rbp0xR@SH0l/RkMlnaJk1odltEFvgOxjV5iQzXIFg2d7ycVvrUhPDERIeYyymmhSxaOh9fCjmjYDMrU4p1XgvMufRiEA28u6pXrnCyh3fjvKnE/2OL8 "Rust โ€“ Try It Online") Rust doesn't have a `zipwith` function but it does have a `zip` and a `map` function. Returns an iterator over the values. [Answer] ## **GNU-C-Preprocessor, 90 + O(48\*n) Bytes** There should be code golf challenges for C preprocessor only, my idea: ``` #define T(x,...) x #define D(x,y...) y #define A(f,x,y) f(x,y) #define Z5(f,x,y) A(f,T x,T y),Z4(f,(D x),(D y)) #define Z4(f,x,y) A(f,T x,T y),Z3(f,(D x),(D y)) #define Z3(f,x,y) A(f,T x,T y),Z2(f,(D x),(D y)) #define Z2(f,x,y) A(f,T x,T y),Z1(f,(D x),(D y)) #define Z1(f,x,y) A(f,T x,T y) ``` This example works for input lists of length <= 5. You can call the function like this: ``` #define C(x,y) x##y (Z5(C,(h,e,l,l,o),(w,o,r,l,d))) ``` which results in ``` (hw,eo,lr,ll,od) ``` The "n" is the maximum list length to process and output. Of course you could use single characters instead of "Z" as name but using a digit allows for more flexibility and easier maintenance. For example you could add a parameter for "Z" to specify the bounds which is concatenated as `Z##n` and used as nested macro call. The C Preprocessor opens a new realm of languages for code golf and is a rather minimal pure-functional primitive-recursive programming language which only features macro substitutions (which look like function calls, '(', ')', ',' and '#' are the only characters with special meaning), stringification, character concatenation (must be result in valid C tokens) and no direct recursion (each call must be defined with different macro name). Primitive-recursive means, it uses inputs of strictly bounded or fixed lengths and the program always terminates for all inputs. If you want a program for unbounded length, you would need an infinite program but program inputs are always bounded in practice. Literally any strictly limited output for strictly limited input values can be programmed by a primitive-recursive program and thus the C preprocessor. The program only must be big enough to compute it. It can become quite memory-inefficient though. --- ## GNU-C Preprocessor, 238 + O(32\*log3(n)) Bytes A more optimal program size with O(log(n)) program growth is possible but requires hacky additional macro definitions and will only pay off starting with slightly larger input lists. This example purposefully does not add commas between elements in the output to allow for higher flexibility in output. ``` #define L4(p) L3(p) L3(p) L3(p) #define L3(p) L2(p) L2(p) L2(p) #define L2(p) L1(p) L1(p) L1(p) #define L1(p) p() p() p() #define T(x,...) x #define D(x,y...) y #define I(x...) x #define W(r,f,a,b,x,y) (I r f(a,b)),f,x,y #define X(r,f,x,y) W(r,f,T x,T y,(D x),(D y)) #define Y(x...) X(x) #define C() ) #define O() ( #define U(x...) T(x) #define Z(f,x,y) U(U(L4(Y O)(),f,x,y L4(C))) ``` Explanation: * `L<x>` is the loop and `<x>` is the exponent of how often to loop. * `T,U` = take first element from comma-separated list * `D` = drop first element from comma-separated list * `I` = identity function (evaluates arguments and can remove parens) * `A` = applies a function but **without lazy argument-evaluation** * `X,Y,Z` = the actual zipWith function * `C` = closing parenthesis, needed for code generation * `O` = opening parenthesis, needed for code generation (prevents unclosed macro call errors) The main idea is to code-generate a long nested expression in a loop so that `Z(args)` evaluates to literally `Y ( Y ( Y ( ... args' ...) ) )` and `Y` reduces the arguments by one step when evaluated in `U(U(...))` (it does not work with only one `U`). This example can process up to 3^4 = 243 elements of two lists. If you want to multiply the processing limit by 3, add a new loop line on the top of the code. You need about 20 loop lines to handle unsigned 32-bit of elements. But keep in mind that each element is evaluated, even if does not exist! This is an example which zip-concatenates elements of two lists and places a comma between elements *iff* the concatenation is not empty: ``` #define V2(x...) ,##x #define V(x...) V2(x) #define CONC(x,y...) y##x #define CONC1(x,y) V(CONC(y,x)) #define D2(x) (D x) D2(Z(CONC1,(h,e,l,l,o),(w,o,r,l,d))) ``` The result is `(hw ,eo ,lr ,ll ,od)` . It works with any lists with any number of elements but will output at most 243 elements. Tested on [godbolt.org](https://godbolt.org/). If you find improvements which aren't only shorter macro names, please feel free to update this answer and leave a comment. [Answer] # [R](https://www.r-project.org/), 32 bytes ``` function(f,x,y)Vectorize(f)(x,y) ``` [Try it online!](https://tio.run/##RYzRCgIhFETf@wof76WJUClkwd/oMdyVlYRYQ4xqo283C9qeBs6cmVzneLnFcrI1XCdfYpoo4I4HH0ZfUo7zSIHpA34mOWsdZKehO8mrhW4cPBlobqFh@F8tzz0GfoZzSpn6o1oPW8WvZu8hDISE@G53LSEaU8z1DQ "R โ€“ Try It Online") If [R](https://www.r-project.org/) *didn't* already have a built-in (`mapply`/`Map`) for zipwith, here's how one could implement it in 32 bytes... (...and if [R](https://www.r-project.org/) *didn't* have `Vectorize`, we'd need to implement it the 'hard' way for [54 bytes](https://tio.run/##RY3BCsIwEETvfkWOWRyRJCihkr/oTZS0xWBAWq0VU6XfHhfBetkHMzu8Pr/i9RmHs8vh0TZD7FoZkDDSO3S9jCK24n66ycolonIfDy7IxMDIh3bl9NtL75yHKgxMoWgxpyuPRloYYhhY@lezr0LNtkvHvuqol/Va08TfWwgLoSC@2w0TgjNNlD8): `function(f,x,y){for(i in seq(a=x))T[i]=f(x[i],y[i]);T}`) [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` mFโ‚Te ``` [Try it online!](https://tio.run/##yygtzv7/P9ftUVNjSOp/7f//o41NdIx0jGKBDCBtGAsA "Husk โ€“ Try It Online") Takes the two arrays as arguments, and the function in the footer. You can use any binary function which operates on two `TNum`s from [Husk's Commands page.](https://github.com/barbuz/Husk/wiki/Commands) ## Explanation ``` mFโ‚Te Main program: accepts two arrays e two element list from the arrays T transpose m map each pair to F itself folded by โ‚ the black box function ``` [Answer] # [Factor](https://factorcode.org/), 24 bytes ``` [ zip swap f assoc>map ] ``` [Try it online!](https://tio.run/##Jcy9CsIwFIDRvU/x7YLg71DBVbp0EafS4RJSWkzbcHNBVPrsseB2ptOJs1nz417VtxJJaXaJp9fJB0axnqje7B11mIxLUdUlyamY64uGDS1fduw5sKw6cuLMkhs@QyS9JNL9z@u4us1OQmCLC140/wA "Factor โ€“ Try It Online") Avoids the obvious built-in `2map` and its trivial generalizations `nmap` and `2map-as`, and uses `zip` and `assoc>map` instead (so it works like e.g. the [Rust answer](https://codegolf.stackexchange.com/a/218037/78410)). Takes the input from the stack in the order of `func arr1 arr2`. Small golfing tip: when using a function that takes an "exemplar" (which specifies the type of the output container), supplying `f` has the same effect as supplying `{ }` (a plain array). ## [Factor](https://factorcode.org/), using `nmap`, 10 bytes ``` [ 2 nmap ] ``` [Try it online!](https://tio.run/##Dcg9DoJAEAbQnlN8vQmJvwUewNDQGCtiMZmMsnEZYHYslHj2dbuX9yD2yfLt2naXBi8xlYiRfMBs4v6ZLagjyfIWZUn1U1SMYviSh0kTzlXbNUhs5DxUK7bYYY8fVhxwxKmoxwb33JfXkeZCphhRg6OQ5T8 "Factor โ€“ Try It Online") `nmap` is a generalized version of `map`-family of functions that works with `n` input arrays and `n`-ary functions. Obviously, `2 nmap` works on two input arrays and binary functions. ## [Factor](https://factorcode.org/), using `2map-as`, 13 bytes ``` [ f 2map-as ] ``` [Try it online!](https://tio.run/##DccxDoJAEAXQnlP8nmgCqAUcgNDQECtiMZkMwbAsy@xYGOLZV7r3JmLbND2Hrm9rLKJeHFayGUHF7Bv07Q1R9o94logm6/oakZWM5@xAgRIVfjhwwx2PUyNyvNKICeVK4ULxHJNzuIKdkKY/ "Factor โ€“ Try It Online") `2map-as` is a simple variation of `2map` that takes an exemplar. `2map` itself is already listed in the [trivial built-in catalogue](https://codegolf.stackexchange.com/a/218018/78410). [Answer] # [GNU sed](https://www.gnu.org/software/sed/), 55 + 1(r flag) = 56 bytes GNU sed doesn't even have integers, not to mention functions, lists / arrays, etc. In order to participate, I used the following assumptions for the I/O methods, which hopefully respect the consensus regarding sed: 1. each input list / array is given on a separate input line, with the integers separated by space. 2. the black-box function is predefined under the label `f`. 3. the black-box function arguments are two space separated integers read from the first pattern space line (generated there at runtime during each iteration). 4. the return value of the black-box function is placed on the first pattern space line 5. the output list / array is given as one integer per line. ``` 1N # read the 2nd input list s:([^ ]+) ?(.*\n)([^ ]+) ?(.*):\1 \3\n\2\4: # put list1[i] and list2[i] on first line tf;: # call the black-box function `f` P # print the function return value D # delete return value, start new iteration ``` [Try it online with sed 4.2.2!](https://tio.run/##TY2xDoIwFEVn@hU30QEwEgq4PEJcXFyMu5UEpEQSKU1bft8KJiZu59zhXCs77/mFWQpvNe67CMcwiYWK/jUiwSFyoUQmCmKuL4ldy5PfNKgqtAnOSs@OkMHq5iFhpW5M42QHNY@tNBaTgntK9IOxDq9BSUY9CyzVvxvBt8RpZIFb5ySm9CueL9EcBQ5IWb4wR7rye9JumJT1e/MB) The implemented black-box function in the link above is `a == b`. The other test functions are significantly harder to implement in sed, but possible since the language is Turing complete. [Answer] # JavaScript (ES6), 32 bytes ``` (F,a,b)=>a.map((x,i)=>F(x,b[i])) ``` [Try it online!](https://tio.run/##fZBPT8JAEMXvfop3kUxh@2/bAjEuHki4@QmaHnaRSqV0GyDGb1@no2g8yGnfzsx788u82Xd73p6a/hJ2/mU31GagjbLKBWZlo6PtiT5Uw58Nv65sqiAYtr47@3YXtf6VaiKr4AKYFWZkYQx/FMpUQStkFctMZMpOxDHKhLVCUt39F2MRwrFv@etfXs2FQljcsk6n0Jjh2V72Ud16fyKHGHpEmnOO7JZUTuJgrulrdsbdOZdzHmK8ft/AgDqFA7@d5B/CEJMJaD12frY6PGFNjGxxP5YeWDzyTvEGTMNRX/oWuEzJ7XI5WCG4wroQ0DT5e0idC6tOvgeHTw "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 24 bytes ``` for 1 2 (`paste $@`)f $@ ``` [Try it online!](https://tio.run/##qyrO@J@moWljY6MSrWKorWIUy2Vj42jnyGXIZcRlzOUI5DnZOXGZcJlymXE5cRWnlig4Kjj9T8svUjBUMFLQSChILC5JVVBxSNBMA5L///8HAA "Zsh โ€“ Try It Online") Uses a [black-box function named `f`](https://codegolf.meta.stackexchange.com/a/13707), with input from two files specified in command line arguments. However, `paste` alone is really just a `zip`, and this brings up some interesting debate depending on your interpretation of what counts as a "function" under the Unix philosophy of "everything should be a text stream": ``` #!/bin/zsh # using a predefined function F z1() { paste $1 $2 | F } # using a function named in the arguments z2() { paste $1 $2 | $3 } F() { while read line; do rev <<< line; done } z1 input1 input z2 input1 input2 F paste input1 input2 | F paste input1 input2 | rev # so maybe paste is just a point-free function? paste ``` So maybe this is a trivial built-in solution: **Unix shell (?), 5 bytes (?)** ``` paste ``` [Answer] # Java 8, 52 bytes ``` A->B->{for(int l=A.length;l-->0;)A[l]=f(A[l],B[l]);} ``` Puts the result in the first argument instead of returning a new integer-array (to save 25 bytes). [Try it online.](https://tio.run/##vVTBjtowEL3zFb5UsjeOl8BCUbNOy1btrdrD9oY4OMGhZo0TOQ4VQvl2aifZFCq0WlroZTz2jMfvvbG9YhvmrxbP@0SyogDfmFC7HgAsLoxmiQGFYUYkoIl@54VxUQAe4xW30RS2DsOtE6MmAQDNTakVFMog5tVDHNahqra1yctY2uorC4KURkiSlioxIlPka@vcN3Vnc3wq63OminLNdZcVRSABdD/1owc/2qWZdgcDSadEcrU0P0Lp@1E/RNOZnNMUugE/WIPCau8AOYRVr9cha@lvMrEAa6sNfDJaqOVsDpheFuhQDLcGKFD8Z7ewC/AAD6uGtgs4AWGn0KfHDddaLHg7f4Oor8j6ImxFEsLyXG4hQ4QlCc8NPAJ1h0d4XKFm19O2MHxNstKQ3DIzUsHfOk@1ZtuCmKxhbQvaXfW2/8cUMErPZTi0YIJLM5xcs5P@X3VyiCeXZjnGExxck@nN0dW9HZxJeYSHeIwHl6Z9Z2/MCF@1xTdfSsk1bHijY9oAuG@qSXCeOqjh5poGYbfw8qsJOgjFvQqF56EuaPNTuEwWUGCFKA0OIxaP54V/vi99CkpdQTlWzp5@lf2P8QeXF79jmKEz@/jedjHo/9s7dYdV@18) **Explanation:** ``` A->B->{ // Method with two integer-array parameters & no return-type for(int l=A.length;l-->0;)// Loop `l` in the range (length,0]: A[l]= // Change the `l`'th item in the first array to: f( // Call the black-box function `f` A[l],B[l]);} // with the `l`'th items of both arrays as parameters ``` **Black box input format:** Assumes a named function `Object f(Object a,Object b)` is present, which is allowed [according to this meta answer](https://codegolf.meta.stackexchange.com/a/13707/52210). I have an abstract class `Test` containing the default function `f(a,b)`, as well as the lambda above: ``` abstract class Test{ Object f(Object a,Object b){ return(int)a+(int)b; } public java.util.function.Function<Object[], java.util.function.Consumer<Object[]>>c= A->B->{for(int l=A.length;l-->0;)A[l]=f(A[l],B[l]);} ; } ``` For the test cases, I overwrite this function `f`. For example, the third test case (which is responsible for the black-box having `Object` as parameters/return-type instead of `int`) is called like this: ``` Object[] a = new Object[]{1,2,3}; new Test(){ @Override Object f(Object a,Object b){ return a==b; } }.c.apply(a).accept(new Object[]{3,2,1}); System.out.println(java.util.Arrays.toString(a)); ``` [Answer] # [Nim](http://nim-lang.org/), 71 70 bytes ``` iterator z[I](f:proc(x,y:I):I;a,b:seq):I= for i,x in a:yield x.f b[i] ``` [Try it online!](https://tio.run/##jY@7jsIwEEV7vuKW9jIg8RQyCqJNvWWUwgYHRgIMjlkFfj47BNFQpZqr0ZyjOxc@ty0nH20KEc8iL1VlrjHsVEMPk2uTry05U/ubxGyASq6YGvAF1jzYn/ZoxhVcwWXL52uICXJ7T3yqCfX9YOPA744BKfz6m3oqZY2wieC6qZFtYDGEI2yLCWFKmJWvPCcsCMtS6z6C0VuwEqijBV31QmUqiyyD098NZl2e9Gvw0z2BPf@9oG2xlAICf1zSR3SynIqu/Qc "Nim โ€“ Try It Online") [Answer] # [Idris](https://tio.run/##y0wpyiz@/7/KSiNR1y5J1y5ZU9fOJ7O4RCERSidB6WSuKoU0jQorqzJNjUorq3JN2zSFCgUgCyisUKZQDpSOB0Hb6Nj/uYmZeQpWCp7@ChqaXGCOrUJBUWZeiYKKQpWChramQrShnp5xrEK0iZ6eWex/AA) - 77 bytes ``` z:(a->b->c)->List a->List b->List c z f(x::v)(y::w)=f x y::z f v w z _ _ _=[] ``` [Answer] ## Stax, 6 bytes invocable, or 3 bytes toplevel Does not make sense to compress functions in stax so I didn't. The two arrays are passed on the stack, and the black-box function is passed in the x register. ``` |\{x!m ``` Explained: ``` |\ Zip input arrays { x push contents of x register ! invoke top of stack m map ``` Program head version: two arrays are passed to it on the stack; body of blackbox program follows ``` |\m ``` Explained: ``` |\ Zip input arrays m map array with rest of program ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 11 bytes ``` Inner[##,]& ``` [Try it online!](https://tio.run/##Vc29CoMwFIbh3asIBLL0SJtYfxaLSwvdhI6SQhBFQSNIOoV46@mxKYWe5SwP3zsrM3SzMmOrfF/6u9bd2lAKkvl6HbVpaHzpq4pKtj1apTcbWVqWVDDyOyCWg4DEgU3wc@cAUfxndlR8SRHAUxxu07JgTRyFZAgyKIB/UAoJZCACJNfX1K31MKKUZIdnzKQQ9nKE/BS6kfNv "Wolfram Language (Mathematica) โ€“ Try It Online") Returns a `Null` of results. [`Inner`](https://reference.wolfram.com/language/ref/Inner.html) *almost* does zipwith - except, by default, it returns the sum of the results. --- ### Also 11 bytes ``` #@@@In@@#2& ``` [Try it online!](https://tio.run/##Vc09C4MwEAbg3V8RCGTpSZtYPxZLlha6CR3FQhBFQSNIOoX419OrDYXechzvw72zMkM3KzO2yvelp1LKu5aSCuarddSmpvGlx7th26NVerORpWWJMfkNEGs5CEgc2AQ3d84BsvhP7awIqAjkKQ63aVnWmoqjaNiHZFAA31kKCWQgAiXX19St1TCibchOz1iWwvdnjpSfQnvk/Bs "Wolfram Language (Mathematica) โ€“ Try It Online") `In` (among others) is as short as a built-in `Listable` function gets, and remains unevaluated with >1 argument. [Answer] # [Red](http://www.red-lang.org), 69 bytes ``` func[a b f][collect[repeat i length? a[keep compose[(f a/:i b/:i)]]]] ``` [Try it online!](https://tio.run/##dc@xCoMwFAXQ3a@4o7aDqFXExX/oGjLE5FlDU001Uu3P2yBOQt9w73K48EZS250U48FX2492XYWtnXvJBBq0nMnBGJKOjWRJOGgY6h@uqyHYk8hCDi87TMTCFiKuNBofEfe32VH3DscqWIIUGQe7IUfBUQmlgj8k8514Qu9ZmPqsysOUXkxz40Yh3dkUKJHsLkeGAinH/tSClfu4YMEV4YoYacS3Hw "Red โ€“ Try It Online") ## Printing the result instead of returning it: ## 61 bytes ``` func[a b f][repeat i length? a[print compose[(f a/:i b/:i)]]] ``` [Try it online!](https://tio.run/##dc@xCoMwFAXQ3a@4o7aDqFXExX/oGt4QTawBq2mMVPvzabBOQpf7hnt4cI0U7i4Fo@Cj9FvZvoLrlrFlHA06YkZqyS0UBjk@bF@DM23UaNFOTz3NkoUdeFwpND4iInK/@vgGliBFRmA35CgIFRci@EMyfxNP5GvhQ31W5WFKL@alsYa39mwKlEh2lyNDgZSwj1mxkY8LVlwRboiRRuS@ "Red โ€“ Try It Online") [Answer] # [Racket](https://racket-lang.org/), 41 bytes ``` (ฮป(x y f)(for/list([i x][j y])(f i j)))) ``` [Try it online!](https://tio.run/##hY8xDoJAFER7TjGJhf9LCAGE0HgSQrEBVhc3QBYSF6/mHbwSbhBL4lQzkzfFGFHdm2k5aNFdYdbgUd1I1TV4quGhpttC7xdZzJBMsjehVuNEhYItixZz6UootOy0UK3GQYtZd6BtjSNFiJGwM2ekyBg@s/eHTJyJGJddMv9xOSPYpTLkiL5kigQZYsb2hqmxopoCqfvekE8nWFim0P2MeRWWDw "Racket โ€“ Try It Online") `for/list` is almost the necessary builtin, just needs some additional syntax. [Answer] # Scala 3 (compile time), 87 bytes ``` type Z[F[_,_],A<:Tuple,B]<:Tuple=(A,B)match{case(a*:b,c*:d)=>F[a,c]*:Z[F,b,d]case _=>A} ``` [Try it online!](https://scastie.scala-lang.org/T4sTqG2OSGyUVe3yjvRtog) Takes tuples instead of lists. This isn't particulary interesting or complicated, but here's an explanation: ``` type Z[ //Declare a type Z taking these arguments F[_,_], //A type F that itself takes two arguments A <: Tuple, //The first list, a tuple B //The second list (actually also a tuple) ] <: Tuple = //The returned type is also a tuple (A, B) match { //Make a tuple (A, B) and match it: //`h*:t` represents a tuple with head `h` and tail `t` (like :: or :) case (a *: b, c *: d) => //If A is of the form a*:b and B is of the form c*:d F[a, c] //Call F on the heads *: //And prepend that to Z[F, b, d] //The result of zipping the rest of the tuples case _ => A //Otherwise, both tuples are empty, so we return an empty tuple } ``` [Answer] # Pure [Zsh](https://www.zsh.org/), 31 bytes ``` b=($=3) for 2 3 (${${=2}:^b})$@ ``` [Try it online!](https://tio.run/##TY7RCoJAEEXf5ysuNrC7hQ9q9RAu9B9R4GKhD7WiRqD47duqYTIwD@feOUzXFK4rq0/ZFlJJVHX5ahH64QgbPGyN/P60zmjJOlE0ghgJJPfc63g43cyg@OwUUZbnUiFNU7742x04vhI1b7OC4Qyr2q6r25lmWkSjW5DRYo8DjoLo9xq8HAFngV8mWKi3T2CKFjrq/2X3BQ "Zsh โ€“ Try It Online") Takes parameters `function name, space-delimited list, space-delimited list` With `-o shwordsplit`, one byte is saved with `b=($3)` instead. ``` b=($=3) # =split $3 and save as array $b # ${${=2}:^b} # Zip $=2 and $b together for 2 3 (${${=2}:^b}) # Loop over 2 at a time as $2 and $3 (argv[2], argv[3]) $@ # $1 $2 $3 ``` [Answer] # [Groovy](http://groovy-lang.org/), 36 bytes ``` {f,a,b->[a,b].transpose().collect f} ``` [Try it online!](https://tio.run/##ddDNDoIwDADgu0/Ro0gBAUE8wGt4WHYYBpSEABnTgMZnxw4XfxLtoema9EvXo2zbyzhdq25fqVM63UoUmDsZo8xdJUXTd21fLC330NZ1cVBQ3qdOVo2qGzBTy9uAo5MN9nhH0MF8hAAh5AhsgxAhxNwCE54HjDpbhB1f/JHS1FCfUjiX/rdUirovEJQ8U54ff1HntV7yFHVJaPIW3@s50Q9nvoxYCTv3ArJYTMO0kdmPpkijXqBB7YSJq/8e6Ux38Nd8egA "Groovy โ€“ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~37~~ 35 bytes ``` lambda f,*a:[f(*t)for t in zip(*a)] ``` [Try it online!](https://tio.run/##fVHBbsMgDL3zFT5CitSmWbcqEl@S5eAsSYO6ACJE0/bzmUFIaTVpvoCe7ff8bPcdJmuq7Ue7Lx0m9b594tz1CKMssG5GXgQxWg8BtAEq4gWKdhu9nWHGMIGenfUBbh89S6B1g8dADTmxrB1j/TCCmzQ3omZAgbNdTQAFJ8iR4KhzjzoezW3gpQQDByhzUww9RiVuJNwFKAXlnnrgPVAi4X4IqzcZZiwMS1hIteHZI8qu1iZwVKoTEhpSPEuoWvpW6Vu2Qu4KnMxQ6rqXXJ/zD7SABdLw3fFINM0rlRJbbrzQK4Gw8z/tUKSVpble0jCXRJIY3lJ7efo7ZMtYOhdZjZtMluunLTsfLed703mpQojtFw "Python 3 โ€“ Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 93 bytes ``` function Z($F,$S,$R={,$args}){[Linq.Enumerable]::Zip($F,$S,[Func[Object,Object,Object[]]]$R)} ``` **Example** ``` Z (1,2,3) (4,5,6) {param($a, $b) ($a+$b)} '-' Z (8,3) (3,8) {param($a, $b) ($a-$b)} '-' Z (6,8,1,3) (5,3,6,2) {param($a, $b) ([math]::pow($a,2)+$b/2)} '-' Z (1,2,3) (3,2,1) {param($a, $b) ([int]($a-eq$b))} ``` [Try it online!](https://tio.run/##bY5BC4JAFITv/oo9LOTSs1BTROhYpyCom8seVtlyQ1czo4P42@0lRUWdhjd882bq6qaaS66KYhgOV5O1ujIkseka6B7obtkBlc3x0rOOb7Q5z1bmWqpGpoUScZzo@knyNWb5Nj2prIUv4UIIumP9kBDbBQ98RuwFBBAy0tWykaVNJRCaok3lFLW3Js7EQjoaWR@if6TzSYYQgTvSAfgQgveb4KVsc5xcV7eH6TGsmnvvF69pPqr7J65NKx616ow3xoY7 "PowerShell โ€“ Try It Online") It is a zip function which can take map expression as its third parameter to know how to pass it then see the demo in the Try it online "Footer" section how to use it. [Answer] # [Python 3](https://docs.python.org/3/), 19 bytes ``` lambda*l:[*map(*l)] ``` [Try it online!](https://tio.run/##fVHLboMwELz7K/ZoO5YSkqaJkPwllIMpEKzgh4xR1f48XbtUJKrUvWDN7MzuLP4zDs6eli/tP3Qc5NsyKtO0io9lxY3ylI@sXvrgDBgVB9DGuxDh9t6SDDrfBRVd@CWmuSGk7Xrwg6aWlQSwlHGzjSDhAGtluEfZHbSFoOyto4UACzsoVlEq3adJ1Aq4M5ASio168N0hkfHQxTnYFSYkdlOccGpFfzKBEk2pbaRKyoYJqHDiUcCpxucpP4uaiW0CxTBIXbeW6zP/YAuKK1y@2e/RpnrFVnRbhWf8CkDs@I8ceD5Z3uslL3POJtnhkuXF4e@SNSHpjClqumSOXD5d2YcUef2/lKcOxpZv "Python 3 โ€“ Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes ``` ยฃZฦ›ยฅR ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%CE%BB%2B%3B%C2%A3Z%C6%9B%C2%A5R&inputs=%5B1%2C2%2C3%2C4%5D%0A%5B3%2C4%2C5%2C6%5D&header=&footer=) I don't know how to input functions properly in Vyxal, so the Vyxal interpreter link just has the function stuffed with the code. ``` ยฃZฦ›ยฅR ยฃ Set the register to the blackbox function Z Zip the two lists ฦ› For each element of that R Reduce using ยฅ The function in the register ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-xp`, 5 bytes ``` aMZbc ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhTVpiYyIsIiIsIiIsIi14cCB7U1FhK0hWYn0gWzY7ODsxOzNdIFs1OzM7NjsyXSJd) ### Explanation This is essentially a built-in, the ternary `MZ` (map-zip) operator. However, I'm pretty sure a bare operator isn't a valid solution, so I've made it a full program. The `-x` flag allows functions and lists to be evaluated as such when passed as command-line arguments, and the `-p` flag means lists will be output in list format rather than concatenated together. [Answer] # [Icon](https://github.com/gtownsend/icon), 52 bytes ``` procedure z(a,b,f) write(f(a[i:=1to*a],b[i]))&\y end ``` [Try it online!](https://tio.run/##ddDBTsMwDAbge57CFAklmyPUlFXVpj4Az1ByyNpkRCoJShpo9/IjlEmgSZx88Gf9tm3v3eXyHnyvhxQ0nKnCIxpGPoOdNDVUdXbflpPfKInHzkrGHl4Wot3wZ8g4OuPCCAAEPaXgYN7MsIXlUXxLQn7pm7KOrvJMuxIFVhK7J9xhLbHYFuwAP8EF57y4dVWuZXbtrcvsHp7zKfCqIpy8Gvlgg@4nPYD@UGNSk81NDt6NC4hWgI0QU9/rGE0a4e4a1FxjmhzC/1mmxgbL1e2wwhqFROPY@pEv "Icon โ€“ Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 8 bytes ``` l'.l++~p ``` [Try it online!](https://tio.run/##S85KzP3/P0ddL0dbu67g//9oQwUjBeNYhWgTBVMFs1iuau1aAA) Or verify the first three cases: [1](https://tio.run/##S85KzP3/P0ddL0dbu67g//9oQwUjBeNYhWhjIG0Yy1VtWwsA), [2](https://tio.run/##S85KzP3/P0ddL0dbu67g//9oCwXjWIVoYwWLWK5q3VoA), [3](https://tio.run/##LcrRCkAwFAbge0/xlwtli0zkXUZapkxHnWIk8erjwvX3DbNZQqAkIyEeDkHXaFCg7KArlKihuuhq@7RVubgxxlgPwxLWM7nBbKPE4mlzTKf8if06QX3F7c5@bqx9AQ). Input is a line with (the string representation of) two arrays, and then a line with (the string representation of) the function, defined as a CJam block. ### How it works ``` l e# Read line containing the two arrays '. e# Push character "." (which will do the actual job) l e# Read line containing a code block ++ e# Concatenate twice ~ e# Evaluate as CJam code p e# Print ``` ]
[Question] [ Given a positive integer `N`, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by `N`. The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. `080` is not the valid answer for `16`. The input will never be a multiple of 10, because of the previous reason. Your program may take as much time as necessary, even if in practice it would be way too long to output the answer. ### Inputs and outputs * You may take the input through `STDIN`, as a function argument, or anything similar. * You may print the output to `STDOUT`, return it from a function, or anything similar. * Inputs and outputs must be in the decimal base. ### Test cases ``` N Output 1 1 2 2 16 272 17 272 42 252 111 111 302 87278 1234 28382 ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # Haskell, ~~45~~ ~~37~~ 34 bytes ``` (+)>>=until((reverse>>=(==)).show) ``` [Answer] # Pyth, 7 bytes ``` *f_I`*Q ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=%2Af_I%60%2AQ&input=1234&debug=0) ### Explanation ``` *f_I`*QT)Q implicit endings, Q=input number f ) find the first number T >= 1, which satisfies: *QT product of Q and T ` as string _I is invariant under inversion (=palindrom) * Q multiply this number with Q and print ``` [Answer] # [2sable](https://github.com/Adriandmen/2sable) / [05AB1E](https://github.com/Adriandmen/05AB1E/), 6 / 7 bytes **2sable** ``` [Dร‚Q#+ ``` **Explanation** ``` [ # infinite loop D # duplicate current number ร‚ # bifurcate Q# # if the number is equal to its reverse, break loop + # add input # implicitly print ``` [Try it online](http://2sable.tryitonline.net/#code=W0TDglEjKw&input=MzAy) **05AB1E** ``` [Dร‚Q#ยน+ ``` The difference to the 2sable code is that input is only implicit once in 05AB1E, so here we need `ยน` to get the first input again. [Try it online](http://05ab1e.tryitonline.net/#code=W0TDglEjwrkr&input=MzAy) Saved 1 byte with 2sable as suggested by [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) [Answer] # **Java, ~~164~~ ~~159~~ ~~126~~ ~~108~~ 94 bytes** Golfed version: ``` int c(int a){int x=a;while(!(x+"").equals(new StringBuffer(x+"").reverse()+""))x+=a;return x;} ``` Ungolfed version: ``` int c(int a) { int x = a; while (!(x + "").equals(new StringBuffer(x + "").reverse() + "")) x += a; return x; } ``` Shoutout to Emigna and Kevin Cruijssen for contributing improvements and cutting the bytes almost in half :) [Answer] **C#, 103 80 Bytes** ``` int f(int p){int x=p;while(x+""!=string.Concat((x+"").Reverse()))x+=p;return x;} ``` **Ungolfed** ``` int f(int p) { int x = p; while (x + "" != string.Concat((x + "").Reverse())) x += p; return x; } ``` [Answer] # Python 2, 46 bytes ``` f=lambda x,c=0:`c`[::-1]==`c`and c or f(x,c+x) ``` [Ideone it!](http://ideone.com/x8gWMH) Recursive solution with `c` as counter. The case for `0` is interesting, because although `c=0` satisfies the palindrome condition, it would not be returned, because `ccc and 0 or xxx` always returns `xxx`. [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 8 bytes ``` :L#>*.r= ``` [Try it online!](http://brachylog.tryitonline.net/#code=OkwjPioucj0&input=MTIzNA&args=Wg) (around 5 seconds for `1234`) [Verify all testcases.](http://brachylog.tryitonline.net/#code=OjFhCjpMIz4qLnI9&input=WzE6MjoxNjoxNzo0MjoxMTE6MzAyOjEyMzRd&args=Wg&debug=on) (around 20 seconds) ``` :L#>*.r= ?:L#>*.r=. Implicitly filling Input and Output: Input is prepended to every predicate, Output is appended to every predicate. ?:L *. Input*L is Output, L#> L is positive, .r . Output reversed is Output, =. Assign a value to Output. ``` [Answer] # PHP, 39 bytes ``` while(strrev($i+=$argv[1])!=$i);echo$i; ``` * Takes number N as argument $argv[1]; * `;` after while to do nothing * `strrev` return string backward Same length with for-loop ``` for(;strrev($i+=$argv[1])!=$i;);echo$i; ``` [Answer] # Javascript (ES6), ~~55~~ 51 bytes **4 bytes thanks to Neil.** ``` f=(x,c=x)=>c==[...c+""].reverse().join``?c:f(x,x+c) ``` ``` <input type=number min=1 oninput=o.textContent=this.value%10&&f(+this.value)><pre id=o> ``` [Answer] ## Pyke, ~~11~~ 9 bytes ``` .f*`D_q)* ``` [Try it here!](http://pyke.catbus.co.uk/?code=.f%2a%60D_q%29%2a&input=16) [Answer] # C, ~~217~~ 189 bytes Standalone version : ``` int a(char*b){int c=strlen(b);for(int i=0;i<c/2;i++)if(b[i]!=b[c-i-1])return 0;}int main(int e,char **f){int b,c;char d[9];b=atoi(f[1]);c=b;while(1){sprintf(d,"%d",c);if(a(d)&&(c/b)*b==c)return printf("%d",c);c++;}} ``` Call to a function version : ``` int s(char*a){int b=strlen(a);for(int i=0;i<b/2;i++)if(a[i]!=a[b-i-1])return 0;}int f(int a){int b;char c[9];b=a;while(1){sprintf(c,"%d",b);if(s(c)&&(b/a)*a==b)return printf("%d",b);b++;}} ``` Ungolfed : ``` #include <stdlib.h> #include <string.h> #include <stdio.h> int check_palindrome(char *str) { int length = strlen(str); for (int i = 0; i < length / 2; i++) { if (str[i] != str[length - i - 1]) return 0; } return 1; } int main(int argc, char **argv) { int number; int pal; char string[15]; number = atoi(argv[1]); pal = number; while (1) { sprintf(string, "%d", pal); if (check_palindrome(string) && (pal / number) * number == pal) { printf("%d\n", pal); return 1; } pal++; } return 0; } ``` Call to a function ungolfed : ``` int s(char *a) { int b = strlen(a); for (int i = 0; i < b / 2; i++) { if (a[i] != a[b - i - 1]) return 0; } return 1; //We can remove it, it leads to a undefined behaviour but it works } int f(int a) { int b; char c[9]; b = a; while (1) { sprintf(c, "%d", b); if (s(c) && (b / a) * a == b) { printf("%d\n", b); //no need for the \n return 1; //just return whatever printf returns, who cares anyway ? } b++; } return 0; //no need for that } ``` I included the standalone version for historicity. This is my first codegolf, any comment is welcome ! [Answer] # R, ~~117~~ ~~113~~ ~~109~~ 101 bytes ``` D=charToRaw;P=paste;S=strtoi;a=P(i<-scan()+1);while(!all(D(a)==rev(D(a))&&S(a)%%i==0)){a=P(S(a)+1)};a ``` **Ungolfed** ``` i<-scan() #Takes the input D=charToRaw #Some aliases P=paste S=strtoi a=P(i+1) #Initializes the output while(!(all(D(a)==rev(D(a)))&&(S(a)%%i==0))) #While the output isn't a palindrom and isn't #divisible by the output... a=P(S(a)+1) a ``` `all(charToRaw(a)==rev(charToRaw(a)))` checks if at each position of `a` the value of `a` and its reverse are the same (i.e., if `a` is palindromic). It might be possible to golf out some bytes by messing around with the `types`. [Answer] # [Actually](http://github.com/Mego/Seriously), ~~15~~ 14 bytes Asked to answer by Leaky Nun. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pWWMmDilZwqJDtSPWDilZNO4pWcKg&input=MTIzNA) ``` โ•–2`โ•œ*$;R=`โ•“Nโ•œ* ``` **Ungolfing** ``` Implicit input n. โ•– Save n in register 0. 2`...`โ•“ Push first 2 values where f(x) is truthy, starting with f(0). โ•œ*$ Push register 0, multiply by x, and str(). ;R Duplicate str(n*x) and reverse. = Check if str(n*x) == reverse(str(n*x)). The map will always result in [0, the x we want]. N Grab the last (second) value of the resulting list. โ•œ* Push n and multiply x by n again. Implicit return. ``` [Answer] # Haskell, ~~64 63~~ 56 bytes ``` x!n|mod x n==0,s<-show x,reverse s==s=x|y<-x+1=y!n (1!) ``` Call with `(1!)16` or simply `1!16`. [Try it on Ideone.](http://ideone.com/qG7FUd) [Answer] **VBSCRIPT, 47 bytes** ``` do:i=i+1:a=n*i:loop until a=eval(strreverse(a)) ``` **ungolfed** ``` do #starts the loop i=i+1 #increments i, we do it first to start at 1 instead of 0 a= #a is the output n*i #multiply our input n by i loop until a=eval(strreverse(a)) #end the loop when our output is equal to its reverse ``` [Answer] # Perl, 25 bytes Includes +2 for `-ap` Run with the input on STDIN: ``` palidiv.pl <<< 16 ``` `palidiv.pl`: ``` #!/usr/bin/perl -ap $_+="@F"while$_-reverse ``` [Answer] # [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 109 bytes ``` readIO n = 0 lbla n + i a = n r = 0 lblb m = a m % 10 r * 10 r + m a / 10 if a b r - n r | if r a printInt n ``` [Try it online!](http://silos.tryitonline.net/#code=cmVhZElPIApuID0gMApsYmxhCm4gKyBpCmEgPSBuCnIgPSAwCmxibGIKbSA9IGEKbSAlIDEwCnIgKiAxMApyICsgbQphIC8gMTAKaWYgYSBiCnIgLSBuCnIgfAppZiByIGEKcHJpbnRJbnQgbg&input=&args=MzAy) [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` VยฑU s w ยฅV?V:รŸ ``` [Try it online!](https://tio.run/nexus/japt#@x92aGOoQrFCucKhpWH2YVaH5///b2hkbAIA "Japt โ€“ TIO Nexus") Thank you ETHproductions for the help! :) [Answer] # [MATL](http://github.com/lmendo/MATL), 10 bytes ``` 0`G+tVtP<a ``` [Try it online!](http://matl.tryitonline.net/#code=MGBHK3RWdFA8YQ&input=MTIzNA) ``` 0 % Push 0 ` % Do...while G+ % Add the input. This generates the next multiple of the input tV % Duplicate, convert to string tP % Duplicate, reverse <a % Is any digit lower than the one in the reverse string? This is the % loop condition: if true, the loop proceeds with the next iteration % End do...while % Implicitly display ``` [Answer] ## PowerShell v2+, 72 bytes ``` for($i=$n=$args[0];;$i+=$n){if($i-eq-join"$i"["$i".Length..0]){$i;exit}} ``` Long because of how reversing is handled in PowerShell -- not very well. ;-) Takes input `$args[0]`, stores into `$i` (our loop variable) and `$n` (our input). Loops infinitely, incrementing `$i` by `$n` each time (to guarantee divisibility). Each iteration, we check whether `$i` is a palindrome. There's some trickery happening here, so let me explain. We first take `$i` and stringify it with `"$i"`. That's then array-indexed in reverse order `["$i".length..0]` before being `-join`ed back into a string. That's fed into the right-hand side of the `-eq`uality operator, which implicitly casts the string back into an `[int]`, since that's the left-hand operand. Note: this casting does strip any leading zeros from the palindrome, but since we're guaranteed the input isn't divisible by `10`, that's OK. Then, `if` it is a palindrome, we simply place `$i` onto the pipeline and `exit`. Output is implicit at the end of execution. ### Test Cases ``` PS C:\Tools\Scripts\golfing> 1,2,16,17,42,111,302,1234|%{"$_ -> "+(.\smallest-palindrome-divisible-by-input.ps1 $_)} 1 -> 1 2 -> 2 16 -> 272 17 -> 272 42 -> 252 111 -> 111 302 -> 87278 1234 -> 28382 ``` [Answer] # MATLAB, 76 bytes ``` function s=p(n) f=1;s='01';while(any(s~=fliplr(s))) s=num2str(n*f);f=f+1;end ``` Call format is `p(302)` result is a string. Nothing clever here. It does a linear search, using the `num2str()` and `fliplr()` functions. This ugly arrangement is a touch shorter than using a `while(1) ... if ... break end` pattern. Ungolfed ``` function s = findFirstPalindromeFactor(n) f = 1; % factor s = '01'; % non-palindromic string for first try while( all(s ~= fliplr(s)) ) % test s not palindrome s = num2str( n * f ); % factor of input as string f = f + 1; % next factor end ``` [Answer] ## Mathematica, 49 bytes ``` (c=#;Not[PalindromeQ@c&&c~Mod~#==0]~While~c++;c)& ``` Starts the search at `c = N`, and increments `c` if not a palindrome and not divisible by `N`. When conditions are met, outputs `c`. [Answer] # Jelly, 12 bytes ``` ยนยต+ยณรŸยตDUโผDยต? ``` [Try it online!](http://jelly.tryitonline.net/#code=wrnCtSvCs8OfwrVEVeKBvETCtT8&input=&args=MTY) Explanation: This link takes 1 argument. The `ยต`s split it into 4 parts. Starting from the last and moving left: ``` ? The three parts in front of this are the if, else, and condition of a ternary expression. DUโผD This condition takes a number n as an argument. It converts n to an array of decimal digits, reverses that array, and then compares the reversed array to the decimalization of n (ie is n palindromic in decimal?) +ยณรŸ This is the else. It adds the original input argument to n and then repeats the link with the new value of n. ยน This is the if. It returns the value passed to it. ``` [Answer] # [Elixir](http://elixir-lang.org), 75 bytes ``` def f(p,a\\0),do: if'#{a+p}'|>Enum.reverse=='#{a+p}',do: a+p,else: f(p,a+p) ``` [Answer] ## Python 2, 66 65 bytes `i` is input and `x` is (eventually) output ``` def f(i,x): y=x if x%i==0&&`x`==`x`[::-1]else f(i,x+1) return y ``` After scrolling through other answers I found a shorter Python 2 answer but I put the effort into my solution so might as well throw it here. ยฏ\\_(ใƒ„)\_/ยฏ [Answer] # REXX, 46 bytes ``` arg a do n=a by a until reverse(n)=n end say n ``` [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes ``` x=lambda n,m=0:m*(`m`==`m`[::-1])or x(n,m+n) ``` [Try it online!](https://tio.run/##HYxBCoQwFEP3niJLqx2wVUYo/JOIoOIMCtOvaBf29J2vi4SQ8LLHsGxsU7roN/ppHsHaU@V8kQ9@IBLrnHuZXm0HrlzGklUKnzOcIHRGw2qYt6jVaO5spKurO9m66bOvcBEr42Ec9mPlIE9RpT8 "Python 2 โ€“ Try It Online") I know that the question was posted over six months ago, but this was shorter than any other Python submission. [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 29 bytes ``` :{c=a*q~!c$=_f!c$||_Xc\q=q+1 ``` Explanation: ``` : Get cmd line param as number 'a' { DO c=a*q multiply 'a' by 'q' (which is 1 at the start of a QBIC program) and assign to 'c' ~ IF !c$ 'c' cast to string = equals _f!c$| 'c' cast to string, the reversed | THEN _Xc Quit, printing 'c' \q=q+1 ELSE increment q and rerun DO Loop is auto-closed by QBIC, as is the IF ``` [Answer] # [Perl 6](http://perl6.org), 35 bytes ``` ->\N{first {$_%%N&&$_==.flip},N..*} ``` ``` ->\N{first {$_==.flip},(N,N*2...*)} ``` ``` ->\N{(N,N*2...*).first:{$_==.flip}} ``` ## Explanation: ``` -> \N { # from a list of all multiples of the input # ( deduced sequence ) ( N, N * 2 ... * ) # find the first .first: # that is a palindrome { $_ == .flip } } ``` [Answer] ## Perl 6, 39 bytes ``` my &f={first {.flip==$_},($_,2*$_...*)} ``` (33 not including the `my &f=`) ]
[Question] [ Given an integer **n** โ‰ฅ 1, output a 2D representationโ€  of a percent sign of width **n**. The construction goes as follows: 1. Create an **n** by **n** matrix (or list of lists) filled with zeroes. 2. Insert ones in the top-left and bottom-right corners. 3. Place ones on the diagonal from the bottom-left to the top-right. For input **n** = 4, this construction would look like: ``` 1. 4x4 matrix of 0s 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2. 1s in TL and BR corners 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 3. 1s across BL-TR diagonal 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. โ€  I use a matrix of 1s and 0s, but it is also acceptable to use a string of any non-whitespace character and spaces. So, the example above could look like: ``` # # # # # # ``` or ``` # # # # # # ``` ## Test cases ``` n output 1 1 2 1 1 1 1 3 1 0 1 0 1 0 1 0 1 4 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 10 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 ``` ## Final note Adding an explanation would be greatly appreciated. [Answer] ## JavaScript (ES6), 52 bytes ``` n=>[...Array(n)].map((_,y,a)=>a.map(_=>y++%~-n<1|0)) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ยฒRmโ€™แนฌs ``` [Try it online!](https://tio.run/##AToAxf9qZWxsef//wrJSbeKAmeG5rHP/w4dHIOG4t@KAnCBDYWxsIGxpbmsuIFByZXR0eSBwcmludC7//zEw "Jelly โ€“ Try It Online") ### How it works ``` ยฒRmโ€™แนฌs Main link. Argument: n ยฒ Square; yield nยฒ. R Range; yield [1, ..., nยฒ]. โ€™ Decrement; yield n-1. m Modular; yield every (n-1)-th element of the range, staring with the first. แนฌ Untruth; yield a Boolean array with 1's at the specified indices. s Split the resulting array into chunks of length n, creating a matrix. ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 15 bytes ``` ร€รฉ ร€ร„|r#L.|รฒ.kl ``` [Try it online!](https://tio.run/##K/v//3DD4ZUKQKKlpkjZR6/m8Ca97Jz///@bAAA "V โ€“ Try It Online") ### Explanation ``` ร€รฉ<space> " Argument times insert a space ร€ร„ " Argument times duplicate this line " This gives an arg-by-arg matrix of spaces " and brings the cursor to the end of the first line |r# " Go to the beginning of this line and replace the first character with # L. " Go to the end of this matrix (bottom-right corner) and replace that character with a # | " Go to the beginning of the last line รฒ " Recursively do: . " Repeat the last action, r#, replace the character under the cursor with # kl " Go 1 up and 1 right ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~58~~ 57 bytes ``` n=input() x='#'.ljust(n-1)*3 exec'print x[:n];x=x[1:];'*n ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDk6vCVl1ZXS8nq7S4RCNP11BTy5grtSI1Wb2gKDOvRKEi2iov1rrCtiLa0CrWWl0r7/9/QwMA "Python 2 โ€“ Try It Online") [Answer] # GNU APL, ~~17~~ 15 bytes ``` {1=โตโˆจโตโตโด1=โณโต-1} ``` This is one weird day ... GNU actually beat Dyalog APL ... woah. TIO doesn't support GNU APL ... Explanation (input is `โต`): ``` 1=โณโต-1 - 1 followed by โต-2 0's โตโตโด - fit into a square โตโˆจ - gcd โต (0 gcd n = n) 1= - test each element for equality with 1 ``` [Answer] # [Python 2](https://docs.python.org/2/), 46 bytes ``` lambda n:zip(*[iter(`10L**n`[:-3]*-~n+'1')]*n) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqiqzQEMrOrMktUgjwdDAR0srLyHaStc4Vku3Lk9b3VBdM1YrT/N/Wn6RQp5CZp5CUWJeeqqGoY6pgaYVF2dBUWZeiUKeTk5qnkaaRp6m5n8A "Python 2 โ€“ Try It Online") Outputs like ``` [('1', '0', '0', '1'), ('0', '0', '1', '0'), ('0', '1', '0', '0'), ('1', '0', '0', '1')] ``` --- # [Python 2](https://docs.python.org/2/), 48 bytes ``` lambda n:zip(*[iter([1]+(n*[0]+[1])[2:]*-~n)]*n) ``` [Try it online!](https://tio.run/##DcqxDkAwFAXQma9442uRYDA08SXVoUJpwtU0XRj8etnOcMKd9gt9duOUD3vOiyWoxweW2qc1su5MxZC6NdVPoXtlZPNCGAmR3RUJ5EHRYlu5qwehyiJEj0SO//AB "Python 2 โ€“ Try It Online") Outputs like ``` [(1, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 1)] ``` --- # [Python 3](https://docs.python.org/3/), 48 bytes ``` lambda n:('%d'*n+'\n')*n%(1,*(*[0]*n,1)[2:]*-~n) ``` [Try it online!](https://tio.run/##Dcq9DkAwFAbQmafoIr33IvETSxNPgqFCkfCRxmLx6uXM53ru9UQdXNuH3R7jZBUM6WTSglT30CxIqMyEpCsGQVZyV5lB8hcc3OkV1AblLZb5X03BJo4uv@EmR2AOHw "Python 3 โ€“ Try It Online") A quite different string-substitution approach in Python 3. Outputs like: ``` 1001 0010 0100 1001 ``` [Answer] # Dyalog APL, ~~12~~ ~~11~~ 10 bytes ``` ,โจโดร—,2โ†“โŠขโ†‘ร— ``` [Try it online](http://tryapl.org/?a=%28%2C%u2368%u2374%D7%2C2%u2193%u22A2%u2191%D7%295&run) -1 byte thanks to lstefano. ## How? ``` ,โจโดร—,2โ†“โŠขโ†‘ร— โŠขโ†‘ร— - argument-length extension of the sign of the argument (1) 2โ†“ - Drop the first two elements ร—, - Prepend a one ,โจโด - Shape into a square array with dimensions of input x input ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` =รพยนUF1Qยฆs ``` [Try it online!](https://tio.run/##ATsAxP9qZWxsef//PcO@wrlVRjFRwqZz/8OHRyDhuLfigJwgQ2FsbCBsaW5rLiBQcmV0dHkgcHJpbnQu//8xMA "Jelly โ€“ Try It Online") ### How it works ``` =รพยนUF1Qยฆs Main link. Argument: n ยน Identity; yield n. =รพ Equals table; compare each i in [1, ..., n] with each j in [1, ..., n]. This yields the nร—n identity matrix. U Upend; reverse each row. F Flatten the matrix. ยฆ Sparse application: Q Unique; yield the unique elements of the constructed array, i.e., [1] if n = 1 and [0, 1] if n > 1. 1 Yield 1. This replaces the elements at indices 0 (last) and 1 (first) with 1. s Split the resulting array into chunks of length n. ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 18 bytes ``` {โต=1:โตโ‹„โต โตโด1=โณโต-1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR24TqR71bbQ2tgOSj7hYgqQBi9W4xtH3UuxnI1DWsBao7tALIMwUA "APL (Dyalog Unicode) โ€“ Try It Online") Making this work for input 1 has added 6 bytes. Looking at testcase 4, we see the output is ``` 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 ``` This is basically 1 0 0 repeated throughout the matrix. In other words, 1 0 0 shaped in a 4-by-4 matrix. So in this solution, we first generate this vector with 1 and trailing 0s using `1=โณโต-1` and then shape it using `โต โตโด`. But this borks for input 1, so we need to create a conditional and gain 6 bytes... ``` {โต=1:โตโ‹„โต โตโด1=โณโต-1} The right argument is โต โต=1:โต If โต is 1 return itself โ‹„ Otherwise โณโต-1 Create a range 1 .. โต-1 1= Equals 1; 1 0 0 {โต-2 0's} ... โต โตโด Shape in a โต-by-โต matrix ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~11~~ 7 bytes ``` n<รI<ร–รด ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/z@bwXE@bw9MOb/n/3wQA "05AB1E โ€“ Try It Online") **Explanation** ``` n<ร # push range [0 ... n^2-1] I<ร– # check each for equality to 0 when modulus with n-1 is taken รด # split in pieces of size n ``` [Answer] # [Haskell](https://www.haskell.org/), 55 bytes At first my approach was to recursively generate the transposed identity matrix, but then fixing the first and last line required some ugly/lengthy case distinctions. So I looked for another way to generate the identity matrix which is how I found [this](https://codegolf.stackexchange.com/a/70397/48198) idea. ``` f n=[[sum[1|x+y`elem`[2,n+1,2*n]]|y<-[1..n]]|x<-[1..n]] ``` [Try it online!](https://tio.run/##PYtBC4IwHEfv@xQ/RqemgkKXSD9BnTqukUKKo@3vcEoKfvelBd4e7/Hayr9rY0JoQLmUfrQyXSYxl7WpbSmziEQaZUdSapkvsUyTZMNpx8BspQk5GqMdbOVuT2zppHDAgxAXeHUMcONwH/orrZbTGRxCwLfdB7TG/@Z6TcPam5/bB85Z@AI "Haskell โ€“ Try It Online") ### Explanation ``` [[x+y|y<-[1..n]]|x<-[1..n]] ``` generates this *matrix* (for `n=4`): ``` [2,3,4,5] [3,4,5,6] [4,5,6,7] [5,6,7,8] ``` As you can see the top left element is `2` (in general), all the diagonal elements are `5` (in general `n+1`) and the bottom right element is `8` (in general `2*n`). So all we need to do is to check if `x+y` is an element of `[2,n+1,2*n]`. [Answer] # [R](https://www.r-project.org/), ~~54~~ 42 bytes *-12 bytes thanks to Jarko Dubbeldam* ``` n=scan();m=diag(n)[,n:1];m[1,1]=m[n,n]=1;m ``` returns a matrix; reads from stdin. creates an identity matrix `diag(n)`, flips it top to bottom `[,n:1]`, sets the top left and bottom right to `1`, and then writes to console (`''`) with width `n`. [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOtc2JTMxXSNPM1onz8ow1jo32lDHMNY2NzpPJy/W1tA697/pfwA) [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` XyPl5L( ``` Try it at [MATL Online!](https://matl.io/?code=XyPl5L%28&inputs=7&version=20.2.1) ### Explanation Create identity matrix (`Xy`), flip vertically (`P`), write (`(`) value 1 (`l`) to the first and last entries (`5L`), which are the top left and bottom right. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 67 bytes ``` param($n)0..--$n|%{-join(("1"+"0"*(($n-1),0)[!$n])*3)[$_..($_+$n)]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVP00BPT1dXJa9GtVo3Kz8zT0NDyVBJW8lASUsDKKtrqKljoBmtqJIXq6llrBmtEq@np6ESrw3UF1v7//9/CwA "PowerShell โ€“ Try It Online") Takes input `$n` and loops from `0` to `--$n` (i.e., `$n` pre-decremented). Each iteration, we construct a string of `1` followed by `$n-1` `0`s, then multiply that out `3` times (e.g., `100010001000` for input of `5`). Then we index into that on a rotating basis starting from `0` to `0 + $n`. Those characters are `-join`ed into a string, which is left on the pipeline. Output is implicit. --- *(NB -- This requires an additional 9 bytes to handle the special case of `n=1`. Below is the 58-byte code if we're guaranteed `n>1`)* ``` param($n)0..--$n|%{-join(("1"+"0"*($n-1))*3)[$_..($_+$n)]} ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform),121 91 88 bytes -30 bytes because the old way was stupid. -3 bytes by moving around the variable initialization ``` n=>{int i=0,k=n-1;int[,]b=new int[n,n];b[0,0]=b[k,k]=1;for(;i<n;)b[i++,k--]=1;return b;} ``` [Try it online!](https://tio.run/##VY5Ba4QwEIXP5lfM0WAsbq/Z7KWwsNCWlrb0IB7UTWV0O0ISW0T87TbRdqEDgeG9@V5ebdO6N3oZLFIDL6N1@lMyVl9Ka@GZTQz8WFc6rOGrxzM8lEgxX@XNDHMcqN4jOeFfLooDNKBgIXWYvACoMtEpSndysytF@hvCToIKWeWZyApV5Z3oCrWTH72JJe5J8irHJBFdmgbZaDcYgkrOi2RRyD09Pr29qtvM9/0rsn0wqiZeTe4vQ9xvC5@6yjJJkE8siu56sv1F37wbdPoeSceBuCKtR9or0nJv/UfiMUfRFgGa1w4zm5cf "C# (.NET Core) โ€“ Try It Online") Loops iterates down the array to fill in the 1's. Returns an array of 1's and 0's. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 12 7 bytes -5 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)! ``` โ†—๏ผฎโธฟ/โ€–๏ผฏโ†˜ ``` [Try it online!](https://tio.run/##ASAA3/9jaGFyY29hbP//4oaX77yu4ri/L@KAlu@8r@KGmP//NA "Charcoal โ€“ Try It Online") [Answer] ## C++, 144 bytes ``` #include<string> #define S std::string S p(int n){S r;for(int i=0;i<n;++i){r+=S(n,32);r[r.size()-1-i]=35;r+=10;}r[0]=r[r.size()-2]=35;return r;} ``` It takes advantage of the one byte difference between '#' and 35 [Answer] # Mathematica, 72 bytes ``` (s=Table[0,#,#];s[[1,1]]=s[[#,#]]=1;Table[s[[#+1-i,i]]=1,{i,#}];Grid@s)& ``` **input** > > [5] > > > **output** > > 1 0 0 0 1 > > 0 0 0 1 0 > > 0 0 1 0 0 > > 0 1 0 0 0 > > 1 0 0 0 1 > > > [Answer] # [Python 2](https://docs.python.org/2/), ~~86~~ 62 bytes ``` n=input();a=('1'+'0'*(n-2))*2+'1' exec'print a[:n];a=a[1:];'*n ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERD0zrRVkPdUF1b3UBdSyNP10hTU8tIGyjAlVqRmqxeUJSZV6KQGG2VFwtUmBhtaBVrra6V9/@/OQA "Python 2 โ€“ Try It Online") -24 bytes: Thanks to an idea from Rod! [Answer] # Dyalog APL v16, 23 bytes ``` {(1@(1 1)(โต โต))โŒฝโˆ˜.=โจโณโต} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE6o1DB00DBUMNTUe9W5VAGJNzUc9ex91zNCzfdS74lHvZqBQren//wA) Explanation: ``` {(1@(1 1)(โต โต))โŒฝโˆ˜.=โจโณโต} -(input โต) โˆ˜.=โจโณโต - identity matrix with size โตร—โต โŒฝ - flip that (1@(1 1)(โต โต)) - place 1 into the corners using the v16 operator @ (At) ``` [Answer] ## Lua, 117 bytes ``` m=arg[1]+0 for y=m,1,-1 do s=""for x=1,m do s=s..((x==1 and y==m or x==m and y==1 or x==y)and"#"or" ")end print(s)end ``` [Try it](https://tio.run/##LcpLCoAwDATQq4S4abGKAbc5ibgoVEWwVloFPX2sn9UMb2Y5rIhnG6eO@rKBMUS42BsyFYELkBjxsZPJ@A9SXSt1MhPY1eUze3gPOX@gHy6dAQsMEQH1kMctzuuu0tNFpL0B) Code is pretty simple. It sets m to the first argument, then adds 0 to it to convert it to a number, then iterates backwards for the Y coord, forward through the X coord and will put a # if x==y or if it's the other corners. *This program never uses the keyword "if".* [Answer] # Octave, 37 bytes ``` @(n)sparse([1 n:-1:1 n],[1 1:n n],!0) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQSNPs7ggsag4VSPaUCHPStfQCkjF6gA5hlZ5IJaigeb/NNvEvGJrrrTSnByNNA1DTU0Y0wjBNEYwTRBMUyDzPwA "Octave โ€“ Try It Online") Generates a sparse matrix representing the percent sign. [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 bytes ``` ยฒovUร‰ hT1 รฒU ``` Returns a 2D array / matrix. [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=sm92VckgaFQxIPJV&input=NAotUQ==) using the `-Q` flag to show array-formatted output. ## Explanation ``` ยฒovUร‰ hT1 รฒU ``` Implicit: `U` = input integer ``` ยฒo ``` Square `U` (`ยฒ`), create the array `[0, U*U)` (`o`), and map each item by... ``` vUร‰ ``` `1` if it's divisible (`v`) by `U-1` (`Uร‰`), else `0`. ``` hT1 ``` Set the item (`h`) at index 0 (`T`) to `1`. ``` รฒU ``` Split the array into slices (`รฒ`) of length `U`. [Answer] # PHP, 53 bytes ``` for(;$i<$l*$l;)echo($i++%($l-1)?0:1).($i%$l?'':"\n"); ``` The length of the side of the matrix is `$l`. This code has a PHP Notice and even a PHP Warning for division by 0 when `$l=0`, but does the job! [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes ``` n=input() a='1'+'0'*(n-2)+'1' print a for i in range(1,n-1):print str(10**i).zfill(n) print a ``` [Try it online!](https://tio.run/##Ncs7CoAwEEXRPqtIl5n4wQg2QhaTws@APEOMhW4@CmJ5Odx45XVHXwq8IJ6ZWAVvnKlMZyyh6bl6S8UkyDqoeU9atECngGUiV6NxPH565ESus1a4vWfZNgL/XymDegA "Python 2 โ€“ Try It Online") [Answer] # Ruby, 47 bytes ``` ->n{([1]+[0]*(n-2)).cycle.each_slice(n).take n} ``` It returns an array of arrays. The code is pretty straightforward. * It creates a `n-1` array with `1` as the first element and the rest filled with `0`s (e.g. `[1, 0, 0, 0]`) * It repeats it * It takes `n` slices of `n` elements [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiPaMFY72iBWSyNP10hTUy@5MjknVS81MTkjvjgnMzlVI09TryQxO1Uhr/Z/gUJatEnsfwA "Ruby โ€“ Try It Online") [Answer] # J, 14 bytes ``` -]\*:$1,0$~-&2 ``` Ungolfed: ``` - ]\ (*: $ (1,0 $~ -&2)) ``` [Try it online!](https://tio.run/##y/r/P81WTwGEdWNjtKxUDHUMVOp01YwUuFKTM/IV0hRMIQx1dZiAObqA8f//AA "J โ€“ Try It Online") [Answer] # Python 3, 97 bytes ``` def f(n): m=[[0+(j==n-i-1)for j in range(n)]for i in range(n)] m[0][0]=1 m[-1]=m[0] return m ``` # Explanation `m=[[0+(j==n-i-1)for j in range(n)]for i in range(n)]` This is a list comprehension, the `0+(j==n-i-1)` is a shorter way to convert `j==n-i-1` to an int (as opposed to `int` function) and then `m[-1]=m[0]` is shorter than making bottom right 1, as top and bottom rows are identical. [Answer] ## Forth, 273 ( without comments ) 170 ( golfed-ish ) ``` : % 2 base ! cr dup 1- 1 swap lshift 1 or . cr 2 over 2 - dup 0< 0= if 0 ?do 2dup s>d rot <# 0 ?do # loop #> type cr 2* loop 1 or . else drop drop then cr drop decimal ; ``` ## ( 273 version to clarify commented version: ) ``` : newbase base @ swap base ! ; : 0u.r swap s>d rot <# 0 ?do # loop #> type ; : frame 1- 1 swap lshift 1 or ; : % 2 newbase swap cr dup frame . cr 2 over 2 - dup 0< 0= if 0 ?do 2dup swap 0u.r cr 2* loop 1 or . else drop drop then cr drop base ! ; ``` ( Note that, since whitespace is the primary delimiter in Forth, removing every carriage return would make no difference. Indentation, of course, does. ) ## ( Commented: ) ``` ( Uses bit array, max 64 width on AMD64 with gforth. ) ( Could shave an extra thirty or so bytes by not restoring ) ( the numeric base, ) ( and a few more by pulling frame and 0u.r into the definition. ) : newbase ( n -- oldbase ) ( swap base with n ) base @ swap base ! ; : 0u.r ( u width -- ) ( unsigned numeric output, no leading zero suppression ) swap s>d rot <# 0 ?do # loop #> type ; : frame ( n -- f ) ( frame ) 1- 1 swap lshift 1 or ; : % ( n -- ) ( Make the % sign ) 2 newbase swap ( Use binary output. ) cr dup frame . cr ( Frame the first line. ) 2 over 2 - dup 0< 0= if ( Are we already done? ) 0 ?do ( Loop doesn't do the first or last. ) 2dup swap 0u.r cr ( Zero fill, right justify. ) 2* loop 1 or . ( Put the second frame out. ) else drop drop then cr drop base ! ; ``` ## ( Execution examples: ) ``` 1 % 1 ok 2 % 11 11 ok 3 % 101 010 101 ok 10 % 1000000001 0000000010 0000000100 0000001000 0000010000 0000100000 0001000000 0010000000 0100000000 1000000001 ok 40 % 1000000000000000000000000000000000000001 0000000000000000000000000000000000000010 0000000000000000000000000000000000000100 0000000000000000000000000000000000001000 0000000000000000000000000000000000010000 0000000000000000000000000000000000100000 0000000000000000000000000000000001000000 0000000000000000000000000000000010000000 0000000000000000000000000000000100000000 0000000000000000000000000000001000000000 0000000000000000000000000000010000000000 0000000000000000000000000000100000000000 0000000000000000000000000001000000000000 0000000000000000000000000010000000000000 0000000000000000000000000100000000000000 0000000000000000000000001000000000000000 0000000000000000000000010000000000000000 0000000000000000000000100000000000000000 0000000000000000000001000000000000000000 0000000000000000000010000000000000000000 0000000000000000000100000000000000000000 0000000000000000001000000000000000000000 0000000000000000010000000000000000000000 0000000000000000100000000000000000000000 0000000000000001000000000000000000000000 0000000000000010000000000000000000000000 0000000000000100000000000000000000000000 0000000000001000000000000000000000000000 0000000000010000000000000000000000000000 0000000000100000000000000000000000000000 0000000001000000000000000000000000000000 0000000010000000000000000000000000000000 0000000100000000000000000000000000000000 0000001000000000000000000000000000000000 0000010000000000000000000000000000000000 0000100000000000000000000000000000000000 0001000000000000000000000000000000000000 0010000000000000000000000000000000000000 0100000000000000000000000000000000000000 1000000000000000000000000000000000000001 ok ``` ( Final note: works to one less than the bit width of the Forth interpreter. I ran the above on gforth, AMD64. An ancient 16-bit Forth would only go to 15 bits wide, and would need a bit of modification. ) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 65 bytes ``` w=>{var l=new int[w*w];for(int i=0;i<w*w;i+=w-1)l[i]=1;return l;} ``` [Try it online!](https://tio.run/##XY89awMxDIbn@FdoCfjyUXKz4yyFTi0UOnQINxhHaQWOfdi@mGLy26@6XDu0CGl4pfeRZNPWhojjkMh/wNtXynhRwpsLpt5YBF@FdSYl6KtI2WSycA10ghdDXjZVkM9Q6JQ/QUO7U@Jp8HbP4obz2B3gFaNFntFj0Yd6NRGc9lhgapdV6dQ5RDlBSO8U7VlStNZl2zbuSJ1uVcQ8RA9O3UYlJn8Ycj8w8Bct7@sbJf6RJnV1r0xcN6KKxWPwKTh8eI@UUc4g3sLeBZ0lLX8e0fNHfAP8cTyTR8nDtznGbw "C# (.NET Core) โ€“ Try It Online") The algorithm is significantly distinct from the other C# answer, so I decided to post it separately rather than as an improvement. Inspired by the top rated Jelly answer actually, I was doing something slightly less compact before. The output is a linear array, so would require some logic to wrap it into a 2D outside the method as-is. An alternate version requires 6 additional bytes to output as a true 2D array: ``` w=>{var l=new int[w,w];for(int i=0;i<w*w;i+=w-1)l[i/w,i%w]=1;return l;} ``` I also have an interesting non-competing version. ``` using System.Linq;w=>new int[w*w].Select((_,i)=>i%(w-1)<1) ``` This ends up with almost the right output, resulting in an `IEnumerable<bool>` with true/false instead of 1/0, and it's a linear rather than 2D structure, and although not needed for that exact line of code, `using System.Collections.Generic` is necessary to do anything useful with the output. Like I said, it's very close to being valid but not quite. ]
[Question] [ ### Inspired by the fact that a few related challenges to this could be answered by Vyxal in 0 Bytes using a special flag combination. Given only one input integer \$n\$, calculate \$f(n,n)\$ where $$ f(x,y)= \begin{cases} x & \text{if } y=0 \\ f(\left(\sum\_{k=1}^xk\right),\text{ }y-1) & \text{otherwise} \end{cases} $$ If you want an explanation in plain English, here it is, quoted from OEIS: > > Let \$T(n)\$ be the \$n\$-th triangular number \$n\*(n+1)/2\$; then \$a(n)\$ = \$n\$-th iteration [of] \$T(T(T(...(n))))\$. > > > Note that a(n) is the function. --- This is also [A099129](https://oeis.org/A099129)\$(n)\$, but with the case for \$n=0\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so as long as you make your answer short, it doesn't matter whether it times out on TIO (my computer can't calculate \$n=6\$ within five minutes!). Yes, standard loopholes apply. --- ## Test cases: ``` 0 -> 0 1 -> 1 2 -> 6 3 -> 231 4 -> 1186570 5 -> 347357071281165 6 -> 2076895351339769460477611370186681 7 -> 143892868802856286225154411591351342616163027795335641150249224655238508171 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` FLO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fzcf//38TAA "05AB1E โ€šร„รฌ Try It Online") #### Explanation ``` # Implicit input F # Repeat input number of times: L # Push the one-range of top of stack O # Sum the resulting list # Implicit output ``` [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` def f(n):exec"n=n*-~n/2;"*n;print n ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0/TKrUiNVkpzzZPS7cuT9/IWkkrz7qgKDOvRCHvf1p@kUKeQmaeQlFiXnqqhpmmFZcCVE6HC6z7PwA "Python 2 โ€šร„รฌ Try It Online") A function that prints. # [Python 3](https://docs.python.org/3.8/), 39 bytes ``` lambda n:eval("(n:=n*-~n//2)*0+"*n+"n") ``` [Try it online!](https://tio.run/##BcFBCoAgEAXQq4irGSWKggjBm7QxyhLsKyJBm65u7@W3XgnTkkvzdm3R3dvuBMzxuEiSYCxU96HvR1aDlgpaQnLzqQiIAFEczoNmNrkEVPIE5vYD "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") The annoying thing in Python 3 here is that `exec` within a function is its own scope and doesn't affect variables outside the `exec`, so we can't port the code like `def f(n):exec("n=n*-~n/2;"*n);print(n)` -- the `n` will be unchanged. The code above works around this by evaluating a string like `(n:=n*-~n//2)*0+(n:=n*-~n//2)*0+n` that modifies `n` using the walrus `:=` and evaluates to `n` within its own scope. If we didn't need `n=0`, we could do: **37 bytes, fails n=0** ``` lambda n:eval("(n:=n*-~n//2),"*n)[-1] ``` [Try it online!](https://tio.run/##BcFBCoAgEAXQq0irGVGkWhSCJ6kWRllBfUUiaNPV7b303ntE26dcghvL6a958QJ2ffxJFcE6SP3BmIZVJcGDrqcSYhYQB0T22FaqVcc25QM3BQJz@QE "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") Here were some other attempts. **39 bytes** ``` lambda n:eval('('*n+'n'+'+.5)**2//2'*n) ``` [Try it online!](https://tio.run/##DchBCoAgEAXQq7ibGYUEo4igm7QxygrsKxJBp7fe8uX3PhLaIZcaprlGfy2rVxi3x0cmJg1DIEOm6URrZ637S2pIRUGdUMVj37iXMZcTNweGSP0A "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") Based on @dingledooper's comment. **40 bytes** ``` def f(n):exec("n*=n/2+.5;"*n+"print(n)") ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PyU1TSFNI0/TKrUiNVlDKU/LNk/fSFvP1FpJK09bqaAoM68EKKuk@T8tv0ghTyEzT6EoMS89VcNM0wqk7T8A "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") **41 bytes** ``` lambda n:0*[n:=n*-~n//2for _ in[1]*n]or n ``` [Try it online!](https://tio.run/##FchLCoAgFAXQeat4Q5XCPhAhuBKTMMoK6ibSpElbtxqeE@5rPdF0ISav@7S7Y5wcQZXCQGmI4oGUtT8jDbTBVFbAfkD6C19RdFhm1nKVUYgbLoacPAPn6QU "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 42 bytes think i might be able to get it down further... lmk if you guys see anything !! ``` lambda x:eval("sum(range("*x+"x"+"+1))"*x) ``` [Try it online!](https://tio.run/##TctLDoIwEAbgvacws@rYWTAd2hITbuKmRlATqASR1NPXbgwsv/8xfZfHK0ru20sewni9hWM6d2sYFLw/o5pDvHcKTklDAg2aEQswT/MzLqpXFVKFh78YiTcZJLdJkIzs2rpsuXHW7/4WSWovJfNsGmZnMf8A "Python 3 โ€šร„รฌ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` RS$ยฌยฐ ``` [Try it online!](https://tio.run/##y0rNyan8/z8oWOXQwv///5sAAA "Jelly โ€šร„รฌ Try It Online") Full program, takes \$n\$ as the first argument and outputs \$f(n, n)\$ ## How it works ``` RS$ยฌยฐ - Main link. Takes n on the left $ - Last two links as a monad f(n): R - Range [1, ..., n] S - Sum; T(n) ยฌยฐ - Apply f n times, beginning with n ``` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 23 bytes ``` i::?\~n; -10.\r:1+*2,r1 ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTo6P1xcfm47XG4tMTAuXFxyOjErKjIscjEiLCJpbnB1dCI6IjQiLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJudW1iZXJzIn0=) [![enter image description here](https://i.stack.imgur.com/ecr7P.png)](https://i.stack.imgur.com/ecr7P.png) [Answer] # [Brainfuck](https://esolangs.org/wiki/Brainfuck), ~~64~~ 48 bytes ``` [>+>+<<-]>[->[[>+>+<<-]>>-[<<+>>-]<<]>[<+>-]<<]> ``` [Try it online!](https://copy.sh/brainfuck/?c=SGVhZGVyOiBnaXZlIE4gaGVyZQorKysrCgpBY3R1YWwgY29kZQpbPis-Kzw8LV0gICAgICAgICAgIyBEdXBsaWNhdGUKPlstICAgICAgICAgICAgICAgICMgUmVwZWF0IGlucHV0IHRpbWVzOgogID5bICAgICAgICAgICAgICAgICAjIFdoaWxlIHggPSBuIGNhbiBiZSBkZWNyZW1lbnRlZAogICAgWz4rPis8PC1dICAgICAgICAgICMgQWNjdW11bGF0ZSByZXN1bHQgYW5kIG1ha2UgY29weQogICAgPj4tWzw8Kz4-LV08PCAgICAgICMgTW92ZSBjb3B5IG1pbnVzIDEgYmFjawogIF0-WzwrPi1dPDwgICAgICAgICAjIE1vdmUgYmFjayBhY2N1bXVsYXRlZCBUKG4pIGFzIG5ldyB4Cl0-Cg$$) (Up to `n = 3` with 8 bit numbers, `n = 4` with 32 bit, `n = 5` with 64 bit, `n = 6` possibly never [with BigInt].) Rather simple brainfuck answer. Assumes you initialise the tape with the input on cell 0 and stores the output in cell 2. If input given in binary, just wrap the code in `,` and `.` for +2 bytes. If the input should be the number in ASCII this would also involve writing the parser, I feel that is not in the spirit of the challenge. The input in the first cell (0) is duplicated and then the loop simply iterates on cell 1. Each value of the triangle is added to cell 3 and copied back with 1 removed to cell 2. At the end of the loop that new value is stored in cell 2. ``` Header: give N here ++++ Actual code [>+>+<<-] # Duplicate >[- # Repeat input times: >[ # While x = n can be decremented [>+>+<<-] # Accumulate result and make copy >>-[<<+>>-]<< # Move copy minus 1 back ]>[<+>-]<< # Move back accumulated T(n) as new x ]> ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` LsSbyF ``` [Try it online!](https://tio.run/##K6gsyfj/36c4OKnS7f9/EwA "Pyth โ€šร„รฌ Try It Online") ### Alternative 6 byte solution ``` usSGQQ ``` [Try it online!](https://tio.run/##K6gsyfj/v7Q42D0w8P9/EwA "Pyth โ€šร„รฌ Try It Online") ### Another alternative 6 byte solution ``` .v*"sS ``` [Try it online!](https://tio.run/##K6gsyfj/X69MS6k4@P9/EwA "Pyth โ€šร„รฌ Try It Online") This one's my favorite. ### Another alternative 6 byte solution ``` em=sSQ ``` [Try it online!](https://tio.run/##K6gsyfj/PzXXtjg48P9/EwA "Pyth โ€šร„รฌ Try It Online") Feels like there's gotta be a 5 byte solution but I got nothing [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 26 bytes ``` [ dup [ [1,b] ล’ยฃ ] times ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkgEm9IoS89JTiyHs0rzM5PyUVIWCotSSksqCosy8EoXi1MLS1LxkoBJrLi4Lhcz8ksT/0QoppQUK0QrRhjpJsQrnFivEKpRk5gKVxP7PTSxQKC5JTM7W@w8A "Factor โ€šร„รฌ Try It Online") Literally just take the sum of the range of the input <input> number of times. Since `sum` dispatches on `range`s to use the arithmetic formula, it's even efficient. [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 3 bytes ``` {RS ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWi6uDgpcUJyUXQ_kLFppCGAA) #### Explanation ``` {RS # Implicit input { # Repeat input number of times: R # One-range of top of stack (initially the input number) S # Sum the resulting list and leave it for the next iteration # Implicit output ``` [Answer] # [Rโ€šรขโ€ข4.1](https://www.r-project.org), 33 bytes ``` \(x){Map(\(i)x<<-sum(0:x),1:x);x} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3FWM0KjSrfRMLNGI0MjUrbGx0i0tzNQysKjR1DIGEdUUtROHa4sSCgpxKoIypTpomRGzBAggNAA) R afficionados should wince when they see `Map` used for it's out-of-scope side-effect due to `<<-` assignment, and the result discarded... # [R<4.1](https://www.r-project.org), 42 bytes ``` f=function(x,y=x)`if`(y,f(sum(1:x),y-1),x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN7XSbNNK85JLMvPzNCp0Km0rNBMy0xI0KnXSNIpLczUMrSo0dSp1DTV1KjQhOtYWJxYU5FRqGFiZ6qRBxWCmAQA) Without the short `\` form, it's too expensive to define two `function`s. [Answer] # [Ruby](https://www.ruby-lang.org/), 34 bytes ``` f=->x,y=x{y<1?x:f[(1..x).sum,y-1]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W165Cp9K2orrSxtC@wiotWsNQT69CU6@4NFenUtcwtvZ/gUJatEEsF4gyjv0PAA "Ruby โ€šร„รฌ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~63~~ 62 bytes ``` f=lambda x,y=-1:f(x,x)if y<0else x if y<1else f(x*(x+1)/2,y-1) ``` [Try it online!](https://tio.run/##TcxBDoIwEIXhPafoDqoldloKxNjDVCyRBJEwmLSnryMLYfn9bzJzXJ/vSafU29G97g/Hgoi2hGtfBBH40LN4k35EzwLbABtoPRXhDPyiRCyBJ4fol5W65NbK7E8gwk5FrHdqotKHvfqdQ1ub5vDDUNRVoyk2oFqA2mTzMkxrkeOn6zxiztMX "Python 3 โ€šร„รฌ Try It Online") Calculates a(n) using the OEIS definition given in the OP, probably still golfable Edit: fixed inputs and added "f=" [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~9~~ 6 bytes *Edit: -3 bytes thanks to ovs* ``` +ยฌยฅโ€šรผรบโ€šรœรฏโ€šรงรผโ€šรคยฃ ``` [Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgK8K04p+c4oaV4o2f4oqjCgpGwqggMOKAvzHigL8y4oC/M+KAvzTigL81) ``` +ยฌยฅโ€šรผรบโ€šรœรฏโ€šรงรผโ€šรคยฃ โ€šรงรผ # Repeat โ€šรคยฃ # number of times equal to argument +ยฌยฅโ€šรผรบโ€šรœรฏ # this function: โ€šรœรฏ # range 0..(arg-1) โ€šรผรบ # as left arg to +ยฌยฅ # fold-addition # with starting value of function arg # (so: sum of 0..arg) ``` [Answer] # [J](https://www.jsoftware.com), ~~11~~ 10 bytes ``` (-:*>:)^:] ``` Requires extended precision integer as input. -1 thanks to @Bubbler. [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxSkPXSsvOSjPOKhYisEmTKzU5I19BR08hTc1OIVPPogIisWABhAYA) ``` (-:*>:)^:]ยฌโ‰ โ€šร…ยฐโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยฃโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยงโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร…โ„ขโ€šร…โ„ขโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร…ยฐโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅยฌโ‰  ^: NB. โ€šร„รฉโ€šร…ยฐrepeat ] NB. โ€šร„รฉโ€šร…ยขy times >: NB. โ€šร„รฉโ€šร…ยฃincrement -: NB. โ€šร„รฉโ€šร…ยงhalve * NB. โ€šร„รฉโ€šร…ยขโ€šร…ยฐmultiply ``` # [J](https://www.jsoftware.com), ~~12~~ 11 bytes ``` (-:*>:)^:x: ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxWkPXSsvOSjPOqsIKIrJJkys1OSNfQUdPIU3NTiFTz6ICIrFgAYQGAA) ``` (-:*>:)^:]ยฌโ‰ โ€šร…ยฐโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยฃโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยฐโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยงโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยขโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยฃโ€šร…โ„ขโ€šร„รจโ€šร…โ€ โ€šร…โ„ขโ€šร…โ„ขโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅโ€šร…ยขโ€šร…ยฐโ€šร„รฃโ€šร„รฉโ€šร„รฉโ€šร…โ„ขโ€šร…ยฐโ€šร…โ„ขโ€šร…โ€ โ€šร…โ„ขโ€šร…ยงโ€šร…โ„ขโ€šร„รจโ€šร„รจโ€šร„รฃโ€šร…ยฐโ€šร…โ€ โ€šร…ยฐโ€šร„รฅยฌโ‰  ^: NB. โ€šร„รฉโ€šร…ยฐrepeat x: NB. โ€šร„รฉโ€šร…ยขy times but promote to extended precision >: NB. โ€šร„รฉโ€šร…ยฃincrement -: NB. โ€šร„รฉโ€šร…ยงhalve * NB. โ€šร„รฉโ€šร…ยขโ€šร…ยฐmultiply ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 29 bytes ``` f=(x,y=x)=>y?f(x*++x/2,y-1):x ``` [Try it online!](https://tio.run/##DcRLDkAwEADQvVNYzmh9lyhnkWplRIyUyPT05S3evrzLbQNdT3ny6lLyBkRHI2imOHuQQimpOx3LFntJQ@Y5AJlmyGns/pUitHzefLjq4A1IeyDE9AE "JavaScript (Node.js) โ€šร„รฌ Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` !โ€šรœรญยฌฯ€ยฌยฐล’ยฃ ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8WiDocF/xUdtkw7tPLTw3OL//wE "Husk โ€šร„รฌ Try It Online") [Answer] # [Racket](https://racket-lang.org) โ€šร„รฌ 52 bytes ``` (define(f x y)(if(= y 0)x(f(/(*(+ x 1)x)2)(- y 1)))) ``` [Try it online!](https://tio.run/##nY7BbsIwEETv@YoRqOqagki4VCLiA3rqhRtCwpB1a9VZI9spyYVfT522h567h5F23mg0QV8@OI1zp@UN4eehho0VJoMegyJraIcBperJ0JoW9JT9SvVqo2iVQaXyjWR8WDsbE@ggICurkCsZm7JUR1UA1Nh4dXpwmeZsqxNmB9niro/YZcX9YYaJZZGpsihq7D26yNi/vD5GWLl2Ccaya5AbcJLTEhfftiwJ6Z2hz/6TkW4eLu@Py8kUdPI3801wZudv26Imx7@DA@tmGlr/Y@lYPX8B "Racket โ€šร„รฌ Try It Online") ## Explanation We `define` a function `f` that receives two arguments: `x` and `y` where `y` is used as decrementing iterator that when equal to zero will make `f` return the result of `x`. ``` (define (f x y) (if (= y 0) x (f (/ (* (+ x 1) x) 2) (- y 1)))) ``` We can represent this function mathematically using the following: $$ f(x, y) = \begin{cases} x & y = 0 \\ f(\frac{x(x+1)}{1}, y - 1) & y > 0 \end{cases} $$ ## Sub-optimal variations To allow user input I could've done: ``` (let([n(read)])(let f([x n][y n])(if(= y 0)x(f(/(*(+ x 1)x)2)(- y 1))))) ``` Which consists of 72 bytes when minified. We could also have used a combination of a lambda and `let` statement to save one byte: ``` ((ล’ยช(n)(let f([x n][y n])(if(= y 0)x(f(/(*(+ x 1)x)2)(- y 1)))))(read)) ``` (The `ล’ยช` character equals two bytes.) ## Conclusion Have an amazing day! I am still mind blown at Racket's speed and capability of handling large numbers. At \$n = 17\$, TIO can't seem to render all the digits alongside all iterations of the `for` loop in the footer. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` ร”ยบร†ล’โˆร”ยบยถล’โˆโ€šรขรฎล’ยฃโ€šร„ยถยฌโˆ‘ยฌฯ€ล’โˆล’โˆร”ยบยฉล’โˆ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IAchQcCwuzkzP0wguzdXwzEvOKS3OLEsNSsxLT9Uw1FEo1NQEEdZcAUWZeSUazonFJUA9mtb//xv/1y3LAQA "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. Explanation: ``` ร”ยบร†ล’โˆ ``` Input `n`. ``` ร”ยบยถล’โˆ ``` Repeat `n` times... ``` โ€šรขรฎล’ยฃโ€šร„ยถยฌโˆ‘ยฌฯ€ล’โˆล’โˆ ``` ... replace the current value the sum of its range. ``` ร”ยบยฉล’โˆ ``` Output the final value. 14 bytes for an efficient version: ``` ร”ยบร†ล’โˆร”ยบยถล’โˆโ€šรขรฎโˆšโˆ‘โˆšรณโ€šรครฏล’โˆล’โˆยฌโ‰คล’โˆร”ยบยฉล’โˆ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IAchQcCwuzkzP0/DMK3HJLMtMSdUIycxNLQbyk4tSc1PzSlJTgKp0FEDYCExbcwUUZeaVaDgnFpcApTSt//83@69blgMA "Charcoal โ€šร„รฌ Try It Online") Link is to verbose version of code. Explanation: Uses the triangle formula to sum the range. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `R`, 14 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 1.75 bytes ``` (โ€šร รซ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJSPSIsIiIsIijiiJEiLCIiLCI0Il0=) Yeah... ``` ( # Input number of times: โ€šร รซ # Sum top of stack # (R flag makes it take the range instead of the digits) ``` [Answer] # [J-uby](https://github.com/cyoce/J-uby), 23 bytes ``` ~(:-&(:**&(:+|:sum))).D ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboW2-s0rHTVNKy0tICEdo1VcWmupqamngtE9qZSgYJbtGEsF4gyglDGEMoEQpnGQlQuWAChAQ) ## Explanation With some whitespace: ``` ~(:- & (:** & (:+ | :sum))).D ``` The core function here is `:** & (:+ | :sum)`, where `:+` constructs a range and `:sum` sums it, and `:**` applies that function to its own result `n` times. That does what we wantโ€šร„รฎbut only if we call it like `F.(n).(n)`. In order to be able to call it like `F.(n)`, we use `:-` to turn it into `F.(n, n)`, `D` to force `F` to be treated as a dyad, and then `~` to repeat the given argument the necessary number of times (which is two, thanks to `D`). [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` t:":s ``` [Try it online!](https://tio.run/##y00syfn/v8RKyar4/38TAA "MATL โ€šร„รฌ Try It Online") ### How it works ``` t % Input (implicit). Duplicate : % Range " % For each : % Range s % Sum % End (implicit). Display (implicit) ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes ``` ยทยตรซ{Rโ€šร รซ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fisebp1YHfSoY-KS4qTkYqjggpUGXIZcRlzGXCYQAQA) ``` ยทยตรซ{Rโ€šร รซ ยทยตรซ{ Repeat R Range โ€šร รซ Sum ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes ``` Nest[#(#+1)/2&,#,#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCRaWUNZ21BT30hNR1lHOVbtf0BRZl5JtFKeQppGnqZSLJdbflF0nq2BTp6NrRGQ1NbWgajI01FSUNJRSIvOi42N/Q8A "Wolfram Language (Mathematica) โ€šร„รฌ Try It Online") This code simply nests the short-hand expression for the triangular numbers the given number of times. The computation time starts to become noticeable around `n=20` and my laptop takes around 50 seconds to compute `n=27`, which is a number that takes 63.5 MB to store. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ;?{โ€šรผยถ+}โ€šร…ยฑโ€šร…รฆ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39q@@tH8Zdq1jxo3Pmrc9/@/yf8oAA "Brachylog โ€šร„รฌ Try It Online") ### Explanation ``` ;?{ }โ€šร…ยฑโ€šร…รฆ Iterate <Input> times on the Input: โ€šรผยถ Range + Sum ``` [Answer] # Haskell, 29 bytes ``` (!!)=<<iterate(\x->sum[0..x]) ``` Expands to ``` \n -> iterate (\x -> sum [0..x]) n !! n ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BVkFDUVHT1sYmsyS1KLEkVSOmQteuuDQ32kBPryJWkys3MTMPqKigKDOvREFFITexQCFNASRpEvv/PwA "Haskell โ€šร„รฌ Try It Online") [Answer] # x86-64 machine code, 17 bytes Standard System V ABI, signature `long fsor(int n)` (`n` is taken in `edi`, and the output is placed in `rax`). ``` 57 58 50 5e ff c6 48 f7 e6 48 d1 e8 ff cf 7f f2 c3 ``` [Try it online!](https://tio.run/##pVTJbtswEL3zKwYuAtiwJSWO4QJ2klOvRQ899FAXBiWOJCYUqXLxgqLf7g7pJU57CVAfBHLmcd6bzSV37QGr1sDg8L2U3sF89oOxJXwNHZgaLNcNQp7nZGq9792iKCojsDGqzp3n1QvuqjaC8sp0xc@AzkujXTGdT@ezj4ULXWbqjGcp0PH4H7aoTHPXgTPJmMdzZs43A1mNqp7PGHNYRSGQe9x5BvRrlCm5gprAMYwyukmXodQe9IhMlI8W3Apwe7cBXkqySd0Hv4CEoS/YAkW0m@CTI4Wx6ILyyc13LAZdJEoSC97EN2SOhj64FiwFSBfTJ/wJ2nEdSJ8yZC6x4sEhxIa41liPNgZ6QeyhMkHHe2SjSOt15Fur/pXyEfRQj@9GxRQooRQx@S4AyoZUOXml6SwwaiLHGTq@ewtewhYpXR@sBh5d89naT6gdJ0qgkgftZKNRONhKpcBs0NbKbEnLfsv3IOuLDmHQgTYeaumPPBzup0BzCH7f4wQ65FpSgYnU8Q2Su9x7hBYtQnDRgxdhUjuPXKSpdTJPVqmrhDgzHjUeMzplvKSJT4xdUDEP33Jib/HUYZCOyrxbEPyaAcl0bmp8aP8modq/oXGtjecJ3J1xAiuLHdJg0URdGgUl7RSEnspE8xjr9wS36QXhIzKdnxu49P21tdSXwwCernaDseNusw9UCRUEwoPzQpq8fWKsKKCpqrhKNq/gaofiPlnIvnFiz77cU5AdDZz@Z2WWjMVDx6UebowUI/iVdNTGQoLIx1vqy8OcPuPxKPnSkFly1sPVIMW6oXePcKPEaqVXgwnIyYljFAlOecV5u12y3@yYHwlm7F1/BO/LMC@igZnyWYSuh@wTZJ9JI6rXR4c/) ## Explanation ``` 0000000000000000 <fsor>: 0: 57 push rdi ; cnt (edi) 1: 58 pop rax ; n = cnt ; 0000000000000002 <__fsor_lp>: ; start_loop: 2: 50 push rax ; 3: 5e pop rsi ; n1 = n 4: ff c6 inc esi ; n1++ 6: 48 f7 e6 mul rsi ; n *= n1 9: 48 d1 e8 shr rax,1 ; n >>= 1 c: ff cf dec edi ; cnt-- e: 7f f2 jg 2 <__fsor_lp> ; if (cnt > 0) goto start_loop 10: c3 ret ; return ``` [Answer] # Dyalog APL, 10 bytes ``` {+/โ€šรงยงโ€šรงโ‰ฅโ€šรงยฃโ€šรงยตโ€šรคยขโ€šรงยต} ``` ## Explanation ``` โ€šรงยง โ€šรงรน โ€šร„รฉโ€šร…ยฐFunction composition: +/ โ€šรงรน โ€šร„รฉโ€šร…ยข sum reduce โ€šรงโ‰ฅ โ€šรงรน โ€šร„รฉโ€šร…ยฃ the numbers from 1 to the argument of the composed function โ€šรงยฃโ€šรงยต โ€šรงรน โ€šร„รฉโ€šร…ยงrepeated input times โ€šรคยขโ€šรงยต โ€šรงรน โ€šร„รฉโ€šร…ยขโ€šร…ยฐstarting from the input ๏ฃฟรผรญรฉ Created with the help of Luminespire at https://vyxal.github.io/Luminespire ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 25 bytes ``` {($_,{.++*$_/2}...*)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@79aQyVep1pPW1tLJV7fqFZPT09LM1olPrb2vzVXcWKlQhpQXlMhLb9IIc7QwPo/AA "Perl 6 โ€šร„รฌ Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~33~~ 26 bytes ``` ~x=(1:x.|>_->x*=(x+1)/2;x) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v67CVsPQqkKvxi5e165Cy1ajQttQU9/IukLzf7RCQVFmXklOnoaSikZOQWKKRp6OiaamlYKKRl2eppKmQlp@kUKeQmaegqGVaex/AA "Julia 1.0 โ€šร„รฌ Try It Online") -7 bytes thanks to MarcMush: replace `for` loop with pipe operator `|>` ## Alternate approach, ~~39~~ 35 bytes ``` ~x=x|>โ€šร รฒ(fill(n->n*(n+1)โˆšโˆ‘2,x)...) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjeV6ypsK2rsHnXM0EjLzMnRyNO1y9PSyNM21Dy83UinQlNPT08TqlQ_WqGgKDOvJCdPQ0lFI6cgMUUjT8dEU9NKQUWjLk9TSVMhLb9IIU8hM0_B0MpUIRaiDWYTAA) -4 bytes thanks to MarcMush: remove call to `reduce` [Answer] # [Alice](https://github.com/m-ender/alice), ~~24~~ 20 bytes ``` /O \I@/.!wrd&+?t.!$K ``` [Try it online!](https://tio.run/##S8zJTE79/1/fnyvG00FfT7G8KEVN275ET1HF@/9/k/8A "Alice โ€šร„รฌ Try It Online") Times out for larger values as it creates a range from 0 to the sum of the last range. ## [Alice](https://github.com/m-ender/alice), 21 bytes ``` /O \I@/.!w.h*2:?t.!$K ``` [Try it online!](https://tio.run/##S8zJTE79/1/fnyvG00FfT7FcL0PLyMq@RE9Rxfv/f7P/AA "Alice โ€šร„รฌ Try It Online") Does not time out as it uses the `n*(n+1)/2` formula instead ]
[Question] [ Inspired by [this question on SO](https://stackoverflow.com/q/23047198/916299), your task is to produce a program that is valid in (at least) two major versions of your chosen language that produce different output. ## Rules * Any language that has more than one major version can be used. + For the purposes of this challenge, I would suggest a "major version" is where the first number in the version number changes. - PHP 4 and PHP 5 are different, PHP 5.3 and PHP 5.4 are not. + However, since I don't know the versioning scheme for all languages, if you can argue your case well enough, I'm sure the community will determine if you have been fair in determining "major version" yourself. * The code must be compiled and run with the same flags and input each time + Except to change the version of the language if this is pertinent * Errors don't count as output and answers that produce errors are disqualified (rather than error output is just ignored) * The program should take no input other than that required to make it run. * For each given version, the output should always be the same * The intention is that the change should be a consequence of a change in the language spec rather than the VM spec or environmental metadata ## Scoring * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") type scoring for length, so `+1` for each char/byte * `-1` for each character *difference in the length* of the output. + e.g. Version 1 outputs `abcde` (5 characters), Version 2 outputs `123abc` (6 characters) = `-1` ## Other Rules * Standard exceptions apply - no external programs,web requests etc. * Your program should terminate (within 2 seconds) * Lowest score wins. ## "Better" Scoring *Keep your original answers, in the interest of fairness, I'll mark the winner based on the original rules.* Since my original scoring is fundamentally broken, why not re-score / retry with the following scoring system: * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") type scoring for length, so `+1` for each char/byte * `+1` for each character *difference in length* of output + `abcde` and `123456` -> `+1` * `-1` for each *unique character difference* in the output (capped to length of shortest output) + `abcde` and `123456` -> `-5` + `12345` and `123456` -> `-1` + `12345` and `123455` -> `0` * Scores closest to zero win * In the event of a second tie break, simple [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") score wins. [Answer] **Revised answer for "better" scoring system** # C89 / C99, Score: 0 My program is 52 characters long and uses the same mechanism as in my original answer to achieve the different output. This works because C89 doesnt treat `//` as a comment: ``` i=32;main(){putchar(i+++0//**/ +52)&&i<84&&main();} ``` The results: ``` $ ./diff2c89 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRS $ ./diff2c99 TUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~โŒ‚ร‡รผรฉรขรคร รฅรง $ ./diff2c99 | wc 0 1 52 $ ./diff2c89 | wc 0 1 52 $ wc diff2.c 1 2 52 diff2.c ``` **Old answer:** # C89 / C99, Score: -Infinity? I'm not entirely sure if this program doesn't break the rules, but never mind. This program exploits the fact that in C89 `//` is not a valid comment but `/* ... */` is. Using the comment trick an other function is executed. In C89 the function just prints `"trolololol..."` until the stack overflows (so it might finish within 2 seconds). ``` f1(){printf("ol");f1();} f2(){printf("oll");} main(){ printf("tr"); void (*f[])() = {f1,f2}; f[0 //* trollololol */ +1](); } ``` ## C99 ``` $ ./diffc99 troll ``` ## C89 ``` $ ./diffc89 trolololololololololololololololololololololololololololololololololololololololololo lolololololololololololololololololololololololololololololololololololololololololol ololololololololololololololololololololololololol .... ``` [Answer] # Python - 10 points less than the next best answer ``` print(range(100)) ``` In Python 2, this will print the entire list of integers from 0 to 99. In Python 3, `range` is a generator and so it will print only "range(0,100)". Seeing as I've never run into a size limit on numbers in Python, I can replace that 100 with a much bigger number (2\*\*1000, for example) and end up with a virtually infinite difference in the output. *Edited to reflect the fact that, while I can get a score that is infinitely low for any practical purpose, I cannot reach actual infinity with a program that terminates under 2 seconds* For the updated tie-breaker scoring system, I'd submit: ``` print(range(4)) ``` Output: Python 2: `[0, 1, 2, 3]` Python 3: `range(0, 4)` The first print has 5 unique characters (`[123]`), the second print has 8 unique characters (`range(4)`), the difference in length of output is 1, the code has 15 characters, the shortest output is 11 characters... these rules are pretty confusing but I think this brings me to a final score of 15+1-min(11,5+8) = 5. [Answer] ## C# I also changed the generic method type inference algorithms between C# 2, 3 and 4. For example: ``` using System; class C { static int M<T>(T x, T y) { return 1; } static int M(object x, object y) { return 2; } static void Main() { Console.WriteLine(M(1, new int?())); } } ``` In C# 2 method type inference says that T cannot be both `int` and `int?`, and so produces `2`. In C# 3 method type inference says "the best compromise between `int` and `int?` is `int?`" and so chooses `M<int?>` and produces 1. [Answer] # Python - 0 points No idea how this one works :P Just stumbled upon it while trying out random code. ``` int ``` On Python 3, it's `<class 'int'>` and on Python 2, it's `<type 'int'>` (using interative console) "Better" Score: 3 (length) + 1 (char diff.) - 4 (unique chars) ## Older Python 1 - 7 points ``` print() ``` Big thanks to [@grc](https://codegolf.stackexchange.com/users/4020/grc) for this version and helping me subtract four points ! In Python 2, this statement is interpreted as `print ()` which prints the empty tuple `()`. In Python 3, the `print` is a function and results in nothing being printed. "Better" Score: 7 (length) + 2 (char diff.) - 2 (unique chars) ### Older Python 2 - 13 points: ``` print(1,2) ``` "Better" Score: 12 (length) + 2 (char diff. o/p) - 1 (unique chars o/p) I know this isn't going to win but still gave an answer, as this is my first Python try :) [Answer] # Ruby, 4 characters + 0 char length difference - 3 unique char difference = score of 1 ``` p ?d ``` On Ruby 1.9, it will print `"d"`. On 1.8, it prints `100`. Explanation: `?d` is `"d"` in 1.9 and `100` (the ASCII code for d) in 1.8. `p x` is equivalent to `puts x.inspect`. `*` is both string repetition and multiplication. --- "Optimized" version for old scoring: # Ruby, 8 characters - 999999989 chars difference = score of -999999981 ``` p ?!*1e9 ``` Prints `33000000000.0` for 1.8 and `"!!!!!!`...`!!!"` for 1.9. (`?!` is `33` in 1.8 and `"!"` in 1.9, and `*` is both string repetition and multiplication.) Really, you could go as far as you wanted with the multiplication, it just depends on how fast your computer is. [Answer] ## Bash โ€” -โˆž (up to practical limits) Effectively, however much memory you have. E.g. with about 10GB: ``` echo {0..999999999} ``` Bash 2: doesn't support ranges in brace expansion, so prints `{0..999999999}`. Bash 3: --- ## Any language โ€” -โˆž (up to practical limits) You'll have this in pretty much any language, even if it ends up being a little more complex. As soon as you can make two different values, you can write code that produces arbitrarily different output. A better scoring method would ignore the differences in the output. ``` version = โ€ฆ # some arbitrarily weird stuff if version = 2: while not timed_out(): print "version2" ``` [Answer] ## Python, -14 Points ( 3 - 17 char length difference = -14) ``` 2/3 ``` Python 2 outputs: `0` Python 3 outputs: `0.6666666666666666` ## Better Scoring version, 5 points (3 + 2 char length difference = 5) ``` 3/2 ``` Python 2 outputs: `1` Python 3 outputs: `1.5` [Answer] ## C# I added covariance and contravariance to C# 4, so programs of the form: ``` using System; using System.Collections.Generic; class C { static void Main() { Console.WriteLine((new List<string>()) is IEnumerable<object>); } } ``` Would produce `false` in C# 2 and 3 and `true` in C# 4. However, one might argue that this does not count because the *library* containing the definition of `IEnumerable<T>` also had to change. [Answer] ## C# Following code would produce the different output for C# 5.0 and previous versions of C# ``` using System; using System.Collections.Generic; namespace TestConsoleAppClosure { class Program { static void Main(string[] args) { var actions = new List<Action>(); List<int> list = new List<int> { 10, 20, 30, 40 }; foreach (var item in list) { actions.Add(() => Console.WriteLine(item)); } foreach (var act in actions) act(); } } } ``` **Output: C# 5.0** ``` 10 20 30 40 ``` **Output: C# 4.0** ``` 40 40 40 40 ``` The reason is explained in this blog post by Eric Lippert: [Closing over the loop variable considered harmful](https://docs.microsoft.com/en-us/archive/blogs/ericlippert/closing-over-the-loop-variable-considered-harmful). [Answer] ## **C++98/11 - "Better" Scoring (115 characters - 115 unique character differences in output = score of 0)** **A slightly edited version to comply to the new scoring rules** Golfed: ``` #include<cstdio> #define u8 "\x0B" int main(){int i=116;char c[i];c[--i]=0;while(i-->0)c[i]=u8"\x7E"[0]+i;puts(c);} ``` Ungolfed version: ``` #include <cstdio> #define u8 "\x0B" int main() { int i = 116; char c[i]; c[--i] = 0; while(i-- > 0) c[i] = u8"\x7E"[0] + i; puts(c); } ``` The new solution doesn't differ much to the old one. In the new solution the output in both C++11 and C++98 is with 116 characters equally long, but the only character they have in common is the new line character appended by the puts function. For C++98 the `u8` in `u8"\x7E"[0]` will still be replaced, but now with `"\x0B"`. So the resulting value after preprocessing will be `"\x0B""\x7E"[0]`. The two strings will be concatenated to `"\x0B\x7E"` and the subscript operator will access the first element, in this case the character with the value 11 in the character encoding. Additionally the value of `i` will be added, which intially is 114. So the character with the value 125 will be written to the resulting array. As `i` goes to zero all values from 125 to 11 will be written to the array and `puts` will print all characters with the values from 11 to 125, plus the trailing new line. In C++11 `u8"\x7E"[0]` will be interpreted as an UTF-8 string consisting of the single character with the hexadecimal value 7E. The subscript operator will now access this character and the value of `i` is added to it, resulting in the decimal value 241 during the first iteration. While `i` goes to zero, all the values down to 126 will be written to the array and `puts` will print the characters with the values from 126 to 241, plus the trailing new line. Depending on the used character set, this will produce different results, as most character sets only have the first 128 characters in common. For ISO-8859-2 the output would be the following: C++98: ![Output for C++98](https://i.stack.imgur.com/q5vU3.png) C++11: ![Output for C++11](https://i.stack.imgur.com/BGGYy.png) **C++ (106 characters - 107 difference in output = score of -1) (OLD RULES)** Golfed: ``` #include<cstdio> #define u8 "f" int main(){int i=108;char c[i];c[--i]=0;while(i-->0)c[i]=u8""[0];puts(c);} ``` Ungolfed version: ``` #include <cstdio> #define u8 "f" int main() { int i = 108; char c[i]; c[--i] = 0; while(i-- > 0) c[i] = u8""[0]; puts(c); } ``` Compiled with `g++ -std=c++98 main.cpp` and `g++ -std=c++11 main.cpp`. Actually you can replace `108` with any positive number in integer range to achieve negative scores. As long as it's bigger than 108 ;) In C++98 `#define u8 "f"` will cause the preprocessor to replace `u8""[0]` with `"f"""[0]`. This will result in `"f"[0]`, which finally becomes the single character `'f'`, which is written to an array. `puts(c)` will print the resulting array, consisting of i-1 `'f'`. In C++11 `u8""[0]` will cause the empty string to be interpreted as an UTF-8 string, so no string concatenation is done. As this is a C-string, the subscript operator will access the terminating null-byte and write it to an array. In the end `puts(c)` will print the resulting array, which consists only of null-bytes. But as `puts` stops reading the input as soon as it encounters a null-byte, it will only print a newline and nothing more. [Answer] **CSS2 vs CSS3 48 points** ``` <i style='font-feature-settings:"smcp" on;'>abcdefghijklmnopqrstuvwxyz</i> ``` Rendered as `ABCDEFGHIJKLMNOPQRSTUVWXYZ` (small caps) on CSS3 browsers Rendered as `abcdefghijklmnopqrstuvwxyz` on non-CSS3 browsers 74 chars - 26 unique chars difference = 48 [Answer] # Python - 0 ``` a='a=%r\ntry:print a%%a\nexcept:pass' try:print a%a except:pass ``` Python 2 prints a quine, while Python 3 prints nothing. EDIT: Updated, fixed. [Answer] **Perl, 24 characters - (9\*(10^9))-1 char difference = score of -((9\*(10^9))-1)+24** ``` print$]>=5?"a":"a"x9e9; ``` Prints 9e9-times `a` for all versions below 5, prints `a` for all versions above 5. You could make the score infinitely low by just adding more `a`s to the second output. [Answer] # Befunge, 36 - 378 = -342; 164 - 2576 = -2412 ``` "v "<v " <v " <v " <v <v:,< ^_@ ``` In Befunge 93, this would output 3 spaces, followed by `<v`, followed by 76 spaces, followed by `<v`, then 76 space, then `<v`, then 76 spaces, then `<v` followed by 77 spaces, then `v` followed by 78 spaces. Length: `3 + 2 + 76 + 2 + 76 + 2 + 76 + 2 + 77 + 1 + 78 = 395`This is trivially extendable by adding extra lines similar to the first 5 lines. In Befunge 98, this would output `<v <v <v <v v`. The difference in length: `395 - 17 = 378`. So the score would have been (by the old rules): `-342` Note: I could have gotten an even bigger difference if I used `.` instead of `,`; the difference would have been `-684` --- Rule change: This is a bit more tricky. ``` " "-v>"Befunge 93 very long strings"v>"F"0g" "1-`!#v_ "F"0g1-"F"0pvz _^p0"F"-1g0"F"_v# `-1" "g0"F"<^"j++a81zzzzzz]zzzzzzzzzzzzzzz"< _@#`0:,< ``` Befunge 93 output: ``` sgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeB ``` Befunge 98 output: ``` j++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzz ``` Lengths: `2576`. None of the characters between the strings are the same, so if I understood the challenge correctly, my score is `164 - 2576 = -2412` (yes I was supposed to aim for `0`, but this was more fun). If I need to make it so that each character in each string are unique and different from each other, I can do so, please tell me. [Answer] ## Powershell, "Better" scoring, -163 (15 - 178 char diff = -163 ) ``` $PSVersionTable ``` **Powershell V2** ``` Name Value ---- ----- CLRVersion 2.0.50727.5477 BuildVersion 6.1.7601.17514 PSVersion 2.0 WSManStackVersion 2.0 PSCompatibleVersions {1.0, 2.0} SerializationVersion 1.1.0.1 PSRemotingProtocolVersion 2.1 ``` **Powershell V3** ``` Name Value ---- ----- WSManStackVersion 3.0 PSCompatibleVersions {1.0, 2.0, 3.0} SerializationVersion 1.1.0.1 BuildVersion 6.2.9200.16398 PSVersion 3.0 CLRVersion 4.0.30319.1022 PSRemotingProtocolVersion 2.2 ``` [Answer] # PHP, Score: 0 (best case) ``` srand(2);echo rand(); ``` Wow, this is going to be fun to explain. According to [this website](http://sandbox.onlinephpfunctions.com/), the `srand()` function appears to be broken from **PHP 5.1.5** to **PHP 5.3.14**. Therefore, we are going to keep under consideration PHP 4.4.9 and one random version of PHP 5 that falls in the version interval specified above. **PHP 4.4.9 output:** `1505335290` I don't think this is rule-breaking; Since this appears to be a bug, the output **should** be the same, but it's not. Our other PHP version will simply skip the `srand()` function and output a random number. [Answer] # Java (around -2.000.000.000) The Java versions are sometimes called 1.x, but I think it still is within the rules. The easy way is to check whether a class exists that was introduced in a specific version. ``` try { Class.forName("java.lang.AutoCloseable"); // Java 7 or later char[] text = new char[Integer.MAX_VALUE]; Arrays.fill(text, 'a'); System.out.println(new String(text)); } catch (Exception e) { // Java 6 or earlier System.out.println("-"); } ``` (Depends a bit on your terminal whether it is possible to output 2 billion characters in two seconds / For the new scoring, replace `Integer.MAX_VALUE` with the byte count of the program to achieve perfect zero score.) This code depends on the version of the VM/JDK that is used (does that count?) ``` import java.lang.reflect.Field; import java.util.Arrays; { Field fValue = null; for (Field f: String.class.getDeclaredFields()) { if (f.getName().equals("value")) { fValue = f; } } char[] text = new char[10]; Arrays.fill(text, 'a'); String s1 = new String(text); String s2 = s1.substring(1); fValue.setAccessible(true); text = (char[]) fValue.get(s2); Arrays.fill(text, 'z'); System.out.println(s1); } ``` It prints `z`s for Java 6 and earlier JDKs and `a`s for recent versions. [Answer] # JavaScript (ES3 vs ES5) - 9 points length `10` **+** length difference `0` **-** output difference `1` ``` [].map?1:0 ``` Outputs `1` for modern browsers that support Array.prototype.map. Outputs `0` on older browsers. I tested this with IE8. # With old rules: 0 points length `26` **-** length difference `26` ``` Array([].map?27:0).join(0) ``` Outputs `00000000000000000000000000` on modern browsers. And empty string on old. [Answer] # C++98/C++11 ``` #include <iostream> int main() { for (long i = 0; i < __cplusplus; ++i) std::cout << "x"; } ``` For a standard conforming C++98 compiler, this outputs 199711 times the letter 'x', while for a standard conforming C++11 compiler, this outputs 201103 times the letter 'x'. The length difference of the output is therefore 1392 characters. This means that actually golfing the source code is not worthwhile, since a much larger effect can be achieved by just replacing `"x"` with a longer string, or by multiplying `__cplusplus` with some number. [Answer] # TI-Basic 83 Plus vs. 84 Plus, score 5-1 = 4 ``` length("setTime( ``` Outputs `2` on the TI-83 Plus, where the same program is parsed as something that looks like `length("?โ–บDMS` because the `setTime(` command had not yet been introduced. So the string contains two 1-byte tokens, its length is 2. Outputs `1` on the TI-84 Plus, because a string containing a single 2-byte token has length 1. [Answer] ## APL (5 - (1988894 - 1) = -1988888) In old-style APLs (like Dyalog if `โŽ•ML=0`\*), `โ†‘` means *mix*, which, on a 1-dimensional vector does nothing. In APL2-style APLs, like GNU APL, (or Dyalog if `โŽ•ML=3`), `โ†‘` means *first*, which takes the first item of a vector. Thus, the following `5` bytes (the APL charset *does* fit in a byte), ``` โ†‘โณ3e5 ``` will output `1988894` bytes (the space separated list of numbers from 1 to 3e5) in old-style APL dialects, and `1` byte (just the first number in said list, which is `1` and therefore of length `1`), in APL2-style APL dialects. Notes: * `โŽ•ML` means *migration level*. In Dyalog APL, the higher you set `โŽ•ML`, the more APL2-style features are enabled. It defaults to `0`. (And it's a global variable! Fun!) * `3e5` was the highest 3-character value Dyalog APL would accept with `โณ`. `4e5` gave me a `LIMIT ERROR`. This restriction is probably interpreter-dependent. (GNU APL had no trouble with higher values.) [Answer] # Bash 7 (14 bytes program length + 0 difference in output length - 7 difference in unique chars in output) Related to @Gilles answer, but a different expansion feature and different versions. Scoring according to the edited question: ``` echo {1..9..2} ``` Output for bash 3.x: ``` {1..9..2} ``` Output for bash 4.x: ``` 1 3 5 7 9 ``` [Answer] # PHP: โˆ’134217684 (43 - 134217727) ``` echo str_pad("",ip2long("")&0x7ffffff,"a"); ``` Usage: ``` time php -r 'echo str_pad("",ip2long("")&0x7ffffff,"a");' > /tmp/test 1.61user 0.17system 0:01.79elapsed 99%CPU (0avgtext+0avgdata 142272maxresident)k 0inputs+0outputs (0major+35922minor)pagefaults 0swaps ``` In PHP5+ this will print nothing since ip2long with invalid argument turns into false which casts to zero. In PHP4 it `ip2long("")` returns -1 and we pad the empty string with 128MB og `a`. The mask is fitted so that it returns long before the 2 seconds on my machine. If you can't make it in 2s buy better hardware! # With new rules: 0 (40 - 40. You can't get any closer to zero.) ``` echo str_pad("",40,chr(97+ip2long(""))); ``` Outputs: ``` In PHP4: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa In PHP5: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb ``` [Answer] ### C89/C99 comment exploit, 45 character, 0 score ``` main(a){while(++a<47)putchar(79-a//**/~0 );} ``` ### c89 output `QRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}` - 45 char. ### c99 output `MLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!` - 45 char. [Answer] # SmileBASIC 3 / SmileBASIC 2, Score: -5 (original scoring) ``` ?1E9 ``` In modern versions of SB, this prints `1000000000` as expected, but in version 2 and earlier it printed `10` due to a bug. [Answer] # Go 1.9->1.10. Score = 1 - 1 = 0 From [1.10 notes](https://golang.org/doc/go1.10#runtime): > > There is no longer a limit on the GOMAXPROCS setting. (In Go 1.9 the limit was 1024.) > > > ``` package main import (r"runtime") var g=r.GOMAXPROCS func main() {g(10340) print(g(0))} ``` 1.8: `256` 1.9: `1024` 1.10: `10340` [Answer] # ARMv4T/ARMv5TE+ with libc, `pop {pc}` bug, for old scoring system, ~~42~~ 40 bytes, old score ~~-4294967252~~ -4294967255 ``` 1009 e28f 4002 e92d e001 e04f f004 e49d e002 e201 ff11 e12f 4674 2021 f7ff fffe 3401 d1fa bc01 4700 ``` ARMv4T, the ISA used in the ARM7TDMI, famous for powering the Game Boy Advance, introduced the Thumb instruction set. It is a 16-bit (later mixed with 32-bit) instruction set encoding that is more compact, but more limited, than the standard 32-bit ARM instruction set. I write a lot of my golfs in it, because it is ~~torture~~ fun. Basically, the idea is, since ARM instructions are always 4 byte aligned, if you jump to an odd address, the CPU will switch to Thumb execution mode at the address rounded down, and vice versa for an even address. One cool thing that ARM lets you do is `pop` the return address directly into the program counter from the stack, resulting in incredibly easy stack cleanup (similar to `leave; ret` in x86, but you can pop ALL registers at once) ``` push {..., lr} @ put the return address in the link register on the stack pop {..., pc} @ pop the return address into the program counter to return ``` On ARMv5TE and later, this will magically switch between ARM and Thumb state. However, ARMv4T had an infamous bug here. They forgot to implement Thumb switching: `pop {pc}` will ignore the lowest two bits and not switch to Thumb mode. [Source: ARM docs](https://developer.arm.com/documentation/dui0283/latest/Babefbce) So all we have to do is write a polyglot that will do something different if it is in ARM or Thumb state, which is easy because the encodings are entirely different. ``` .text .arm .globl main main: add r1, pc, #9 push {r1, lr} sub lr, pc, r1 @ define to simulate ARMv4T behavior #ifdef SIMULATE_ARMV4T b simulate_armv4t_bug #else pop {pc} #endif .Larmv4t_polyglot: and lr, r1, #2 @ b .Lthumb_entry; (skipped) bx r1 .thumb .Lthumb_entry: mov r4, lr .Lloop: movs r0, #'!' bl putchar adds r4, #1 bne .Lloop pop {r0} bx r0 #ifdef SIMULATE_ARMV4T .arm .align 2 simulate_armv4t_bug: pop {r12} @ clear thumb bit bic r12, r12, #3 bx r12 #endif ``` This program starts in ARM state. We need `r1` to contain the address of `.Larmv4t_polyglot`, with the Thumb bit set. (So `.Larmv4t_polyglot | 1`, or `.Larmv4t_polyglot + 1`) Therefore, we add 9 to the program counter (which points 8 bytes after the currently executing instruction because of questionable design decisions) to get 16 bytes, or 4 instructions, ahead, with the Thumb bit set. ``` add r1, pc, #9 ``` Push `r1` and `lr` to the stack. The former is so we can perform the `pop {pc}` bug, and the latter is to save the return address so we can use `lr` as a temp register and make function calls. ``` push {r1, lr} ``` Subtract `r1` from `pc`. This results in `lr` being `-1`. ``` sub lr, pc, r1 ``` Then, we pop the value from `r1` into the program counter. An ARMv5+ processor will execute the polyglot in Thumb mode, but an ARMv4T processor will ignore the low 2 bits (rounding down) and execute `.Larmv4t_polyglot` as ARM code. To simulate the buggy behavior, define `SIMULATE_ARMV4T` which will replace `pop {pc}` with a veneer that jumps to that address in ARM mode. ``` pop {pc} ``` Now, it is time for our polyglot. **ARM mode:** Set `lr` to `0` by setting it to `r1 & 2`. Since that contains the address of `.Larmv4t_polyglot` plus one, we know the second bit is clear. Then, jump to the polyglot again on ARMv4T (the address is still in `r1`), this time using `bx`, which DOES switch to Thumb mode. ``` .Larmv4t_polyglot: and lr, r1, #2 bx r1 ``` **Thumb mode:** Jump to `.Lthumb_entry`. ``` .Larmv4t_polyglot.thumb: b .Lthumb_entry @ skipped ``` Now, we are in Thumb mode on both machines, we can do our output loop. We first need to make a copy, because `lr` will be overwritten. ``` mov r4, lr ``` Then, we loop calling `putchar('!')`, until `r4 += 1` == 0. ``` .Lloop: movs r0, #'!' bl putchar adds r4, #1 bne .Lloop ``` On ARMv5TE+, `r4` will be `-1`, so the loop will only run for one iteration, but on ARMv4T, `r4` will be `0`, so it will run `4294967296` times (`0x100000000`) until it wraps back around to zero. I could technically make this infinite, but the rules say that it must eventually finish. Equivalent C: ``` uint32_t r4 = lr; do { putchar('!'); } while (++r4); ``` Finally, do an ARMv4T compatible return using the "Thumb interworking" hack: We pop into a low register and `bx` to it to return from `main`. ``` pop {r0} bx r0 ``` Program size: 40 bytes Output length in ARMv5TE+: 1 byte Output length in ARMv4T: 4294967296 bytes **Score: -4294967255** # ARMv4/ARMv5TE+ with libc, same bug, for new scoring system, 42 bytes, score 0 Mostly the same, but instead of dumping near-infinite `'!'`s, both will dump 42 bytes to `stdout`. However, for a maximum negative score, all you have to do is change `movs r5, #42` to `movs r5, #128` for a score of -86. Machine code: ``` 1009 e28f 4002 e92d e080 e3b0 f004 e49d e002 e201 ff11 e12f 252a 4676 19a8 f7ff fffe 3d01 d1fa bc01 4700 ``` (ARMv4T simulator left out, it is the same) Assembly: ``` .text .arm .globl main main: add r1, pc, #9 push {r1, lr} movs lr, #128 pop {pc} .Larmv4t_polyglot: and lr, r1, #2 @ b .Lthumb_entry; (skipped) bx r1 .thumb .Lthumb_entry: movs r5, #42 mov r6, lr .Lloop: adds r0, r5, r6 bl putchar subs r5, #1 bne .Lloop pop {r0} bx r0 ``` The main differences are that instead of initially setting `lr` to `-1`, we set `lr` to `128`, and that our print loop will always run 42 times, subtracting 1 from the char it prints each time. The equivalent C loop looks like this: ``` uint32_t r5 = 42, r6 = ARMv4T ? 0 : 128; do { putchar(r5 + r6); } while (--r5); ``` ARMv5TE+ output ``` termux ~/golf $ clang -m32 valid-through-the-ages.S termux ~/golf $ ./a.out | hexdump -C | cut -d' ' -f 3-19 aa a9 a8 a7 a6 a5 a4 a3 a2 a1 a0 9f 9e 9d 9c 9b 9a 99 98 97 96 95 94 93 92 91 90 8f 8e 8d 8c 8b 8a 89 88 87 86 85 84 83 82 81 ``` ARMv4T (simulated) output: As stated before, the compiler option is just to emulate the bug on my device. It is not needed on actual hardware. ``` termux ~/golf $ clang -m32 valid-through-the-ages.S -DSIMULATE_ARMV4T termux ~/golf $ ./a.out | hexdump -C | cut -d' ' -f 3-19 2a 29 28 27 26 25 24 23 22 21 20 1f 1e 1d 1c 1b 1a 19 18 17 16 15 14 13 12 11 10 0f 0e 0d 0c 0b 0a 09 08 07 06 05 04 03 02 01 ``` Program size: 42 bytes Difference in output length: None Differing bytes: 42. **Score: 0** ]
[Question] [ The **minmod** function is a variant of the familiar **min**, which appears in slope-limiting high-resolution schemes for partial differential equations. Given a number of slopes, it picks out the flattest slope, while taking care of relative signs between the slopes. The function takes an arbitrary number of parameters. Then *minmod(x1, x2, ..., xn)* is defined as: * *min(x1, x2, ..., xn)*, if all xi are strictly positive * *max(x1, x2, ..., xn)*, if all xi are strictly negative * *0*, otherwise. We'll only consider integer inputs, because that does not really affect the implementation and should be more inclusive for some (esoteric) languages. Write a program or function, which takes *n* signed integers (for *n > 0*) via STDIN, ARGV or function argument (you can use an array if that's more convenient than a variadic function), and returns or prints (to STDOUT) the result of *minmod(a,b)*. You must not use built-in *min* or *max* functions (and obviously, no built-in *minmod* either, if you can actually find that). In addition, you must not use any built-in sorting functions, *except* to sort a *fixed* small number of items (less than 5). If your language doesn't have signed types, you may use an unsigned type and *interpret* it as two's complement. E.g. if your language only uses unsigned bytes, you can use `255` to stand in for `-1` and `128` to stand in for `-128`, etc. This is code golf, so the shortest answer (in bytes) wins. # Test Cases ``` Input Output 2 2 -3 -3 0 0 3 -5 0 2 4 1 1 0 1 2 0 -1 1 2 0 -4 -2 -3 -2 -2 -5 0 -1 0 1 0 -1 0 ``` # Leaderboards The following Stack Snippet generates both a regular leaderboard and an overview of winners by language. So even if your language of choice doesn't let you win the entire challenge, why not try to snatch a spot on the second list? To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` ``` function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=42079;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/ ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table> ``` [Answer] ## Mathematica, 19 bytes ``` Median[#~Riffle~0]& ``` Code and golfing thanks to Martin Bรผttner. This is an unnamed pure function that takes in a list of integers as input. Invoke it like ``` Median[#~Riffle~0]&[{-2, -3, -2, -4}] ``` or similarly saved to variable. The code first riffles a zero in between every two elements of the input list, which inserts `n-1` zeroes among `n` elements. Then, it takes the median to produce the answer. This gives min-mod because it handles each case: 1. All the numbers are positive, in which case the zeroes are below them and the median is the lowest positive number. 2. All the numbers are negative, in which case the zeroes are above them and the median is the least negative number. 3. There's both a positive and negative number, and so the middle element is a zero. If Mathematica implements its median using the [linear-time selection algorithm](http://en.wikipedia.org/wiki/Median_of_medians#Algorithm), then this is also O(n). [Answer] ## GolfScript, 10 9 bytes ``` ~{0]$1=}* ``` Assumes input from stdin in the format `[-4 -2 -3 -2]` This uses the built-in sort function `$`, but every time it's invoked it's on an array of 3 elements, which is permitted. [Online demo](http://golfscript.apphb.com/?c=OydbMl0KWy0zXQpbMF0KWzIgNCAxXQpbMCAxIDJdClstMSAxIDJdClstNCAtMiAtMyAtMl0KWy01IDAgLTFdClsxIDAgLTFdJ24vewojIwoKfnswXSQxPX0qCgojIwpwfS8%3D) [Answer] # Haskell, ~~62~~ ~~61~~ ~~39~~ ~~38~~ 37 bytes ``` f s=last[x|x<-0:s,and[x*x<=x*y|y<-s]] ``` using some comparison magic borrowed from @Zgarb's answer\* , namely, `x*x<=x*y`. `x*x<=x*y` is true only when `x` and `y` have the same sign and `y`'s absolute value is bigger. note that when `x` is `0` it is always true. we determine that `x` is the result iff it is contained in `s`, and that for all `y` in `s` `x` has the same sign as `y` and is smaller in absolute value. if no value in `s` satisfies this definition, then `0` is the result. `f` then works by searching `s` for an element to satisfy this, and uses `0` as a default. \*though he didn't use it for the reasons I'm using it, and he actually got rid of it by now [Answer] # JavaScript (ES6), 39 bytes ``` a=>a.reduce((p,c)=>p*c>0?p*p>c*c?c:p:0) ``` [Answer] # Marbelous, 210 bytes ``` @0 00 ]]\\&002 /\..//&0@0 00..02 MMMMMM//\\ :M }0}1}0}1}0}1}0}2..}2 ^7^7||||&0&1&4<3&0=2{> EqalLteq{0{<{<<2&1-- &2..&3..}100..&2\/{> >0&6=0&4&5&6..\/ &3..&5\/{<{0 \/..\/ :| }000}0 &0Subt {0&1 }0{0 ^7 =0&1 &0 \/ ``` There are three boards used here. The `|` board (`Ab` in the readable version) takes the absolute value of a marble (by either returning the passed marble or zero minus the passed marble, as all arithmetic in Marbelous is unsigned). The `M` board (`Minabs` in the readable version) finds and outputs to the left either the first or second marble passed (whichever has a smaller absolute value), and exiting if a different signed marble is passed. The `M` board also releases the marble it holds downward instead of leftward once the last character from STDIN is fetched. The `M` board is used in the main board to store the minmod of all checked values at any given time, as it releases the value to be saved leftward, which is then deflected back in. Trashbins (`\/`) were only placed under synchronisers that would otherwise print to STDIN. Input/Output uses STDIN/STDOUT. Both deal with 8-bit values (if you wanted to pass +0x30 and +0x38, place `08` into STDIN). Libraries and cylindrical boards are both required. Viewing output as decimal numbers is recommended (note that this displays the unsigned value of the minmod result). [Test it here.](https://codegolf.stackexchange.com/a/40808/29611) **Note:** For more human-friendly input/output, add `Dp` under the last line of the main board (before `:M`), replace `]]` with `Rd`, and add the following at the bottom: ``` :Rd }0}0}0 ]]]]]]{> -O-O-O -O-O-O *A Plus \\*A ..Plus ..{0 :*A }0}0 <<<< << << Plus {0 ``` This simply changes the output to be 3 decimal digits. Likewise, input with these changes requires a space separated list of 3 decimal digits per number. ### Readable Version: ![Board Picture](https://i.stack.imgur.com/8yZPH.png) [Answer] # Python 2, 53 ``` lambda l:reduce(lambda a,b:sorted([a,b,0])[1],l,l[0]) ``` The idea is to use `reduce` to turn the two-input min-mod finder into an `n`-input one. I came up with it independently of the other answers that use it. Only Python 2 supports `reduce`. The two-input solution simply finds the median of the two numbers and zero. See my [Mathematica answer](https://codegolf.stackexchange.com/a/42100/20260) for a more direct way to use the median. Less golfed: ``` def f(l): A=l[0] for x in l:A=sorted([a,b,0])[1] return A ``` A hypothetical amalgam of Python 2 and Python 3 would be a character shorter, with the starred assignment from Python 3 and `input()` and `print` from Python 2. ``` #Not real code! A,*l=input() for x in l:A=sorted([A,x,0])[1] print A ``` Old code, without sorting: ``` lambda l:reduce(lambda a,b:[a,b][a*a>b*b]*(a*b>0),l,l[0]) ``` [Answer] # TIS-100, ~~696~~ 526 bytes ``` @1 MOV UP ACC SAV ADD 999 JEZ A SWP MOV 1 ANY MOV ACC ANY JRO -7 A:MOV 12 ANY @5 S:JRO UP MOV UP ACC JLZ A JEZ B MOV 1 DOWN JMP B A:MOV 7 DOWN NEG B:MOV 1 RIGHT MOV ACC RIGHT MOV ACC RIGHT JMP S MOV 14 DOWN MOV 9 RIGHT @6 MOV 999 ACC L:JRO LEFT SAV SUB ANY JGZ A MOV ANY NIL SWP JMP L A:MOV ANY ACC JMP L MOV ACC ANY @9 S:JRO UP JEZ A SUB 1 JEZ A JMP X A:MOV 1 ACC JMP S JEZ B SUB 2 JEZ B X:MOV 6 ACC JMP S B:MOV 2 ACC JMP S MOV ACC ANY @10 MOV LEFT ACC ADD 1 JRO ACC JRO 6 MOV UP ANY MOV UP ACC NEG MOV ACC ANY !NOP MOV 0 ANY ``` Expects the sequence to be terminated by `-999`. TIS-100 is newer than this question, but it's not like that matters here anyway. Node 9 keeps track of whether we're all positive, all negative or mixed. Nodes 5 and 6 work to find the minimum of the absolute value of all input numbers. Node 10 then selects the minimum, the minimum negated, or 0 depending on node 9's state. [![enter image description here](https://i.stack.imgur.com/Od6Vb.png)](https://i.stack.imgur.com/Od6Vb.png) [Answer] # Haskell, ~~83~~ ~~40~~ 39 bytes This is probably not the shortest possible Haskell solution (and certainly won't beat the others here), but it's a start. *EDIT:* Now over 50 % shorter! *EDIT2:* One byte less... ``` a#b|a*b<0=0|a*a<b*b=a|1<2=b m=foldr1(#) ``` This is just a straightforward fold (or reduce, as some languages call it) by the binary operator `#`, which computes the median of `a`, `b` and `0`. Even though the rules would now allow me to sort small lists, this requires an import in Haskell and results in a higher byte count (**49** bytes, but **31** without the import): ``` import Data.List a#b=sort[a,b,0]!!1 m=foldr1(#) ``` [Answer] # CJam, 20 bytes (or 10 bytes) ``` q~{]__~z\z<=\~*0>*}* ``` Using @xnor's approach, reduce calculating minmod of 2 numbers at a time from the array. *This would have been 19 bytes if `:z` worked* --- Using the new rule of using sorts on short arrays: ``` q~{0]$1=}* ``` which is exactly equivalent to @Peter's answer --- Previous 26 bytes asnwer: ``` q~_{g}%_|:+\(z\{za+_~>=}/* ``` This can be golfed further... Input (via STDIN) is the integer array like : ``` [-4 -2 -3 -2] ``` and output is the minmod of the input array [Try it here](http://cjam.aditsu.net/) *If only `:g` and `:z` worked, this would have been 4 bytes shorter.* [Answer] # Java, 84 bytes This is Java in all its glory. Beats GolfScript by a factor of slightly over 900%. ``` int f(int[]a){int b=a[0],c;for(int d:a)b=(c=d<0?-1:1)*b<0?0:d*c<b*c?d:b;return b;} ``` Wrapped in class: ``` public class MinModGolfed{ public static void main(String[] args){ int[] numbers = new int[args.length]; for (int i = 0; i < args.length; i++){ numbers[i] = Integer.parseInt(args[i]); } System.out.println(new MinModGolfed().f(numbers)); } int f(int[]a){int b=a[0],c;for(int d:a)b=(c=d<0?-1:1)*b<0?0:d*c<b*c?d:b;return b;} } ``` Expanded with comments: ``` public class MinModExpandedGolfed{ public static void main(String[] args){ int[] numbers = new int[args.length]; for (int i = 0; i < args.length; i++){ numbers[i] = Integer.parseInt(args[i]); } System.out.println(new MinModExpandedGolfed().f(numbers)); } int f(int[]a){ //a is the input numbers int b=a[0],c; //b is the best number found so far. for(int d:a) //Iterate over a with current element as d. b=(c=d<0?-1:1) //c is equal to the sign of d. *b<0? 0: //If b has opposite sign of d, b = 0. d*c<b*c?d:b;//If the absolute value of d is less than b, b = d. return b; } } ``` ***Note: This can be improved using Java 8.*** ***Note: Effort to improve in Java 8 failed.*** [Answer] # J, ~~20~~ 12 bytes Function taking the list as argument. Stolen from the Golfscript/CJam/whatever. ``` (1{0/:~@,,)/ ``` The minmod of `x` and `y` is the median (sort `/:~` and take the middle `1{`) of the three item list `0,x,y`. Reduce the list (*folding* in J parlance) by taking this minmod between adjacent elements. In use at the REPL. (J spells its negative sign `_`.) ``` (1{0/:~@,,)/ _4 _2 _3 _2 _2 f =: (1{0/:~@,,)/ NB. give it a name f 1 1 2 1 f 0 1 2 0 f _1 1 2 0 ``` Old garbage, before I noticed short sorts are allowed: `0:`<.`>.@.(*@]*0<*))/` The minmod of `x` and `y` is 0 (`0:`) if 0 is greater than or equal to the product of `x` and `y`, else it is the min (`<.`) or the max (`>.`) between `x` and `y` depending on the sign. Fold this over the whole list. [Answer] # TI-BASIC, 19 bytes Assumes input in the format `{-2,4,3}`. Works similarly to xnor's answer: ``` Input Lโ‚ get user input into the L1 array dim(Lโ‚)2-1โ†’dim(Lโ‚ get the length of the array; multiply by 2 and subtract 1 make this the new length (new elements always default to 0) median(Lโ‚ calculate and return (since it's the last line) median of new array ``` [Answer] # Python 2, ~~82~~ ~~79~~ ~~71~~ ~~69~~ 61 bytes ``` lambda l:reduce(lambda G,H:[H,G][(G>H)^(G>0)]*(G*H>0),l,l[0]) ``` This is based off of my pyth answer, which was inspired by [Mig's](https://codegolf.stackexchange.com/a/42083/31625) answer. --- Old answer: ``` l=input() m=l[0] k=1-2*(m<0) for i in l:m=[m,i][m>i*k] print(k*m>0)*m ``` This is a very long answer. ~~I feel like having 2 variables is a waste...?~~ I was right...? ish? ;p [Answer] # KDB/Q, 43 characters for function body definition Thanks to great ideas from previous posts: ``` f:{$[all 1_0<(*':)x;{$[<[x*x;y*y];x;y]}/[x];0]} ``` Enter single number using enlist ``` f[enlist 2] f[enlist 0] f[enlist -2] f[2 4 1] f[0 1 2] f[1 0 2] f[-1 1 2] f[-4 -2 -3 -2] f[-5 0 -1] f[-5 -0 -1] f[1 0 -1] ``` I'm sure some Q guru can come up with shorter ones. [Answer] # Pyth, ~~25~~ ~~22~~ ~~20~~ 12 ``` uhtS[0GH)QhQ ``` Probably not novel, but original :P --- Pre-sorting allowed ``` u*?Gx>GH>G0H>*GHZQhQ ``` [Pyth](https://github.com/isaacg1/pyth) [Try it online.](http://isaacg.scripts.mit.edu/pyth/index.py) The idea to use `reduce` and ternary statements was shamelessly stolen from [Mig's answer](https://codegolf.stackexchange.com/a/42083/31625), but I have no idea if these algorithms are otherwise even similar, as I can't read ternary statements. Explanation: ``` Q=eval(input) : implicit u QhQ : print reduce(lambda G,H: ..., Q, Q[0]) * >*GHZ : ... * (G*H>0) ?G H : G if ... else H x>GH>G0 : G>H xor G>0 ``` [Answer] # C#, 101 bytes My first try at code golfing and in a pretty golfing hostile language. Based on reduce (`Aggregate` in LINQ) and very similar to [the JavaScript answer by Mig](https://codegolf.stackexchange.com/a/42083/33152). Can be run like `(new System.Linq.M()).m(new[] {1, 2, 3})`. Passes all test cases, but doesn't handle empty input arrays. ``` namespace System.Linq{class M{public int m(int[]i){return i.Aggregate((a,b)=>a*b>0?a*a<b*b?a:b:0);}}} ``` [Answer] # J, 12 bytes ``` (=&**>&|{,)/ ``` The function reduces the list (called folding (`/`) in J) with the expression: `(signum(x) == signum(y)) * [x,y][abs(x)>abs(y)]` where `[x,y][abs(x)>abs(y)]` is `y` if `abs(x) > abs(y)` else `x`. Example: ``` (=&**>&|{,)/ 5 2 6 2 ``` [Try it online here.](http://tryj.tk/) [Answer] # Game Maker Language, 489 bytes [About Game Maker Language](http://gmc.yoyogames.com/) Riffles the array (zeros are appended) and returns the median (similar to my other answer) ``` i=0a=argument0 while(variable_local_array_get(a,i))i++ for(j=0;j++;j<i-1)a[j+i]=0var i,j,d,m=0d=ds_list_create()if variable_local_exists(a){if variable_local_array_get(a,0){for(i=0;i<32000;i++){if variable_local_array_get(a,i)=0break ds_list_add(d,variable_local_array_get(a,i))}ds_list_sort(d,0)i=ds_list_find_value(d,ds_list_size(d) div 2)j=ds_list_find_value(d,(ds_list_size(d) div 2)-1)m=ds_list_find_value(ds,ds_list_size(d) mod 2)ds_list_destroy(d)}if m return (i+j)/2return i break} ``` [Answer] # Java, ~~353~~ ~~304~~ 124 bytes Put together the worst language for code golf with the world's worst golfer and you get... ``` int m(int[]a){int m=a[0];if(m<0)for(int i:a){m=(i>m)?i:m;m=(i>0)?0:m;}else for(int i:a){m=(i<m)?i:m;m=(i<0)?0:m;}return m;}} ``` Ungolf it and you get: ``` int m(int[] a) { int m = a[0]; if (m < 0) { for (int i : a) { m = (i > m) ? i : m; m = (i > 0) ? 0 : m; } } else { for (int i : a) { m = (i < m) ? i : m; m = (i < 0) ? 0 : m; } } return m; } ``` This is a function (if it wasn't pretty damn obvious) that receives an array of numbers and processes its values, returning the minmod value. My old benemoth of a sollution is also included, which is a whole program - as always. ``` class M{public static void main(String[]a){java.util.Scanner s=new java.util.Scanner(System.in);int n,m=0;try{m=s.nextInt();if(m<0)while(true){n=s.nextInt();m=(n>m)?n:m;m=(n>0)?0:m;}else while(true){n=s.nextInt();m=(n<m)?n:m;m=(n<0)?0:m;}}catch(java.util.InputMismatchException e){System.out.print(m);}}} ``` Ungolf it and you get: ``` class M { public static void main(String[] a) { java.util.Scanner s = new java.util.Scanner(System.in); int n = 0, m = 0; try { m = s.nextInt(); if (m < 0) { do { n = s.nextInt(); m = (n > m) ? n : m; m = (n > 0) ? 0 : m; } while (true); } else { do { n = s.nextInt(); m = (n < m) ? n : m; m = (n < 0) ? 0 : m; } while (true); } } catch (java.util.InputMismatchException e) { System.out.print(m); } } } ``` Receives infinite numbers, stops when a non-number value is entered, presenting the Minmon value. [Answer] # R, 20 chars R is usually not good for codegolf, but I use it for my work so I wanted to try. Before I tried, I didn't know that R is willing to accept such a dirty syntax! :-) **52 chars**: ``` if((q=summary(x))[6]<0)q[6]else if(q[1]>0)q[1]else 0 ``` Then I looked the other answers I tried @xnor's genial median trick, which is great! ``` median(c(x-x,x)[-1]) ``` [Answer] # Python, 52 I still couldn't help feeling that it's bad to have two `lambda`s. This function takes in a list and then returns a one-element list containing the result. ``` f=lambda a:a[1:]and[sorted([a.pop(),0]+f(a))[1]]or a ``` Hopefully, it will not cause an enormous amount of offense to have the result in a one-element list. [Answer] # Matlab/Octave, 26 This is basically just a translation of [the Mathematica answer by xnor.](https://codegolf.stackexchange.com/a/42100/24877) It works by appending one zeros less than the length of the input vector. Note that appending one more would not work, since then the result would be 0 all the time. Thanks to MartinBรผttner for the -4 chars of this solution=) ``` @(x)median([x,0*x(2:end)]) ``` [Answer] # Python, ~~72~~ 60 bytes This is the first solution I thought of, and it's quite naive. The second half is basically a duplicate of the first half of the code, but I wasn't sure how to slim it. I wonder if it can be shortened using `eval`... Edit: Changed lambdas to comprehensions. [**Try them here**](http://ideone.com/n3OSXM) ``` lambda l:min(l)*all(x>0for x in l)+max(l)*all(x<0for x in l) ``` This is only 4 chars longer, but still worth looking at, using Sp3000's [TIP](https://codegolf.stackexchange.com/a/48994/34718). ``` lambda l:eval("+m%s%s(l)*all(x%s0for x in l)"*2%tuple("ax<in>")) ``` [Answer] ## Javascript, 63 ``` a=>a.reduce((p,c)=>p<0?c<0?Math.max(p,c):0:c>0?Math.min(p,c):0) ``` A more readable version: ``` function (arr) { return arr.reduce(function (p, c) { if (p < 0) { if (c < 0) { return Math.max(p, c); } else { return 0; } } else { if (c > 0) { return Math.min(p, c); } else { return 0; } } }); } ``` ]
[Question] [ Your task is to print this exact text: ``` ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช ``` (You are allowed to print a trailing newline) SHA256 hash of the UTF-8 encoding of the text: ``` 0ab6f1e0bf216a0db52a4a5a247f95cba6f51496de7a24dfd01f3985dfcf6085 ``` Base64 encoding: ``` 15DXkdeS15PXlNeV15bXl9eY15nXm9ea15zXnted16DXn9eh16LXpNej16bXpden16jXqdeq ``` ### Rules * You can't use a builtin outputting this text. * Standard loopholes are disallowed. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins. Good luck! [Answer] # MATLAB, ~~52~~ 51 bytes ``` [cumsum([1488 'CCCCCCCCCDADDAEADCDAEADCCC'-66]) ''] ``` Example use: ``` >> [cumsum([1488 'CCCCCCCCCDADDAEADCDAEADCCC'-66]) ''] ans = ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช ``` ### Explanation `'CCCCCCCCCDADDAEADCDAEADCCC'-66` produces the array `[1 1 ... -1 2 1 1 1]`, which contains the consecutive differences between the codepoints of the desired characters. `[1488 ...]` prepends `1488`, so the array is now `[1488 1 1 ... -1 2 1 1 1]`. `cumsum(...)` computes the cumulative sum: `[1488 1489 ... 1514]`. `[... '']` concatenates with the empty string. This has the effect of converting to char (and is one byte shorter than `char(...)`) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ ~~21~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 27R+โ€œยฟร‡ร‘รžรฆโ€˜ยฆ2แปค+1487แปŒ ``` [Try it online!](http://jelly.tryitonline.net/#code=MjdSK-KAnMK_w4fDkcOew6bigJjCpjLhu6QrMTQ4N-G7jA&input=) ### Idea If we subtract **1487** from each code point, we get the array **R** that follows. ``` 1 2 3 4 5 6 7 8 9 10 12 11 13 15 14 17 16 18 19 21 20 23 22 24 25 26 27 ``` That's just the range from **1** to **27**, but not in ascending order; the pairs **(11, 12)**, **(14, 15)**, **(16, 17)**, **(20, 21)**, and **(22, 23)** have been swapped. If we take the ascending range and add **2** to **11**, **14**, **16**, **20**, and **22**, we get the array **A** that follows. ``` 1 2 3 4 5 6 7 8 9 10 13 12 13 16 15 18 17 18 19 22 21 24 23 24 25 26 27 ``` This is no longer a permutation of the range, but if we stably sort the range by the values in that array, we can reconstruct the original array. ### Code ``` 27R+โ€œยฟร‡ร‘รžรฆโ€˜ยฆ2แปค+1487แปŒ Main link. No arguments. 27R Yield [1, ..., 27]. ยฆ Conditional application: โ€œยฟร‡ร‘รžรฆโ€˜ At indices 11, 14, 16, 20, and 22... + 2 add 2 to the corresponding value. This yields the array A from the previous section. แปค Grade up; sort the indices of the result by its corresponding values. This yields the array R from the previous section. +1487 Add 1487 to each integer in R. แปŒ Unordinal; convert integers to characters. ``` [Answer] ## PowerShell v2+, [58 bytes](https://ethproductions.github.io/bytes/?e=utf-16&t=%27%u05D0%u05D1%u05D2%u05D3%u05D4%u05D5%u05D6%u05D7%u05D8%u05D9%u05DB%u05DA%u05DC%u05DE%u05DD%u05E0%u05DF%u05E1%u05E2%u05E4%u05E3%u05E6%u05E5%u05E7%u05E8%u05E9%u05EA%27) (UTF-16) ``` 'ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช' ``` PowerShell Unicode is UTF-16 unless explicitly specified otherwise, and then it's a crapshoot anyway since it's all UTF-16 in the background. This just puts the literal string on the pipeline and the default `Write-Output` at the end of program execution prints it to screen. The shortest I could get the ASCII version is **63** ``` -join([char[]]'ABCDEFGHIJLKMONQPRSUTWVXYZ['|%{[char](1423+$_)}) ``` Which takes the ASCII value of the string `ABC...` and adds `1423` to each `char` to get the appropriate string. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~36~~ ~~29~~ ~~26~~ ~~25~~ 23 bytes Saved 2 bytes thanks to *Adnan* Uses [CP-1252](http://www.cp1252.com) encoding. ``` 1488โ€ขโ€™ร‰ร‡Wโ€“moรปโ€ข5Bvy<+Dรง? ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MTQ4OOKAouKAmcOJw4dX4oCTbW_Du-KAojVCdnk8K0TDpz8&input=) **Explanation** ``` 1488 # push 1488 (accumulator) โ€ขโ€™ร‰ร‡Wโ€“moรปโ€ข # push 2235174277545950437 5B # convert from base-5 to base-10 (122222222230330403230403222) v # for each digit in above number y< # decrease it by 1 + # add to accumulator Dรง? # print a copy of accumulator converted from code point ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 172 bytes This answer is based largely one [DJMcMayhem's solution here](https://codegolf.stackexchange.com/questions/96950/output-the-hebrew-alphabet/96958#96958) so I recomend you check it out. Like DJMcMayhem's solution this uses the `-rA` flag to reverse output and print to unicode. ``` (((((()()()()()){})))<(((({}{}{}()){({}[()])}{})){}{})>){({}[()]<(({})())>)}{}(((((()()())((((((((({}(((({}())[()])()())()())[()]))[()])()())())()())[()]))[()])()())())())()) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMMNGFQs7pWU1PTBiRWXQuCICEgM1pDM1azFiQJEtS0gwvagBSCNNqBpJFM09SAAYgw2CiwMRBZTRgXRRCPOAj9//9ft8gRAA "Brain-Flak โ€“ Try It Online") ## Explanation I made this answer by running a bunch of micro-optimizations over the original solution provided by DJMcMayhem. These optimizations while saving bytes, make the code unreadable and the algorithm obtuse. I, to be honest, do not really understand how or what my code does. Perhaps someday I will understand how this works... [Answer] # Python 3, 50 bytes ``` #coding:cp862 print('ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช') ``` The file must be created using the CP862 encoding or by reversing the following hexdump. ``` 0000000: 23 63 6f 64 69 6e 67 3a 63 70 38 36 32 0a 70 72 #coding:cp862.pr 0000010: 69 6e 74 28 27 80 81 82 83 84 85 86 87 88 89 8b int('........... 0000020: 8a 8c 8e 8d 90 8f 91 92 94 93 96 95 97 98 99 9a ................ 0000030: 27 29 ') ``` This could probably be ported to Python 2 (thus saving two bytes), but I lack the proper locale to test it. Python 3 dutifully prints an UTF-8 encoded version (or whatever is appropriate for the current locale) of the alphabet. ### Verification ``` $ base64 > hebrew.py -d <<< I2NvZGluZzpjcDg2MgpwcmludCgngIGCg4SFhoeIiYuKjI6NkI+RkpSTlpWXmJmaJyk= $ wc -c hebrew.py 50 hebrew.py $ echo $LANG en_US.UTF-8 $ python3 hebrew.py ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช ``` [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 23 bytes ``` 27,"%(*.0"{i_)e\}/'ืf+ ``` [Try it online!](http://cjam.tryitonline.net/#code=MjcsIiUoKi4wIntpXyllXH0vJ9eQZis&input=) ### How it works ``` 27, Push [0 ... 26]. "%(*.0" Push that string. Its code points are [37 40 42 46 48], which are [10 13 15 19 21] modulo the length of the string. { }/ For each character: i Compute its code point. _) Push an incremented copy. e\ Swap the integers of [0 ... 26] at those indices. 'ืf+ Add all resulting integers to the first character of the Hebrew alphabet. ``` [Answer] # [///](http://esolangs.org/wiki////), 27 bytes ``` ABCDEFGHIQSRTVUXWYbdcfeghiq ``` [Try it online!](http://slashes.tryitonline.net/#code=QUJDREVGR0hJUVNSVFZVWFdZYmRjZmVnaGlx&input=) Output is encoded in [CP424](http://unicode.org/Public/MAPPINGS/VENDORS/MISC/CP424.TXT). To verify it yourself: ``` $ echo ABCDEFGHIQSRTVUXWYbdcfeghiq | ./slashes.pl | python3 -c 'print(bytes(input(), "utf-8").decode("cp424"))' | base64 15DXkdeS15PXlNeV15bXl9eY15nXm9ea15zXnted16DXn9eh16LXpNej16bXpden16jXqdeqCg== ``` [Answer] ## JavaScript (ES6), 59 bytes ``` _=>"ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช" ``` Best I could do in ASCII was ~~80~~ ~~79~~ 78 bytes: ``` _=>String.fromCharCode(...[...0x377babbcf7f.toString(3)].map(c=>++n-c,n=1488)) ``` If a character array is acceptable, 75 bytes: ``` _=>[...0x377babbcf7f.toString(3)].map(c=>String.fromCharCode(++n-c),n=1488) ``` Edit: Saved some bytes thanks to @IsmaelMiguel. Saved another byte thanks to @ETHproductions. If you use Firefox 30-57 then you can save another 2 bytes thanks to @ETHproductions using generator or array comprehensions: ``` _=>String.fromCharCode(...(for(c of 0x377babbcf7f.toString(3,n=1488))++n-c)) _=>[for(c of 0x377babbcf7f.toString(3,n=1488))String.fromCharCode(++n-c)] ``` [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), 186 bytes ``` (((((((((((((((((((((((((((((((((()()()()()){})){}{}()){({}[()])}{})){}{})())())())())())())())())())()())[()])()())()())[()])()()())[()])()())())()())[()])()()())[()])()())())())()) ``` This code is 182 bytes long, and I added 4 bytes for two command line flags: `-r` and `-u` [Try it online!](http://brain-flak.tryitonline.net/#code=KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCkoKSgpKCkoKSl7fSkpe317fSgpKXsoe31bKCldKX17fSkpe317fSkoKSkoKSkoKSkoKSkoKSkoKSkoKSkoKSkoKSkoKSgpKVsoKV0pKCkoKSkoKSgpKVsoKV0pKCkoKSgpKVsoKV0pKCkoKSkoKSkoKSgpKVsoKV0pKCkoKSgpKVsoKV0pKCkoKSkoKSkoKSkoKSk&input=&args=LXJ1&debug=on) Many thanks to @Neil for this [awesome integer metagolfer](https://codegolf.stackexchange.com/a/90608/31716) that created this sweet way of pushing 1488 (the code point of the first character) ``` (((((((()()()()()){})){}{}()){({}[()])}{})){}{}) ``` Explanation: Pushing large number in brain-flak is relatively difficult. However, since the act of pushing a number also evaluates to that number, we can push several numbers at the same time for massive byte savings. Here is a more concrete example. The innermost part (that I wrote above) in psuedo code is ``` push(1488) ``` This expression evaluates to 1488, so we wrap the entire thing in another push statement: ``` push(push(1488) + 1) ``` This pushes 1488 *and* 1489, as well as evaluating to 1489. So we wrap this: ``` push(push(push(1488) + 1) + 1) ``` which pushes 1488, 1489, and 1490, as well as evaluating to 1490. Repeat this step for each number we need to push. However, since the increments aren't always 1, it's a little bit more complicated than that. Here is a more readable version: ``` ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( #Push 1488 (((((((()()()()()){})){}{}()){({}[()])}{})){}{}) ()) # + 1 ()) ()) ()) ()) ()) ()) ()) ()) ()()) # + 2 [()]) # - 1 ()()) # + 2 ()()) [()]) # - 1 ()()()) # + 3 [()]) # - 1 ()()) # + 2 ()) # + 1 ()()) # + 2 [()]) # - 1 ()()()) # + 3 [()]) # - 1 ()()) # + 2 ()) # + 1 ()) ()) ``` [Answer] # [///](//esolangs.org/wiki////), 54 bytes ``` ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช ``` [Try it online!](//slashes.tryitonline.net#code=15DXkdeS15PXlNeV15bXl9eY15nXm9ea15zXnted16DXn9eh16LXpNej16bXpden16jXqdeq) There can't be any version more golfed than this :( [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 28\*2-1=55 bytes ``` "ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช ``` [Try it online!](http://05ab1e.tryitonline.net/#code=IteQ15HXkteT15TXldeW15fXmNeZ15vXmtec157Xndeg15_Xodei16TXo9em16XXp9eo16nXqiI&input=) -1 byte thanks to Emigna + 28 bytes thanks to DJMCMayhem ;). [Answer] # Scala/Groovy/Python 3, 9 ascii-chars + 27 2-byte chars = 63 bytes ``` print("ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช") ``` assuming UTF-8 # Scala, 59 bytes ``` print("ABCDEFGHIJLKMONQPRSUTWVXYZ["map(x=>(x+1423).toChar)) ``` `x+1423` is the same as `x-'A'+1488` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 35 bytes ``` dโ†โณ27 d[โŽ•Aโณ'KNPTV']+โ†2 โŽ•UCS 1487+โ‹d ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@VR24RHvZuNzLlSoh/1TXUEstW9/QJCwtRjtYFSRlxAQZCSvqmhzsEKhiYW5tqPertT/v8HAA "APL (Dyalog Unicode) โ€“ Try It Online") [Answer] # C#6+, ~~76~~ ~~86~~ 82 bytes ``` void f()=>Console.Write("ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช"); ``` First attempt at Golfing. Am I doing this right? **EDIT**: +6 bytes for forgetting to enclose in a function. Thanks @Kevin # C#5 and below version, ~~86~~ 82 bytes ``` void f(){Console.Write("ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช");} ``` [Answer] # Fourier, 53 bytes ``` |+2a|X1488~i+10(ia^~i)^avaXXva+3avaX^aXva+3avaX^a^a^a ``` Uses functions again. [**Try it FourIDE!**](https://beta-decay.github.io/editor/?code=fCsyYXxYMTQ4OH5pKzEwKGlhXn5pKV5hdmFYWHZhKzNhdmFYXmFYdmErM2F2YVheYV5hXmE) [Answer] # ArnoldC, 112 bytes ``` IT'S SHOWTIME TALK TO THE HAND "ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช" YOU HAVE BEEN TERMINATED ``` [Answer] ## [Keg](https://github.com/JonoCode9374/Keg), 34 bytes Inspired by a Powershell solution. ``` ZYXVWTUSRPQNOMKLJIHGFEDCBA(ึ+")(, ``` [TIO](https://tio.run/##y05N//8/KjIiLDwkNDgoINDP39fbx8vTw93N1cXZyVHjWr@2kqaGzv//AA) [Answer] # **[BaCon](http://www.basic-converter.org), 57 bytes** * In most BASICs, the question mark simply represents PRINT. * At first glance, the solution below looks like 30 bytes, but the Hebrew characters need 2 bytes of storage because of UTF-8. So there are 27 characters x 2 bytes + 1 byte for the '?' and 2 bytes for the double quotes = 57 bytes. Solution: ``` ?"ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช" ``` [Answer] # [s-lang](http://dgrissom.com/s-lang/), 59 bytes Really simple answer... ``` t[][ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช] ``` * `t` - replace function (replaces "nothing" in the input with the alphabet...) ## [Try it here](http://dgrissom.com/s-lang/?t[][%D7%90%D7%91%D7%92%D7%93%D7%94%D7%95%D7%96%D7%97%D7%98%D7%99%D7%9B%D7%9A%D7%9C%D7%9E%D7%9D%D7%A0%D7%9F%D7%A1%D7%A2%D7%A4%D7%A3%D7%A6%D7%A5%D7%A7%D7%A8%D7%A9%D7%AA]) [Answer] # zsh, ~~25~~ 21 bytes ``` echo ${(j..):-{ืช..ื}} ``` My browser is messing it up: the ืช should be the first letter, then the ื. If you paste somewhere else, though, it should work. The old version: ``` for i in {ืช..ื};printf $i ``` [Answer] # Java 7, 85 bytes ``` void c(){System.out.print("ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช");} ``` I'm not even gonna bother posting test code or a 'Try it here' like I usually do.. [Answer] ## Perl 6 (74) ``` (map (*+1488).chr,[\+] '122222222230330403230403222'.comb >>->>1.join.say ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 49 bytes ``` -11.upto(15){|r|$><<(""<<r+1499-2601[r]+5202[r])} ``` [Try it online!](https://tio.run/##KypNqvz/X9fQUK@0oCRfw9BUs7qmqEbFzsZGQ0nJxqZI29DE0lLXyMzAMLooVtvUyMAISGvW/v8PAA "Ruby โ€“ Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 23 bytes ``` main=putStr['ื'..'ืช'] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKQoWv36BHU9PfXrq9Rj//8HAA "Haskell โ€“ Try It Online") This works in TIO's version of Haskell [Answer] # C, 49 bytes ``` f(i){for(i=0x5d0;i<=0x5ea;i++)wprintf(L"%lc",i);} ``` Some users may need to call `setlocale` before using this but it worked fine for me. [Answer] # [Clean](https://clean.cs.ru.nl), 62 bytes ``` Start="ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืšืœืžืื ืŸืกืขืคืฃืฆืฅืงืจืฉืช" ``` [Try it online!](https://tio.run/##BcFtEkJQGIDRrTT@W0KrsIJLGDMXM2gfJUL5iIja0LMbb@c42lWRhPHprN1DqIJIrEwl2dHgwpWcGwUldypqGp48aOnpeDEwMjHz5sPCysaXnyGyO55Wfiqm/Qc "Clean โ€“ Try It Online") ]