text
stringlengths
180
608k
[Question] [ Write a program with length n that outputs another program whose length is the next Fibonacci number after n. The new program must do the same thing - output another program whose length is the next Fibonacci number, etc. n itself (the original program's length) does not have to be a Fibonacci number, although it would be nice if it is. Shortest code wins. No external resources, ASCII only, free compiler/interpreter required. If your output ends in a newline, it is also counted. [Answer] # Python 2, 160 bytes ``` s='s=%s;c=s;l=len(s%%c)+4;a,b=1,1\nwhile b<l:a,b=b,a+b\nc+="1"*(b-l-1);print s%%`c`;a=1' c=s l=len(s%c)+4 a,b=1,1 while b<l:a,b=b,a+b c+="1"*(b-l-1) print s%`c` ``` This is a true quasi-quine; it doesn't read its own source, but it generates it. First output (has trailing newline): ``` s='s=%s;c=s;l=len(s%%c)+4;a,b=1,1\nwhile b<l:a,b=b,a+b\nc+="1"*(b-l-1);print s%%`c`;a=111111111111111111111111111111111111111111111111111111111111111111111';c=s;l=len(s%c)+4;a,b=1,1 while b<l:a,b=b,a+b c+="1"*(b-l-1);print s%`c`;a=1 ``` Second: ``` s='s=%s;c=s;l=len(s%%c)+4;a,b=1,1\nwhile b<l:a,b=b,a+b\nc+="1"*(b-l-1);print s%%`c`;a=1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111';c=s;l=len(s%c)+4;a,b=1,1 while b<l:a,b=b,a+b c+="1"*(b-l-1);print s%`c`;a=111111111111111111111111111111111111111111111111111111111111111111111 ``` Edit: Oops. Forgot to change the string when I changed from `;`s to `1`s, so the second output was outputting extra semicolons (which Python doesn't support). Fixed [Answer] # CJam, ~~41~~ 31 bytes ``` {1$+S@]_1=4+1$`,-S*"2$~"}21D2$~ ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### Output ``` $ cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~'); echo {1$+S@]_1=4+1$`,-S*"2$~"}34 21 2$~ $ cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~') | wc -c 34 $ cjam <(cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~')); echo {1$+S@]_1=4+1$`,-S*"2$~"}55 34 2$~ $ cjam <(cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~')) | wc -c 55 $ cjam (cjam <(cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~'))); echo bash: syntax error near unexpected token `cjam' $ cjam <(cjam <(cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~'))); echo {1$+S@]_1=4+1$`,-S*"2$~"}89 55 2$~ $ cjam <(cjam <(cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~'))) | wc -c 89 ``` ### How it works ``` { " {…} 21 13 "; 1$+ " Duplicate the higher number and add. {…} 21 34 "; S@ " Push a space and rotate the lower number on top. {…} 34 ' ' 21 "; ] " Wrap the stack into an array. [ {…} 34 ' ' 21 ] "; _1= " Push the second element of the array. [ {…} 34 ' ' 21 ] 34 "; 4+ " Add 4 to it. [ {…} 34 ' ' 21 ] 38 "; 1$`, " Push the length of the stringified array. [ {…} 34 ' ' 21 ] 38 37 "; -S* " Subtract and push that many spaces. [ {…} 34 ' ' 21 ] ' ' "; "2$~" " Push the string '2$~'. [ {…} 34 ' ' 21 ] ' ' '2$~' "; } " {…} "; 21D " Push 21 and 13. {…} 21 13 "; 2$~ " Copy the code block an evaluate. [ {…} 34 ' ' 21 ] ' ' '2$~' "; ``` [Answer] # Python - 89 ``` g="%(s,b,a+b);print o.ljust(b-1)";s,a,b="s,a,b=%r,%i,%i;o=s%"+g,89,144;exec("o=s"+g)##### ``` My perfect character count is *gone*. ;\_; Thanks to TheRare for pointing out the newline thing and Quincunx for suggesting I use Python 2, shaving off 2 chars. **EDIT**: Now just uses more `#`s instead of `1`s; 12 chars shorter. **EDIT 2**: 94 chars! Eliminated some repetition. >:3 **EDIT 3**: Shorter repr alternative for Python 2. **EDIT 4**: Output is a character shorter now. **EDIT 5**: The use of `%r` to shorten it was taken from an answer on another question by @primo. **EDIT 6**: Shorter. :D Here's a Python 3 version: ``` g="%(s,b,a+b);print(o.ljust(b-1))";s,a,b="s,a,b=%r,%i,%i;o=s%"+g,89,144;exec("o=s"+g)#### ``` This answer is similar to the one by @Quincunx. [Answer] # CJam, 26 23 I just had a try with your language. ``` 7{9\@5mq)2/*')*\"_~"}_~ ``` 9 is `(22*0.618 + 0.5 - 1)/1.618 + 1`. It computes its own length`*1.618` instead of repeatedly adding the two numbers. In the first version, it will fill the output before `{` like `1)))))))))`, which counts those characters themselves. Say the result `n`. The total length is `n+22`, and the new length before `{` should be `(n+22)*1.618-22`, rounded. Decrease it by one to count the number of `)`'s. Then it will be approximately equal to `(n+8)*1.618`. Older version: ``` -3{1\@5mq)2/*E+')*\"_~"}_~ ``` The number 14 is `24*0.618 + 0.5 - 1`. [Answer] # JavaScript, 94 ``` (function q(w,e){return ('('+q+')('+e+','+(s=w+e)+')'+Array(s).join('/')).substr(0,s)})(55,89) ``` Based on a well-known [JavaScript Quine](http://www.nyx.net/~gthompso/self_javas.txt), this returns almost the same function, only followed by amount of slashes, such that it sums up to 144 which is the next Fibonacci number after N. And so on... N is not a Fibonacci number, but it was only "nice to have". [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 65 bytes ``` a,b=55,89;exec(s:="print((f'a,b={b,a+b};exec(s:=%r)#'%s*b)[:b])") ``` [Try it online!](https://tio.run/##RY7BCoMwEETv@YolRUza5CBFsCl@iXhINGkDEiXxUBG/3Rot9rQ7O8ubGabx3bt7Mfi16VtdYoxXyVSZ56x4PPVHNySIEg/eupEQk0ZvVkze1HK6iaeXNAlXRSuhaorpulGqTPCsRqjVBlobhk5OJFCBAA6WSTnnBOZOu@2@AN1kSk87xPXV9Up2EIttKg4oISBkeg8WrAMv3UuTfMfubeIPm4@6WPxylz@Wrl8 "Python 3.8 (pre-release) – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 63 bytes ``` (f(a,b)=print1(s=Str("(f="f")("b","a+b");")10^(b-#s-1)))(55,89) ``` [Try it online!](https://tio.run/##BcFBCoAgFATQu0ybGVLIhVCEp2gf@BeGmxDt/vZey736p83JwuxMqfX6foEjXV8nWBIKRBgc8mrQCYXtpvll@CCJMbr90Jw/ "Pari/GP – Try It Online") [Answer] ## Mathematica ``` ({0}; With[{n = Ceiling[ InverseFunction[Fibonacci]@LeafCount@#0 ], l = Length[#0[[1, 1]]]}, #0 /. {0..} -> ConstantArray[0, Fibonacci[n+1] - LeafCount[#0] + l] ]) & ``` This is a very straightforward implementation (i.e. no obfuscation here). It is an anonymous function that returns itself with a bit of padding to achieve the correct length. Mathematica is homoiconic: code and data are both represented as Mathematica expressions, which makes it realtively easy to modify/generate code on the fly. This also means that character counts are not a natural measure of code length. Epxression size (["leaf count"](http://reference.wolfram.com/language/ref/LeafCount.html)) is. This version is based on leaf counts as code length measure. If we assign this anonymous function to a variable `f` (so I can show what happens in a readable manner), and keep calling it 1, 2, 3, ... times, each time measuring the length of the return value, this is what we get: ``` In[]:= f // LeafCount Out[]= 42 In[]:= f[] // LeafCount Out[]= 89 In[]:= f[][] // LeafCount Out[]= 144 In[]:= f[][][] // LeafCount Out[]= 233 ``` Regarding the free interpreter requirement: Mathematica is free for the Raspberry Pi. Otherwise this code should be straightforward to port to [Mathics (open source)](http://www.mathics.net/). The only thing missing from Mathics is `InverseFunction`, which can be replaced as [here](https://stackoverflow.com/a/5162856/695132) (but I'm lazy :). [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 78 bytes ``` p,c=55,89;exec(s:="print((a:=f'p,c={c},{p+c};exec(s:=%r)'%s)+'#'*(c-len(a)))") ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v0An2dbUVMfC0jq1IjVZo9jKVqmgKDOvREMj0co2TR0kXZ1cq1NdoJ1cC1eiWqSprlqsqa2urK6lkaybk5qnkaipqamk@f8/AA "Python 3.8 (pre-release) – Try It Online") --- # [Python 2](https://docs.python.org/2/), 79 bytes ``` p,c,s=55,89,"a='p,c,s=%d,%d,%r;exec s'%(c,p+c,s);print a+'#'*(c-len(a))";exec s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v0AnWafY1tRUx8JSRynRVh3CV03RAaEi69SK1GSFYnVVjWSdAm2gjKZ1QVFmXolCora6srqWRrJuTmqeRqKmphJU5f//AA "Python 2 – Try It Online") ]
[Question] [ [Balanced ternary](https://en.wikipedia.org/wiki/Balanced_ternary) is a modified version of ternary (base 3), using the three digits `1`,`0` and `-1` (written as `T`) to represent numbers. The balanced ternary representation of `-n` can be obtained by replacing `1` with `T` and `T` with `1` in the balanced ternary representation of `n`. Examples: ``` 1 // decimal: 1 T // decimal: -1 1T // decimal: 3-1 = 2 T1 // decimal: -3+1 = -2 1TTT0 // decimal: 3^4-3^3-3^2-3^1+0= 42 ``` Your task is to write a function or program that outputs all positive integers `n` for which reversing the balanced ternary representation gives the balanced ternary representation of `-n` ([OEIS 233571](https://oeis.org/A233571)). Example: `1100T0100TT` (decimal `78080`) reversed is `TT0010T0011` (decimal `-78080`) The first few numbers in the sequence: ``` 1 -> 2 // balanced ternary: 1T 2 -> 8 // balanced ternary: 10T 3 -> 20 // balanced ternary: 1T1T 4 -> 26 // balanced ternary: 100T 5 -> 32 // balanced ternary: 11TT 6 -> 56 // balanced ternary: 1T01T ... 100 -> 14600 // balanced ternary: 1T1T001T1T ... 9999 -> 132258878 // balanced ternary: 1001T00TT11001T00T ``` # Rules * The standard sequence [I/O rules](https://codegolf.stackexchange.com/tags/sequence/info) apply * It is allowed to output numbers in balanced ternary: (as a string using three distinguishable characters, or as a list of digits) * Your code should be able to handle at least the first 10000 elements of this sequence * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution (in each language) measured in bytes wins [Answer] # [JavaScript (V8)](https://v8.dev/), 59 bytes Prints the sequence infinitely. ``` for(k=1;v=++k;t+k||print(k))for(t=0;v;v=v/3|0)t=++v%3-1+t*3 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPb1tC6zFZbO9u6RDu7pqagKDOvRCNbUxMkV2JrYF0GlC3TN64x0CwBqipTNdY11C7RMv7/HwA "JavaScript (V8) – Try It Online") ### How? We convert \$k\ge2\$ to balanced ternary. Each produced digit is immediately used to convert the reversed balanced ternary representation of \$k\$ back to a decimal value \$t\$. If we end up with \$k=-t\$, we print \$k\$. ### Commented ``` for( // outer loop: k = 1; // start with k = 1 v = ++k; // increment k and set v = k // (this is > 0, so we loop forever) t + k || print(k) // after each iteration: print k if t + k = 0 ) // for( // inner loop: t = 0; // start with t = 0 v; // stop when v = 0 v = v / 3 | 0 // after each iteration: update v to ⌊v/3⌋ ) // t = // update t: ++v % 3 - 1 + // increment v and compute the next balanced // ternary digit (v mod 3) - 1 t * 3 // add t * 3 ``` --- # [C (gcc)](https://gcc.gnu.org/), 74 bytes ``` v;t;main(k){for(;v=++k;t+k||printf("%d ",k))for(t=0;v;v/=3)t=++v%3-1+t*3;} ``` [Try it online!](https://tio.run/##FcpBCoAgEADAr4QQaCYVHhcfI4YRlkUt26H6eludZ4IZQmAmQJj9mGVSZ1w2CeS0ToA6Xde6jRmjFGVfiDop9Tu6FgiocVbhN6m0ptNYWbiZnxAnP@xsjhc "C (gcc) – Try It Online") [Answer] # [Python](https://www.python.org), 86 bytes ``` f=lambda x:x and[-~x%3]+f(-~x//3)or[] i=1 while i: if f(i:=i+1)==f(-i)[::-1]:print(i) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3w9JscxJzk1ISFSqsKhQS81KidesqVI1jtdM0gAx9fWPN_KLoWK5MW0Ou8ozMnFSFTCsuhcw0hTSNTCvbTG1DTVtboMpMzWgrK13DWKuCosy8Eo1MTYjpUEtglgEA) * -3 bytes thanks to [SuperStormer](https://codegolf.stackexchange.com/questions/262985/numbers-that-can-be-negated-by-reading-backwards/262988?noredirect=1#comment576201_262988) * -3 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/questions/262985/numbers-that-can-be-negated-by-reading-backwards/262988?noredirect=1#comment576235_262988) * -1 byte thanks to [Value Link](https://codegolf.stackexchange.com/questions/262985/numbers-that-can-be-negated-by-reading-backwards/262988?noredirect=1#comment576245_262988) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 21 bytes ``` L?b+y/hb3%b3Y.fq_yZy_ ``` [Try it online!](https://tio.run/##K6gsyfj/38c@SbtSPyPJWDXJOFIvrTC@Mqoy/v9/QwMDAA "Pyth – Try It Online") Outputs the first `n` terms of the sequence. ### Explanation ``` L?b+y/hb3%b3Y.fq_yZy_ZQ # implicitly add ZQ # implicitly assign Q = eval(input()) L # define y(b) ?b # conditional, if b: y/hb3 # y((b+1) / 3) + %b3 # append b % 3 Y # else: [] .f Q # return the first Q inputs where lambda Z is true _yZ # y(Z) reversed q # equals y_Z # y(-Z) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` Nθ1Φ⍘θT01κF⊖⊟⮌↨θ³0⮌Φ⍘θ10TκT ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0RDyVAJznbLzCkBSjolFqcGlwBF0jUKdRSUQgyASnQUsjWB6tLyixQ0XFKTi1JzU/NKUlM0AvILNIJSy1KLilPB@kA6jDVBQAFqvgHCfJhC7PYYGoRA7UE4Dihi/f@/oYHBf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `n`th term of the sequence. Explanation: ``` Nθ ``` Input `n`. ``` 1 ``` Start by printing a `1`. ``` Φ⍘θT01κ ``` Print `n` in base 3, decrementing all of the digits (so `0` becomes `T`), but skipping the first digit. ``` F⊖⊟⮌↨θ³0 ``` Print a `0` if `n`'s first digit in base 3 is `2`. ``` ⮌Φ⍘θ10Tκ ``` Print `n` in base 3, again decrementing after skipping the first digit, but then negating and reversing the result. ``` T ``` Print a `T`. [Answer] # [Raku (Perl 6) (rakudo)](https://raku.org), ~~69~~ 66 bytes ``` .&(my&g={1 x?$_&&g(-+^$_ div 3)~$_%3})==g(-$_).flip&&.say for 1..* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hY5PCoJAHIX3nWIGf45_RgdlNoEMQgdpEEqTlMK0ErWLtHFRh7LTZCghEbV5b_H4Pt71lgXbou0eSrjLkMuY6zgOqgALboL00hJy4Xh9UApY5bZLITc5Om3iZI0Ao1V8FLzfKci6ZoegbGbKCFsDbOl_aMOa4GhyY6YwoqcliUQF0vcj3aZLkC8IceMCUuUYa1pjCNFPIA0WJvGekE_NvchDe94t3jIXnX2QhHwR_pSZg6kda-wn) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞ʒD(‚ε[©_#®>D3%s3/ï})}`RQ ``` Inspired by [*@mousetail*'s Python answer](https://codegolf.stackexchange.com/a/262988/52210) and [*@CursorCoercer*'s Pyth answer](https://codegolf.stackexchange.com/a/262995/52210). Outputs the infinite sequence. [Try it online.](https://tio.run/##ASwA0/9vc2FiaWX//@KInsqSRCjigJrOtVvCqV8jwq4@RDMlczMvw699KX1gUlH//w) Unfortunately 05AB1E rounds towards 0 for integer-division of negative values, unlike Python which always floors. Otherwise `[©_#®>D3%s3/ï}` could have been `[©_#®>3‰R`}` for -3 bytes by using divmod builtin `‰`. [See that it gives the expected result for positive integers, but not for negative ones.](https://tio.run/##yy9OTMpM/f/fReNRw6xzW6MPrYxXPrTOzvhRw4aghFrN//8tAA) **Explanation:** ``` ∞ # Push an infinite positive list: [1,2,3,...] ʒ # Filter it by: ‚ # Pair the current value ( # with a negative D # copy of that value ε # Map over this [n,-n] pair: [ # Start an infinite loop: © # Store the current value in variable `®` (without popping) _ # Pop and if it's 0: # # Stop the infinite loop ® # If not, push `®` again > # Increase it by 1 D # Duplicate it 3% # Modulo-3 s # Swap so the value+1 is at the top again 3/ # Divide by 3 ï # Floor (by casting to an integer) }) # After the infinite loop: wrap all values on the stack into a list }` # After the map: pop and push both lists to the stack R # Reverse the second list Q # Then check if the two lists are the same # (after which the filtered infinite list is output implicitly as result) ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 14 bytes ``` Ňᵐ{3r~←}1c:↔_= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FluPtj_cOqHauKjuUduEWsNkq0dtU-JtlxQnJRdDVcBUAgA) Outputs the numbers in balanced ternary (as lists of digits). --- # [Nekomata](https://github.com/AlephAlpha/Nekomata), 16 bytes ``` Ňᵐ{3r~←}1c:↔_=3b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FtuPtj_cOqHauKjuUduEWsNkq0dtU-JtjZOWFCclF0PVwNQCAA) Outputs the numbers in the usual form. ``` Ňᵐ{3r~←}1c:↔_=3b Ň Choose a natural number n ᵐ{ } Map the following function to the range [0, n) 3r~ Choose a random number from [0, 3) ← Decrement (These two steps generate any tuple of [-1, 0, 1]) 1c Prepends 1 (This ensures that it is the balanced ternary representation of a positive number) : Duplicate ↔ Reverse _ Negate = Check equality 3b Convert from base 3 ``` [Answer] # [ForWhile](https://esolangs.org/wiki/ForWhile), 119 bytes ``` {1:2$4$[2@4;+'[1-:@48+#)1-:@[48#.]2@[1+:@48'-#).10#.4::@1+'$2@[:@2=[0~;$1+::@1+'$]:)2@4+=[3::@~'$@![2:@1+'$]2@3+1'$]1)} ``` Input: integer `n` on the stack Prints the first `n` numbers of the sequence in balanced ternary with `/` as symbol for `-1` [Online Interpreter](https://bsoelch.github.io/OneChar.js/?lang=forwhile&src=ewogMToyJDQkCiBbCiAyQDQ7KydbMS06QDQ4KyMpMS06QFs0OCMuXTJAWzErOkA0OCctIykuMTAjLjQKIDo6QDErJyQyQFs6QDI9WzB-OyQxKzo6QDErJyRdOikyQDQrPVszOjpAfickQCFbMjpAMSsnJF0yQDMrMSckXQogMSkKfTAkCgoxMDAgMEA_) Explanation: Memory: * cell 2 -> length of first half of number * cell 3 -> marker if total length is odd * cells 4ff -> digits of first half of number (from center outwards) ``` { \ procedure 1:2$4$ \ store 1 in cells 2 (length) and 4 (start of value) [ \ loop-without pushing the loop-counter 2@4;+'[1-:@48+#) \ write the first digits of the number 1-:@[48#.] \ write 0 if number has odd length 2@[1+:@48'-#).10#.4 \ write digits reversed and mirrored ::@1+'$2@[:@2=[0~;$1+::@1+'$]:) \ increment number 2@4+=[ \ check for overflow 3::@~'$ \ flip cell 3 @![2:@1+'$] \ increase length if new length is even 2@3+1'$ \ set top trit (ternary digit) to 1 ] 1) \ go back to start of loop } ``` [Answer] # [Perl 5](https://www.perl.org/), 134 bytes ``` while(++$n){for$c("",0){$_="T"x$n;s/T/1/;do{($b=reverse)=~y/1T/T1/;print"$_$c$b$/"}while(/(?=[T0]1*$)/g&&substr($_,pos)=~y/T01/01T/)}} ``` Like some other answers, it uses string manipulations only, no math, to produce the reflected pattern of the sequence elements. * `while (++$n)` : Loop over increasing length of the prefix, endlessly. + `for $c ("",0)` : Do all the following twice, once with an empty string for the "center" and once with digit "0" for the "center". - `$_ = "T" x $n; s/T/1/;` : Form the smallest positive value of length `$n`, by creating a string of "T" characters then changing its first character to "1". - `do`... * `($b = reverse) =~ y/1T/T1/;` : Form the suffix by reversing the prefix then negating its digits. * `print "$_$c$b$/"` : Print the full output: prefix, center, suffix, and newline. - `while (/(?=[T0]1*$)/g && substr($_, pos) =~ y/T01/01T/)` : Increment the prefix as a ternary string. Find the position of the last digit which is not a "1". The loop ends if the string is nothing but "1" digits. Otherwise, change the digit found from "T" to "0" or from "0" to "1", and change all the following "1" digits (if any) to "T" digits. [Try it online!](https://tio.run/##JcxNCsMgEEDhuwxD0CYwuugqSC/hrhTB1LaBoKLpH2KvbkO7frwvurTsW3ve5sWxvkfPyyUknBjAIHhBo0DDC/2YSZOk8RwKQ6uSe7iUHVefN0lNeisxzX4FNDihRYL6J4kd1FGLk9whp2vX5bvNa2Johhjyb9dCktgMXmtrXw "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Port of [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s Charcoal [answer](https://codegolf.stackexchange.com/a/263003/53748) - go show your love. ``` b3’µḢR¬;ṚN⁸;Ø+j ``` A monadic Link that accepts a positive integer, \$n\$, and yields the \$n^{\text{th}}\$ reverse-negate-invariant number in balanced ternary as a list of integers from \$\{-1,0,1\}\$. **[Try it online!](https://tio.run/##ASUA2v9qZWxsef//YjPigJnCteG4olLCrDvhuZpO4oG4O8OYK2r///85 "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ATAAz/9qZWxsef//YjPigJnCteG4olLCrDvhuZpO4oG4O8OYK2r/w4figqzhuIUz//8xMDA "Jelly – Try It Online") (first 100 converted to integers). ### How? ``` b3’µḢR¬;ṚN⁸;Ø+j - Link: positive integer, n e.g. 21 b3 - convert {n} to base three [2,1,0] ’ - decrement {each digit} D = [1,0,-1] µ - start a new monadic chain - f(D=that) Ḣ - pop the head off {D} and yield it 1 (and D -> [0,-1]) R - range {that} (1 -> [1] else []) [1] ¬ - logical NOT {that} ([] -> []; [1] -> [0]) [0] Ṛ - reverse {modified D} [-1,0] ; - concatenate [0,-1,0] N - negate {that} [0,1,0] ⁸ - chain's left argument -> modified D [0,-1] ; - concatenate [0,-1,0,1,0] Ø+ - signs literal -> [1,-1] [1,-1] j - join [1,0,-1,0,1,0,-1] ``` ]
[Question] [ Given two non-negative integers e.g. `27, 96` their multiplication expression would be `27 x 96 = 2592`. If now each digits is replaced with a symbol, such that * *two digits are replaced with the same symbol if and only if they are equal* we could get something like `AB x CD = AECA` or `0Q x 17 = 0Z10` or `!> x @^ = !x@!`. (following this rule we can also get the original expression itself but we'd lose the meaning of the digits being numbers since they will become just placeholders). We call such an expression a ***cryptic multiplication*** of `{27, 96}`. Is clear that some information is lost and the process is not always reversible, indeed an `AB x CD = AECA` ***cryptic multiplication*** can be obtained from each of the following pairs * `{27, 96}` `27 x 96 = 2592` * `{28, 74}` `28 x 74 = 2072` * `{68, 97}` `68 x 97 = 6596` There is no other pair of numbers that yields `AB x CD = AECA`. Hence ***3*** is the ***cryptic multiplication ambiguity*** of `{27, 96}` Write a function or a program that given two non-negative integers prints their ***cryptic multiplication ambiguity***. ## Test cases ``` {0, 0} -> 2 {5, 1} -> 17 {11, 11} -> 1 {54, 17} -> 18 {10, 49} -> 56 {7, 173} -> 1 {245, 15} -> 27 {216, 999} -> 48 {1173, 72} -> 3 ``` *[Mathematica reference program](https://tio.run/##fY/LasNADEX3/ooBgUmK0sm4i1DyQBATCBRaSneDA0MqP8CZBEcGg/G3uxPidRdC4iLOkS5OSr44qc5uHG9OhBuvturQ@rNUV2877PTrT9mw@7VgFjtIYgv47XzB9MG@kJIgy2JKuWbhtL3VgSR8p0P9gHnqsnWUB@L@2nqxk0HTPiz5UPazDYE9euGCm7QqKrlr6sEgJAjmBZIhRoBgoNnTSsfcwmZrsF/i@4C9WZ5msDBzDEPoQxZrmnDPAx84GOYZqsn@ry08s46inKhfJaiMWb0NSmv11VRexvEP)* [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~41~~ 36 bytes -5 bytes inspired by [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/250748/64121). ``` {#*={.(=`k@x,*/x)_" "}'?+x,'!10*1+x} ``` [Try it online!](https://ngn.codeberg.page/k#eJw1jEsOwjAMRPc+xVAWhbQisZPUBKmCm8CqGy4QqWrPToRBmsVoPm+5rUc3r5fT/Ho/6uh8PT87dFt/H+rYHzg4HupGJMCOBQGBWL82g4ktZW4ivlqewEp5siYgFfK/nbYmkhcDSGqITD7ZT3hCKW0c/1CNUPkAaV4iZw==) The last 4 cases are too slow to run online. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 17 bytes ``` vL↵ʀΠƛ?"ƛΠJṄ:vḟ;≈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJUcyIsIiIsInZM4oa1yoDOoMabP1wixpvOoErhuYQ6duG4nzviiYgiLCIiLCJbNSwxXSJd) This would flaglessly be 19 bytes. It can be shorter flagless, though: # [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes ``` vL↵ʀΠ?wJƛΠJṄ:vḟ;ṫO ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwidkzihrXKgM6gP3dKxpvOoErhuYQ6duG4nzvhuatPIiwiIiwiWzUsMV0iXQ==) ``` vL↵ʀΠ?wJƛΠJṄ:vḟ;ṫO vL # For each number in the input, get its length ↵ # Take 10 to the power of each ʀ # For each, generate an inclusive zero range [0, n] Π # Get the cartesian product of these two lists ?wJ # Append the input to this ƛ # For each: Π # Get the product of the two J # Append that onto the list Ṅ # Join by spaces : # Duplicate vḟ # For each in the duplicate, get the first index that it occurs in the other identical copy ; # Close map ṫ # Tail extract - push a[:-1] and a[-1] O # Count the number of times this a[-1] appears in this a[:-1] ``` [Answer] # [Knight](https://github.com/knight-lang/knight-lang), ~~416~~ 219 bytes ``` ;=mB;=u=s+++++""a" "t" "*a t;=o"";=h 10;WhE++"=x"=h-h 1"N";=w=n 0;Wu;=v+"x"-Au 48;I?32Au=o+o" "E+++++";I"v"N="v"=w+1w=o+o "v=uGu 1Lu o;=a+0P;=b=t+0P;=qCm;=a^10La;=b^10Lb;=z 0;W>a~1;=t b;Wt;=t-t 1;=oCmI?q o=z+1zN=a-a 1Oz ``` [Try it online!](https://tio.run/##lVhrV9s4Gv7eXyG0HbBixyTd7uwWI3IoQ@dwtg3dwgxnN0kb2VYSTx0r@AKUxPPXu698lXOBTs8pJNKj96bnvYg/2B2LnNBbxO1AuPy747MoQv8OvOksPg9DESL@EPPAjVD2bZnmgI8sjHhzXzlToj4lQezNn8ddxSFn86UjgigOEycWocbIMp55kRmJJHQ4ZSnseIubmRfzaMEcrhX7cxY7M@3wszYYjoaDYQTr6dFIX/1t8HkYjFraMFi9JKR1SNIF519hN@RxEgZIET7ojFarIPH9NBdmGw7tkKXPY8SobfIH7mgKnFiFCHmEUsp68sORCqHKZzNKbLBdY6DG9HkwjWfEYANnRNJYgONeMN1qVZpm4UDX//14fkUHIysP1e/MT/gyilnsOWghb0GzydI2N8JjTSCKdywEHzoWO87EFPotpuu5fw7N1gdsZJayLG@iOaSwx0kVX9MwCbKwh@IeBfw@Z0TqcjuZblnf4V0mxKw3AddP5jYPd@DKTcC9FcLnLNgBrHbTglXvIRgh8yvi5aFbI1mULKR0IxP1xWUxA67ljipKtjhTfK/PbfOk@N4EbbhRLqgwfutL8woEQx5YzQKHi0nuteLG/r5iPPAx/1RGQQqvQlCEZIM/JdfrbLp@NyKD0/b/Rq1Do1tRnu3vywuWMjV8jaU2krrJfFE5My6deZnlZ0rGqR/Palf2alv391nj2qYqDqm4vSYwzcm8SKKZJleJlafKef/3i0@X/Q/n/Wu6TIuEuXB5EK9x4Dn3B6z9@GUkf3bab75ACNYDkAkFY9On2ORJELCpGZ/sqDfxAJeHKMfJQIG53jSQchRPBjVmVFEzN3gHSmbwnfBc1NmT91NabtUJqtZlbfxb8DUQ9wHyKsvQQcO0g3Ez5pkLpIyvEt0fpdfQ1TdDCgEt0oWRdVIVGzWnmOsqXCnP15zRmVI6SAo1@El4uwmfJ/6T8FYT7np3qpf1lryJxiWUoj6weGYCbwJHkXoIfu@6JHzGgkDECFTBnSD7G3rkocBgqnD/ou5a4U/sWX0gPvGFom8h7p/WV4tfrfY0dtwhP@R8q/UD3vOHhQgkSVnMM4NQLKA2BnwKfLvjCIzjIRjp76gkx@q97aw3Jw1Ug/g17fvQEJ/mvVK9K@L3i5JKcs5LIY0SUlYQ2W7XcgBLsEbwU50hk1c4/0woHTEHM3l2xMRVMP7iKTU4cq2MDjTHZ4MjKWRTpvQcfDAiMMdFw6tRq0eG3UPjVUYrGQ1glq0SCTTIYSUfYpiZD3cSjA9kW3JWqwN8ID@Q2qV6aJVFD6yaewEwyUW3iQBC8cARiVzm7hF6uWTpeFtLz@xv5pHR7ZDVqrNWs4oB4amaJZ0YF4BC4WbpkaBalxnyBWfQe9QK9Azjq1HrScZXKPVSYbHornCKuVffAueIpTTkt4kXcg1PIkyMpRyRsy1b2XJmnu9@WYTC4ZFEvfutf3Z9cdm/qnvzO6gBT7VmhSX5BcNkXokZ2Eqny25amVUthVe9oyzr9JVJDnPGcDlPy/lYfnFhPnaPnXI2dsvZeEIzi8zSFKlsb7KDTh886N3BFLFwmszlwPFy6erdFIESNJFeQke1ZSO1eB7YCUmVO5aB0BzDNvjaSAFLztpYIcVRln8O2JxTO/8MqiPqbM6u2QHNNM0KVVWWvIpjqT32RKBhvZJahcdG5ciZHWU6xQbCum3mMqouruON2nRp/8Gd2PSijL8GjEvppFCFQj71ophnLpIlhLYre1X5QFp7S2i4DyaheQJDng2J@sCc2P@GoBcgZ8ZC@AYziy@CKdQkqyYIG1Fb0QiBqTqXerVFksELVLOVPCBq7anHqPy9YW2lAe4LdCclQ6FMfFfamqlw96BWKlklA06MKgT4IzY0Qk@KJxnGhk3fJpMJD03m@8LRYAB3hQwS0zrAiA5M5AZQ3oYnJbHB8K@Wo4Or95BxXOtCF852specKXPrxoPEx8MAE@JQx4x8D16IHQO168m@rDQOSVXLPuWWNVr3xBfg6@tXb16/@fmfr9783MpWQxa4Yi7Dpp4/xwajJzJkrBHaGnJweiAhVaLn4S2sstXuBgb0SjNzSeYkFPMzYMCZcGHQLN5O5Kg0V71O0ylwp7Gc2VQj32ZGMnXpLF8qHpfZT3V7nG1Xfajp3A5H8X@yQ0VBNPmDt17FFexepSB7azUfQA3k@wopPVYNKZNJRf8iuXVSjW@NYJeWRbErkti8D6Fxg8A8z4nBGjG7bAqqtRbS8HCYPQ/LP38A1Xo7FBSIjlGmP2DJ0VbwWHbJF2NiVNOTapMOZJXlpL442XILLxthaG8g5QthG7K1gZQdehvycAOZvQu2IH/alCm22/l5A5nN31uQxxWyIk15RM4G1RH1zMnuM9NdZ3q7z8jiv/XMfnVGY2WGN/5i0yuOHTVycPXsMXZkb@ampRzLd41tAaMKrFFl5ON2tQKVykO/mdLMLF7qNq302w3hN5XwpeyjViN9LbKWeFvJfJGLgPZPT9jWYDmbvv@qHMqCVttt2I3nmiEbgfK1rGVVOkohqxXGzahdFQrcTEV56BlVLnU3NVfgMuvlgN9jOsyXdUWwie7otUm6K7ty3Tr@PFBrX/MRDziIzvi7RedvLZrQSJf/MGYY4Rj@txiKLSowtugMdTvWzewctukDprM2LOA@bNzTAMFOYtE7HT/g9mmCXv/Luuj9/dVpQoUuQMx5Lta6wHe4T@EHvde793IT4Tua/Jqg7vsECYsyvfPRojaNs9@3Z3NY@tztvGewKH/bFn2Uyk7Yn12LQi@0bsC@uB0j@CrO5he9WyToo9597FPWZqh7@fh9DM9oT/Zc6/s/XnRf/B8) -190 bytes thanks to Adam and emanresu A Ungolfed and explained: ``` ; = m BLOCK # m = block: ; = u = s # + (+ (+ (+ (+ "" a) " ") # t) " ") (* a t) # u = s = a + " " + t + " " + a * t ; = o "" # o = "" ; = h 10 # h = 10 ; WHILE h # while h: : EVAL + + "=x" = h - h 1 "N" # eval("=x" + (h = h - 1) + "N") ; = w = n 0 # w = n = 0 ; WHILE u # while u: ; = v (+ "x" (- (ASCII u) 48)) # v = "x" + (ord(u[0]) - 48) ; IF ? 32 ASCII u # if ord(u[0]) == 32: : = o (+ o " "( # o = o + " " # else: (implicit) : EVAL + + + + + ";I" v # "N=" v "=w+1w=o+o " v # eval(";I" + v + "N=" + v + "=w+1w=o+o " + v) : = u (GET u 1 (LENGTH u)) # u = u[1:] : o # return o ; = a (+ 0 PROMPT) # a = int(input()) ; = b = t (+ 0 PROMPT) # b = t = int(input()) ; = q (CALL m) # q = m() ; = a (^ 10 (LENGTH a)) # a = 10 ** len(a) ; = b (^ 10 (LENGTH b)) # b = 10 ** len(b) ; = z 0 # z = 0 ; WHILE > a ~1 # while a > -1: ; = t b # t = b ; WHILE t # while t: ; = t - t 1 # t = t - 1 ; = o (CALL m) # o = m() : IF (? q o) # if q == o: : = z + 1 z # z = z + 1 N # else: (do nothing) : = a - a 1 # a = a - 1 : OUTPUT z # print(z) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20 18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan) for a speed up! (`‘×⁵` -> `æċ⁵`) and a byte that ended up saving elsewhere! Save of 2 using Steffan's idea of counting >.< - thanks again Steffan! ``` ;PDKĠṢ æċ⁵ḶŒpÇ€ċÇ ``` A monadic Link that accepts a pair of non-negative integers and yields a non-negative integer. **[Try it online!](https://tio.run/##ATAAz/9qZWxsef//O1BES8Sg4bmiCsOmxIvigbXhuLbFknDDh@KCrMSLw4f///81NCwgMTA "Jelly – Try It Online")** ### How? ``` ;PDKĠṢ - Helper Link, cryptic multiplication identifier: pair of integers [a,b] P - product -> a×b ; - concatenate -> [a, b, a×b] D - to decimal digits -> [[a1, a2, ...],[b1, b2, ...],[P1, P2, ...]] K - join with space characters (representing times and equals) Ġ - group indices by their values -> [indices of spaces, indices of 0s, ...] Ṣ - sort æċ⁵ḶŒpÇ€ċÇ - Link, cryptic multiplication ambiguity: pair of integers [x,y] ⁵ - 10 æċ - next power of (10) of each -> [u, v] (N.B. 0 -> 10, not 1) Ḷ - lowered range of each -> [[0, 1, ..., u-1], [0, 1, ..., v-1]] Œp - Cartesian product -> [[0, 0], [0, 1], ..., [u-1, v-1]] Ç€ - call the helper Link for each Ç - call the helper Link with [x, y] ċ - count occurrences ``` [Answer] # JavaScript (ES6), ~~127~~ 120 bytes Expects `(p)(q)`, as strings. ``` p=>q=>eval("for(n=0,x=1+p;x--;)for(y=1+q;y--;)n+=(g=(p,q)=>(a=[...p+=[,q,p*q]]).map(c=>a.map(C=>c==C))+0)(p,q)==g(x,y)") ``` [Try it online!](https://tio.run/##dc7BboMwDAbge58C5WSPkAKFphNyLn2MqoeIAerESAITgqdnpdAeqHaynXz5nW/d6y5vb/Y3aMxXMZU0WVKOVNHrGlhpWmgo5ANFvs2GIMhwPhrvo8vGeWx8gorAcoekQNNFCGF9unDH7Ye7XlH8aAs5Kf1ozqRyojOiH@LyiCoY@IgMp9w0nakLUZsKSmAh8zxcC3r7vRfvNiJdRPQSkdyS6H6Ja1nIW0iyCPkSp7eQ8EGSzydJj1si16/IA/tnT5ykbBbpMySW0x8 "JavaScript (Node.js) – Try It Online") **NB**: This algorithm is rather slow, and made even slower by `eval()`. So the larger test cases time out on TIO. ### Commented This is a version without `eval()` for readability. ``` p => // p = first integer q => { // q = second integer for( // outer loop: n = 0, // start with n = 0 x = 1 + p; // and x = p prefixed with '1' x--; // decrement x while it's not 0 ) // for( // inner loop: y = 1 + q; // start with y = q prefixed with '1' y--; // decrement y while it's not 0 ) // n += ( // update n: g = (p, q) => // g is a helper function taking (p, q) ( a = // append to p a comma followed by q, [...p += // followed by another comma, followed [, q, p * q] // by the product p * q ] // split the resulting string and save ) // this array in a[] .map(c => // for each character c in a[]: a.map(C => // for each character C in a[]: c == C // is c equal to C? ) // end of inner map(); what we get is a // list of Boolean values telling where // c can be found in a[] ) // end of outer map() + 0 // coerce to a string with a trailing '0' )(p, q) // do a 1st call with (p, q) == g(x, y); // do a 2nd call with (x, y) // increment n if both results are equal // implicit end of both loops return n // return the final count } // ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` €g°Ý`âIšεDPª»DSk»}㢠``` Port of [*@Steffan*'s Vyxal answer](https://codegolf.stackexchange.com/a/250749/52210), but with less convenient builtins. [Try it online](https://tio.run/##ATEAzv9vc2FiaWX//@KCrGfCsMOdYMOiScWhzrVEUMKqwrtEU2vCu33Eh8Ki//9bMjcsOTZd) or [verify (almost) all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R01r0g9tODw34fCiyqMLz211CTi06tBul@DsQ7trj7QfWvRf5390tJG5jqVZrE60gY4BkDTVMQSShoY6hiDa1ETH0BzEN9AxsQTS5kCuMZA2MgGqM42NBQA) (the last two are omitted). **Explanation:** ``` € # Map over the (implicit) input-pair: g # Pop and push its length ° # Pop and push 10 to the power these lengths Ý # Pop and map both to a [0,n]-ranged list ` # Pop and push both lists separated to the stack â # Pop both, and get all possible pairs using the cartasian product Iš # Prepend the input-pair ε # Map over each pair: D # Duplicate the pair P # Pop the copy, and push its product ª # Append it to the pair » # Join it by newlines D # Duplicate this string S # Convert it to a list of characters k # Get the first index of each character in the string » # Join that by newlines again to a string }ć # After the map: extract the head ¢ # Count how many times this string occurs in the remainder-list # (after which it is output implicitly as result) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 108 bytes ``` ->a,b{[*0..9].permutation.map{|c|"#{a}*#{b}==#{a*b}".tr('0-9',c*'')}.uniq.count{|c|/^0|\*0|=0/!~c&&eval(c)}} ``` [Try it online!](https://tio.run/##bc5NDoIwEIbhPadASKRtYGxcaIip7LwEYFKaEkkUsBQTgXp1xL@F0d1svnkf1WbXMWdjsOV@1seEAoQp1FKdWs11UZVw4nU/iMFxe26I22eGsekkmXFAK@TRIPR8QTwPG2jL4gyiakv9WCz2dEgIHRhdzG5iPpcXfkQCGzO69o43WirLtXP2KiuGUMf@RDCIA1fN83cQR8SPWIqn3OaPFSloik7ij7mbhLZ66t64Rh6l@NIlPzzLqu08Xq79cJWOdw "Ruby – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` FXχLθFEXχLη⪫⟦ικ×ικ⟧¶⊞υEκ⌕κλI№υ§υI⁺θη ``` [Try it online!](https://tio.run/##ZY2xCsIwEIb3PsXR6QInWFAcOokgKAoZ3NQhtNEEY2KTRn37mHT1hrsPvp//OiV854RJ6eY8IHcf6bGZExykvY8KB8YYTOooXv9aMUawd9riWRM8CE76KQMWZleC@mLrUsBjUBgJSkcObbXtyzXZtRX32o64ESEvFzPm4Hrc2V5@C06CmxhwIMj/yrQpLRdVs0qzt/kB "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FXχLθ ``` Loop through numbers with no more digits than the first number. ``` FEXχLη ``` Looping through numbers with no more digits than the second number, ... ``` ⪫⟦ικ×ικ⟧¶ ``` ... forming a string of the two numbers and their product, ... ``` ⊞υEκ⌕κλ ``` ... get a list of the first indexes of each character in the string. ``` I№υ§υI⁺θη ``` Output the number of entries matching that of the input values. [Answer] # Python 3, 128 bytes ``` lambda x,y,c=lambda z:list(map(z.find,z)):sum(sum(c(f"{f,g,f*g}")==c(f"{x,y,x*y}")for g in range(1+y<<4))for f in range(1+x<<4)) ``` [Try it online!](https://tio.run/##Zc7LDoIwEAXQPV8xwU2rjaE8rBL6J24QLDaBQgATwPjtlacQXcxiTu7cTNHWj1w5OuZXnYbZLQ6hIS2J@Lx0fiqrGmVhgbqjkComHcZ@9czQMBES5kuQhIh98jYx5yMMBc2@7UHkJSQgFZShSu6IHtogcPHIYsvNyLoopapRjCwCFsYAO7CNxTwCdDLKjE3wHyntdeH13u2VzXpew32Fe5nYO32ZDWHnt8N2hy@8@TWmPw) ]
[Question] [ In this challenge you will receive a list of pairs of non-negative integers representing a mushroom forest. Each pair represents a mushroom whose center is at that horizontal coordinate. The only part of the mushroom we care about is the cap (the flat bit at the top). The first integer in each pair represents which row the cap is placed in. i.e. the height of the mushroom. The second integer represents the radius of the cap. If it's zero then there just isn't a mushroom in that position. Other for size \$n\$ a total of \$2n-1\$ spaces are occupied centered at the index of the pair. For example `1` means that its cap only occupies a space above it, a `2` means it occupies a space above it and the spaces one unit to the left and right. As an example here's an example with the forest drawn: ``` =-=-= =-=-=-=-=-=-= = | | | | =-=-= | =-=-= | | | | | =-=-= =-=-=-=-= | | | | | | | [ 2,0,1,0,0,2,0,0,1,2 ] <- Heights [ 2,2,2,0,0,4,0,3,2,1 ] <- Widths ``` (For clarity, stems are drawn with `|` and extra spacer rows are added between layers) Your task is to determine from an input list whether there are any collisions between mushroom caps. That is if there is any pair of mushrooms that both occupy 1 or more common spaces. You should output one of two distinct values. One if there is a collision and the other if there is not. You may take input instead of a list of pairs as two separate lists of the same length. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. ## Test cases Test cases are provided with an illustration. ### No collision ``` =-=-= =-=-=-=-=-=-= = | | | | =-=-= | =-=-= | | | | | =-=-= =-=-=-=-= | | | | | | | [ 2,0,1,0,0,2,0,0,1,2 ] <- Heights [ 2,2,2,0,0,4,0,3,2,1 ] <- Widths =-=-= = | | =-=-= =-=-=-=-= | | | | [ 0,1,0,1,0 ] <- Heights [ 2,2,0,1,3 ] <- Widths =-=-=-=-=-=-= | =-=-=-=-=-=-= | | =-=-= | | | | = | | | | | | | =-=-= | | | | | | | | [ 0,1,2,3,4 ] <- Heights [ 2,1,2,4,4 ] <- Widths ``` ### With Collisions Locations with a collision are marked with `X`. ``` =-X-X-= | | | | | | [0,1,1] <- Heights [0,2,2] <- Widths X-=-=-=-=-=-= | | [0,0,0,0,0] <- Heights [0,1,0,0,4] <- Widths =-=-X-=-=-=-= | | [0,0,0,0,0] <- Heights [0,2,0,0,3] <- Widths ``` ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 31 bytes ``` {a~?a:,/x,''(!#y)+(?,/-:\!:)'y} ``` [Try it online!](https://ngn.codeberg.page/k#eJxdTTEOgCAM3HlFjQMaMdjSCQYfogwsvkFj9O0WwcU011zvLr3Nn+mekzd2N1p3TXv0QzcbO/q18b0+LqW2hWACFExA70agQED1YoETjlGiJSgIxUZwn0ySYpEzY+CoVDUw5MdUcnXC18h/uZS6+ADotiRa) -4 bytes thanks to @ovs! Golfed even more with inspiration from @UnrelatedString's approach. ## Explanation Height list is *x*, width list is *y*. * `(?,/-:\!:)'y` convert each width to range `(-width, width)` * `(!#y)+` add indices * `x,''` add corresponding height to each index in each width range * `a~?a:,/` flatten, check for duplicates [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 22 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` mÆ╤╞╡ï+m▐ò┤\h?a*^~]_▀= ``` Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/249028/52210) (the 19-bytes version; since the 22-bytes version was using a group-by, which MathGolf lacks and I also couldn't find any suitable alternative for with its available builtins after some trial-and-error for more than an hour.. :/) Just like my 05AB1E answer: input as two separated (equal-length) lists, first being the list of widths, second the heights. [Try it online.](https://tio.run/##y00syUjPz0n7/z/3cNujqUseTZ33aOrCw@u1cx9Nm3B406MpS2Iy7BO14upi4x9Na7D9/z/aSAcEDYDQBIiNgWzDWIVokIghWBQiZ6hjFMsVDVFpqGMMVAGRB2KwOFAeqN8EKm4ENMcEKA7SbQQVMwTzIWZC1EEhVB2IbYwiDgA) **Explanation:** Basically the same three steps as my 05AB1E answer: Step 1: Change each value in the input to a list of indices it can reach: ``` m # Map over the first (implicit) input-list of widths, Æ # using 5 bytes as inner code-block: ╤ # Convert it to a list in the range [-n,n] ╞╡ # Remove the first/last items to change it to range (-n,n) ï+ # Add the 0-based map index to each value as offset ``` [Try just this first step.](https://tio.run/##y00syUjPz0n7/z/3cNujqUseTZ33aOrCw@u1//@PNtIBQQMgNAFiYyDbMFYhGiRiCBaFyBnqGMVyRUNUGuoYA1VA5IEYLA6UB@o3gYobAc0xAYqDdBtBxQzBfIiZEHVQCFUHYhujiAMA) Step 2: Pair each inner index with the height of the second input: ``` m▐ # Append each value in the second (implicit) input-list of heights to # the (-n,n)-list at the same position ò # Loop over the lists, using 8 bytes as inner code-block: ┤ # Extract tail; push remainder-list and last item separated \ # Swap so the remainder-list is at the top h # Push its length (without popping) ? # Triple-swap the [tail,list,length] to [list,length,tail] a # Wrap the tail into a list * # Repeat it the length amount of times ^ # Zip to create pairs of the list with these repeated tails ``` [Try just the first two steps.](https://tio.run/##y00syUjPz0n7/z/3cNujqUseTZ33aOrCw@u1cx9Nm3B406MpS2Iy7BO14v7/jzbSAUEDIDQBYmMg2zBWIRokYggWhcgZ6hjFckVDVBrqGANVQOSBGCwOlAfqN4GKGwHNMQGKg3QbQcUMwXyImRB1UAhVB2Ibo4gDAA) Step 3: Check if all (flattened) pairs are unique, and output the result: ``` ~ # Still in the loop of step 2: dump the pairs to the stack ] # After the loop: wrap all pairs on the stack into a list _▀= # Check if all pairs are unique: _ # Duplicate the list of pairs ▀ # Uniquify the copy = # Check if both lists are still the same # (after which the entire stack is output implicitly as result) ``` [Answer] # [Python](https://www.python.org), ~~153~~ ~~105~~ 86 bytes *-19 bytes thanks to [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)* ``` lambda l:len(d:=[(h,z)for i,(h,x)in enumerate(l)for z in range(-x-~i,x+i)])==len({*d}) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVDbSsQwEMXH5ivmMdEUbLaIFPIbvtQi0aY20M2WNouxoj_iS0H0n_RrzGVtd1-EYWY458xwOO9f_bNpd3r-aPjt59406fX3TSe297WAruikxnXBS9zSiTS7ARR1qyVKg9T7rRyEkbgLzAQOHIR-lDi16Zui9kKRinDuf7yc168kfv85uzJyNHcPYpQjcChRgktG4ZJCFror9rc4hFUUPM-O4Dz0TUCyilD_Yrn3fb2JwOZExMJtfhBFIPfAsSjzdPTCVmKtA714zv8RLcaDjwohH1hL4clntqZRoMS6RBo8qR57mhCU9IPSBluCYnzzHOcv) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εD(Ÿ¦¨N+INèδ‚}€`DÙQ ``` -3 bytes using a similar approach as [*@UnrelatedString*'s Python answer](https://codegolf.stackexchange.com/questions/249026/check-a-mushroom-forest/249027#comment556224_249027) Input as two separated (equal-length) lists, first being the list of widths, second the heights. [Try it online](https://tio.run/##yy9OTMpM/f//3FYXjaM7Di07tMJP29Pv8IpzWx41zKp91LQmweXwzMD//6ONdEDQAAhNgNgYyDaM5YoGiRiCRSFyhjpGsQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P9zW100ju44tOzQCj/tCL/DK85tedQwq/ZR05oEl8MzA//r/I@OjjbSAUEDIDQBYmMg2zBWJxokYggWhcgZ6hjFxuooQJSDuMZARRAlQAyTAqoCmmIClTICmmYCkQIZYwQVNoQJQcyHqIZChGoQ1xhVKhYA). **Explanation:** Step 1: [Exact same first step as in the previous related challenge](https://codegolf.stackexchange.com/a/248968/52210): Change each value in the input to a list of indices it can reach: ``` ε # Map over each value of the (implicit) input-list: D( # Create a negative copy Ÿ # Pop both, and push a list in the range [n,-n] ¦¨ # Remove the first and last to make the range (n,-n) # (or empty the list if n=0) N+ # Add the current map-index as offset ``` [Try just this first step.](https://tio.run/##yy9OTMpM/f//3FYXjaM7Di07tMJP@///aCMdEDQAQhMgNgayDWO5okEihmBRiJyhjlEsAA) Step 2: Pair each inner index with the height of the second input: ``` I # Push the second input-list of heights Nè # Use the map-index to get the current height δ # Apply double-vectorized: ‚ # Pair this height with each index in the (n,-n) range } # Close the map ``` [Try just the first two steps.](https://tio.run/##yy9OTMpM/f//3FYXjaM7Di07tMJP29Pv8IpzWx41zKr9/z/aSAcEDYDQBIiNgWzDWK5okIghWBQiZ6hjFAsA) Step 3: Check if all (flattened) pairs are unique, and output the result: ``` €` # Flatten the list of lists of pairs one level down DÙQ # Check if all pairs are unique: D # Duplicate the list Ù # Uniquify this copy Q # Check if both lists are still the same # (after which the result is output implicitly) ``` [Answer] # [Haskell](https://www.haskell.org), ~~112~~ ~~85~~ 75 bytes *-37 bytes thanks to [@Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)'s tips* ``` import Data.List f k|z<-do(i,(y,x))<-zip[0..]k;(y,)<$>[2-x+i..x+i]=z==nub z ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVHLSsQwFMVtvuIyzKLBNEwzXQi2rtypG3UhlDDEscXQJ0kKM8U_cTMb8QP8Gv0a06a2OgvD5RDOPfdwc_L6_ix0nhbFR7LwH-7bpkjv0q2RdaUX_PDWmsw_-7ySZVMrA5fCCHottUEZ5C9d5D_VniTenuwwjvxONsmKUp6fWwZHy4uE-btTSakFHndxXLWP0DnLr5Nbk2qz2QqdaoghQWCPlzACKwLBgLbYz8UyjBPo--wXHQ64HpiAYzK6TBY9zmOOWB_r2OAQjjpHhD1xpAt6hVuK_enNNSqm_cP_ddM77E4cIWWDKEUDXlttW6X2sAQvA4qBgs0Ww5wYQqWQlZPfbKBRsjKgXLSH8de-AQ) [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~22~~ ~~21~~ 18 bytes ``` {Is.e,RGtr-keAb+kH ``` [Try it online!](https://tio.run/##K6gsyfj/v9qzWC9VJ8i9pEg3O9UxSTvb4///aA0jHSNNHQ0DMGkIZRvASSMdEyQRY7gaIx1DzVgA "Pyth – Try It Online") or [Verify all test cases](https://tio.run/##K6gsyfiv/L/as1gvVSfIvaRINzvVMUk72yNQwdb1//9oDSMdI00dDQMwaQhlG8BJIx0TJBFjuBojHUPNWK5oLPoMgTIQtcjyhmA9ILYx2EQTIAmRN4DrB5EIMQOoOQZIpAmKvBGGPNBOAA "Pyth – Try It Online") ### Explanation `.e` enumerates over the implicit input with index `k` and value `b`. `Ab` sets `G` and `H` to the elements of `b` (in this case, height and width respectively) `tr-keAb+kH` builds a range from **k-H+1** to **k+H** (half inclusive) `,RG` appends the height to each element of that list, resulting in a list of coordinates for the current mushroom. `s` flattens the list by one level. And `{I` checks whether the list remains invariant under deduplication, meaning that no two mushrooms share a coordinate. [Answer] # JavaScript (ES6), 58 bytes Expects `(heights)(widths)`. Returns a Boolean value. ``` h=>w=>w.some((w,x)=>h[H=~h[x]]&(h[H]|=m=4**w/2-1<<x>>w,m)) ``` [Try it online!](https://tio.run/##jY/BDoIwDIbvPAUns5GBbOzIdvYdyA4EQTTAjBjHwfjqs2wQEyOJ2br0X7/@aS/loxyr2/l6jwd9rG0jbCukgZuMuq8RMmTCQrbFQbzaYlJqhyBXT9ELHkVmz2Ka55OUhvQY20oPo@7qpNMn1KAiZCQlFCIlzL2UsFBhV2DLF4fIIKdQwMG3gW@H@LTNMtuEGZjxFZ4ldxIHP2nqyXk8tmG5nBX02/D/YL@hG9a@AQ "JavaScript (Node.js) – Try It Online") ### How? This is using the same method as in [my answer to the other challenge](https://codegolf.stackexchange.com/a/248986/58563). But since there's no search involved, we can just store the bitmasks in one of the input arrays with negative indices. --- # JavaScript (ES6), 65 bytes Expects `(heights)(widths)`. Returns a Boolean value. ``` h=>w=>w.some((p,i)=>w.some((q,j)=>p*q&&h[i]==h[j]&j>i&i+p-1>j-q)) ``` [Try it online!](https://tio.run/##jY/BDoMgDIbvPoUnAhsaQa74IsaDcTohTlCX7fFZBY3JMpMF2vDTr39aXb/qpZmVfSajubWuk66XxRtuuphHi7GlihxqohqUvUwI9aWqpOxLXSFdKKSuNmGFTiZCXGPGxQxtOpg77nAZc5pRBpFR7jOjPK6IL/DtS0Dk8GZQING3QWiHONpWmZ/CHMzEDq9SeEminzQL5DoeP7Hczg6GbcR/cNjQD@s@ "JavaScript (Node.js) – Try It Online") ### Commented ``` h => // h[] = array of heights w => // w[] = array of widths w.some((p, i) => // for each mushroom of width p at index i: w.some((q, j) => // look for another mushroom of width q at index j: p * q // such that they both actually exist, && h[i] == h[j] // they have the same height, & j > i // the 2nd one is located after the 1st one, & i + p - 1 // and the right part of the 1st one intersects > j - q // with the left part of the 2nd one ) // end of inner some() ) // end of outer some() ``` [Answer] # [Desmos](https://desmos.com/calculator), 156 bytes ``` l=W.length k=max(0,i-W[i]) L=[1...n] g(n)=L[L0+n>0]0 f(H,W)=0^{0^{[max(∑_{i=1}^ljoin(g(k),g(W[i]+i-1-k)+1,g(l))[1...l]0^{(h-H[i])^2})forh=H[1...]].max-1}} ``` My attempt at solving this challenge without looking at the other answers lolol. You can see how terribly that came out just by how long the answer is. The function `f` takes in the height list first and the width list second, and returns `0` for no collisions, `1` if there is a collision. Also the `H[1...]` can't be golfed to `H` (I checked), because apparently `H` is recognized as a number, not a list, so the list comprehension errors out. `H[1...]` circumvents this error by forcing Desmos to recognize `H` as a list. [Try It On Desmos!](https://www.desmos.com/calculator/8tqo5bq7yn) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/mbr5uifcgl) I have added an explanation of my code below because I'm bored :P. ### Explanation The general rundown of my strategy is for each height, construct lists of `1`'s and `0`'s which correspond to the spaces that each mushroom takes up for that particular height. Then, all these lists are summed together. If there is a collision at that height, then there will be a number \$>1\$ in the list. Now, to explain each part of the code. ``` L=[1...n] g(n)=L[L0+n>0]0 ``` `g` is a function that will return a list of `n` zeroes. ``` f(H,W)=0^{[max(∑_{i=1}^ljoin(g(k),g(W[i]+i-1-k)+1,g(l))[1...l]0^{(h-H[i])^2})forh=H[1...]].max-1} ``` `f` is the function that returns the answer. Let's break it down: ``` ... [ ... forh=H[1...]] ``` For `h` in list `H` (looping over all heights)... ``` ... ∑_{i=1}^l ... ``` Take the summation from `i=1` to the length of list `W` of (looping over indices of the width list)... ``` join(g(k),g(W[i]+i-1-k)+1,g(l))[1...l] ``` A list of `1`'s and `0`'s, representing the spaces that the mushroom at index `i` in the width list takes up, with `1` representing the space taken up by the mushroom. This list is constructed by joining three individual lists into one list: `g(k)`, `g(W[i]+i-1-k)+1`, and `g(l)`. The first list, `g(k)`, consists of the `0`'s before the range of `1`'s which represent the mushroom. The number of `0`'s needed can be calculated by subtracting the width of the mushroom `W[i]` from its index `i` (The mushroom extends `W[i]-1` spaces to the left from the center space, so `i-W[i]` is essentially calculating the index of the last `0` right before the mushroom.). The issue with this is that some mushrooms extend past the front of the list, which will make `i-W[i]` negative. While this is no problem for `g` (it returns an empty list for negative inputs), it may cause issues for length calculations later on (i.e. the list of `1`'s right after), so instead we store the length of the list as `k=max(0,i-W[i])`, and call `g(k)` to construct the list of `0`'s. The second list, `g(W[i]+i-1-k)+1`, constructs a list of `1`'s which represent the space that the mushroom takes up. `g` returns a list of `0`'s, so we convert that to a list of `1`'s by adding 1 to the list. At first, it might be obvious to do `g(2W[i]-1)+1` as each mushroom takes up \$2w-1\$ spaces. But this runs into the problem of width 0, as `g(-1)+1` is just an empty list, but what we actually wanted was the list `[0]`. Also, the bigger problem is that it doesn't account for mushrooms extending past the front of the list, and will have too many `1`'s for those mushrooms. To counteract this problem, note that the length of the list up to the end of the mushroom has to be `i+W[i]-1` (the mushroom extends `W[i]-1` spaces to the right of its center, `i`, so the index of the last `1` in the mushroom is `i+W[i]-1`). The first list already accounted for `k` of the elements, so the second list will have a length of `i+W[i]-1-k` to account for the rest of the elements. The last list, `g(l)`, is simply to pad the end of the list with enough `0`'s to make the list have a length of at least `l=W.length` for the slice (explained below). `[1...l]` is a slice that takes the first `l` elements of the list. This is to ensure that all the lists being summed have the same length, as Desmos gives an error if they aren't all the same length. ``` 0^{(h-H[i])^2} ``` This checks if the height of the mushroom at index `i` is the same as the current height `h` (if we don't have this code, then the function would detect for collisions as if they were all on the same height). `(h-H[i])^2` returns `0` if the current height `h` is the same as the mushroom's height `H[i]`. Otherwise, it returns a positive integer. Then, `0^{(h-H[i])^2}` returns `1` if `(h-H[i])^2` is `0`, and `0` if `(h-H[i])^2` is a positive integer. Putting that all together, `0^{(h-H[i])^2}` returns `1` if `h` equals `H[i]`, and returns `0` otherwise. When multiplying this value with the list, if it is `1`, then nothing happens to the list, but if it is `0`, then all the entries in the list become `0`, which essentially means that the list won't contribute to the summation at all. This causes any mushroom that isn't at the current height of the loop to be nullified, leaving only the mushrooms which are at the current height to contribute to the summation. ``` 0^{0^{[max( ... ) ... ].max-1}} ``` Recall that if the summed list contains any number \$>1\$, then that means there is a collision. If there are any numbers \$>1\$, then the `max` of the summed list will be \$>1\$. The list comprehension will create a list of maximums for each height in `H`. By taking the maximum of the list comprehension, we can then detect if there were any collisions in any of the heights if the maximum is \$>1\$. We can do this by first subtracting one from the maximum, and then wrapping `0^{0^{ ... }}` around it. `0^{0^n}` for any integer `n` returns `1` if `n` is positive, and `0` if `n` is `0` or negative. This means if the maximum is `0` or `1`, the function will return `0`, because both `0^{0^{-1}}` and `0^{0^0}` return `0`. If the maximum is `2` or above, then the function will return `1`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` ⊙η∧ι⊙…ηκ∧λ∧⁼§θκ§θμ›⁺ιλ⊕⁻κμ ``` [Try it online!](https://tio.run/##RUxNC4MwDL37KzxG6MB2u@0kMoaHgXfxUGpAMdZZ65i/vosfsMDLy/sgptXOjJpCKF1nPWR2hVbEmW2g22iFfDWEeTu@N79PjowOekyLphkyX9gGvzCdhb8cEtZPh9qjg5KWeftK7BXWOBzQemzg1VkO@r19zj2EKqpiJVIhGalQ@5ZCxXUk9kSd3o1x5VtyUofLh34 "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if there's a collision, nothing if not. Explanation: ``` η Input widths ⊙ Any element satisfies ι Current width ∧ Logical And η Input widths … Truncated to length κ Outer index ⊙ Any element satisfies λ Current width ∧ Logical And θ Input heights § Indexed by κ Outer index ⁼ Equals θ Input heights § Indexed by μ Inner index ∧ Logical And ι Outer width ⁺ Plus λ Inner width › Is greater than κ Outer index ⁻ Minus μ Inner index ⊕ Incremented ``` [Bonus program!](https://tio.run/##bU9Na4NAED3HXzF4GmEFtT314xASShOwhNDSg3iwOtEl667RVVJKf7udmPTQj4EZhjfvzZvJq6zNTabGMTYD4ROVmSWMPAGhd@tsWqktJhvVdzgVNwFXwNpIjQfBresx04UU7nx4JFlWtnMZ@VdQ/Ra8ysJWzE/ZaWdawC0N1HaEK52zVg60zXRJGAiIs6Os@xoPHgdM5Aepi7lSpzskY3IHOLcrXdDx5LRn6MOZrfu6eTa4NP2bogL3bB6w2@z82M1LI4DNWqpJW55/83jhiRX3ysrmTPUFLN5zRYvKNOje@/zVkv4qf54wrfkcx8RJIBKBCDkDEU01FBGkjpgm0QW75rziPuRJOvqD@gI "Charcoal – Try It Online") [Answer] # [Factor](https://factorcode.org) + `math.unicode`, 100 bytes ``` [ [ swap dup neg (a,b) n+v ] map-index zip expand-keys-push-at values [ concat dup members = ] ∀ ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVGxTsMwEBVrvuJGECRK0g4IBCtiYQGmqIObXNqojWNiO6RUkRj5B5YssPFBMPIlPdtJpQph6-y753fvTr73z5ylqqr7n6OHx_vbu5sLWGHNcQ0lU0t7BDXjC5TOb9CwJUh80shTgpmUVTpeAbaqZuZZDQmaF2mVIYgaldqIuuAKLj1v6wGtLe0YQojIQusZP4bO4vGATMkm5EeEd_s8l2VsZJto8ocTEzYdOCaa2qjzDkiRJYRW5lBg3N2-ZDgI_MdxTbtGug-tcv_8O0sgAfnMBGRaAMcFHLOz-Qnw0wZm9FHCL3iGLbwUArAVjGf-CjfSF1oufaagYWtNf51AWvGUYqNSYjlHGsUVKfy-vcLM1frK3SyuSRUCh_W9u3c) Oh how I wish there was a word for `expand-keys-push-at values` that was around 6 bytes instead of 26. This uses the algorithm described in Kevin Cruijssen's [05AB1E answer](https://codegolf.stackexchange.com/a/249028/97916). [Answer] # [R](https://www.r-project.org), 100 bytes ``` \(h,w,a=\(x,y,z)`if`(z>=0,complex(0,x,-z:z+y),y),p=mapply(a,h+1,seq(!h),w-1))any(table(unlist(p))>1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bU9LDoIwEN17C3czYUjawsKYwElYUBECCWAVCJ-ruEETL-FNvI2txc_CtNP2fdo3PV9O8zULbl2buZvHPoKcepJBBAONNGFcZDFMYcAoOVSqTAdgNJA7bSdnRNJTBZVUqhxBUu5watIjrHOk3uWIsh6hlbsyha4ui6YFhRhyXLLuGSQgiBHXxUi8Vk4CydBiIXxdnj7r51bmgrXretsM8H5Eoe2-FQ3wNfiK3AgmS3zIZVjBtuL_F21DJsv-YJ7t_gQ) Complex numbers! [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 36 bytes ``` (∨˝⍟2((∧´+´>≠⋈⌈´)¨·∾´↑¨∘↓)˘)∘⍉=⌜⟜⍷⊸× ``` Dyadic function; takes a list of heights as its left argument and a list of widths as its right argument. Returns 0 for no collisions or 1 for one or more collisions, wrapped in a [unit array](https://mlochbaum.github.io/BQN/doc/enclose.html#whats-a-unit). [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKOKIqMud4o2fMigo4oinwrQrwrQ+4omg4ouI4oyIwrQpwqjCt+KIvsK04oaRwqjiiJjihpMpy5gp4oiY4o2JPeKMnOKfnOKNt+KKuMOXCgpoZWlnaHRzIOKGkCDin6gKIFsyLDAsMSwwLDAsMiwwLDAsMSwyXSwKIFswLDEsMCwxLDBdLAogWzAsMSwyLDMsNF0sCiBbMCwxLDFdLAogWzAsMCwwLDAsMF0sCiBbMCwwLDAsMCwwXQrin6kKd2lkdGhzIOKGkCDin6gKIFsyLDIsMiwwLDAsNCwwLDMsMiwxXSwKIFsyLDIsMCwxLDNdLAogWzIsMSwyLDQsNF0sCiBbMCwyLDJdLAogWzAsMSwwLDAsNF0sCiBbMCwyLDAsMCwzXQrin6kKCmhlaWdodHMgRsKoIHdpZHRocw==) ### Explanation ``` =⌜⟜⍷⊸× ``` Splay the widths out into different columns of a 2D array, one column for each distinct height in the heights list. ``` (...)∘⍉ ``` Transpose so each list of widths-at-a-given-height is now a row. Then: ``` (...)˘ ``` Map over each row: ``` ·∾´↑¨∘↓ ``` Generate a list of all sublists; then: ``` (...)¨ ``` Map this function to each sublist: ``` ∧´+´>≠⋈⌈´ ``` Is the sum of the sublist greater than both the length of the sublist and the max of the sublist? This function will always return 1 for any sublist that: * Starts and ends with a nonzero mushroom width, and * Has all zeros between the two nonzero values, if * The two mushrooms overlap It will also return 1 for certain other sublists, but only if they contain a sublist that matches the above criteria. Thus, if there are any 1's in the results, that indicates the existence of some overlapping pair of mushrooms. ``` ∨˝⍟2 ``` We have a 2D array of 0's and 1's; fold its leading axis on logical OR twice, giving a 0D array containing 1 if there were any 1's and 0 otherwise. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes ``` ¨2$:NrḢ+⁰ntiv";ÞfÞu ``` [Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCqDIkOk5y4biiK+KBsG50aXZcIjvDnmbDnnUiLCIiLCJbMiwyLDIsMCwwLDQsMCwzLDIsMV1cblsyLDAsMSwwLDAsMiwwLDAsMSwyXSJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJQIiwixpvDt8KjIiwiwqgyJDpOcuG4oivCpW50aXZcIjvDnmbDnnUiLCI7WmAgPT4gYHZq4oGLIiwiW1tbMiwyLDIsMCwwLDQsMCwzLDIsMV0sWzIsMCwxLDAsMCwyLDAsMCwxLDJdXSwgW1syLDIsMCwxLDNdLFswLDEsMCwxLDBdXSwgW1syLDEsMiw0LDRdLFswLDEsMiwzLDRdXSwgW1swLDIsMl0sWzAsMSwxXV0sIFtbMCwxLDAsMCw0XSxbMCwwLDAsMCwwXV0sIFtbMCwyLDAsMCwzXSxbMCwwLDAsMCwwXV1dIl0=). Port of 05AB1E. Too bad we don't have a loop index variable. Then it could be 16 bytes. ``` ¨2$:NrḢ+⁰ntiv";ÞfÞu ¨2 # Open a dyadic map lambda: Map over the implicit first input, pushing both item and index $ # Swap so the item is at the top :Nr # Range [n, -n) Ḣ # Remove the first item to make this (n, -n) + # Add the index ⁰nti # Index the loop-index into the second input v" # Pair each in the list with this ; # Close map Þf # Flatten one level Þu # Is this unique? ``` [Answer] # [Python 3](https://docs.python.org/3/) with NumPy, 83 bytes ``` def f(h,w): for j in h:x,=(w*(h==j)>0).nonzero();1**((x-w[x])[1:]+1-(w[x]+x)[:-1]) ``` [Try it online!](https://tio.run/##fVHRjoMgEHyWr9j4BBYvBX2i8X7EmIvpYbSJQJCL2p@3gp72Xi7ZbGBmdpkMZnatVtmyfMsGGtzSkQgEjbbwgE5BKyZa4DHBbVE8yOeVfCitntJqTG4sSTCe0rGcKlIyUV1Yiv3lMpFSpKwiS2N1D@qnNzN0vdHWQW1tPSPk5OC@7vUgByigRBEuOYUrBRb6Wvz3sCK8ouB5/gbnoWcBWV@ifsUx7/s5swHZHxEPs/ku2oDcA@8i5unNCz@Js3b68Jz/IzqMBx8VQj7hlsLoQz7TEChydhYNTvra4BAWDX9CyM3YTjkcz3KICYrkdJfGiR1UOibLCw "Python 3 – Try It Online") Takes two array arguments and signals by error/no error. [Answer] # [C (clang)](http://clang.llvm.org/), 128 bytes ``` i;j;k;*c;r;f(*h,*w,n){for(r=i=0;i<n;++i)for(c=calloc(n,8)+n,j=i;j<n;++j)for(k=-~j-w[j];h[i]==h[j]&k<j+w[j];)r|=++c[k++]>1;*h=r;} ``` [Try it online!](https://tio.run/##rZRtr5owFMff30/RkbhQKJmWh2yrvXux7FMgWbTiBdRqwKRuzn30uUIplO4me7ERrIdzfv2fc9oCC9hhzV8ej5JUZE88Rmqyc70CeQJxeNudaremJZ2TcsmJ75ew9TDK1ofDibkcvYc@RxWVs7t41cX3NPhZBSKtMlKkZUZpIc23@2Xldz5Y/6C@z9K972fPC@IVtCb3R8kv4LguuQvB7QnIq3Vc8ubytVikGaDghhGYI7DoRnljbUgPvpORFyOPDSzqxrDzLEy@wIofxNtxIohNQQWEE4XQVMBdlmiiEA4KCogsoIhMhUl5Ygxhq9MiHkLjPZkbW63N7bzJ3xQSM7sCZO96h7xeRkH9diG9rtoItRFpI9ZGopL1OsLQEVpHaB2hdYTWEVpHJGNNysOVVFN@z087t68MvuufPe1AYEJgm8A2EdpEaBORTUQ2EdtEbBOJTSTQaDC/nnN2ybeqxYU6M8b2dSA78eYCWLGuPTnmbJ/XindW1y94df3wWf5iBwHzOXT62fI9Bm6bq@Tb/CqnzUlvLnWluoqx1MFDgPxWtDTsxNQLPRyZQsr1x6aDMjKNCx0Xr8UB12H@R3isuq9YVsu7YuDAtNe5ltDOdWbNbCtXoPzULsNHJ5V/7RcLjoqazFbcgf81kZgmasU2KTeaOeZHdv7mbmRN8q31uJm@9QoEuCXQyGq8zdSXS9@b4cTYKzb0B4JnMNuCWSMblYcRDWemoTTP/qH1IAicVxZ0XM/70/3xi@0O65fmEYjf "C (clang) – Try It Online") Inputs a pointer to an array of mushroom heights \$h\$, a pointer to an array of mushroom widths \$w\$, and the length of the arrays (since pointers in C carry no length info). Returns, through the input pointer \$h\$, \$0\$ if there aren't any collisions between mushroom caps and \$1\$ otherwise. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḥ’R_"ƲĖS€;€"ẎQƑ ``` A dyadic Link that accepts the widths on the left and the heights on the right and yields `0` if there are collisions or `1` if not. **[Try it online!](https://tio.run/##y0rNyan8///hjiWPGmYGxSsd23RkWvCjpjXWQKz0cFdf4LGJ////jzbSAUEDIDQBYmMg2zAWJGqgYwgWhcgZ6hjFAgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjiWPGmYGxSsd23RkWvCjpjXWQKz0cFdf4LGJ/w8vd9AHcv//j46ONtIx0DEEYgMdIzBpqGMUy6WgAxQ3goqYALExkG0YG8ulEx0NUQ7EcGUgnjFC0gio2gQqCeKZAHlwSUOwBMgyI5ggFEIlIG4xwS4JcRDIrlgA "Jelly – Try It Online"). ### How? ``` Ḥ’R_"ƲĖS€;€"ẎQƑ - Link: widths, heights Ʋ - last four links as a monad - f(widths): e.g. widths = [3,2,0,1] Ḥ - double [6,4,0,2] ’ - decrement [5,3,-1,1] R - range [[1,2,3,4,5],[1,2,3],[],[1]] " - zip with: _ - subtract [[-2,-1,0,1,2],[-1,0,1],[],[0]] Ė - enumerate [[1,[-2,-1,0,1,2],],[2,[-1,0,1]],[3,[]],[4,[0]]] S€ - sum each [[-1,0,1,2,3],[1,2,3],[],[4]] " - zip with heights applying: ;€ - concatenate (the current height) to each Ẏ - tighten Ƒ - is invariant under? Q - deduplicate ``` ]
[Question] [ You are going to be given a string containing some alphabetic characters along with `[` and `]`. Your task is to split into sections that are enclosed in a "group" created by `[...]` and those that are not. e.g. ``` "absbn[mesl]meslo[eyyis]me" -> "absbn" "mesl" "meslo" "eyyis" "me" ``` Super simple right? Well hold your horses. What happens when multiple brackets conflict? like `co[[x]t` or `m[[e]]it`? We don't have any guarantee that the brackets are matched or not nested. The rule we are going to use is that when multiple possible groups could be made we will always choose the smallest ones. Any `[`s left without a match are just regular characters and appear in the output. So in `co[[x]t` we could do `co` `[x` `t`, but we could also do `co[` `x` `t`. Since the group here is either `[x` or `x` we choose the smaller one and the result is `co[` `x` `t`. In the second case `me[[e]]it` there are 4 ways to make groups here, but unambiguously `me[` `e` `]it` results in the smallest group. Your task will be to take a non-empty string of characters `a` through `z` plus two brackets of your choice (`[]`, `{}`, `()` and `<>`) and to split it as described above, providing a list of strings as output. In cases where a group is on the boundary of the string, e.g. `aaa[b]` or `[ems]ee` you may choose to include or omit an empty string `""` on that boundary. The test cases always include them. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Answers will be scored in bytes with the goal being to minimize the size of your source code. ## Test cases ``` go[cat]me -> "go" "cat" "me" absbn[mesl]meslo[eyyis]me -> "absbn" "mesl" "meslo" "eyyis" "me" co[[x]t -> "co[" "x" "t" me[[e]]t -> "me[" "e" "]t" mon[g]]u -> "mon" "g" "]u" msy]mesl -> "msy]mesl" eoa[m -> "eoa[m" a[b[ -> "a[b[" mesi]mmp[mo -> "mesi]mmp[mo" meu[ems[mela[] -> "meu[ems[mela" "" "" w[[[] -> "w[[" "" "" [foo]foobar[bar] -> "" "foo" "foobar" "bar" "" [][] -> "" "" "" "" "" ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 9 bytes ``` S`<(\w*)> ``` [Try it online!](https://tio.run/##HYxBCsJQDET3uYdQBW9QuvUAuhsDP7/EUmga6a/UXswDeLGaCpnHkBlm0rkfZbslcKob@n7izsFDdUnbNdXVfTkdm8jrJipb52hlZlOSXPII0zLwDoeua1/2pHXgzTOZAsq78REd84usrP8yqQuMBBnRKj2bPWEe/gW1EquDgGkBgni4cyjLhFA8GPwD "Retina 0.8.2 – Try It Online") Link includes test suite that switches between `[]` and `<>` and separates the output lines for each case with `-` for convenience. Explanation: Simply splits on a minimal group, capturing the contents. The question now requires empty chunks, but the previous 10-byte version only required an extra `_` prefix to disable them: ``` _S`<(\w*)> ``` [Try it online!](https://tio.run/##HYxRCsJADET/cw@hCt6g7K8H0L8xuLsllkLTSLel9mIewIvVVMg8BuaRUaZuSNstgmMd6PvxOzsP1SVuj2usq/tyOgYX6uDO1hqaNLEKpVzyAJXS8w6DrGtX9qUx4M0TqQDCe7EBLfNMWta/TGIJSgkZbpWOVV9Q8z5DtPjXPoFpAZx4mrEnpxEe/gE "Retina 0.8.2 – Try It Online") Link includes test suite that switches between `[]` and `<>` and separates the output lines for each case with `-` for convenience. Explanation: Splits on a minimal group, capturing the contents even if it is empty, but skipping empty chunks. [Answer] # [R](https://www.r-project.org/), ~~68~~ ~~63~~ 62 bytes *Edit: -1 byte thanks to pajonk* ``` function(x,`[`=gsub)"@"["",scan(t="<(\\w*)>"[" @\\1 ",x],,"")] ``` [Try it online!](https://tio.run/##fZHBjoMgEIbvfQoye9GNPex9JH2P2rRoKDERMAKpPr07uLvFA@5hRubP//06OK1uHHp/F4M16q4mG0ZXr89gOt9bU8zV4/qolQttCRe4AlSuE6bwNWDRNK/PkpPILk3zxaCab1UFUN4ykQUoi53wXEso2Qc7c0YKMCCNOqmnHCRa1xrU0g08NotyWXq3D9kcW4Ibfh8xdvP9E9xZxJn7dwzN5J6pfB7QElHyHUFCfA8VP0KsQcV5SIiNX6oiEg4Qt2yLJuRPyNqlFajf3p8pf4/YYrqyOBws6Xqu9Yja7vZM2gEUUGpHf2kQyHdckmnjPPtC3CE0HTrxaS2nasWEVAkiDbZOKh1iP63f "R – Try It Online") Would be [55 bytes](https://tio.run/##fZJBboQwDEX3nCJKN0k1XXRbuTkJ0iigTIpE4hFONHB6atJ2YBG6sIm//vtgYFrpPg7pakeM/uonzHf6XG859mnAqGbtRkVpKiblKXdKgmrbx6s28iJF274LeZk1H6XWlSwlPUJvkwlOavEi3oxghd2scWe1qUG2oy5CcDSarSG4ZRnoGFIcJYHG38sWW3z/BPcIMJv0jOGZ3TNXqgPBAThzIFjY7sNlzhCM4I3JO4Lbk/oNyScILWXRHfkTqnaHFsLT@zPV3yN0sL@ybThZkgYTwh0CHvbctRMogwvEX2m0YA7cLvPGdfYBcEB4Ks6Gfwol25i@nLAx4jJEL5KjJHpL7qONUlfT4IZouDo7AdcezJosnVU@lN6s3w) if it wasn't for the annoying behaviour of [R](https://www.r-project.org/)'s `strsplit` function, which outputs an extra empty string if the split pattern occurs at the start of the string-to-be-split. We first search for bracket-pairs (using `<` and `>` as brackets) that contain only letters between them, and swap these brackets for spaces. Then, we use `scan` to split the resulting string (because of the annoying `strsplit` behaviour). `Scan` has it's own problem, though, which is that it treats consecutive whitespace as a single delimiter, and so would miss any empty groups: so, we add a spurious `@` character to each group, and then remove it with `gsub` when we're done splitting. [Answer] # [sed](https://www.gnu.org/software/sed/), 92 21 20 bytes ``` s/<\(\w*\)>/\ \1\ /g ``` [Try it online!](https://tio.run/##LY1BCsMwDATvfklbMKH3RS/xxU7VEIiiUjUkeb3r2D5IzKwkZPzy07rlbAPCLeyPcKchuPAMbphyjsnSCmFb6GoKPs/ZCjvvvROAieZflVGBgxqLrpiItiZ21uMqrBFSKSKhzdlmEvlAtPsGFitflwhquwk0viruQA/xVqVSKX5RqofH0eGiin8 "sed – Try It Online") Thanks to DLosc for pointing out the specs had changed, greatly simplifying my answer, and for a -3 bytes golf -1 thanks to "emanresu A" for pointing out I could use `<>` as my bracket chars Prints each group on its own line. * Finds all matches of the form `[<string of chars without brackets>]`. * Replaces them with `\n<string of chars without brackets>\n` [Answer] # Python3, 158 bytes: ``` import re def f(l): t='' while l: if(j:=re.findall('^\[\w+\]|^\[\]',l)):yield t;yield j[0][1:-1];l=l[len(j[0]):];t='' else:t+=l[0];l=l[1:] if t:yield t ``` [Try it online!](https://tio.run/##XY5NboMwEIX3nMI77CatEnVTGXGSYSqZMBBHY4ywI0Dq3SkEVRVs5ud7T2@mm@Ldt59fXT/P1nW@j6KnpKJa1JKVTkTM0zQRw90yCV52YWv50HlPH7VtK8Ms0@8CiuFU4M86YHpmpfRkiSsRs60/4IJw1e9XzDhnYGrlipTGbMsXxIF0PC3iZfNcNSbLLRH/ouYmZ@PKyohRw1stR4VJ19s2ykamjYebiegoVeqfmjKULTgKjGvxQNNkw9F18wAjxh1zBEB4hL6FBvG5h2F6he8geQNu/wqUcLgQLDrXgfMH/gRyYfmaDeBOGgBeZP4F) [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 11 bytes ``` a^`<(\w*)>` ``` Uses `<>` for brackets. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuharE-MSbDRiyrU07RIgIlCJ9dFKNrmpNjapdnYlNnZw9QA) [Verify all test cases](https://ato.pxeger.com/run?1=LY_BCoJAEIbvPsWyJw303OFn3iCQrmW4yhqC20qrmERP0kWIunTt1Jv0Nu26Hmbmm3_4Z5j7o63b147HLc8-6YpdBUsYZzHZlLBtGj77rorXb3HIEe6HVUS5V37f6MY2bBcwftQoRUdKctuIwhQnKGkacklDjmNtlmGpgQt1DpUEJC2sTzgS9TObcTY6llpAzUtRwJtMTUq1UNq3PaQy9lojQE4ZAA-otCYbhTjDhtfIzbKg9x9Mk69_) ### Explanation Same idea as [Neil's Retina answer](https://codegolf.stackexchange.com/a/241124/16766): the smallest possible group is always one that does not include any brackets. ``` a ; Command-line input ^ ; Split ` ` ; on this regex: < ; Opening bracket ( ) ; Group the following part so it is included in the list of results: \w* ; 0 or more word characters (here, letters) > ; Closing bracket ``` [Answer] # Javascript, ~~113~~ ~~103~~ 39 bytes ``` s=>s.replace(/<(\w*)>/g,'0$10').split(0) ``` Uses `<>` as the brackets. First time code golfing, yay! I'm pretty sure there's some regex magic which will beat this, but this was the best I could come up with. EDIT: First version didn't properly handle strings starting or ending with groups, e.g. `<a>b<c>` EDIT2: Shaved off 10 bytes thanks to [emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a) EDIT3: Figured out the regex magic [Answer] # [Python](https://www.python.org), 83 bytes ``` lambda s:[t for i,t in enumerate(re.split(r"\[([^][]*)\]",s))if(i&1)or t] import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RZDBTsMwDIbFNU8R5YCaaUPaDU3q3gFx9IJIR9pFauoqSdn6LFwmIXgneBqcNMDBru3P_u307XOc4wmH63tbHz6m2G7uvx577ZoXzcMOIm_Rc7uO3A7cDJMzXkdTeXMXxt7GyosDVPCkQK3kQYl1kNK2lb3dShqLilk3oo_cmyL9cD7Z3vDtjpEo8ppkxylWssgJvtlzIRlPCFZOj5V51f0aC5dSMT56O8SKtsi6RrkIX79vnjuEo47KmSzSoeCCcvLOCKab0AzgTOhVcghmnm34bc40d4a-fNJ47ikCRwS4qJjbKabqhSwK5gyAUYVQkubIVEI4QKfUtCBMG7qEJkJhzocsqCSCGdTgci1HdDc0sJxIQVoWrHJuBIdl31-e4ATGBXplr0EV_l-izYKdAQqiKFegRVRkjfZAtkDKRfZUoSB5tvzpHw) This uses `re.split` which returns a list containing both the stuff between matches and those parts of matches that are in grouping parentheses. This is then filtered to remove empty strings but only between groups; empty groups are retained. [Answer] # [Perl 5](https://www.perl.org/), 57 bytes ``` s/<(\w*)>/ $1 /g;s/^ (.*) $/$1/;print for split/ +/,$_,-1 ``` [Try it online!](https://tio.run/##HYzBigIxEETv@Yoc5qCuGuawJ4v@ElnJSBwC6XSYjuj8/MaMh1cU1KNKWNJva@qwu74Oe3J2GK2bL@r@7O582NvBDaO7lCXmah@yWC0pVmd/3HG4HU9ja7Pg7itxMH7SKYODJtpCENY16rbcBXhTNRyAQFuRjJnoaVjXr2yCeLDxmNAtjcRcwNL7E4G1vyYPMi@gJx4i1Jn8gg79S6lRsrZTTh8 "Perl 5 – Try It Online") [Answer] # JavaScript, 21 bytes ``` s=>s.split(/<(\w*)>/) ``` [Try it online!](https://tio.run/##LY09c8MgDIZ3/wqfJ2gSsvdkderSoR06tr0LtsGhB8hncAO/3sVOBkmP3lcfv/JPhn42Uzx5GtSq2zW0GESYrInsDOz79sTxzFfZfjUjQS8jOtUcG9mFzoNTweKWCFTOJty9ngASxkJOASi8I3kYEZcNQ96XCiqS4LZz0ME@Hww6N4GjvVtAuVC@WAlYhBvAXkETYYlOzlBil7A4P5VtpZjVsPSKsXTMvMUkrPJjvGJ@wEt6zvzBlaaZpZp0LXnVkw9klbA0siQmObz6gVl@uNQnrC@Ht8@PdxHibPxodGaaJc75@g8) [Answer] # [Raku](https://raku.org/), 28 bytes ``` ~«*.split(/\[<(\w*)>\]/,:v) ``` No TIO link, because the version of Raku/Perl 6 found there appears to have a regex bug. All of the test cases work fine on my local system though. * `*.split(/.../, :v)` splits the input parameter on the given regex. The `:v` adverb causes the delimiters to be included in the returned list as well, as Match objects. * `~«` converts everything in the split return list to strings. The nondelimiter groups are already strings, but the delimiter Match objects need to be converted. * `\[` and `\]` match the literal square bracket delimiters. * `<(` and `)>` cause the delimiter Match objects to only reference the enclosed text; that is, the square brackets are excluded. * `\w*` is a sequence of letters. All of the allowed delimiter pairs are Raku regex metacharacters, so there's no avoiding having to escape them. ]
[Question] [ In musical notation, groups of notes shorter than one beat are joined together by a line at the bottom called a beam. Here are a few bars of music with the beams highlighted: [![enter image description here](https://i.stack.imgur.com/zci9B.png)](https://i.stack.imgur.com/zci9B.png) (Taken from *Second Suite in F* by Gustav Holst; you can hear how these notes sound at [0:13 in this video](https://www.youtube.com/watch?v=7nz7tvRdL94).) You may notice that beam #6 is above the ovals that define the notes, and its vertical lines attached to their right sides, while the others are below the notes and attached to their left. What determines this? There are a few simple rules, which are the subject of this challenge. 1. By default, the placement of the beam is determined by its highest or lowest note. If the note farthest from the centermost line of the staff is above it, then the beam goes below the notes. If the note with the highest absolute value is above the centermost line of the staff, then the beam goes below the notes. 2. If the highest and the lowest note are the same distance from the center line, the direction of the beam is determined by which side of the center line the majority of notes in the beam lie on. If a majority of notes lie above the centre line, the beam goes down. If a majority of notes lie below the centre line, the beam goes up. Notes on the center line do not count either way. 3. If the highest and the lowest note are the same distance from the center line, and equally many notes lie above and below the center line, the beam may be placed either above or below the notes. In the sample notation above, the beams of clusters #1, 2, 3, and 5 are determined to be below the notes because their highest notes (their second, second, first, and third respectively) are above the center line. #6's lowest note is its first/third note, which is below the center line. #4's highest and lowest note are equally distant from the center line and it contains no majority either way. Its beam could be placed either above or below, but my composition program renders it as below. # Your commission Write a program that takes in a list of integers, which may be zero or negative, and outputs a truthy/falsey value. These integers represent notes and their distance from the center line; positive values represent notes above the line, zero represents notes on the line, and negative values represent notes below the line. Determine, given a cluster of notes that sit those distances from the center line, which way the cluster's beam should go; output `TRUE` if the beam should go above the notes and `FALSE` if the beam should go below the notes. To restate the rules above and give the algorithm: 1. Find the number in the list with the largest absolute value. If it is greater than zero, output `FALSE`. If it is less than 0, output `TRUE`. If it is 0, output may be `TRUE` or `FALSE` as convenient. If there are positive and negative numbers with the same, maximal absolute value, continue. 2. Determine whether the majority of numbers are positive and negative, ignoring zeroes. If a majority of numbers are positive, output `FALSE`. If a majority of numbers are negative, output `TRUE`. 3. Otherwise, output may be `TRUE` or `FALSE` as convenient. You might be given only one number. In that case, it has the highest absolute value, so if it is greater than 0 output false; if it is less than zero output true; and if it is 0 you may output true or false. You may not assume the numbers are sorted. # Test cases ``` 5, 4, 3 -> FALSE # #3 1, 0, -1 -> TRUE or FALSE # #4 0, 1, 2, 0 -> FALSE # #5 -2, -1, -2 -> TRUE # #6 3, 1, 4, 1, 5, -9 -> TRUE # Largest absolute value below 0, rule 1 3, 1, 4, 1, 5, -5 -> FALSE # Largest absolute value tied, determined by majority, rule 2 3, 1, -3, -1, 5, -5 -> TRUE or FALSE # Largest absolute value tied and no majority, unspecified ``` [Answer] # [R](https://www.r-project.org/), 40 bytes ``` function(x)min(x)+max(x)+mean(sign(x))<0 ``` [Try it online!](https://tio.run/##K/qfpmCr8D@tNC@5JDM/T6NCMzcTRGrnJlaAqdTEPI3izHSQmKaNwf80jWQNUx0FEx0FY01NLhDPUEfBQEdB1xDKBbKBIkZAQaiArhFIFoiNFKAixmAlJmASaJauJS4JUxRxXWOIQWAZoJb/AA "R – Try It Online") If `min(x)+max(x)` is non-zero, its sign corresponds to the note farthest from the centre and gives the direction of the beam. Adding `mean(sign(x))` can never change the sign. Indeed, either (a) all notes are of the same sign and `mean(sign(x))` is of the same sign as `min(x)+max(x)` or (b) notes are of both signs and `mean(sign(x))` is strictly in \$(-1,1)\$ whereas `min(x)+max(x)` is an integer, so the sign of the sum is unchanged. If `min(x)+max(x)==0`, the sign of the mean decides the direction. If undecided, defaults to `FALSE`. [Answer] # [Python 3](https://docs.python.org/3/), 55 bytes ``` lambda a:(min(a)+max(a)or sum((i>0)-(i<0)for i in a))<0 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRSiM3M08jUVM7N7ECSOUXKRSX5mpoZNoZaOpqZNoYaKYBhTIVMvMUEjU1bQz@FxRl5pVopGlEm@oomOgoGCsggVhNTQVlBTdHn2BXLrg6Qx0FAx0FXUMMdSFBoa4KQMPR1AMVA7UYAXXhN1fXCGQqEBthMRehzBhsnAmYBDpZ15I4ZaY4bIWo0zWG2A1WicU3/wE "Python 3 – Try It Online") [Answer] # JavaScript (ES6), ~~66~~ 64 bytes ``` a=>(a.map(m=v=>(k+=v>0||-!!v,a=v>a?a:v,m=v<m?m:v),k=0)|a+m||k)<0 ``` [Try it online!](https://tio.run/##lY89D4IwEIZ3f8W50dgCgg4SKnHQycmPyThcEIxiKUHTqf8dT1yMEqNN2lzS57n37owGr2l9qm6i1IesyWWDcuqgq7BylDRUFwNppr61ot83HKnGBCPD6TNWiYoM44X0mcWBsrZgsd@kurzqS@Ze9NHJnd2Yw4hDCC9nzxh4Hixmy/W894YPOfgcxPAT36y2c9B1t0YOmQHJP6WI4JFBN@hKeafDtvmofWkdMfmLHn8f5YmL8DlQK3Qt3NwB "JavaScript (Node.js) – Try It Online") ### Commented ``` a => ( // a[] = input array, re-used to store the minimum value a.map(m = // initialize m = maximum to a non-numeric value v => ( // for each value v in a[]: k += // update k: v > 0 || // increment it if v > 0 -!!v, // decrement it if v < 0 a = v > a ? a : v, // update a to min(a, v) (always v if a is non-numeric) m = v < m ? m : v // update m to max(m, v) (always v if m is non-numeric) ), // k = 0 // start with k = 0 ) // end of map() | a + m // use a + m if it's not equal to 0 || k // otherwise, use k ) < 0 // test if the above value is negative ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 9 bytes ``` ṠÆm+Ṁ+Ṃ<0 ``` [Try it online!](https://tio.run/##y0rNyan8///hzgWH23K1H@5sAOImGwOgwD7rRw1zFHTtFB41zLU@3M71cPeWo5PCDrc/aloT@f@/kpKSqY6CiY6CMZehjoKBjoKuIReQBLKNgFwuXSOQCBAbcRmDRU3AJFCLriWGiClURNcYogksBrQAAA "Jelly – Try It Online") A monadic link taking a list of integers and returning a Jelly Boolean indicating the direction of the stems as per the spec. Modified with inspiration from [@RobinRyder’s excellent R answer](https://codegolf.stackexchange.com/a/198134/42248) so be sure to upvote that one too! ## Explanation ``` Ṡ | Signs Æm | Mean +Ṁ | Add max (of original argument) +Ṃ | Add min (of original argument) <0 | Less than 0 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÄZQÏ‚¤Ëè.±Od≠ ``` Output will be false if either of the two is a possible output. -1 byte and fixed a bug for `[0,0,1,-1,-1]` thanks to *@Grimmy*. [Try it online](https://tio.run/##yy9OTMpM/f//cEtU4OH@Rw2zDi053H14hd6hjf4pjzoX/P8fbaxjqGMCxKY6uqaxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCf8Pt0QFHu5/1DDr0JLD3YdX6B3a6J/yqHPBf53/0dGmOiY6xrE60YY6Bjq6hkCGgY6hjpGOAZClawQU0dE1AjKNgYImQGyqo2uJyjWFcnWNQYqhAgZAwwzAhhrpGIOlQFaADQPxjME2gizShdgEUm8ItswwNhYA). **Explanation:** ``` Ä # Convert each value in the (implicit) input-list to their absolute value # i.e. [3,1,-5,4,1,5,-5] → [3,1,5,4,1,5,5] # i.e. [0,1,-2,0] → [0,1,2,0] Z # Push the maximum of these absolute values (without popping the list itself) # i.e. [3,1,5,4,1,5,5] → 5 # i.e. [0,1,2,0] → 2 Q # Check for each absolute value whether it's equal to this maximum # i.e. [3,1,5,4,1,5,5] and 5 → [0,0,1,0,0,1,1] # i.e. [0,1,2,0] and 2 → [0,0,1,0] Ï # And only leave the values of the (implicit) input-list at the truthy indices # i.e. [3,1,-5,4,1,5,-5] and [0,0,1,0,0,1,1] → [-5,5,-5] # i.e. [0,1,-2,0] and [0,0,1,0] → [-2] ‚ # Pair it with the (implicit) input-list # i.e. [3,1,-5,4,1,5,-5] and [-5,5,-5] → [[3,1,-5,4,1,5,-5],[-5,5,-5]] # i.e. [0,1,-2,0] and [-2] → [[0,1,-2,0],[-2]] ¤ # Push the last value of this pair (without popping) again Ë # And check if all values are equal (1 if truthy; 0 if falsey) # i.e. [-5,5,-5] → 0 # i.e. [-2] → 1 è # Use it to index into the pair # i.e. [[3,1,-5,4,1,5,-5],[-5,5,-5]] and 0 → [3,1,-5,4,1,5,-5] # i.e. [[0,1,-2,0],[-2]] and 1 → [-2] .± # Take the signum of each value # i.e. [3,1,-5,4,1,5,-5] → [1,1,-1,1,1,1,-1] # i.e. [-2] → [-1] O # Sum those together # i.e. [1,1,-1,1,1,1,-1] → 4 # i.e. [-1] → -1 d # Check if it's non-negative (>=0) ≠ # And invert the boolean (so basically check if it's negative / <0) # i.e. 4 → 1 → 0 # i.e. -1 → 0 → 1 # (after which this is output implicitly as result) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 58 bytes ``` O#`\S+ \d+ $* +` -1+ +1+ ^-(1+)($| ((?!.*\1$)|-.* \1$)) ``` [Try it online!](https://tio.run/##TYstDwIxEET9/oohlGTbzV76cRWnkEgEtiElAYFBXJD330t7CvGSeZOZ9fV9fx7txJfarsdabkLlKWQcSYUGgXQIdFcOYtlsYD4fJleCsZtODiPY1jJmJArw/UQeARGeNHaDRkq9mDsZuvxL3kXTmA39AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` O#`\S+ ``` Sort the numbers numerically. ``` \d+ $* ``` Convert to unary. ``` +` -1+ +1+ ``` Match inner pairs of negative and positive numbers and delete them until only one negative and/or positive number remains. ``` ^-(1+)($| ((?!.*\1$)|-.* \1$) ``` Output a truthy value if the (largest) negative number is the only number, or if its absolute value is greater than the largest positive number, or if another negative number remains and its absolute value equals the largest positive number. [Answer] # [PHP](https://php.net/), ~~178~~ ~~127~~ ~~111~~ ~~107~~ 105 bytes ``` <?php foreach($argv as$n){$c+=$s=$n<=>0;($a=$n*$s)>$m&&$x=$s;$a-$m||$x=0;$a>=$m&&$m=$a;}echo$x?$x<0:$c<0; ``` [Try it online!](https://tio.run/##HcnBCoMwEIThV/EwSG0RUqqHNtn4LEuwzSUaDEhA@@zbpYeBf/hyzCJuyjE373WbOcQLePvsDRcs3YFwIxTC4sgbq6R5Rek8Utuiqllwj3Seeoy2p78kAtvvHOKKOqE680JwxorIQ@4y6Ebpnz8 "PHP – Try It Online") ## Ungolfed ``` <?php $notes = explode(',', $argv[1]); $max_note = 0; $max_sign = 0; $counts = 0; foreach ($notes as $note) { $sign = $note <=> 0; $counts += $sign; if (abs($note) > $max_note) { $max_sign = $sign; } elseif (abs($note) == $max_note) { $max_sign = 0; } if (abs($note) >= $max_note) { $max_note = abs($note); } } echo ($max_sign == 0) ? ($counts < 0) : ($max_sign == -1); ?> ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes ``` Min@#+Max@#+Mean@Sign@#<0& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983M89BWds3sQJEpibmOQRnpgNFbAzU/gcUZeaVRKcp6DsoVFeb6iiY6CgY1@ooVBvqKBjoKOgagthABpBrBBQB8XSNQOJAbATiGYPluBSAwATMBJqha4mQQQiaIgR1jSFGQIRrY/8DAA "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a list of numbers as input, and returns `True` or `False` as output. Uses the same logic as [Robin Ryder's answer](https://codegolf.stackexchange.com/a/198134). Additionally, here's the 49-byte function I came up with myself: ``` Tr[{}⋃Sign@MaximalBy[#,Abs]/.{-1,1}->Sign@#]<0& ``` [Answer] # [J](http://jsoftware.com/), 17 bytes ``` 0>>./+<./+#%~1#.* ``` [Try it online!](https://tio.run/##fZCxasMwEIb3PsVPQzBNFNWy4yEmydBCp9ChLyDk@Jw4yBHIcoqXvrorux3UDhGcDn5O33foMjzyqMIuRwSGGLmvFcfrx@FtiPd7/rzc@prNv8SML4anBzqejR/ZoUKGNdIwEL5LgeC8v3A42xGMRaV0S1Bam08qw2cxg2BIvP0nFVMqk5ElkzBLp8n1dGcMcjMJDsqeqHVQRWt05wg3pb2yIG8a4bbTBBEa/3OyexxXU8lQkiPb1FcqUfRo1MXY2vW/8OQP3C8r03H5bCTf@4XhGw "J – Try It Online") Based on [Robin Ryder's insightful alrogithm - make sure to upvote his](https://codegolf.stackexchange.com/a/198134). * `0>` Is 0 greater than... * `>./` The max... * `+` Plus... * `<./` The min... * `+` Plus... * `#` The input length... * `%~` Divided into... * `1#.` The sum of... * `*` The signs. [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 23 bytes ``` psJ)snav/^>]j<]CL++@0.< ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/oNhLszgvsUw/zi42yybW2Udb28FAz@b/f10jBV1DBV0jAA "Burlesque – Try It Online") Following the logic of [@RobinRyder](https://codegolf.stackexchange.com/a/198134/42248). Takes input as `A B C ...` ``` psJ # Parse input to list of ints and dup )sn # Map sign av # Average (returns double) /^ # Swap and Dup >] # Max j<] # Min CL++ # Collect all and sum @0.< # <0.0 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~118~~ ~~115~~ 109 bytes ``` #define A a[p] p;s;q;r;f(a,t)int*a;{p=t;for(q=r=*a;p--;s+=(A>0)-(A<0))q=q>A?q:A,r=r<A?r:A;a=q+r+(s>0)<(s<0);} ``` Uses Robin Ryder's method. [Try it online!](https://tio.run/##ddDdboMgFAfwe5@CdFkCE1K/umVF2vAcWy@o4kdinYC7Mr76HNqaLSu7gIST8@N/ICNllk3TQy6LupWAA/HWnbyOGqqopgUUuEd12z8JOnSsp8WHhoppZs8dIdT4DPJDgAjkaYCQYurAj2rPsWY65Ue951Qw5WsfGtuVQmO76DhdRN1CNIDtFoTRi2fvt7EnNuwwSDCIR@p12hYLuHnM39sNnseIEaIWFKIx0lvIeSYhBgEGJHSY82pk3VdSX1E2Iyusiyx1sAwnd1H5rEg0B9kVOVS@hvX684bkjOIlKll2@zzy6rASP/@1pcvuHLZc7a9pqx9M4uvM//Fq5bc/GqevrGhEaSbSXL4B "C (gcc) – Try It Online") [Answer] # [~~Perl 6~~ Raku](https://github.com/nxadm/rakudo-pkg), 31 bytes ``` {0>.min+.max+sum($_».sign)/$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1uplmb7v9rATi83M09bLzexQru4NFdDJf7Qbr3izPQ8TX2V@Nr/1lxcxYmVCmkK0aY6CiY6Csax1jABQx0FAx0FXUOECJALFDQCiiPEdI1AaoDYSAEhaAxWaAImgebqWuKRM0WX0jWGmAiV/A8A "Perl 6 – Try It Online") Based on [Robin Ryder's solution](https://codegolf.stackexchange.com/a/198134). [Answer] # [Factor](https://factorcode.org/), 44 bytes ``` [ dup minmax + swap [ sgn ] map mean + 0 < ] ``` [Try it online!](https://tio.run/##fZBPTwIxEMXvfIpnOMqShWU1/omJBzQmxIPIiXAouwNWS1vbrrgaPvsyEBRUpEkn6cxv3pvORGTBuGrQv7u/PccLOU0KMxGemj6IIH2QmV@/4em1IJ2Rh3UUQmmd1AFT0uSEkh8MG@1xUat9IkUHCRb4PkeIrnBz3et3t7l6wmQLMaLWDromHx8GXRj31VHvMBkz2@a4OKiZMhm1V5IcF380d8gTJhPW7PBNEZ2t6X1kT7gp@QAx9kYVgfAmVEEYkzJzxA24QhFaP9XSrdqvCf9RC5LyBnIK5GZSU45xyVt/Nk6GcmPR3lhEyep7G5N96zpgAaFzaLMjXWhvKZMTLtaqIfLCggeYiXccw8@FxRB@qjHiFq6Q0JyPcYlRdQotrFUlmh6ZIuGqJQ "Factor – Try It Online") Port of Robin Ryder's [R answer](https://codegolf.stackexchange.com/a/198134/97916). ]
[Question] [ Inspired by [this question](https://codegolf.stackexchange.com/questions/75587/zigzagify-a-matrix) Another way to unroll a 2D image into a 1D string is to use an [Hilbert Curve.](https://en.wikipedia.org/wiki/Hilbert_curve) There are many version of this curve, depending on the number of iterations used while computing it. Below follow example of Hilbert Curves from first order to fifth order. [![enter image description here](https://i.stack.imgur.com/MfnFG.png)](https://i.stack.imgur.com/MfnFG.png) The way of computing this curve is the following. First we define the first order Hilbert Curve as the one shown in figure (the one for n = 1), so that it fits in a 1x1 square. We than make four copies of this curve, spacing them in a 4x4 square, so that they all present the "concavity" towards the left side. We then flip the two leftmost order 1 curves, so that the top one concavity faces toward the top, while the bottom's faces the bottom. We finally connect the the corners of the adjacent Hilbert Curves. If wanting to obtain a (n+1)-order Curve, we just need to repeat the process with four n-order Curves. We can see a visualisation of the process [here](https://youtu.be/DuiryHHTrjU?t=4m23s) (I will also add an image detailing the process soon) Your task in this challenge is to unroll a matrix of integers along the **lowest order Hilbert Curve** for that matrix. For simplicity's sake, we will have the curve starting from the top left corner of the matrix. You can receive the input either as a list of list of integers, where each sub-list represents a row of the matrix. You can assume that the input will be a square matrix (n\*n). For example: Input: ``` [[ 1, 2,] [ 3, 4 ]] ``` Output: ``` [ 1, 2, 4, 3 ] ``` Since we are using the first order Hilbert Curve shown in figure Input: ``` [[ 1, 2, 3, 4, ] [ 5, 6, 7, 8, ] [ 9, 10, 11, 12, ] [ 13, 14, 15, 16 ]] ``` Output: ``` [ 1, 5, 6, 2, 3, 4, 8, 7, 11, 12, 16, 15, 14, 10, 9, 13 ] ``` Using the second order Hilbert Curve As usual, standard loopholes are not permitted. This is code-golf, so the shortest answer in byte wins. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 41 [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") Saved 30 bytes (!) by consulting the wisdom of the APL Orchard, especially @ngn and @Sherlock9. ``` {0::⍵⋄∊∇¨⌽∘⊖¨@4,⌽@1⊢∘⍉\⌽↑∘⍵¨∘.,⍨2 ¯2÷⍨≢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rAyupR79ZH3S2POroedbQfWvGoZ@@jjhmPuqYdWuFgogPkORg@6loEEurtjAFJtk0Ec7YClXbM0NN51LvCSOHQeqPD24GsR52LgDK1/9MetU141Nv3qG@qp/@jruZD641B2vqmBgc5A8kQD8/g/0BDc4GqjBSMHvVuedS72YTrUe8arjSFXDANlTVRMIHIGpqhSvfshTDSQCwA "APL (Dyalog Unicode) – Try It Online") Explanation as follows: ``` {0::⍵⋄∊∇¨⌽∘⊖¨@4,⌽@1⊢∘⍉\⌽↑∘⍵¨∘.,⍨2 ¯2÷⍨≢⍵} ⍝ Recursive function - takes input as an ⍝ n*n square matrix 0::⍵ ⍝ Our base case - this is an error guard ⍝ If there's any error, catch it and ⍝ return the function's input ≢⍵ ⍝ Find the number of rows in the input 2 ¯2÷⍨ ⍝ Divide the above by 2 and negative 2, ⍝ resulting in a 2-element vector ∘.,⍨ ⍝ Outer product - take the above vector and ⍝ apply concatenation (,) with each element ⍝ against all elements in the vector. Since ⍝ we have a 2-element vector, this results in ⍝ a 2-by-2 matrix, e.g. ⍝ [[(2,2),(2,¯2)],[(¯2,2),(¯2,¯2)]] ↑∘⍵¨ ⍝ For each element in the matrix, we apply ⍝ "take" against our original input matrix. ⍝ Take, given a negative number, will take ⍝ elements from the end of a particular rank. ⍝ With our argument above, this means that we end ⍝ up with our original original input matrix ⍝ split by quadrant into a 2-by-2 matrix. ⍝ It is also worth noting that take expects ⍝ an integer argument, so for matrices whose ⍝ rowcount divided by two results in a decimal ⍝ (i.e., 1-by-1 matrices), we throw an error ⍝ which is caught by the guard above, returning ⍝ the original input. ⌽ ⍝ Flip the above matrix about the vertical axis. ⊢∘⍉\ ⍝ Apply a "monadic transpose scan". More details ⍝ on how this works below, but for our purposes ⍝ this applies transpose to each of the two ⍝ sub-matrices on the right half. ⌽@1 ⍝ Swap the two upper sub-matrices. Given our ⍝ flip for the overall matrix above, this returns ⍝ the two upper quadrants to their original ⍝ positions. , ⍝ Ravel: flatten the 2-by-2 matrix into a ⍝ 4-element vector ⌽∘⊖¨@4 ⍝ Take the last element of the list (the lower ⍝ right quadrant originally) and flip it ⍝ along the vertical and horizontal axes. Given ⍝ the transposition above, this has the final ⍝ effect of transposition along the antidiagonal. ∇¨ ⍝ For each element in the above vector, recurse. ∊ ⍝ Recursively flatten the results into a single ⍝ vector. ``` More details on "[monadic transpose scan](https://codegolf.stackexchange.com/questions/150117/boustrophedonise/150153#150153)". Dyalog documentation on [error guards](http://help.dyalog.com/latest/Content/Language/Defined%20Functions%20and%20Operators/DynamicFunctions/Error%20Guards.htm). [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~86~~ 85 bytes This solution is based upon Jonas Lundgren's [File Exchange entry](http://www.mathworks.com/matlabcentral/fileexchange/27577-fractal-curves/content/hilbert.m) which utilizes complex numbers to generate the Hilbert curve. These complex numbers are then converted to index values to retrieve the elements of the matrix that fall along the curve. ``` nZl2/1XLJQXH1J-XI0,1L:"XJJZj1j*XKKH-JI-JH+IK-,4$h2/]XJJ1L*XJJH+J1)-XHGHXjHYj3$)1$Xd1$ ``` [Try it online!](https://matl.suever.net/?code=nZl2%2F1XLJQXH1J-XI0%2C1L%3A%22XJJZj1j%2aXKKH-JI-JH%2BIK-%2C4%24h2%2F%5DXJJ1L%2aXJJH%2BJ1%29-XHGHXjHYj3%24%291%24Xd1%24&inputs=%5B1%2C2%2C3%2C4%3B5%2C6%2C7%2C8%3B9%2C10%2C11%2C12%3B13%2C14%2C15%2C16%5D&version=15.1.0) **Explanation** ``` %--- Define some numbers to be used throughout ---% n % Retrieve the number of elements in the input matrix Zl2/ % Compute the order of the curve (log2(numel(i))/2) 1XL % Store the order in the 1L clipboard JQ XH % Store 1 + j in H clipboard 1J- XI % Store 1 - j in I clipboard 0 % Place 0 onto the stack %--- Compute the hilbert curve ---% 1L:" % For k = 1:order XJ % Store the top of the stack (z) in J clipboard JZj % Compute the conjugate of z (stored in J) 1j* % Multiply by j to get conj(z) * j XK % Store result in K clipboard KH- JI- JH+ IK- 4$h % Horizontal concatenation of K-H, J-I, J+H, and I-K 2/ % Divide entire array by 2 ] % End for loop XJ % Store z in J clipboard %----- Convert complex decimal values to complex integer indices ----% J1L* % Multiply z by the order XJ % Store result in clipboard J JH+ % Add 1 + j to H J1)- % Subtract the first element of z XH % Store integer complex numbers in H %--- Retrieve the elements from the input along the curve ---% G HXj HYj 3$) % Index into input using real/imag components input(real, imag) % This will yield an numel(real) x numel(imag) matrix where % the diagonal values are the values we want 1$Xd % Extract the diagonals using diag with one input 1$ % Display only the top element on the stack ``` [Answer] # Python 3, ~~327~~ ~~289~~ ~~275~~ ~~271~~ ~~239~~ 234 bytes This is a solution I modified from [my answer](https://codegolf.stackexchange.com/a/67178/47581) for another Hilbert curve question [here](https://codegolf.stackexchange.com/questions/66958/map-string-to-hilbert-curve). Any golfing tips are appreciated. **Edit:** Changed how `g` is incremented and decremented. Now using `eval()` and `str.translate`. No longer using `l=len(s)`. ``` def h(s): t=[s[0][0]];x=y=g=0;b="A" for j in range(len(bin(len(s)))-3):b=b.translate({65:"-BF+AFA+FB-",66:"+AF-BFB-FA+"}) for c in b:g+=(c<"-")-(c=="-");a=c>"B";x,y=[[x,y],[[x+1-g%4,y],[x,y+g%4-2]][g%2]][a];t+=[s[x][y]]*a return t ``` **Ungolfed:** ``` # the following function is implemented in the code with b=b.translate def hilbert(it): s="A" n="" for i in range(it): for c in s: if c == "A": n += "-BF+AFA+FB-" elif c == "B": n += "+AF-BFB-FA+" else: n += c s=n;n="" return s def matrix_to_hilbert(mat): length = len(mat) # this returns the number of rows in the matrix if length < 2: return mat it = len(bin(length)) - 3 hil = hilbert(it) output = [mat[0][0]] # a list that starts with the first element of the matrix x = 0 y = 0 heading = 0 for char in hil: # navigating the Hilbert curve if char == "-": heading += -1 elif char == "+": heading += 1 elif char == "F": if heading % 4 == 3: y += 1 elif heading % 4 == 2: x -= 1 elif heading % 4 == 1: y -= 1 else: x += 1 output.append(mat[x][y]) return output ``` [Answer] # Mathcad, 302 bytes The Mathcad program below is based on the @Sherlock9 Python program. It differs by curvifying rectangular matrices by ignoring those parts of the Hilbert Curve that lie outside of the matrix bounds. Note that as Mathcad has relatively poor string handling, I've mapped the Lindenmayer symbols to integers in the Hilbert function. [![enter image description here](https://i.stack.imgur.com/00QNo.jpg)](https://i.stack.imgur.com/00QNo.jpg) Mathcad works through a 2D interface that allows the user to place (and freely mix) mathematical expressions, plots, text, inputs and outputs. I've equated a byte to the minimum user keyboard equivalent operation to create a symbol (for example, the definition operator (:=) is entered by simply typing :. [Answer] # [Uiua](https://www.uiua.org/), 36 bytes ``` ⊏⍏∩♭⍥(⊂∶¯+¬×2⧻♭.⇌.≡⊂⊃⍉+∶⧻♭.)ₙ2⧻,↯1⇡1 ``` [Try it online!](https://www.uiua.org/pad?src=ZyDihpAg4oqP4o2P4oip4pmt4o2lKOKKguKItsKvK8Ksw5cy4qe74pmtLuKHjC7iiaHiioLiioPijYkr4oi24qe74pmtLinigpky4qe7LOKGrzHih6ExCmcgW1sxXV0KZyBbWzEgMl0gWzMgNF1dCmcgW1sxIDIgMyA0XVs1IDYgNyA4XVs5IDEwIDExIDEyXVsxMyAxNCAxNSAxNl1d) Constructs the path on the matrix directly, and uses it to index into the matrix. ``` ⊏⍏∩♭⍥(⊂∶¯+¬×2⧻♭.⇌.≡⊂⊃⍉+∶⧻♭.)ₙ2⧻,↯1⇡1 input: matrix M of size 2^n*2^n ↯1⇡1 the initial Hilbert matrix [[0]] ₙ2⧻, log 2 of the length of M (= n) ⍥(...) repeatedly construct the Hilbert matrix by calling the inner function n times... ∶⧻♭. put the number of elements in the current matrix under itself ⊃⍉+ construct the top two submatrices: 1) transpose 2) add to each element ≡⊂ join horizontally ⇌. create a copy and reverse its rows ¯+¬×2⧻♭. a bunch of arithmetic to get the bottom two submatrices ⊂∶ join vertically in reverse ∩♭ flatten the Hilbert matrix and M ⊏⍏ put the elements of M in the increasing order in the Hilbert matrix ``` # [Uiua](https://www.uiua.org/), 41 bytes ``` ⊡⍉∧(≡⊂∶⍜⊢-≡⇌,-1×2∶≡⊂∶⇌⍜⊢+,,⇌)↯2⇡1ⁿ∶2⇡ₙ2⧻. ``` [Try it online!](https://www.uiua.org/pad?src=ZyDihpAg4oqh4o2J4oinKOKJoeKKguKItuKNnOKKoi3iiaHih4wsLTHDlzLiiLbiiaHiioLiiLbih4zijZziiqIrLCzih4wp4oavMuKHoTHigb_iiLYy4oeh4oKZMuKnuy4KZyBbWzFdXQpnIFtbMSAyXSBbMyA0XV0KZyBbWzEgMiAzIDRdWzUgNiA3IDhdWzkgMTAgMTEgMTJdWzEzIDE0IDE1IDE2XV0=) Constructs the list of coordinates and indexes into the original matrix using `⊡` "pick". [Answer] # Wolfram - 233 Based on representation as [Lindenmayer system](https://en.wikipedia.org/wiki/Hilbert_curve#Representation_as_Lindenmayer_system): ``` f[m_]:=m[[Sequence@@Reverse[#+1]]]&/@DeleteDuplicates@AnglePath[Pi/2,List@@StringReplace[Last@SubstitutionSystem[{"A"->"-BF+AFA+FB-","B"->"+AF-BFB-FA+"},"A",Round@Sqrt@Length@m],{"A"|"B"->"","-"->{0,-Pi/2},"+"->{0,Pi/2},"F"->{1,0}}]] ``` [Answer] # Ruby, ~~224~~ ~~221~~ 216 bytes This answer is based on [my Python answer](https://codegolf.stackexchange.com/a/76300/47581). ``` ->s{t=[s[0][0]];x=y=g=0;b=?A;(s.size.bit_length-1).times{b=b.split("").map{|c|c==?A?"-BF+AFA+FB-":c==?B?"+AF-BFB-FA+":c}.join("")};b.each_char{|c|g+=c==?-?-1:c==?+?1:0;(g%2>0?y+=g%4-2:x+=1-g%4;t<<s[x][y])if c==?F};t} ``` **Ungolfing:** ``` def hilbert(mat) result = mat[0][0] x = 0 y = 0 heading = 0 b = "A" (mat.size.bit_length-1).times do each |j| # Hilbert curve using a Lindenmayer system a = b.split("").map do |char| if char == "A" "-BF+AFA+FB-" else if char == "B" "+AF-BFB-FA+" else char end end b = a.join("") end b.each_char do |char| # navigating the matrix if char == "-" heading += -1 else if char == "+" heading += 1 else if char == "F" if heading % 2 == 0 y += heading % 4 - 2 else x += 1 - heading % 4 end result << s[x][y] end return result end ``` [Answer] # CJam, 60 ``` Lq~:A,2mL{:B1f^0B1B2B3f^]:+}*1+{AT=U=\2md'U^_~)@2*-':@+~;}%p ``` [Try it online](http://cjam.aditsu.net/#code=Lq~%3AA%2C2mL%7B%3AB1f%5E0B1B2B3f%5E%5D%3A%2B%7D*1%2B%7BAT%3DU%3D%5C2md'U%5E_~)%402*-'%3A%40%2B~%3B%7D%25p&input=%5B%5B1%202%203%204%5D%20%5B5%206%207%208%5D%20%5B9%2010%2011%2012%5D%20%5B13%2014%2015%2016%5D%5D) **Explanation:** I'm building the fractal as a series of movement directions: 0=right, 1=down, 2=left, 3=up. ``` L push an empty array (level 0 fractal) q~:A read the input, evaluate and store in A ,2mL get the length (number of rows) and calculate the logarithm in base 2 (to get the desired level) {…}* repeat <level> times :B store the previous-level fractal in B 1f^ XOR it with 1 (top-left part) 0 (move right) B copy the fractal (top right part) 1 (move down) B copy the fractal (bottom right part) 2 (move left) B3f^ copy the fractal and XOR it with 3 (bottom left part) ]:+ put everything in an array and concatenate the parts 1+ add a dummy move (needed for the last step) {…}% apply to each direction in the array AT=U= push A[T][U] (T and U are initially 0) \2md bring the direction to the top and get the quotient and remainder mod 2 'U^ XOR the 'U' character with the remainder, to get the variable we want to modify _~) make a copy of it, then evaluate it and increment @2*- bring the quotient to the top, multiply by 2 and subtract ':@+ concatenate ':' with the variable name ~; evaluate (this updates the variable) and pop the result p pretty-print the resulting array ``` ]
[Question] [ Consider a permutation of the integer values from `1` to `N`. E.g. this example for `N = 4`: ``` [1, 3, 4, 2] ``` We'll consider this list to be cyclic, such that `1` and `2` are treated as adjacent. One quantity we can compute for such a list is the total squared difference of adjacent values: ``` (1-3)² + (3-4)² + (4-2)² + (2-1)² = 10 ``` Your task is to find a permutation which maximises this quantity, given a positive integer `N`. In the case of `N = 4` the above example is not optimal (in fact, it's minimal). We can achieve a total squared difference of `18` with the following permutation (as well as several others): ``` [1, 4, 2, 3] ``` Your algorithm must run in polynomial time (of `N`). In particular, you cannot simply compute the total squared difference of all permutations. 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. Output may be in any convenient, unambiguous, flat list or string format. You may choose to return a list with values from `0` to `N-1` instead of `1` to `N`. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test Data There is a nice analytical solution for this problem. E.g. all valid solutions for `N = 10` are equivalent to the following list (up to cyclic shifts and reversal): ``` [7, 5, 6, 4, 8, 2, 10, 1, 9, 3] ``` I don't want to reveal too much beyond that (although it's probably enough to figure out the pattern), so instead of giving any more examples, you can check that your results have the following total squared differences for a given `N`: ``` N Total squared difference 1 0 2 2 3 6 4 18 5 36 6 66 7 106 8 162 9 232 10 322 33 11936 100 333202 333 12308236 1000 333332002 ``` This is OEIS entry [A064842](https://oeis.org/A064842) (which also contains a reference to a paper with a solution to this challenge if you're stuck). [Answer] # Jelly, ~~24~~ ~~21~~ ~~15~~ ~~14~~ ~~10~~ 9 bytes ``` RU˵«/€ị" ``` To compute the total squared difference, append `µ_ṙ1$²S` to the code. [Try it online!](http://jelly.tryitonline.net/#code=UlXElsK1wqsv4oKs4buLIg&input=&args=MTA) ### Background One way to generate a permutation with maximized squared difference is to take the integers **1** to **n** in ascending order, and swap the second from the left with the second from the right, the fourth from the left with the fourth from the right, and so forth until we meet in the middle. For example, for **n = 8, 9** we have ``` 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 ^ ^ ^ ^ ^ ^ ^ ^ ``` (carets mark integers to be swapped), which results in ``` 1 7 3 5 4 6 2 8 1 8 3 6 5 4 7 2 9 ``` after swapping. One way to achieve these swaps, independently of the parity of **n**, is as follows. Start by writing the integers in ascending order and in descending order, one below the other. ``` 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 ``` For each pair of integers, compute the minimum of the pair. This gives the distance to the nearest edge, i.e., the index from the left or the right (whichever is lower). ``` 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 1 2 3 4 4 3 2 1 1 2 3 4 5 4 3 2 1 ``` If the minimum is odd, the integer should stay in its place, so we select the one from the first row; if it is even, the integers should be swapped, so we select the one from the second row. ``` 1 3 6 8 1 3 5 7 9 7 5 4 2 8 6 4 2 ``` This is the desired output. ### How it works ``` RU˵«/€ị" Main link. Input: n R Range. Yields [1, ..., n]. U Upend. Yields [n, ..., 1]. Ė Enumerate. Yields p := [[1, n], [2, n-1], ... [n-1, 2], [n, 1]]. µ Begin a new, monadic chain. Argument: p / Reduce... € each pair of p... « by minimum. " For each minimum and the corresponding pair of p: ị Select the element at that index. Indices are modular and 1-based in Jelly, so this selects the first element if the minimum is odd, and the second one if it is even. ``` [Answer] # JavaScript (ES6), 52 bytes ``` n=>[...Array(n)].map((_,i)=>(i<n/2|n%2)^i%2?i+1:n-i) ``` *9 bytes saved thanks to @Neil!* ## Explanation This approach determines the number that should be at index `i` with a length of `n` rather than concatenating the results to an array. This is based on the following observation (using `n = 7` as an example): * Start with the lowest number on the left and the highest on the right: `[ 1, 7 ]` * Switch the order so the lowest is on the *right* and the highest is on the left, increment the lowest, decrement the highest, and place them in the middle of the array: `[ 1, 6, 2, 7 ]` * Repeat until the highest and lowest converge: `[ 1, 6, 3, 4, 5, 2, 7 ]` The higher and lower numbers can easily be expressed as `n-i` and `i+1` respectively. ``` var solution = n=> [...Array(n)] // create an array of length n .map((_,i)=> // set each value of the array at index i (i<n/2 // if we're on the left side, |n%2) // or we're on the right and n is odd, even i => lower, odd i => higher ^i%2? // else even i => higher, odd i => lower i+1:n-i ) ``` ``` N = <input type="number" id="input" oninput="result.textContent=solution(+this.value)" /> <pre id="result"></pre> ``` [Answer] ## Python2, ~~105~~ 98 bytes *7 bytes saved thanks to the comment by @Dennis* ``` n=input() r=([],[n/2+1])[n%2] for i in range(n/2,0,-1):k=[n+1-i];r=([i]+r+k,k+r+[i])[i%2] print r ``` ### Edited version 58 bytes ``` lambda n:[(n-i-1,i)[(i+(n,1)[i<n/2])%2]for i in range(n)] ``` I already believed it should be possible to do it as a one-liner, but the logic was too complex for me. Seeing the JavaScript-answer by @user81655 and the lambda-notation in @Dennis Python-answer, I gave it new try. The condition is equal to ``` if i < n/2: i%2 != n%2 else: (i+1)%2 ``` Unfortunately all the transformation effort saves only ~~one~~ no byte compared to the direct translation `(i<n/2or n%2)!=i%2` of the JavaScript-logic. [Answer] # Python, ~~51~~ 49 bytes ``` lambda n:[(i^min(i,~i%n)%-2)%n for i in range(n)] ``` *Thanks to @xnor for golfing off 2 bytes!* Try it on [Ideone](http://ideone.com/Gbqc29). ### How it works If **i** is a number in **[0, ..., n - 1]**, then **~i % n = -(i + 1) % n = -(i + 1) + n = (n - 1) - i**, meaning that it maps **0** to **n - 1**, **1** to **n - 2** and, in general, the **j**th item from the left to the **j**th from the right. As explained in [my Jelly answer](https://codegolf.stackexchange.com/a/71792), we can construct the output by peeking at the lower value among **i** and **~i % n**, and pick **i** if it is even and **~i % n** if it is odd. We achieve this as follows. * If the minimum is even, `min(i,~i%n)%-2` will yield **0**, so XORing the result with **i** will yield **i**, and computing its residue modulo **n** will return **i**. * If the minimum is odd, `min(i,~i%n)%-2` will yield **-1**, so XORing the result with **i** will yield **~i**, so the entire expression evaluates to **~i % n** as desired. [Answer] # PHP, ~~77~~ ~~76~~ ~~51~~ ~~50~~ 49 bytes Uses ISO 8859-1 encoding. Assembling the first half of the array like this: * Odd numbers have their index value (1, 3, 5..) * Even numbers have the value of `N+1-index` (9, 7, 5) * This results in `1, 9, 3, 7, 5` As for the second half of the array, the outermost values add up to `N+1`, which means you can get the corresponding right value from `N-[left value]` where the left value is already known. ``` for(;$k=$argv[1]-$j++;)echo" ",min($j,$k)%2?$j:$k; ``` Run like this (this also shows the total squared difference) (`-d` added for aesthetics only): ``` php -d error_reporting=32757 -r 'for(;$k=$argv[1]-$j++;)echo~ß,$x[]=min($j,$k)%2?$j:$k; for(;$c=$x[+$i++];)$b+=($c-($x[$i]?:$x[0]))**2;echo"\n$b\n";' 10 ``` * Saved a byte by negating left/right condition so the second ternary can be nested without parentheses * Saved 25 bytes by shamelessly implementing Dennis' algorithm * Saved a byte by getting rid of the needed space after `echo` * Saved a byte by using `~ß` to yield a space. [Answer] # Python 2, 100 I know there's already a python answer, but I think I may have done this differently. ``` n=input();a=n%2;b=n/2;x=[b+1,b+a][a:] for i in range(b+a-1):f=1-i%2*2;x=[x[-1]-f]+x+[x[0]+f] print x ``` And as an extra to test the total score: ``` def t(x,n):return sum((x[i]-x[(i+1)%n])**2for i in range(n)) ``` [Answer] # CJam, ~~17~~ ~~15~~ 14 bytes ``` {,W%ee_::e<.=} ``` This is a function that pops an integer **n** from the stack and pushes a permutation of **[0 … n-1]** in return. The code uses the same approach as [my Jelly answer](https://codegolf.stackexchange.com/a/71792). [Try it online!](http://cjam.tryitonline.net/#code=cX4gICAgICAgICAgICAgICBlIyBSZWFkIGFuZCBldmFsIGlucHV0Lgp7LFclZWVfOjplPC49fQp-cCAgICAgICAgICAgICAgIGUjIEV4ZWN1dGUgYW5kIHByaW50Lg&input=MTA) ### How it works ``` ,W%ee_::e<.= Function body. Stack: N , Turn N into [0 ... N-1]. W% Reverse to push [N-1 ... 0]. ee Enumerate. This pushes [[0 N-1] [1 N-2] ... [N-2 1] [N-1 0]]. _ Push a copy of the array of pairs. ::e< Reduce each pair by minimum. .= Vectorized selection. For the Ith minimum M, select the Mth element of the Ith pair. Indices are modular and 0-based in CJam, so this selects the first element if the minimum is even, and the second one if it is odd. ``` [Answer] ## LISP, 86 bytes ``` (defun g(n m)(if(= n m)(list n)(if(< m n)(cons m(reverse(cons n(g(- n 1)(+ m 1)))))))) ``` The inputs of the function allow to choose the start (m) and the end (n) values of the sequence. For testing the function according to the provided samples, n is fixed to N and m to 1. Here the code to test the function: ``` (defun g(n m)(if(= n m)(list n)(if(< m n)(cons m(reverse(cons n(g(- n 1)(+ m 1)))))))) (defun sq (c) (apply #'+ (mapcar #'(lambda(x y) (* (- x y) (- x y))) c (append (cdr c) (list (car c)))))) (format t "N~20TSequence~50TSquared Difference~%") (mapcar #'(lambda (x)(format t "~S~20T~S~50T~S~%" x (g x 1) (sq (g x 1)))) '(1 2 3 4 5 6 7 8 9 10 33 100 333 1000)) ``` Try it on [Ideone](http://ideone.com/CuIn9b)! [Answer] # Julia, 39 bytes ``` n->map(i->min(i-1,n-i)%2>0?n-~-i:i,1:n) ``` This prints a permutation of **1:n**. A permutation of **0:n-1** does neither cost nor save bytes: ``` n->map(i->min(i,n+~i)%2>0?i:n+~i,0:n-1) ``` This last version is a direct port of [my Python answer](https://codegolf.stackexchange.com/a/72012). [Answer] ## ES6, 77 bytes ``` n=>[...Array(n)].map(_=>r[++i&2?"push":"unshift"](i&1?n--:++j),i=j=0,r=[])&&r ``` The `i&1` samples the digits from the extremes to the middle. The `i&2` adds them to the beginning or end of the result in pairs. [Answer] # R, ~~117~~ 86 bytes ``` z=1:(n<-scan());a=pmin(z,n:1);for(i in seq(2,,2,n%/%2))z[b]=z[rev(b<-which(a==i,T))];z ``` *edit* replaced buggy long version with an implementation of @Dennis' Jelly algorithm ]
[Question] [ ## Challenge Given an integer, `n`, as input where `36 >= n >= 2`, output how many Lynch-Bell numbers there are in base `n`. The output must be in base 10. ## Lynch-Bell Numbers A number is a Lynch-Bell numbers if: * All of its digits are unique (no repetition of digits) * The number is divisible by each of its digits * It doesn't contain zero as one of its digits Since, all of the digits have to be unique, and you have a finite set of single digit numbers in each base, there is a finite number of Lynch-Bell numbers. For example, in base 2 there is only one Lynch-Bell number, `1`, since all other numbers either repeat digits or contain a 0. ## Examples ``` Input > Output 2 > 1 3 > 2 4 > 6 5 > 10 6 > 10 7 > 75 8 > 144 9 > 487 10 > 548 ``` *Mathematica Online ran out of memory above base 10. You can use the following code to generate your own:* ``` Do[Print[i," > ",Count[Join@@Permutations/@Rest@Subsets@Range[#-1],x_/;And@@(x\[Divides]FromDigits[x,#])]&[i]],{i,10,36,1}] ``` ## Winning Shortest code in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` Q⁼g *`Ṗ©bç"®S ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//UeKBvGcKKmDhuZbCqWLDpyLCrlP///8z "Jelly – Try It Online") Another *O(nn)* solution. ## Explanation ``` Q⁼g Helper link. Input: digits (LHS), integer (RHS) Q Unique (digits) ⁼ Match g GCD between each digit and the integer *`Ṗ©bç"®S Main link. Input: integer n *` Compute n^n Ṗ Pop, forms the range [1, n^n-1] © Store previous result in register b Convert each integer to base n ç" Call the helper link, vectorized, with ® The register's value S Sum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` *ḃ€’Q€Qḍḅ¥€⁸Ạ€S ``` [Try it online!](https://tio.run/##y0rNyan8/1/r4Y7mR01rHjXMDARSgQ939D7c0XpoKUioccfDXQuAjOD///@bAAA "Jelly – Try It Online") Complexity `O(nn)`. [Answer] # Java, ~~222~~ ~~212~~ 190 bytes -10 bytes thanks to Herman -22 bytes thanks to Kevin ``` import java.util.*;a->{int c=0,i=1;A:for(;i<Math.pow(a,a);i++){Set g=new HashSet();for(char b:a.toString(i).toCharArray())if(!g.add(b)|b<49||i%a.parseInt(b+"",a)>0)continue A;c++;}return c;} ``` Ungolfed: ``` a -> { int count = 0; OUTER: for (int i = 1; i < Math.pow(a, a); i++) { Set<Character> found = new HashSet<>(); for (char b : Integer.toString(i, a).toCharArray()) { if (!found.add(b) || b == 48 || i % Integer.parseInt(b + "", a) != 0) { continue OUTER; } } count++; } return count; } ``` [Try it online!](https://tio.run/##XVBRawIxDH72fkUmDNqdFge@zHqCDMYG88nH4UOu1zvrzrb0coqov/1W2YFgXpJ8yZd8yQ4POHZe213x25m9d4FgFzHRkqnFi0x8m9dGgaqxaWCFxsI5GfRgQ0jRHZwpYB9LbE3B2OpnAxiqht86B/dhZWsVGWfFRx/MvyzpSocR9MECSsg6HC/OxhKobDIy2atczkoXmDTzFdJWeHdkOEIuTZry81oTVJnVR/jEZhszxuWtW20xQD77drYS5P5lMRNpMXuPtWUIeGKcm5I9VQKLguX8ks@nb5eLeUbhMTQ6imJ5OhxG1mLClbNkbKthKVWaymvQ1AYLSl47eDCZJI/Q@tSQ3gvXkvBRC9WWlQK9r0@sv/2@8/a7n8mGcy6TwTW5dt30Dw "Java (OpenJDK 8) – Try It Online") Gets very slow for large numbers. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~86~~ ~~84~~ 77 bytes *-2 bytes thanks to Ramillies* ``` ->\n{n-1+grep {.Set==$_&&.reduce(* *n+*)%%.all},map {|[X] (1..^n)xx$_},2..^n} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf1y4mrzpP11A7vSi1QKFaLzi1xNZWJV5NTa8oNaU0OVVDS0ErT1tLU1VVLzEnp1YnNxGoqiY6IlZBw1BPLy5Ps6JCJb5WxwjErv2fll@kAGRaKFQrFCdWKqRpqMRrKtT@BwA "Perl 6 – Try It Online") Works for n=8 on TIO. [Answer] # [Actually](https://github.com/Mego/Seriously), 24 bytes ``` ;╗DR⌠╜DR╨i⌡M⌠;╜@¿♀%ΣY⌡MΣ ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/9/60dTpLkGPehY8mjoHSE9dkfmoZ6EvkA@UmONwaP@jmQ2q5xZHggTPLf7/3xwA "Actually – Try It Online") ## Explanation This program consists of two main parts: the permutation generation, and the Lynch-Bell test. So, this explanation will look at each part separately, for greater clarity. ### Generating Permutations Input: `n` (an integer in `[2, 36]`) Output: all partial and total permutations of `[1, n-1]` (sequences containing values from `[1, n-1]` without repetition whose length is in `[1, n-1]`) ``` ;╗DR⌠╜DR╨i⌡M ;╗ store a copy of n in register 0 DR range(1, n) ⌠╜DR╨i⌡M do the following for each element k in range: ╜DR range(1, n) ╨ k-permutations of [1, n-1] i flatten ``` ### Lynch-Bell Test Input: a list of base-`n` integers, represented as lists of base-`n` digits Output: the number of Lynch-Bell numbers in base `n` ``` ⌠;╜@¿♀%ΣY⌡MΣ ⌠;╜@¿♀%ΣY⌡M for each base-n digit list a: ;╜ duplicate a, push n @¿ convert a from base-n to decimal ♀% modulo a with each of its base-n digits Σ sum Y boolean negation (1 if all modulo results are 0, else 0) Σ sum (count the 1s in the resultant list) ``` [Answer] # Mathematica, ~~82~~ ~~79~~ 76 bytes ``` Count[Join@@Permutations/@Subsets@Range[#-1],x_/;x==x~FromDigits~#~GCD~x]-1& ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes ``` mLIBε0KÙ}ÙvyIöySIö%O_O ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/18fT6dxWA@/DM2sPzyyr9Dy8rTIYSKj6x/v//28OAA "05AB1E – Try It Online") `O_O` was also my face when this finally worked. `<ÝIBJ0Kæ¦Ù€œ˜` is faster than the way I use to generate the numbers in the actual answer but randomly stops working for anything bigger than 7 (for no apparent reason?) ### Explanation ``` mLIBε0KÙ}ÙvyIöySIö%O_O # (input = i) m # Push i^i L # ...and get a range from one to this value IB # Map every element to their base i representation ε } # Map every element to ... 0K # Itself without 0s Ù # ...and only unique digits Ù # Uniquify the resulting list v # For each element... yIö # Push it converted to base 10 ySIö # Push every digit of it converted to base 10 in a list % # Calculate the modulo for each digit O # Sum all results together _ # Negate: Returns 0 for every positive number and 1 for 0 O # Sum with the rest of the stack (Basically counting all Lynch-Bell-Numbers) # Implicit print ``` [Answer] ## Perl 5, 80 76 bytes (75 + `-p`) ``` $\+=!grep$_?$;%$_|$|{0,$_}++:1,@@until($@[$}++]+=1)%=$_ and++$;,$}=$}==$_}{ ``` Abusing [`$;`](http://perldoc.perl.org/perlvar.html#$SUBSEP) for fun and profit. Times out on inputs > 8. EDIT: -4 bytes by merging the two loops. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~80~~ 65 bytes ``` ->n{(1..n**n).count{|i|(d=i.digits n)-[0]==d|d&&d.sum{|j|i%j}<1}} ``` [Try it online!](https://tio.run/##BcFLDkAwEADQq9iQVmKClYW6iFhgfEZiCO1COj17vfe46YuriUXHXlUAnOesYb4cWy8kCg0B0kb2TVgXfTkYg4JZhvC608shlB6hrUKIqgZoNCzjvHuxcidrb4cQfw "Ruby – Try It Online") Thanks to G B for -15 bytes. [Answer] # [Japt](https://github.com/ETHproductions/japt) `-x`, ~~25~~ 19 bytes -6 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) ``` pU õìU ËeDâ f myDìU ``` [Try it online!](https://tio.run/##y0osKPn/vyBU4fDWw2uAZHeqy@FFCmkKuZUuQP7//2ZcuhUA "Japt – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 204 174 bytes ``` lambda x,r=range,i=chain:sum(0**any(int(''.join(map(str,y)),x)%z for z in y)for y in i(*map(permutations,i(*[combinations(r(1,x),e)for e in r(x)]))))-1 from itertools import* ``` [Try it online!](https://tio.run/##bY7BbsIwEETPzVf4UmUduQjTG1L4kcLBUAcWYa@1WaQYxLendnplTqPRm9GkLBeK3/PAFBSKZyG6jQpDIpauGfr9fHPh@OvUZLhnF8/eYH@6OIzb8R5g3XUuZsAo0LarK2GE4BKMwiZrbSb9@VADsXoojCrranO1CF3lkudwFydIcTQl@zlROGL8D4DBlgXjl5qvNYZJH3TRl23eX54riwtbz8LGWKu3zUfi5eNz/ep3T/tqV4ULTgCNGgDL4vwH "Python 3 – Try It Online") For each permutation of each element of powerset of range(1,n) (no zeros, unique), convert to numerical string to base n. Sum all that are divisible by each digit, subtract 1 due to powerset generating the empty set. -30 bytes thanks to @ovs! [Answer] # [Haskell](https://www.haskell.org/), 117 bytes ``` f n=sum[1|x<-id=<<[mapM(\_->[1..n-1])[0..m]|m<-[0..n]],all(\y->[mod(sum(zipWith((*).(n^))[0..]x))y|c<-x,c==y]==[0])x] ``` [Try it online!](https://tio.run/##HcuxDsIgFEDRX2FweJhCyuTC8w@cHejTkNamRKDE1oQa/h2r2x3umezyfHhf68giLu9gVMlauAG1NsGmC3R3cTZKyigUcdNKGagELX4ViRrrPXTbvoR5gN3Dx6WrWyeAI5cQb/xvKHO@lV6L3PSIGyGalnimGqyLDFl6ubiyAxvZqX4B "Haskell – Try It Online") Works on TIO up to `n=7` before timing out. [Answer] # [Perl 5](https://www.perl.org/), 108 + 1 (`-p`) = 109 bytes ``` while(@a<$_){$r=%k=@a=();for($t=++$i;$t;$t=int$t/$_){push@a,$t%$_}$r||=!$_||$i%$_||$k{$_}++for@a;$r||$\++}}{ ``` [Try it online!](https://tio.run/##HYxRCsIwEETPImwgJVbrR0FoF3IBbyCEfFQaWpqQrviR5OquqTAw8OYxYYprz/yZ3TpJbUcwTYKIYkFtUTbDy0cJhEqBG4Bq0G0EdD288N5nbc9AAkyBmDOewOQMTvxrSRUrVR@0HY4ZnkqVkpjvXx/I@W3n9tFfulvHbfgB "Perl 5 – Try It Online") It's a pig. Not sure if it will do more than base 8 on TIO without timing out. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 144 bytes ``` n=>{int j,i,p;for(j=i=0;i++<~0UL;){p=i;var a=new List<int>();for(;p>0;p/=n)a.Add(p%n);j+=a.All(c=>c>0&&i%c<1&a.Count(x=>x==c)<2)?1:0;}return j;} ``` Goes through all the numbers from 0 to `ulong.MaxValue`, and selects those that are Lynch-Bell numbers in the specified base. Takes forever to run, even for 2, though if you set the `~0UL` part in the for loop to something smaller, you can get output for input up to 7 within a minute on TIO. [Try it online!](https://tio.run/##HY5NS8QwGITv/RVhYbsJrTXrSTZ9IyIKCwXFD7zsJaQppi1vQ5rqQql/vWY9DMwDw8zo8UqPdn2aUJcWQx4lG1gR5BwtaXObO9EMnrZggQubZeUv/6gEmx1Y8a08UYDmh1R2DJcCSdl/XDjJhbsGZKq4r2vqtshEm0GkvqcapJY8Te1Wl/tUFQ/DhIGeQZ4BNCtv2N3@wMXiTZg8klYsq0hiq1H6i142O2KRHLF4Nap@Hx6xpqx4c70NdHfCHWPJnHx6G0xl0dDNEd0UyIHMfDnh8xQiRdhH2ORd3tB4u3hRfjS0Y4yJZFlv/wA "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ A Chinese checkerboard looks like this (based on [this question](https://codegolf.stackexchange.com/q/51003/25180), but this time it has a fixed size): ``` G . G G G G G G . G B B B B . . Y G . Y . Y Y B B B . . G . . . Y Y Y B . B . . . . . Y . Y B . . . . . . . . Y . . . . . . . . . . P . . . . . O O . P P . . . . . . . O O P P P . . . R . . O O . P P P P . . R . . O O O O R . R R R R R R . R ``` Each non-space character in this example can be replaced by any non-space printable ASCII character in the input, while spaces are never changed. Note that it isn't guaranteed to be a valid arrangement in Chinese checker (such as it may not have exactly 7 different kind of characters). Your task is to rotate it by a multiple of 60 degrees. This is the above example rotated by 60 degrees clockwise: ``` B B B B B B B . B B P P P . . . B . . G G . G P P P P . . . . . G G G P P . . . . . G Y . G P . . . . . . . G G . . . . . . . . . R . . . . . . . . Y R . R R . . . . Y Y . R R R . . . O . . . Y Y R . R R . . . O . Y Y Y Y O O O . O O O O . O ``` The input is a non-negative integer and a Chinese checkerboard. Your program (or function) should rotate it by the integer \* 60 degrees. You decide whether to rotate clockwise or counterclockwise, as long as it is consistent. Both the input and output shouldn't have extra leading or trailing spaces. This is code-golf. Shortest code wins. [Answer] # CJam, ~~61~~ ~~59~~ ~~43~~ ~~40~~ ~~38~~ 36 bytes ``` {{_N/eeSf.*:sW%zsS-\{_' >{;(}&+}/}*} ``` This is an anonymous function that expects a string and an integer on the stack. *Thanks to @jimmy23013 for golfing off 19 bytes.* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=li%20e%23%20Read%20the%20first%20line%20of%20input%20and%20cast%20to%20integer.%0Aq%5C%20e%23%20Read%20the%20remaining%20input%20and%20swap%20it%20with%20the%20integer.%0A%0A%7B%7B_N%2FeeSf.*%3AsW%25zsS-%5C%7B_'%20%3E%7B%3B(%7D%26%2B%7D%2F%7D*%7D%0A%0A~%20%20e%23%20Execute%20the%20code%20block.&input=1%0A%20%20%20%20%20%20%20%20%20%20%20%20G%0A%20%20%20%20%20%20%20%20%20%20%20.%20G%0A%20%20%20%20%20%20%20%20%20%20G%20G%20G%0A%20%20%20%20%20%20%20%20%20G%20G%20.%20G%0AB%20B%20B%20B%20.%20.%20Y%20G%20.%20Y%20.%20Y%20Y%0A%20B%20B%20B%20.%20.%20G%20.%20.%20.%20Y%20Y%20Y%0A%20%20B%20.%20B%20.%20.%20.%20.%20.%20Y%20.%20Y%0A%20%20%20B%20.%20.%20.%20.%20.%20.%20.%20.%20Y%0A%20%20%20%20.%20.%20.%20.%20.%20.%20.%20.%20.%0A%20%20%20.%20P%20.%20.%20.%20.%20.%20O%20O%20.%0A%20%20P%20P%20.%20.%20.%20.%20.%20.%20.%20O%20O%0A%20P%20P%20P%20.%20.%20.%20R%20.%20.%20O%20O%20.%0AP%20P%20P%20P%20.%20.%20R%20.%20.%20O%20O%20O%20O%0A%20%20%20%20%20%20%20%20%20R%20.%20R%20R%0A%20%20%20%20%20%20%20%20%20%20R%20R%20R%0A%20%20%20%20%20%20%20%20%20%20%20R%20.%0A%20%20%20%20%20%20%20%20%20%20%20%20R). ### Idea We can assign an order to the printable characters of the checkerboards by reading them eastwards, then southwards. This way, the original and rotated checkerboard ``` G B . G B B G G G B B B G G . G B . B B B B B B . . Y G . Y . Y Y P P P . . . B . . G G . G B B B . . G . . . Y Y Y P P P P . . . . . G G G B . B . . . . . Y . Y P P . . . . . G Y . G B . . . . . . . . Y P . . . . . . . G G . . . . . . . . . . . . . . . . . . . P . . . . . O O . R . . . . . . . . Y P P . . . . . . . O O R . R R . . . . Y Y . P P P . . . R . . O O . R R R . . . O . . . Y Y P P P P . . R . . O O O O R . R R . . . O . Y Y Y Y R . R R O O O . R R R O O O R . O . R O ``` become ``` G.GGGGGG.GBBBB..YG.Y.YYBBB..G...YYYB.B.....Y.YB........Y..........P.....OO.PP.......OOPPP...R..OO.PPPP..R..OOOOR.RRRRRR.R ``` and ``` BBBBBBB.BBPPP...B..GG.GPPPP.....GGGPP.....GY.GP.......GG.........R........YR.RR....YY.RRR...O...YYR.RR...O.YYYYOOO.OOOO.O ``` respectively. We can find the second sequence in the first checkerboard by reading its characters northeastwards, then southeastwards. To achieve this in code, we start by prepending **n - 1** spaces to the **n**th row of the checkerboard (shown on the left). Then, we reverse the order of the rows (shown on the right). ``` G R . G R . G G G R R R G G . G R . R R B B B B . . Y G . Y . Y Y P P P P . . R . . O O O O B B B . . G . . . Y Y Y P P P . . . R . . O O . B . B . . . . . Y . Y P P . . . . . . . O O B . . . . . . . . Y . P . . . . . O O . . . . . . . . . . . . . . . . . . . . P . . . . . O O . B . . . . . . . . Y P P . . . . . . . O O B . B . . . . . Y . Y P P P . . . R . . O O . B B B . . G . . . Y Y Y P P P P . . R . . O O O O B B B B . . Y G . Y . Y Y R . R R G G . G R R R G G G R . . G R G ``` Finally, we transpose rows with columns: ``` ​ B BB BBB B.BB PPP...B..GG.G PPPP.....GGG PP.....GY.G P.......GG ......... R........Y R.RR....YY. RRR...O...YY R.RR...O.YYYY OOO. OOO O. O ``` The whitespace is all over the place, but the printable characters are in the correct order if we read them eastwards, then southwards. All that's left to do is replacing the **n**th printable character of the original checkerboard by the **n**th printable character of the last modification. ### Code ``` e# Stack: String B, Integer A { }* e# Repeat A times: _N/ e# Push a copy of B and split it at linefeeds. ee e# Enumerate the lines of B. Sf.*:s e# Execute S.*s for each line: e# [4 "abc"] -> " abc" W% e# Reverse the order of line lines. z e# Zip; transpose rows with columns. s e# Flatten the arrays of strings. S- e# Remove spaces. e# This pushes a string L. \{ }/ e# For each character C in the unmodified B: _' > e# Check if C is bigger than ' '. { }& e# If it is: ;( e# Discard C and shift out a char from L. + e# Append a char (C or from L) to L. e# L is B rotated by 60 degrees. Set L := B. ``` [Answer] # Python 2, 171 bytes ``` def f(S,n): o="";E=enumerate;B=S.splitlines(1) for r,l in E(B): for c,q in E(l):z=r-8;y=6-(z+c)/2;x=-y-z;exec"x,y,z=-y,-z,-x;"*n;o+=q*(q<"!")or B[z+8][12-y+x] print o ``` This is perhaps the only time I've ever found `str.splitlines` useful — for all other times, `.split("\n")` is shorter. Use like `f(S,10)`. ## Explanation For each char in the input, we either: * Keep it if it's a space or newline, or * Replace it with the correct char otherwise To figure out which char to replace with, we convert the grid to [cube coordinates](http://www.redblobgames.com/grids/hexagons/#coordinates) `(x, y, z)`, rotate `n` times by transforming `(x, y, z) -> (-y, -z, -x)`, then convert back. ]
[Question] [ The Mongolian language has "vowel harmony". In short the vowel harmony means that certain vowels are not allowed to be placed next to each other in a word. This means that suffixes of words have to care about the vowels present in the words they attach to and need to resolve to a vowel that matches the harmony of the word. ## Vowels Mongolian harmony compares about 3 binary properties that vowels can have. * A vowel can be **round** * A vowel can be **high** * A vowel can be **ATR** (advanced tongue root) If a vowel has a property, we indicate that with a `+` and square brackets if it does not we indicate that with a `-` and square brackets. e.g. **[-ATR]** indicates that the vowel does not have the **ATR** property. There are thus 8 combinations of these properties that can be made. Mongolian has exactly 1 vowel for each combination except **[+high][-ATR][-round]** which is missing a vowel. The 7 vowels and their values can be given in the table below: | | | [+ATR] | [-ATR] | | --- | --- | --- | --- | | **[+round]** | **[+high]** | `u` (u) | `U` (ʊ) | | **[+round]** | **[-high]** | `o` (o) | `O` (ɔ) | | **[-round]** | **[+high]** | `i` (i) | *(Absent)* | | **[-round]** | **[-high]** | `e` (e) | `a` (a) | This table gives both the XSAMPA (code block) and IPA (parentheses) values for each vowel, but we will care about the XSAMPA values for this challenge. ## Harmony ### [ATR] harmony Every word in Mongolian is either **[+ATR]** or **[-ATR]** with only vowels of the corresponding **[ATR]** value appearing in that word. The once exception is `i` which is "transparent" for **[ATR]** harmony. Meaning it acts as if it is in *both* categories even though it is **[+ATR]**. Meaning that `i` can appear in words with any vowels. This can be illustrated with the following Venn diagram: ![Venn diagram with two circles. In the left part are the letters u, e, and o. In the right part are the letters capital U, a, capital O. In the intersection is the letter i.](https://i.stack.imgur.com/hXX3x.png) Modified with permission from [Mongolian vowel harmony Venn diagram](https://commons.wikimedia.org/wiki/File:Mongolian_vowel_harmony_Venn_diagram.svg) by wikimedia commons user AquitaneHungerForce. Liscensed under the Creative Commons Attribution-Share Alike 4.0 International license. See link for full attribution. ### [round] harmony Mongolian also has **[round]** harmony which only affects **[-high]** vowels. At its simplest under **[round]** harmony if a **[-high]** vowel is the next vowel after a **[-high]** vowel, it must have the same **[round]** value. `i` is also transparent for roundness harmony so we skip over `i` when looking for the last vowel. ## Task Given a sequence of Mongolian vowels determine if they follow the rules of vowel harmony. Input can be either a list of XSAMPA vowels, or a string of XSAMPA vowels. Input will always be non-empty. You should output one of two distinct values, the first if it is a valid sequence the second if it is not. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so your goal is to minimize the size of your source code as measured in bytes. ## Test cases ### Valid ``` iiiiiii oi Oi ui Ui ei ai UO oiou uie ouie OUia ``` ### Invalid ``` uU oO eia oiie OUie eieio ``` # Reading This post is based off of the description from: * Godfrey, Ross (2012). "Opaque Intervention in Khalkha Mongolian Vowel Harmony: A Contrastive Account" [pdf](https://www.mcgill.ca/mcgwpl/files/mcgwpl/godfrey2012_0.pdf). [Answer] # [JavaScript (Node.js)](https://nodejs.org), 45 bytes *Saved 1 byte thanks to @dingledooper* Expects a string. Returns *false* for valid or *true* for invalid. ``` s=>Buffer(s).some(n=>n%7&&s*((s^(s=n))%18%8)) ``` [Try it online!](https://tio.run/##ddCxDoIwEAbg3ccgAVoTSZxkqYObUydcUJMGrqYG7wxnef2qcdF4dPx6vfuvVzc57sZwf6yQekjeJDbbXfQeRsW6YrqBQrPFfFMUvFSKz4oNap2v67zWOnWETANUA11U2R7cEPpTqRff7FUWPifTfzckoZUwSthICBI68bkVI1EU54NULLNtgnvzj5dHbPc4zfxRbKT2VtzPibHnkoDYAwK9PD0B "JavaScript (Node.js) – Try It Online") ### How? In this version, we work directly on the ASCII codes of the characters: ``` char | O | U | a | e | i | o | u ------+-----+-----+-----+-----+-----+-----+----- code | 79 | 85 | 97 | 101 | 105 | 111 | 117 ``` Conveniently, `i` is the only character whose ASCII code is congruent to \$0\$ modulo \$7\$. Once the `i`'s have been filtered out using the above property, a pair of consecutive ASCII codes \$(x,y)\$ is valid if and only if: $$\big((x\operatorname{XOR}y)\bmod 18\big)\bmod 8 = 0$$ Below is a summary of all possible outcomes (using the same order as in my first version for easier comparison): ``` | e u O o U a ---+------------- e | 0 0 6 2 4 4 u | 0 0 4 0 6 2 O | 6 4 0 6 0 2 o | 2 0 6 0 4 6 U | 4 6 0 4 0 0 a | 4 2 2 6 0 0 ``` --- # JavaScript (ES6), 54 bytes Expects an array of characters. Returns *false* for valid or *true* for invalid. ``` a=>a.some(c=>(n="ieuOoUa".search(c))&&a*((a^(a=n))%3)) ``` [Try it online!](https://tio.run/##fdDBDsIgDAbgu49B4gYmcvHM7p444WXOpGGdYiY1Q/b6GPWiiV2PfKH92yvMkPwU7o9tpB7LYAqYBnSiG0pvGhmNCJgtORA6IUz@Ir1SVQUbKeEkwUSl1juliqeYaEQ90lnW7QHG0He1Wn0/D7LVWovwKdGpv0ysWFYyK44VZAX4bpZPTZlPh@y3BbMuwNt@sD7Gdh/nhftmx06z/DGA32wxIvItMdALyxM "JavaScript (Node.js) – Try It Online") ### How? We map `"ieuOoUa"` to \$[0,1,2,3,4,5,6]\$. We ignore the `i`'s and consider each pair of indices \$(x,y)\$ for the remaining consecutive characters. The pair is valid if and only if: $$(x\operatorname{XOR}y)\bmod 3=0$$ Below is a summary of all possible outcomes: ``` | e u O o U a ---+------------- e | 0 0 2 2 1 1 u | 0 0 1 0 1 1 O | 2 1 0 1 0 2 o | 2 0 1 0 1 2 U | 1 1 0 1 0 0 a | 1 1 2 2 0 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḟ”iOµPƝ+⁽D§ẒẸ^+4ẒEƊ ``` A monadic Link that accepts a list of characters and yields `1` if valid and `0` otherwise. **[Try it online!](https://tio.run/##y0rNyan8///hjvmPGuZm@h/aGnBsrvajxr0uh5Y/3DXp4a4dcdomQIbrsa7///@HZmb6Z2YmZmYCGQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjvmPGuZm@h/aGnBsrvajxr0uh5Y/3DXp4a4dcdomQIbrsa7/D3dvOdz@qGnN//@ZEMCVn8nln8lVmskVmsmVmsmVCGT4AwXzS4FiqVz5IMI/NDORqzSUK98fqCIRKAkRSwUA "Jelly – Try It Online"). ### How? Removes the `i`s and then takes the exclusive-or of these two checks using the remaining character's ordinal values: 1. (`PƝ+⁽D§ẒẸ`) whether any neighbouring pair are from the same **[ATR]**, both **[-high]**, but with different **[round]** values. That is `oe`, `eo`, `Oa`, or `aO`. 2. (`+4ẒE`) whether all are from the same **[ATR]** ``` ḟ”iOµPƝ+⁽D§ẒẸ^+4ẒEƊ - Link: list of characters, S (from 'aeoiuOU') ”i - an 'i' character ḟ - S filter-discard 'i's O - ordinal values µ - start a new monadic chain, call that V Ɲ - for neighbours in V: P - product ⁽D§ - 18226 + - add (vectorises) Ẓ - is prime? -> 1 if the neighbours are oe, eo, Oa, or aO else 0 Ẹ - any? -> X1 Ɗ - last three links as a monad - f(V): 4 - four + - V add 4 (vectorises) Ẓ - is prime? E - all equal? -> X2 ^ - X1 XOR X2 ``` That is: 1. Identifying those neighbours with the same **[ATR]** where both are **[-high]** but with different **[round]** values makes use of this table of ordinal products plus \$18226\$ with primes in bold: | x×y+18226 | u | e | o | U | a | O | | --- | --- | --- | --- | --- | --- | --- | | **u** | 31915 | 30043 | 31213 | 28171 | 29575 | 27469 | | **e** | 30043 | 28427 | **29437** | 26811 | 28023 | 26205 | | **o** | 31213 | **29437** | 30547 | 27661 | 28993 | 26995 | | **U** | 28171 | 26811 | 27661 | 25451 | 26471 | 24941 | | **a** | 29575 | 28023 | 28993 | 26471 | 27635 | **25889** | | **O** | 27469 | 26205 | 26995 | 24941 | **25889** | 24467 | 2. **[ATR]** groups identified by whether four more than the ordinal is a prime: | | ordinal+4 | prime? | | --- | --- | --- | | u | 121 | no | | e | 105 | no | | o | 115 | no | | U | 89 | yes | | a | 101 | yes | | O | 83 | yes | [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 32 bytes ``` A`[oue]i*[OUa]|oi*e|Oi*a 2}V` .+ ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zEhOr80NTZTK9o/NDG2Jj9TK7XGP1MrkcuoNiyBS0/7///8zPxSAA "Retina – Try It Online") or [Verify all test cases](https://tio.run/##JYqxCsMwEEN3/UfAOFBo/iBTx5ucJQR8ww1aelDqzfl294o1PMSTPvblW59jSelVx15Pb3Yxn1L06s5sXZgV231UPNYxOAMnhGhEIYzQKBLSWziD/yGFilbgEg@NcTr7AQ) ### Explanation ``` A`[oue]i*[OUa]|oi*e|Oi*a 2}V` ``` Do the following twice: * `A`ntiGrep -- Remove lines containing a match for the regex `[oue]i*[OUa]|oi*e|Oi*a` * Re`V`erse the input string If the input contains any of the invalid combinations, this process will result in an empty string. ``` .+ ``` Count matches of the regex `.+`. Outputs 1 if the line is non-empty, 0 otherwise. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes Returns `0` for valid or `1` for invalid. ``` \ioC¨pλ꘍∑8%7%;a ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJcXGlvQ8KocM676piN4oiROCU3JTthIiwiIiwiZWllaW8iXQ==) This currently fails for the case `iiiiiii` [due to a bug](https://github.com/Vyxal/Vyxal/issues/1095), but it should work after that gets fixed. ## How? Ignoring `i`s, the digit sum of the xor of pairwise codepoints is good if it's one of `0`, `7`, or `8`. ``` O U a e o u O 0 8 10 6 5 13 U 8 0 7 12 13 5 a 10 7 0 4 5 2 e 6 12 4 0 1 7 o 5 13 5 1 0 8 u 13 5 2 7 8 0 ``` ``` \ioC¨pλ꘍∑8%7%;a \i # literal i o # remove is C # to codepoints ¨pλ ; # pairwise map ꘍ # xor ∑ # digit sum %8 # mod 8 %7 # mod 7 a # are any truthy? ``` [Answer] # [Python](https://www.python.org), 239 bytes ``` def f(x): x=x.replace('i','') if not x:return 1 a='ueoi';b='UaOi';m='oOea';v='oO' for c in x: if(x[0] in a)^(c in a):return-1 r=2 for c in x: if r!=2: if(c in m)&r^(c in v):return-1 else:r=2 elif c in m:r=c in v return 1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVAxbsMgFN05xY-HAlIcNZkqR6xZbanyFKUSTUBGcgzCJnXv0a1LlvZOOUWv0A_20CoMj_f5730efH6796Gx3fX6FQadP91-TkqDZiMvCIxiXHnlWnlUjBq6pJQTMBo6O8BYeDUE38GagBQ0KGvo9lXQWpZIzoLaUkm6vURCCWjr4QimQx8BnMHG_eMh1pK_sONE5ok5TvRic-8BvxCbSKM_Nc78wc_2y187gGp7VaQpSNE6yfFkEuMNc_r52R9vjWkVMNM5KARqXBgY57AQkOXrrEjvxlNMLQStaIzhvOkGlj03NrQncLLvC8iWqjuJ9FEpwp1MS9P-k01tHW9e9a41KIWM79cHzqds11tTgZkWqcBGKCOECHUEFUGmskwSG1JfxWLaytpIsoNQI9gSQaXaGuzuYleRfP6MXw) A very boring solution, using the most obvious application of the rules. [Answer] # Python3, 177 bytes: ``` lambda s:(S:=set)()in[S(T:=s.replace('i',''))-S('uoe'),S(T)-S('UOa')]and all(T[i:i+2]in'oo,oO,Oo,OO,ee,ea,ae,aa'.split(',')for i in range(len(T)-1)if S()==S(T[i:i+2])-S('oOea')) ``` [Try it online!](https://tio.run/##ZY6xTgMxEER7vsLd2uBEEBp00n3DFs5VIcVC9shKxrZ8dwVffzhBCths90azM5O@5nMMzy8pr2P/unr6fDuRmjrtun7i2Wgj4eD0vtA2c/L0zhoELIAxG6dhiQzGFsOVBiQwRwonRd7r/UE6edgdJUCMNqLFaBEts2WyxJYItlPyMuuSZ8aYlSgJKlP4YO05XEKfjIzKadP37pZ3rYrIpcusKUuY9VhG/VzR7m5arBFrXGocauQaqTFjUxSXJptrQyvgIPQrwAbud49//4f6HZtt1NT/T78I6zc) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḟ”iṢƝ“E“¬(’ḥⱮḂẸ ``` A monadic Link that accepts a list of characters from `aeiouOU` and yields `0` if valid and `1` otherwise. **[Try it online!](https://tio.run/##y0rNyan8///hjvmPGuZmPty56NjcRw1zXIH40BqNRw0zH@5Y@mjjuoc7mh7u2vH/4e4th9sfNa35/z8TArjyM7n8M7lKM7lCM7lSM7kSgQx/oGB@KVAslSsfRPiHZiZylYZy5fsDVSQCJSFiqQA "Jelly – Try It Online")** ### How? Beats my other one, but I kind of prefer that one :) ``` ḟ”iṢƝ“E“¬(’ḥⱮḂẸ - Link: list of characters, S ”i - an 'i' character ḟ - S filter-discard 'i's Ɲ - for each neighbouring pair: Ṣ - sort Ɱ - for each sorted pair of neighbours: ḥ - hash using [salt, domain]: “E“¬(’ - list of base 250 integers [70, 2041] Ḃ - modulo two Ẹ - any? ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` ≔⁺c⁻Siθ›№⁺⌊θ⌈θc⊙⪪oeOa²№⁺⮌θθι ``` [Try it online!](https://tio.run/##TY09CsMwDIX3niJokiFdumYKHUqH0NCcwBiRChw78U9oT@8oIUMFkp4e70Pmo4Px2pbSxsijw97miGCgrjp2Ip9uzmlIgd2Iqq6AQclaVHPpxUv4CKQTBbz7LNdBC8hTnnCRYKe/p95hAzJb98NhtpwQPL20fLqJ@8e/aaUQ6eD3ZiXVlEJM7Mt1tRs "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if the input is harmonic, nothing if not. Explanation: ``` ≔⁺c⁻Siθ ``` Remove `i`s from the input, but also prefix a `c`. ``` ›№⁺⌊θ⌈θc... ``` Check that `c` is now either the minimum or maximum of the string, and... ``` ⊙⪪oeOa²№⁺⮌θθι ``` ... that neither the string nor its reversal contain either `oe` or `Oa`. [Answer] # [R](https://www.r-project.org), 83 bytes ``` \(x,g=\(p)grepl(p,x,perl=TRUE))!(g('[ueo]')&g('[UaO]'))&!(g('oi*e|ei*o|Oi*a|ai*O')) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY-_DsIgEId3n6J2KH-Cu0tHZxKVyRpDzLW5pAmElqRDn8PFpQ6-hS_St5FCE2X47gf3hYPny03zo3cebj10fZeV2Z3mmFYustxEykgfqSIhUqcTmUzjkwVxu1apUOdsU-u2-59BvCKCGBkAqJeICKEEHUjQg_T2fb3bz6eKDqIpK2pZ48C21IpBWHBteT6qA2Nb2lBy8WCuhBVLVFqGyIrYMMhhBORmlMj1qJHL0EtXf2r6-3mYSf8euSrTlOoX) Very straightforward regular expression solution - can't have both sets of vowels, can't have o/e or O/a adjacent with any number of intervening is. (The other combinations are ruled out by [ATR] harmony.) [Answer] # [Python](https://www.python.org), ~~98~~ ~~97~~ 96 bytes ``` lambda s:len(t:=s.replace("i",""))>1and(y:=ord(t[0]))and any((y^(y:=ord(x)))%18%8for x in t[1:]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rZDBSsQwFEVxab4iPhjIg1rsrgTq3lVXdTMdNU5TfBKT0qQy_RY3BdF_0q8xnagbt2aRhPvIPYe8vA9zeHB2ee2r9m0K_Xn5cWfU032nuJdGWxFk5fNRD0bttQCCDADxslC2E7Os3NiJsL3YIcaAKzsLMd_8DA6IuCnKTdm7kR84WR62hdxh4nyenA0j2SDgWhnqAFnQPtzuldeeVxwAKC3miNXEJmINMU1MxUsdQzfFTDO3bnVDKr7I_WAoNrY21q3UtfII_q2W7DRh1yg3j5MPosyAA2bQBsh4f5wgsm-71l7Z5z-GVaRNDXN1NFJRJjnof3ZIP7Us6fwC) Port of @Arnauld's [Node.js answer](https://codegolf.stackexchange.com/a/248305/110555). -1 byte from @Arnauld altering their answer -1 byte thanks to @mathjunkie --- # [Python](https://www.python.org), ~~116~~ 115 bytes ``` lambda s:4in[len({*s}|{*g})for g in["ueoi","UaOi"]]and not any(t in s.replace("i","")for t in["eo","oe","aO","Oa"]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pVDNSsQwEMaTOE8R5tQudU8eZKEP4CmnerFFxu10HahJaVJhWfdJvCyIvpM-jdNG8ODRHL4kX-b7Ia8fwz4-end668r6fYrd5fVn6OnpoSUTNlfi7np22WEVji-H1e6Yd340O6M0TuwFC6zICjYNudY4Hw25fRb13YT1yENPW85wHsNFGRcleyU8K5BVsIRNnqK_zs6HUVzM8JZ6aTGHyCHebylwMKVBREkLvIAVmAQqARYgPVgl_aQcg5_BVkKqWIehF3WsndotJdRybvhrvYGLFDtTBdYRC9MtlzyHn0K1u3HPf0qVGjBV4K2WIM1Psfz_2PQfp1PavwE) Checks if the set of the characters in the string matches the two valid options (from the Venn diagram) and that none of the illegal combinations (`"eo","oe","aO","Oa"`) are in the `"i"`-stripped string. -1 byte thanks to @mathjunkie [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 38 bytes ``` i 1`[oue][OUa]|[OUa][oue]|oe|eo|Oa|aO ``` [Try it online!](https://tio.run/##JYohDsAwDAO5/zFpdK8YDCqqKjUgwGSRppXl713WGVj22bc9vHRu@9kngaNXH9aqFG2xfPVwC/MQDZU5@QtOCDGIQhihGSShj2QG/0wKFaPAJR@a48/sBQ "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `0` for harmonic, `1` if not. Explanation: Retina 0.8.2 doesn't have any handy reversal operations so I have to test for all six non-harmonic vowel combinations. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 'iKÇü^18%8ÖP ``` Port of [*@Arnauld*'s first JavaScript answer](https://codegolf.stackexchange.com/a/248305/52210). I tried to find a -1 byte alternative for the `18%8Ö` using any of 05AB1E's single-byte builtins and constants, but was unable to. [Try it online](https://tio.run/##yy9OTMpM/f9fPdP7cPvhPXGGFqoWh6cF/P/vH5qZCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/9Uzvw@2H98QZWqhaHJ4W8F/nf7RSJgQo6Sgo5YNJfzBZCiZDwWQqmEyEiPhDVOaXQlSlgrlQ2j80MxEsHAoW9YdoToTogCtJhQinZuYrxQIA). **Explanation:** ``` 'iK '# Remove all "i" from the (implicit) input-string Ç # Convert the string to a list of codepoint-integers ü # For each overlapping pair: ^ # Bitwise-XOR them together 18% # Modulo-18 each integer 8Ö # Check for each integer whether it's divisible by 8 P # Check if all are truthy by taking the product of the list # (after which the result is output implicitly) ``` ]
[Question] [ # Roll for Initiative! # Introduction In tabletop games like Dungeons and Dragons, when you begin a battle, all involved parties *roll for initiative*. In DnD 5e, this is `1d20 + DEX + Other bonuses`, where `DEX` is the bonus given by your Dexterity stat. The characters that roll higher numbers go first. We'll use a similar, deterministic system in this challenge. # The Challenge Write a program or function that, when given a list of characters, will output a list of characters in order of initiative. A character is defined as this: ``` character = { name: "name" // a string statblock: [SPD, DEX, WHT] // a list of numbers // DEX = dexterity, SPD = speed, WHT = weight } ``` The formula for initiative is the following: $$\text{Initiative} = \left\lfloor{ \frac{\text{SPD}^2}{\sqrt{\lvert\text{DEX}\rvert}} }\right\rfloor - \text{WHT}$$ # Input A list of characters, unsorted. This can be a JSON object, a list of lists, a list of dictionaries, a series of strings etc. It is guaranteed that all names will be unique. # Output A list of characters, or character names, sorted by initiative order from highest to lowest, based on the above formula. # Rules * IO can be used with [any convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so smallest program wins! # Sample IO ``` Input --> Output [[Name, SPD, DEX, WHT], ...] --> [[Name, SPD, DEX, WHT], ...] (or [Name, Name, ...]) --------- [[Alice,1,2,3],[Bob,10,5,0],[Charlie,3,2,1]] --> [Bob, Charlie, Alice] // Alice = -3, Bob = 44, Charlie = 5 [[Z,1,1,1],[B,1,1,1],[XY,5,1,1]] --> [XY, Z, B] // Retain the order of characters from the input if they have the same initiative. // Z = 0, B = 0, XY = 24 [[Neg,-3,-3,-1],[SomeNeg,5,-2,-4],[NoNeg,4,6,8]] --> [SomeNeg, Neg, NoNeg] // Negative values are valid. // Neg = 6, SomeNeg = 21, NoNeg = -2 [[Flo,1.5,2.5,3.5],[MoreFlo,2,2.5,3.5]] --> [[MoreFlo,2,2.5,3.5], [Flo,1.5,2.5,3.5]] // Floats are also valid. // Flo = -2.5, MoreFlo = -1.5 [[Lonely,1,2,3]] --> [[Lonely,1,2,3]] // Input with 1 item. [] --> [] // Empty input leads to empty output. [[Foo,2,1,4], [Baz,5,5,4], [Bar,5,1,4]] --> [Bar, Baz, Foo] // Foo = 0, Bar = 21, Baz = 7 [['Adam', 2, 4, 1], ['Eve', 2, 3, 1]] --> [Adam, Eve] // Adam = 2, Eve = 2 // If you do not floor, you'll end up with [Eve, Adam] (Adam = 2, Eve ~= 2.3) ``` [Sandbox link](https://codegolf.meta.stackexchange.com/a/18320/77309) [Answer] # JavaScript (ES7), ~~73~~ 60 bytes *-13 bytes by just sorting the input without isolating the names, as suggested by @asgallant* Expects a list of `[SPD, DEX, WHT, Name]`. ``` a=>a.sort((a,b)=>(g=([s,d,w])=>~(s*s/(d*d)**.25)+w)(a)-g(b)) ``` [Try it online!](https://tio.run/##RZBBT4MwFMfvfApubfFRBwxjYiBxRk/qxYva9FCgMEzHW@ji4sWvjl0ZM@07/H/9vbR9X@pb2Xrs94d4wEZPbTGpolTc4nigVEHFipJ2BRUWGjhKl36pjew1baKGRRFPc3Z1ZFSxuKMVY9OdCMJQiARSyIDcm77WREIokhXksAKywcrnzAkJkIetGk3vFAnnvtMin3PPHDY@5HN4/7i4cQan7eCr7s5OnEK8BvKGO73ANdzArXPQg@UenkPqKnNFngx6M/1HLzhqjy/v8v95xkGbn4XKQAa8xfFR1VuqwqIMaxwsGs0NdrR1Q@E7tZ9PlMgkc/P5Aw "JavaScript (Node.js) – Try It Online") ### How? To save a few bytes: * we compute \$-\text{Initiative}-1\$ instead and sort the list the other way around * we compute \$\sqrt{|\text{DEX}|}\$ as \$(\text{DEX}^2)^{\frac{1}{4}}\$ [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Σ`nsÄt÷- ``` Input in the format and order `["name", WHT, DEX, SPD]`, and output are the same inner lists sorted from highest to lowest `initiative`. -2 bytes thanks to *@Grimmy*. [Try it online](https://tio.run/##yy9OTMpM/f//3OKEvOLDLSWHt@v@/x8dreSXmq6ko2uoo2sMRLE60UrB@bmpEEETHV0jHVOQmF8@WMRCx0zHJDYWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpeRfWgLj/T@3OCGv@HBLyeHtuv9rdQ5ts/8fHR2t5JiTmZyqpGOsY6RjGKsTreSUn6SkY6BjqmNoAOI6ZyQW5WQCFRgCFRjHxuooAPVEgbiGUPVI7IhICMcUqs4vNV1JR9dQR9cYiEAKgvNzUyGCJjq6RkB1QDG/fLCIhY6ZjglUn1tOPtBFeqY6RkBsqAdW5ptflIoibgRV7JOfl5pTCfMBSCw2FgA). **Explanation:** The sort builtin `Σ` sorts from lowest to highest by default, so I'm using the following modified formula to not only save bytes, but sort from highest to lowest at the same time with this builtin (thanks *@Grimmy*): $$Initiative = WHT - \left\lfloor\frac{SPD^2}{\sqrt{\lvert DEX\rvert}}\right\rfloor$$ ``` Σ # Sort the (implicit) input-list by: ` # Pop and push all values of the inner list separated to the stack n # Square the SPD at the top of the stack s # Swap so the DEX is now at the top of the stack Ä # Take its absolute value t # Then its square-root ÷ # And integer-divide the squared SPD by this - # Subtract this from the WHT (to sort in descending instead of ascending order) # (after which the result is output implicitly) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~20~~ 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ñÈÌ-(Xg1 ²/Xg2a ¬f ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8cjMLShYZzEgsi9YZzJhIKxm&input=LVEgW1siWiIsMSwxLDFdLFsiQiIsMSwxLDFdLFsiWFkiLDUsMSwxXV0) Simply calculates the formula for each character and sorts. Negates the formula to sort in the correct order. Takes input as a list of lists `[Name, SPD, DEX, WHT]`. (I could save a byte taking input as `[SPD, Name, DEX, WHT]` but that feels cheaty.) [Answer] # [Python 3](https://docs.python.org/3/), ~~63~~ 59 bytes ``` lambda c:sorted(c,key=lambda x:x[3]-x[1]**2//abs(x[2]**.5)) ``` [Try it online!](https://tio.run/##TZBBT4MwFMfv@xQvu5QtDzZaMIZkJtPoSXfxMq09FCiOCHQBYuDTYylClrZp3y@/f5u@a99edMWG7PA1FLKMUwlJ1Oi6VamT4I/qD/@0izrOhNtxX2y3dLeTceN0nJrCCzebIdM1tKppE9koyCvgKwDOybHIE0XQR4pMICePOjbVHkPcj@XTRdZFbgRmBF8InFKfY8IMm7g5nz@ISfo35kl9E3SZnVZ516WyMESXohuM7KQtCfAO75fkS6HNzV6I1CzmhaP4pmtlOV3orL/qShX9/JOZHlNZEgSKECCY94GT5181ETaSSRQrEZkdrnVetc7cJoQ1uA@wRsgWZjr5Bw "Python 3 – Try It Online") Pretty straigtforward. Sorts by `- initiative` to get the right output order. # [Python 2](https://docs.python.org/2/), ~~60~~ 56 bytes ``` lambda c:sorted(c,key=lambda(a,b,c,d):d-b*b//abs(c)**.5) ``` [Try it online!](https://tio.run/##TZBBa4MwFMfv/RSPXqLytDWaUoQOurGdtl522eY8JDGuMjVFZeCndzGilCS8vB@/f0JyG/qrbuhYnL7Hitci5yCTTre9yh2Jv2o4zdThKFBi7ia5Lzyx23HROdL1vIC5Y6Fb6FXXS94pKBtINwBpSs5VKRXBEClGGabkUQvT7ZHhfmqfrrytSiNERgizDOfU15Qwwybu9h@fxCTDO/Oifgj6kZ1Wede1spChT9GPJ3bRlsR4wOOafKm0OTlgSM2KAjaJb7pVltOVLvqrblQ1LC9Z6DnnNUGgCDGCuR9S8vynZhJNZBazTZaYCre2bPr1mxC24D/AFqFwFuaO/w "Python 2 – Try It Online") *thanks to @Chas Brown* [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 28 bytes ``` f:{(!x)@>{-z-(x*x)%%y|-y}.'.x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWkOxQtPBrlq3SlejQqtCU1W1ska3slZPXa@i9n@aQkJiTmZyakJSflJCckZiUU5mqqKGoYKRgrG1oYGCqYKBtTGQY6j5HwA "K (oK) – Try It Online") -10 thanks to ngn :-) [Answer] # [Ruby](https://www.ruby-lang.org/en/), 44 bytes ``` ->d{d.sort_by{|_,x,y,z|-x*x/y.abs()**1/2+z}} ``` [Try it online!](https://tio.run/##bcxLC4JAFIbhvb9icKV2xrxGm4IKWrppKSIzXkqwJkYFr7/dRrEoCM7q4Tsvr2gzprsR7@Mu1gvGy5A2XR9CDQ20Pa61et3ohBaKqmnm2lq1wzAStEO@hJAvH/IsSmQwwQI7gJmOjAowwAVjkdON8DwTM1vMzEAKJPoJeMlVBmzPZy77C7sns7uALcDOwh6b0YENbKdI9ImcGZOnNLynR8Kn729oJ3AFiM8nzx4lSvWI5LlCVOlZlcUv0n8YqeML) -3 bytes thanks to @79037662 [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 24 bytes ``` D,g,@#~,p2^$|.5^/i_ L,§g ``` [Try it online!](https://tio.run/##XZBNTsMwEIX3PsXIdDkJtd0gpEoVFMSqlAWbtpaLUmKFSC6OukNCXId7cLEwdp1SIv/I896bz5bLqmrbrrvHGm8uvrCV29FnXmwvmxe2wJ/vuhu5cr@rShAzrfmta14tBwESlAHN535H1RgKGIfy7q08uIYCigLCGPbEpqAphJAshIgwjP3jbgKTRmSenVdrTmzxx1qtETYI8yFgaWsOmYozdj77vY1iAZmEbBK0pY/KBK7gugemHMJxC4kh@8F5elJegKSl8iKgHv3BRl2e1ATUyUKJ5GBwEHQQCHGShncs/Lt1H/3P9qijioJYatCSIqb7BQ "Add++ – Try It Online") Inputs and outputs a list of lists representing the characters, in the same order given in the challenge (`[Name SPD DEX WHT]`) ## How it works On the second line, we define an anonymous function that takes in an argument and sorts it on the result of **g**, defined on the first list. **g** starts by reversing its argument and splatting the elements to its stack: `#~`. It then removes the name and squares the first stat, Speed, (`p2^`) before square rooting the absolute value of the second stat, Dexterity, (`$|.5^`). Finally, we integer divide the two (`/i`) and subtract from Weight (`_`). This is the opposite to the formula (where Weight is subtracted from the division), as it will cause the sort function in the second line to sort in the order we want. As Add++ uses a stable sort, order is retained if two characters have the same initiative. [Answer] # APL+WIN, 41 bytes Prompts for a n x 4 matrix where n is the number of rows 1 per character and the columns are Name, SPD, DEX, WHT. The output is a 1 column matrix of character names ``` m←⎕⋄⊃m[⍒⌊((m[;2]*2)÷(|m[;3])*.5)-m[;4];1] ``` [Try it online!Courtesy of Dyalog Classic](https://tio.run/##TY/BSsNAFEX3@Yq3e0khJTOTiNBVW@iq7caNWrKIcdoGJh1pVwV3ikq1IoLf4UboXv9kfiTeJrXI48Kd8@4deNmNCa/XmbGzMDfZalXklXv9GA3dw5vy3NPjtCphgdzzvdvclRO3fXcvG98vJx2ZtmTws/Nv4VUatNpJEMLGaUekFbrV1FMUu@0Xd02RayZBkhRxz17BR5RQRNyfZ0tTYKmwFN6xcrmP74d7R3d@wSiJ/7GxnjF9f6qDEDqzpa5pgreEYuKxrUlMJ3SKrmy6A2PxdTshCSmIR3apayr/GNKiSQ/tQpv14QjgqMHs/QI "APL (Dyalog Classic) – Try It Online") [Answer] # [Red](http://www.red-lang.org), ~~108~~ 107 bytes -1 byte thanks to raznagul ``` func[b][extract next sort/skip collect[foreach e b[keep 0 -(e/2 ** 2 /(e/3 ** 2 ** .25)- e/4)keep e/1]]2 2] ``` [Try it online!](https://tio.run/##XY/NTsMwEITveYo50kr5sR0jxI0icYIe4AJYPiTupo1q4sgNEjx9WBdUClqvNTs732EjbeZH2hibdddz9z4401pDH1Ns3ISBBQ4hTuVh349wwXtyk@lCpMbtQFlr9kQjKuQXVEosl5AoWapvyV8h9SIHlfXimKRSWCsh7TzG0BI6GHPje0cQnFcWZhVaiAoaFQ@3uyb6nqB4yWD2C70ywJWAk3p@YUz8C65pi1wdX8o8hTdKlkYukdfsrEOaa1zi6g945wNEoSG5VaE5@cB3J1eevPP8fRjIf/7ccbaw8xc "Red – Try It Online") [Answer] # Google Sheets, ~~49~~ 37 bytes -12 bytes thanks to Black Owl Kai ``` =Sort(A:A,D:D-B:B^2/Sqrt(Abs(C:C)),1) ``` Input is in the range `A1:D` with the four columns being player, speed, dexterity, and weight. Explanation: `D:D-B:B^2/Sqrt(Abs(C:C))` do the math bit. The values are actually `Initiaive * -1` so we can sort them ascending and get the order we want. Otherwise, all the blank rows would be sorted before the player names. `=Sort(A:A,~,1)` sorts the player list based on the math bit output. Test cases: [![Test Cases](https://i.stack.imgur.com/pbdSX.png)](https://i.stack.imgur.com/pbdSX.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ḊA2¦U*ؽj.¤UŒH:/€IµÞ ``` [Try it online!](https://tio.run/##y0rNyan8///hji5Ho0PLQrUOzzi0N0vv0JLQo5M8rPQfNa3xPLT18Lz/h9uBzIc7FgFJIHL//z@aizM6WskxJzM5VUnHUMdIxzhWJ1rJKT8JyDPQMdUxAHGdMxKLcjKBCoyBCgxjY3XAmqJAGoAQrAGJHRGpBNRoiFDol5qupKNrDEZgFcH5ualgQVMdXSMdXROQmF8@WMREx0zHAqbRLScfaK6eqY4REBvrmYLU@eYXpYLFjeCiUNU@@XmpOZUwX4AFY7liAQ "Jelly – Try It Online") Well, this is horribly hacked together but it works. The Footer in the TIO link simply runs the code over each list then returns just the names. The code itself returns the names and all stats in the same format as the input, namely `[Name, SPD, DEX, WHT]` Will post an explanation after any more golfing [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` FA⊞υ⟦⁻⌊∕X⊟ι²₂↔⊟ι⊟ι⊟ι⟧W⌈υ«≔Φυ¬⁼ικυ⟦⊟ι ``` [Try it online!](https://tio.run/##RY1PawJBDMXP@imGPWUhe6i1IngSqtCDy1KPwxxWnbrB2Y2d2dFC6Wefxn8YkvB4Ib@3bWq/5dql9MVewUd3jD3kuapiaCCi0ivqYoClY/bwTifaWaj4bL3sI1COaiSz/o61t5/MPcw34X66FKq7fgiTz4bnhpxVsKp/qI0tRIn7HQ7mIdC@gyW5XugSXQptIWAXgFAdrrQo74PKU9eDfgL/UtJaZ6XdZ1i8YPEqbVBna27tzRxjMcK3i1fy1ZniBMfGmFSc3D8 "Charcoal – Try It Online") Takes quadruples in the order name, weight, speed, dexterity. Explanation: ``` FA ``` Loop over the quadruples. ``` ⊞υ⟦⁻⌊∕X⊟ι²₂↔⊟ι⊟ι⊟ι⟧ ``` Square the dexterity, floor divide by the square rooted absolute speed and subtract the weight, then create a tuple with the result and the name and push that to the predefined list. ``` W⌈υ« ``` While there are still tuples in the list, take the maximum. ``` ≔Φυ¬⁼ικυ ``` Remove the tuple from the list. ``` ⟦⊟ι ``` Output the name on its own line. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes ``` ṛ²:A½$}ɗ_@3ƭ/Þ ``` [Try it online!](https://tio.run/##y0rNyan8///hztmHNlk5HtqrUntyeryD8bG1@ofn/dc53K6t/6hpjeGhZUDy6KSHO2eoABlZjxrmKOjaKTxqmMt1uB0oEPn/f3R0tLpjTmZyqrqOgqGOgpGOgnGsjkK0ulN@EkjEQEfBVEfBACzknJFYlJMJUmgMVmgYCxKOVo@CaAUhiFY0fkSkOtgUQ4QWv9R0oJiuMRRD1AXn56ZCJICKdYEW6JqAxf3yIaImOgpmOgoWUCPccvJB9ugB1RqBCGM9U7Bq3/yiVIicEZIMRI9Pfl5qTiWST0HCsbEA "Jelly – Try It Online") A monadic link that takes a list of characters as its argument. Each list is structured as `[Name, SPD, DEX, WHT]`. Returns a list of characters in the desired order. [Answer] # [Python 3.8](https://docs.python.org/3.8/), 81 bytes This solution uses the formula as described in the question. As input a dictionary is expected in the following form: `{"name":[SPD, DEX, WHT],...}` ``` lambda d:sorted(n:={_:(i:=-a*a/abs(b)**.5+c)for _,(a,b,c)in d.items()},key=n.get) ``` [Try it online!](https://tio.run/##XU9NT4MwGL77K3qjxRfkY9WFhIOa7KS7eHG6ZSlQtkZoSeGCy347tmCmI22T9/l687Tpu6OS8bLRQ5luh4rVWcFQkbRKd7zAMklP@wSLJPWYy@5Y1uKMuK5Pb3NSKo32gBlkkBMhUeGLjtctJmf44n0q/QPvyNBoITtc4pOzUspJPiMIYbED54lpg@gFfY@IGnQm5OYv9ViJnBstBBQBiq1XZRYHgCigwBDPR6YrYU3xaApnKz7GuDk2/G9@3/w2mAfW/GAULwZ7rfNN1XwiKXgReLbyWk3MAu5hOVuwquxXQ59CZF7sU@N/VZpPfHRhr1MvSvKqN4bAdHq4Fg0YfgA) [Answer] # APL(NARS), chars 40, bytes 80 ``` {⍵≡⍬:⍬⋄↑¨⍵[⍒{(4⊃⍵)-⍨⌊(2*⍨2⊃⍵)÷√∣3⊃⍵}¨⍵]} ``` test: ``` f←{⍵≡⍬:⍬⋄↑¨⍵[⍒{(4⊃⍵)-⍨⌊(2*⍨2⊃⍵)÷√∣3⊃⍵}¨⍵]} ⎕fmt ,⊂(('Lonely') 1 2 3) ┌1────────────────┐ │┌4──────────────┐│ ││┌6──────┐ ││ │││ Lonely│ 1 2 3││ ││└───────┘ ~ ~ ~2│ │└∊──────────────┘3 └∊────────────────┘ ⎕fmt f,⊂(('Lonely') 1 2 3) ┌1────────┐ │┌6──────┐│ ││ Lonely││ │└───────┘2 └∊────────┘ ⎕fmt (('Alice') 1 2 3)(('Bob') 10 5 0)(('Charlie') 3 2 1) ┌3──────────────────────────────────────────────────┐ │┌4─────────────┐ ┌4────────────┐ ┌4───────────────┐│ ││┌5─────┐ │ │┌3───┐ │ │┌7───────┐ ││ │││ Alice│ 1 2 3│ ││ Bob│ 10 5 0│ ││ Charlie│ 3 2 1││ ││└──────┘ ~ ~ ~2 │└────┘ ~~ ~ ~2 │└────────┘ ~ ~ ~2│ │└∊─────────────┘ └∊────────────┘ └∊───────────────┘3 └∊──────────────────────────────────────────────────┘ ⎕fmt f (('Alice') 1 2 3)(('Bob') 10 5 0)(('Charlie') 3 2 1) ┌3─────────────────────────┐ │┌3───┐ ┌7───────┐ ┌5─────┐│ ││ Bob│ │ Charlie│ │ Alice││ │└────┘ └────────┘ └──────┘2 └∊─────────────────────────┘ ⎕fmt f ('Z' 1 1 1)('B' 1 1 1)(('XY') 5 1 1) ┌3────────┐ │┌2──┐ │ ││ XY│ Z B│ │└───┘ ¯ ¯2 └∊────────┘ ⎕fmt f (('Neg') ¯3 ¯3 ¯1)(('SomeNeg') 5 ¯2 ¯4)(('NoNeg') 4 6 8) ┌3─────────────────────────┐ │┌7───────┐ ┌3───┐ ┌5─────┐│ ││ SomeNeg│ │ Neg│ │ NoNeg││ │└────────┘ └────┘ └──────┘2 └∊─────────────────────────┘ ⎕fmt f ⍬ ┌0─┐ │ 0│ └~─┘ ⎕fmt f (('Flo') 1.5 2.5 3.5)(('MoreFlo') 2 2.5 3.5) ┌2────────────────┐ │┌7───────┐ ┌3───┐│ ││ MoreFlo│ │ Flo││ │└────────┘ └────┘2 └∊────────────────┘ ⎕fmt f (('Foo') 2 1 4)(('Baz') 5 5 4)(('Bar') 5 1 4) ┌3───────────────────┐ │┌3───┐ ┌3───┐ ┌3───┐│ ││ Bar│ │ Baz│ │ Foo││ │└────┘ └────┘ └────┘2 └∊───────────────────┘ ⎕fmt f (('Adam') 2 4 1)(('Eve') 2 3 1) ┌2─────────────┐ │┌4────┐ ┌3───┐│ ││ Adam│ │ Eve││ │└─────┘ └────┘2 └∊─────────────┘ ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, 72 bytes ``` sub i{int($_[1]**2/sqrt abs$_[2])-pop}say$$_[0]for sort{i(@$b)-i@$a}eval ``` [Try it online!](https://tio.run/##PYzBasMwEETv/YqFGmSHlWvJ1SmXpKW95QuEKHKqUgXFUiU5UEJ@vapMoQN7mDczG0x0opS0TGCvds5t8yaZ2mz4Q/qKGfSUKuCqo8GHW9LfTbWD@vARko/5attdM3XU7hp9MxftyrZ2CK0i23s4LSlD9pBM0FFnA37JYcmwzrOp2VEnk0or984eDTLkOCqUT35CNqDAoZrnTx2dNTjWkKnurpVk/67PBIEjPCIwhSDJy8X8kXEla@vVeWS9QF5v7EX9dPDRrJT/s@7Hh2z9nAo9iH5gQ6HzLw "Perl 5 – Try It Online") [Answer] # [C++ (clang)](http://clang.llvm.org/), ~~324~~ \$\cdots\$ ~~232~~ 204 bytes Saved ~~18~~ 46 bytes thanks to [cielingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` #import<regex> #import<cmath> #define i(s)int(*s**s/sqrt(abs(s[1])))-s[2] struct C{std::string n;float s[3];};void f(std::vector<C>&v){std::stable_sort(&v[0],&*end(v),[](C a,C b){return i(a.s)>i(b.s);});} ``` [Try it online!](https://tio.run/##fZBRb5swFIXf8yssJkV2ZLIATVUBRVqR9rT1ZS/bKJoMuaSWwM5sgzZZ/PbUQJuoL7VsofP5XO65rk8nv26ZOJ7Pn3h3ksqkCo7wL1u9ybpj5tnJAzRcAOJYEy4M3ujNRn/Wf5XBrNJYF0FJCPF1EZYrbVRfG5RbbQ5x7BQXRySSppXMIF1EZTImg@QH1ODZMUBtpErzbD2QtxpWtfBHuwB4PRS7kq43IA54ILQocY4YzVFFrALTK@Eysa0mGceV@ySj25dhuHTtgXXZqtdzCtaBPrEakOuTuEFQx7jAxL5muETJBn1vrfW@tLwGj9qAhjQaR2q9B1lNekf3dDeD/Jmplk@myJmCcYLWe4SjI35Epx3Mxh@ygwXvqR9S/2amj3JhN/SW3r0W/547BnSpe3infv6afxBcOn1t5WTY7mnoTrTdz7bvUsFyE1757P8mBbT/rzM5OI5JIxVmvZFoiAdNbOPe@sogHkgte5OmsBVp6sXIS1OOwb23U0/CS5Zbz/9wTcZxPL8A "C++ (clang) – Try It Online") # Ungolfed: ``` #include <string> #include <algorithm> #include <cmath> #include <vector> using namespace std; struct C { string n; float s[3]; }; float i(C c) { return floor(c.s[0]*c.s[0] / sqrt(abs(c.s[1]))) - c.s[2]; } void f(vector<C>&v) { stable_sort(begin(v), end(v), [](C a,C b) { return i(a) > i(b); }); } ``` ]
[Question] [ It's August 10th, 2019, but your task still involves Y2K. Weird, right? Create a program that prints itself, with a two digit number appended to it. The first time you run it, it should append 00 to its output (its source code, because this is a quine variant). When you run that output, the original program without a two digit number, it should output the original program, but with 01 appended to it. Run that output to get the OG program with 02 appended, then that to get the program with 03... This chain should continue until 99. That program should output `BREAKING NEWS: WORLD ENDS`. If your program is `Y2Kparanoia: yes` then: 1. It should output `Y2Kparanoia: yes00` 2. That output should print `Y2Kparanoia: yes01` 3. That output should print `Y2K paranoia: yes02` 4. Repeat until step 100: this program outputs the doomsday news specified This is code golf, so the shortest program that can print itself while following these steps wins. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~122 114~~ 106 bytes *-8 bytes thanks to Shelvacu* ``` END {<print $!-199??"END \{<$_>~~.EVAL};\$!="~($!-1&&$!-99)+100!!"BREAKING NEWS: WORLD ENDS">~~.EVAL};$!=1 ``` [Try it online!](https://tio.run/##K0gtyjH7/9/Vz0Wh2qagKDOvREFFUdfQ0tLeXgkkGFNtoxJvV1en5xrm6FNrHaOiaKtUpwFSoqYGJC0tNbUNDQwUFZWcglwdvT393BX8XMODrRTC/YN8XBSAJgQrIXQDNRv@/w8A "Perl 6 – Try It Online") Takes the standard quine format and adds the breaking news string as well as a new function call with the appended number. This uses `END` to execute the function when the program ends. [Answer] # Ruby, ~~158~~ ~~154~~ ~~146~~ ~~128~~ ~~122~~ 100 bytes Inspired by [this answer](https://codegolf.stackexchange.com/a/126026/13400). ``` eval s=%{$><<(D>198?'BREAKING NEWS: WORLD ENDS':'eval s=%%{%s}<<D=%d'%[s[0..-2],D<2?100:D+1])#}<<D=1 ``` EDIT: I was able to remove `(s.split(35.chr)[0]+35.chr).inspect` and replace it with `s[0..-2]` (range of every value except the last) and the `%{ ... }` string syntax I used before. Saved 22 bytes! ### Old version: EDIT: Saved a pair of parens (and corresponding pair in the data section) by realizing that `"BREAKING NEWS: WORLD ENDS"` is a perfectly valid format string, and ruby ignores any extraneos parameters. ``` END{$><<(q=S>198?"BREAKING NEWS: WORLD ENDS":%{END{$><<(q=S>198?"BREAKING NEWS: WORLD ENDS":%%{%s})%%[q,S<2?0:S-99]} S=1%02d})%[q,S<2?0:S-99]} S=1 ``` When starting this I realized that since the number *has* to go at the very end of the program, and ruby doesn't allow using variables before they are declared, I would have to make code run *after* the digits somehow. I could've done something like `def a(s) ... end;a 1` which would become `...end;a 100`, however using ruby's lesser-known [`END`](https://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-END) syntax uses fewer bytes. However, the block inside `END` is in a different scope, so `S` must be a global variable or constant. Explanation: * `END{ ... };S=1`: Run block of code just before program terminates; Set constant `S` to `1` (or `100` - `199` in future iterations) * `$><<( ... )`: `$>` is a shortcut in ruby for stdout, and `<<` on an IO writes to the IO. The parens are required, otherwise it becomes `($><<S)>198...` * `S>198?"BREAKING NEWS: WORLD ENDS":(q=...)%[q,S<2?0:S-99]`: If I were to break this out into slightly more reasonable code it would be: ``` if S > 198 "BREAKING NEWS: WORLD ENDS" else q = ... number_to_append = if S < 2 0 else S - 100 + 1 end q % [q, number_to_append] end ``` The `%` operator applied to a string is effectively `printf`, with the LHS being the format string and the RHS being the arguments. * `%{ ... (q=%%{%s}) ... S=1%02d}`: ruby has an interesting syntax for strings that also allows for pairs of curly brackets to appear *within* the string without any escaping as long as they are balanced. This is very helpful, as otherwise a similar quine would have to escape the string to put it into itself as a string literal. The two substitutions in the format string are `%s` for a regular string and `%02d` for a number right-padded to a size of 2 with the character `0`. My thoughts on shortening further: * ~~It'd be nice to be able to use `s` instead of `$s`, but defining s `s=$s;` or making a function `def a(s) ...` both use more bytes than they save, and I can't think of any other way to do it.~~ EDIT: Constants are global and can be one character! * It'd be nice if `S` was always less then `100`, so that it could be compared using 2-digit numbers instead of 3-digit numbers. However, if I use `S=0` at the end, the next two digits are interpreted as octal, and `8` and `9` are invalid and all is bunk. `S=` simply isn't valid, and I don't know any other way to make a value valid both before and after appending two digits. Of note, `0` (and every other integer) is **truthy** in ruby. Any thoughts on how to make this shorter, please let me know! [Try it online!](https://tio.run/##KypNqvz/P7UsMUeh2Fa1WsXOxkbDxc7Q0sJe3SnI1dHb089dwc81PNhKIdw/yMdFwdXPJVjdSh2mQbVatbjWxsbFVjVFXTW6ONpAT0/XKFbHxcbI3tDAwMpF2zBWUxmswPD/fwA "Ruby – Try It Online") [Answer] # Go, ~~382 366 354 340 305 298~~ 272 bytes Won't win but I had fun with the challenge. ``` package main func main(){if n<199{s+="\x60," print(s[:135],s,100+(n/100)*(n%100+1))}else{print("BREAKING NEWS: WORLD ENDS")}} var s,n=`package main func main(){if n<199{s+="\x60," print(s[:135],s,100+(n/100)*(n%100+1))}else{print("BREAKING NEWS: WORLD ENDS")}} var s,n=`,1 ``` [Try it on the Go Playground!](https://play.golang.org/p/uWv_EO6Jxzd) Based on a quine. If the variable `n` is less than 199, then it adds to the string variable `n` a grave accent (`\x60`), Go's character for multiline strings, followed by a comma `,`. It continues by printing the first 147 characters of `s` (to prevent printing the `,` because that only occurs at the end) then prints `s` as a whole, and finally prints `100` if `n == 1` and `n+1` otherwise. The result is that successive runs change the variable `n` at the end of the program to 100, 101, etc. If the variable `n` is 199 or more, then it prints breaking news. [Answer] # [Haskell](https://www.haskell.org/), ~~240~~ ~~232~~ ~~218~~ 216 bytes ``` p=putStr;h 1=100;h k=k+1;g _=p$"n="++show(h n);main|n>198=p"BREAKING NEWS: WORLD ENDS"|1>0=p<>print<>g$"p=putStr;h 1=100;h k=k+1;g _=p$\"n=\"++show(h n);main|n>198=p\"BREAKING NEWS: WORLD ENDS\"|1>0=p<>print<>g$" n=1 ``` [Try it online!](https://tio.run/##hc3BCoIwGADge0/xMzwUojjoYOmESrEoDNzBixCCS0XdxpxE4LubD1B0@o5fXQwt67q56aVQGsJCFzZlfVMpMUqwLBC8ewNnrGQlPIWC@HwCH1x7a@NZEjlqqpVXAybYcRZb0prYq@BBpIE4QaY51OK1roFvvL5o@MQDvHOJRMc0OlwvSQxJlNE9ZPf0FkKUhBRNOHCI9AOpGq79oDLQnydfovznlP@u8i/XihM8zx8 "Haskell – Try It Online") [Adapted from a quine](https://codegolf.stackexchange.com/a/161036/64748) [Answer] # JavaScript (ES6), 116 bytes ``` setTimeout(s="alert((n-1?++n:n=100)-200?`setTimeout(s=${JSON.stringify(s)}),n=`+n:'BREAKING NEWS: WORLD ENDS')"),n=1 ``` **94 bytes, if stringifying functions is allowed** ``` f=_=>((p=`f=${f}`.split`|`)[4]=p[4]-1?-~p[4]:100)-200?p.join`|`:'BREAKING NEWS: WORLD ENDS'||1 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~81~~ 80 bytes ``` .vh,K"?>J198\"BREAKING NEWS: WORLD ENDS\"s[\".vh,K\"N:KN+C92NN\"J\"?<J2*TT+J1"J1 ``` [Try it online!](https://tio.run/##K6gsyfj/X68sQ8dbyd7Oy9DSIkbJKcjV0dvTz13BzzU82Eoh3D/Ix0XB1c8lOEapODpGCaw4RsnPyttP29nSyM8vRskrRsnexstIwdDAQNvLUMnL8P9/AA "Pyth – Try It Online") Explanation: ``` .vh,K" ... "J1 .v Eval pyth code h Get the first item in list , Make a list of the next two items J1 Set J = 1 (J = 100 to 199 in future iterations) K" ... " Set K to the given string ``` And the code in the string is (breaking news shortened): ``` ?>J198"BNWE"s[".vh,K"N:KN+C92NN"J"?<J2*TT+J1 ? Ternary: If A then B else C >J198 Test if J > 198 "BNWE" String literal; If ternary was true, return this (which is then implicitly printed) s[".vh,K"N:KN+C92NN"J"?<J2*TT+J1 ternary else s concatenate list of strings [ create list ".vh,K" string literal, list[0] N N is set to the double-quote character, list[1] :KN+C92N list[2] : Regex substitution. In A, replace B with C K Variable K (set to the string being eval'd) N N is double-quote +C92N A backslash followed by a double-quote + concat two strings C92 character with code point 92 (backslash) N N is double-quote N N is double-quote, list[3] "J" String literal, list[4] ?<J2*TT+J1 Inner ternary, list[5] <J2 If J < 2 .. *TT return T * T (10 * 10), else +J1 return J+1 ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 193 bytes ``` x=>{var a=t>198?"BREAKING NEWS: WORLD ENDS":"x=>{{var a=t>198?{1}BREAKING NEWS: WORLD ENDS{1}:{1}{0}{1};Write(a,a,(char)34,t+(t<2?99:1));}};int t={2}";Write(a,a,(char)34,t+(t<2?99:1));};int t=1 ``` [Try it online!](https://tio.run/##Sy7WTS7O/O@YXJKZn2eTn5SVmlxil2b7v8LWrrossUgh0bbEztDSwl7JKcjV0dvTz13BzzU82Eoh3D/Ix0XB1c8lWMlKCaQYRXW1YS1O9UA5KyCuNqgFktbhRZklqRqJOok6GskZiUWaxiY6JdoaJTZG9paWVoaamta1tdaZeSUKJbbVRrVKRCiHqjb8b83FlaZhqGnN9R8A "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ I know you've always thought about the trials and tribulations of experiencing the joys of life as a web proxy. Honestly, who hasn't? Today you're tasked with realizing this goal (at least a part of it). Website X gets a lot of traffic on the daily and is looking for a PaaS (clearly this refers to Proxy as a Service) because of the large number of users who insist on passing sensitive information via query parameters (users are silly). Your task is to remove any and all sensitive query parameters from the request before forwarding the request through to its original destination. ## Input * A well-formed absolute HTTP URL that follows the URI grammar in [RFC3986 Section 3](https://www.ietf.org/rfc/rfc3986.txt). + You can assume there is no fragment + Brief format example where anything in square brackets denotes optional: `http[s]://[user:pass@]host.name.com[:port]/[?param1=value1&param2=value2...]` * A list of query parameters to be removed. ## Output The modified HTTP URL without the parameters defined in the input list. ## Examples ``` http://example.com/ [foo] > http://example.com/ http://example.com/?foo=bar [] > http://example.com/?foo=bar http://example.com/ [] > http://example.com/ http://example.com/?foo=1&bar=2&baz=3 [foo,baz] > http://example.com/?bar=2 http://example.com/?foo=1&bar=2&baz=3 [foo,bar,baz] > http://example.com/ http://example.com/?foo&bar=2&baz= [foo,baz] > http://example.com/?bar=2 http://example.com/?abc=1&def=2&baz=foo [foo,bar] > http://example.com/?abc=1&def=2&baz=foo http://example.com/?foobar=baz [foo] > http://example.com/?foobar=baz http://foo:[[email protected]](/cdn-cgi/l/email-protection):8080/?foo=1&bar=foo [foo] > http://foo:[[email protected]](/cdn-cgi/l/email-protection):8080/?bar=foo ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. [Answer] # GNU sed 98 96 88 80 77 74 69 59 54 (48 + 1 for -r) 49 ``` :;s,(.+)(=[^&]*[& ]|&)(.*)\1,\3 , t;s,[?&]? .*,, ``` The list of parameters to remove are separated by spaces. ``` $ echo 'http://example.com/?foo=1&bar=2&baz=3 foo bar baz' | sed -rf sed.txt http://example.com/ $ echo 'http://example.com/?foo&bar=2&baz= foo baz' | sed -rf sed.txt http://example.com/?bar=2 $ echo 'http://example.com/' | sed -rf sed.txt http://example.com/ ``` [Answer] ## JavaScript (ES6), ~~62~~ 60 bytes ``` f= (s,a,u=new URL(s))=>a.map(e=>u.searchParams.delete(e))&&''+u ; s.value=document.URL; ``` ``` <div oninput=o.textContent=f(s.value,a.value.split`\n`)><input id=s><br><textarea id=a></textarea><pre id=o> ``` Edit: Saved 2 bytes thanks to @Shaggy. [Answer] # PHP, 90 Bytes ``` <?=trim(preg_replace("#(?<=\?|&)(".join("|",$_GET[r]).")(=.*)?(&|$)#U","",$_GET[u]),"?&"); ``` -11 Bytes if ? or & is allowed at the end Previous Version 140 Bytes ``` <?=substr($u=$_GET[u],0,strpos($u,"?")+!!$j=join("&",preg_grep("#^(".join("|",$_GET[r]).")(=|$)#",explode("&",parse_url($u)[query]),1))).$j; ``` [Answer] # PHP, ~~120~~ 110 bytes with preg\_replace and array functions: (inspired by [Jörg](https://codegolf.stackexchange.com/q/93815#93815)) ``` <?=preg_replace(array_map(function($s){return"#(\\?|&)$s(=.*)?(&|$)#U";},array_slice($argv,2)),"\1",$argv[1]); ``` save to file, call with `php <scriptname> <uri> <parametername> <parametername> ...` with parse\_str and http\_build\_query (120 bytes): ``` parse_str(end($u=explode('?',$argv[1])),$a);for($i=$argc;$i-->1;)unset($a[$argv[$i]]);echo"$u[0]?".http_build_query($a); ``` run with `php -r <code> <uri> <parametername> <parametername> ...` [Answer] # Java 7, 127 bytes ``` String a(String a,String[]b){for(String c:b)a=a.replaceAll("(?<=[?&])"+c+"(=[^&]*)?(&|$)","");return a.replaceAll("[?&]$","");} ``` ## Explanation ``` String sanitize(String url, String[] params) { for (String param : params) { // please don't modify function parameters in real code url=url.replaceAll("(?<=[?&])" // Look for a leading ? or & but don't consume it + param // Consume the key of the query param (assuming key=value syntax) + "(=[^&]*)?" // Consume the value of the query param if it exists + "(&|$)",""); // Consume the trailing & unless we're at the end of the url and replace with nothing } url = url.replaceAll("[?&]$",""); // If we remove all of the params then we'll have a trailing ? which needs to be removed // If we remove the last param only then we could have a trailing & which also needs to be removed // We will only run into one of these scenarios return url; } ``` [Ideone](https://ideone.com/AQ9mnE) [Answer] # C#, ~~377~~ ~~336~~ ~~330~~ 328 bytes (173 alt) ``` string n(string u,string[]r){var s=u.Split('?');if(s.Length<2)return u;var a=s[1].Contains("&")?s[1].Split('&'):new string[]{s[1]};int B=a.Length,i=0,C=i,c=B;for(;i<B;i++)foreach(var R in r)if(R==a[i].Split('=')[0]){a[i]="";c--;}var t=s[0];t+=c>0?"?":"";for(i=0;i<a.Length;i++)if(a[i]!=""){t+=a[i];C++;if(C!=c)t+="&";}return t;} ``` Ungolfed full program: ``` using System; class a { static void Main() { string input = Console.ReadLine(); string url = input.Split(' ')[0]; string r = input.Split(' ')[1]; r = r.Replace("[", "").Replace("]",""); string[] remove = r.Split(','); a b = new a(); Console.WriteLine(b.n(url, remove)); } string n(string u,string[]r) { var s=u.Split('?'); if(s.Length<2)return u; var a=s[1].Contains("&")?s[1].Split('&'):new string[]{s[1]}; int B=a.Length,i=0,C=i,c=B; for(;i<B;i++) foreach(var R in r) if(R==a[i].Split('=')[0]) { a[i]=""; c--; } var t=s[0]; t+=c>0?"?":""; for(i=0;i<a.Length;i++) if(a[i]!="") { t+=a[i]; C++; if (C!=c)t+="&"; } return t; } } ``` Probably not very efficient, but it works I think. Alternatively, there is a 173 byte solution using @Poke's method from Java. Requires an import for Regex though, so probably can't be shorter. ``` using System.Text.RegularExpressions;string m(string a,string[]b){foreach(var c in b)a=Regex.Replace(a,$"(?<=[?&]){c}(=[^&]*)?(&|$)","");return Regex.Replace(a,"[?&]$","");} ``` [Answer] # Ruby, ~~146 140 127 119 116~~ 113 bytes edit 2: saved 6 bytes by using `$1`, `$2`, and `$*`, and 7 by changing `x.split("=")[0]` to `x[/\w+/]` edit 3: saved 6 bytes by using `*` instead of `.join`, saved 2 bytes from unnecessary spaces edit 4: saved 3 bytes by reformulating inline (changed regex to equivalent `$*[1][/([^?]*)\??(.*)/,1]` and put as assigned to `a`) edit 5: saved 3 bytes by using `($*[2].scan(r=/\w+/)&[x[r]])[0]` instead of `$*[2].scan(r=/\w+/).include?(x[r])` Assuming input to the program when running it: ``` a,b=$*[1][/([^?]*)\??(.*)/,1],$2.split("&").reject{|x|($*[2].scan(r=/\w+/)&[x[r]])[0]}*"&" puts(b[0] ?a+"?"+b: a) ``` ## Explanation ``` a,b=$*[1][/([^?]*)\??(.*)/,1],$2.split("&") ``` This parses the URL given on the command line, and stores the matches into `$1` and `$2`. `$*[1][/([^?]*)\??(.*)/,1]` also returns the first match to store inside `a`, while the second match is referred to as `$2` let a point to $1, and parse `b` into an array of arrays... ``` .reject { |x| ``` ...rejecting all that... ``` ($*[2].scan(r=/\w+/)&[x[r]])[0] ``` ...have a string before the '=' that is included in the list of names given by the second parameter... This works because we scan for words (to get the list) then get the word before the `=`, and see if that word is in the list with `&`. Since `&` returns an empty array on "not found" (the null set), we use the trick explained below to get `nil` if there are no elements in the array. otherwise we return a string, which counts as truthy, which rejects that string. ``` }*"&" ``` ...and join the remaining strings together with '&' At this point, `b` is the GET query string for the URL. Thus, we just need to print it. ``` puts(b[0] ?a+"?"+b: a) ``` This uses a trick in ruby. `b[0]` will be `nil` if b is an empty array or string. So if its *truthy*, (not `nil` or `false`), then there's at least one element in the array, so we need to puts `a+"?"+b` for the correct URL. otherwise, we just puts `a`, because there are no parameters to show Note: this answer assumes that `?` *cannot* appear anywhere except to delimit the URL from the query. (according to what I read from the linked RFC) Also, this is my first golf answer :D [Answer] ## [Pip](http://github.com/dloscutoff/pip), 46 bytes Takes the URL from stdin and the query parameters for removal from command-line args. ``` YgqR`\?.+`{s:J_@`^[^=]+`NIyFI@>a^'&[s&'?sJ'&]} ``` [Try it online!](http://pip.tryitonline.net/#code=WWdxUmBcPy4rYHtzOkpfQGBeW149XStgTkl5RklAPmFeJyZbcyYnP3NKJyZdfQ&input=aHR0cDovL2V4YW1wbGUuY29tLz9mb289MSZiYXI9MiZiYXo9Mw&args=Zm9v+YmF6) Explanation: ``` g Local variable containing list of cmdline args Y Yank into global variable y so it's available inside the function q Grab a line of stdin R`\?.+`{...} Do a regex replace of everything from ? on, using a callback function: s:J_@`^[^=]+`NIyFI@>a^'&[s&'?sJ'&] @>a^'& All but 1st char of match, split on & FI Filter on this function: _@`^[^=]+` Regex match: run of non = from beginning of string @ returns a list (here, of one item), so... J Join to get a scalar NIy True if match not in y; false if in y s: Assign the filtered list to s [ ] Return a list containing: s&'? ? if s is nonempty, [] otherwise sJ'& s joined on & When used as a replacement, a list is first stringified (which, in the absence of flags, means concatenated) ``` [Answer] ## PowerShell v3+, ~~115~~ 90 bytes ``` param($n,$z)$a,$b=$n-split'\?';($z|%{$b=$b-replace"(^|&)$_(=[^&]*)?(&|$)"});$a+"?"*!!$b+$b ``` Takes input `$n` as the URL and `$z` as a literal array of strings as the parameters to remove. `-split`s the input URL on `?`, stores the first half into `$a` and the second into `$b`. Next, `$b` is re-formulated by taking a loop through `$z`, performing a regex `-replace` on each banned query word to remove them. Then, outputs `$a` (unmodified), plus a `/` depending upon whether `$b` exists, plus a `?` depending upon whether `$x` exists, plus `$x. [Answer] # Pyth - 27 bytes Kenny was right when he talked about the builtin to transform and then invert, it'll be very hard to right, though. ``` .sjK\?mj\&f!}hcT\=Qcd\&czKK ``` [Test Suite](http://pyth.herokuapp.com/?code=.sjK%5C%3Fmj%5C%26f%21%7DhcT%5C%3DQcd%5C%26czKK&test_suite=1&test_suite_input=%5B%22foo%22%5D%0Ahttp%3A%2F%2Fexample.com%2F%0A%5B%5D%0Ahttp%3A%2F%2Fexample.com%2F%3Ffoo%3Dbar%0A%5B%5D%0Ahttp%3A%2F%2Fexample.com%2F%0A%5B%22foo%22%2C+%22baz%22%5D%0Ahttp%3A%2F%2Fexample.com%2F%3Ffoo%3D1%26bar%3D2%26baz%3D3%0A%5B%22foo%22%2C+%22bar%22%2C+%22baz%22%5D%0Ahttp%3A%2F%2Fexample.com%2F%3Ffoo%3D1%26bar%3D2%26baz%3D3%0A%5B%22foo%22%2C+%22baz%22%5D%0Ahttp%3A%2F%2Fexample.com%2F%3Ffoo%26bar%3D2%26baz%3D%0A%5B%22foo%22%2C+%22bar%22%5D%0Ahttp%3A%2F%2Fexample.com%2F%3Fabc%3D1%26def%3D2%26baz%3Dfoo%0A%5B%22foo%22%5D%0Ahttp%3A%2F%2Fexample.com%2F%3Ffoobar%3Dbaz%0A%5B%22foo%22%5D%0Ahttp%3A%2F%2Ffoo%3Afoo%40foo.com%3A8080%2F%3Ffoo%3D1%26bar%3Dfoo&debug=0&input_size=2). [Answer] ## [Retina](https://github.com/m-ender/retina), ~~44~~ 48 bytes *Crossed-out 44 is still 44. Thanks to Martin for the fix.* ``` [?&](?>([^ =&]+))[^ &]*(?=.* \1( |$))| .* /& /? ``` Takes input like `uri param1 param2`. [Try it online!](http://retina.tryitonline.net/#code=Wz8mXSg_PihbXiA9Jl0rKSlbXiAmXSooPz0uKiBcMSggfCQpKXwgLioKCi8mCi8_&input=aHR0cDovL2V4YW1wbGUuY29tLz9mb28mYmFyPTImYmF6PSZ-fn5-PTQgZm9vIGJhIGJheiB-fn5-) ### Explanation The first replacement deletes the appropriate parameters from the query string. `[?&](?>([^ =&+))[^ &]*` matches a `?` or `&`, a full parameter name, and (optionally) `=` and a value, storing the parameter name in capture group 1. Then `(?=.* \1( |$))` is a lookahead that checks whether that parameter name appears in the list of parameters to delete. If a parameter matches these conditions, it is removed (substituted with an empty replacement). Substitutions are non-overlapping (thanks to the lookahead) and proceed from left to right. On reaching the end of the URL, the `.*` branch matches the list of parameters to delete and removes it as well. The second replacement just makes sure the new query string starts with `?` if the first parameter was deleted. [Answer] # Java 7, 203 bytes ``` String f(String u,List p)throws Exception{String[]g=u.split("\\?",2);String s="";if(g.length>1)for(String q:g[1].split("&")){if(p.indexOf(q.split("=")[0])<0){s+=s.isEmpty()?"?":"&";s+=q;}}return g[0]+s;} ``` Ungolfed: ``` String f(String u, List p) throws Exception { String[] g = u.split("\\?", 2); String s = ""; if (g.length > 1) for (String q : g[1].split("&")) { if (p.indexOf(q.split("=")[0]) < 0) { s += s.isEmpty() ? "?" : "&"; s += q; } } return g[0] + s; } ``` This function passes all of the tests. [Answer] # Python, ~~75~~ ~~81~~ 112 bytes: ``` def Z(A,S):import re;F=A.rindex('/');print A[:F]+re.sub('|'.join(i+'(=\d?|&)&?'for i in S),'',A[F:]).strip('&?') ``` A named function. Takes input in the format ``` D(<String>,<Array>) ``` and outputs a string. [Repl.it With All Test Cases!](https://www.repl.it/DeIw/1) [Answer] # PHP, not competing Heck, PHP was made for this; why not use the actual URL? ``` <?foreach($_GET[x]as$w)unset($_GET[$w]); echo http,s[$_SERVER[SERVER_PORT]-443],"://", $u=$_SERVER[PHP_AUTH_USER],($p=$_SERVER[PHP_AUTH_PW])?":$p":"","@"[!$u&!$p], "$_SERVER[HTTP_HOST]$_SERVER[SCRIPT_NAME]?",http_build_query($_GET); ``` Save to file, call with your wanted query string plus `&x[]=x&x[]=<exclude1>&x[]=<exclude2>&...`. May fail on username and password (depending on wether your browser removes them or not). *Will* fail if password is `0`. ]
[Question] [ Some people say curiosity killed the cat. Other say it was the box and poison. The RSPCA say Erwin Schrödinger needs to lose the right to own pets. With animal rights activists outside his house. The ~~cat murderer~~ scientist Schrödinger has finally come up with his greatest invention. A special, radioactive mix of unobtanium and handwavium that can have any half life, and a single gram of the product is capable of killing any living creature. Unfortunately, when he tried to test it on his final cat: Bob, he forgot that cats have 9 lives, and so would need 9 grams to kill. With some water but no food, poor Bob will live exactly 1 week (7 days) if the product doesn't kill him first. The task: Given an input of a mass in milligrams and a half-life in milliseconds - both integers which can exceed 2^31, write a program that outputs whether or not the mystery super product kills the cat, or if it's 1 week time limit expires first. Assume true/yes/1/anything specified in the answer is for when he does not die from starvation. For the product to kill him, a total of 9 grams must decay. So out of a sample of 18 grams, 1 half-life must pass. If the sample contains less than or equal to 9 grams, this will never be achieved, and so it can be immediately assumed 1 week will pass before 9 grams decays. You may assume: * Bob dies the microsecond 9 grams has decayed. * The change is mass due to decay does not matter. * All days and times follow generally accepted earth time. * The box Bob is sealed in is unbreakable and unopenable, so there is no chance of death from other causes. * Oxygen is also no issue. * If both happen at the exact same time either output is acceptable. * All inputs should be below 2^63-1 Test cases: Example: ``` 18000 604800001 ``` For 9 grams to decay, exactly 1 half life must pass (18000/2 = 9000 milligrams or 9 grams). 1 half life is 604800001 milliseconds, or 168 hours and 1 millisecond, or exactly 1 week and 1 millisecond. Since Bob dies of hunger at exactly 1 week, the output is false as he died from hunger just before the 9 gram product limit was reached ``` 8000 40000 false 70000 800 true 18000 604800000 either 18000 604800001 false 18000 604799999 true 1 1 false 100000 1 true 1000000000 1000000000 true ``` Scoring: Naturally we want Bob's suffering to end quickly, and so a shorter half-life is best. Half-life and byte both end in E, so clearly the shortest byte count wins. [Answer] # Python 3, 33 bytes ``` lambda a,b:a-a*.5**(6048e5/b)>9e3 ``` Explanation: ``` 6048e5 # number of milliseconds in 1 week /b # half-lifes per week a*.5**( ) # mgs of substance remaining after 1 week a- # mgs of substance decayed after one week >9e3 # return true if more than 9000mgs has decayed in 1 week ``` [Try here](http://ideone.com/0YJqBy) [Answer] ## CJam (22 bytes) ``` q~dX.5@6048e5\/#-*9e3> ``` [Online demo](http://cjam.aditsu.net/#code=q~dX.5%406048e5%5C%2F%23-*9e3%3E&input=70000%20800) ### Dissection A quick explanation of the maths: if the halflife is `λ` then after time `t` the proportion of the radioactive material remaining is `(1/2)^(t/λ)`, so the proportion decayed is `1 - (1/2)^(t/λ)`. ``` q~d e# Parse input, ensuring that the later division will use doubles X.5@6048e5\ e# Rearrange stack to: m 1 0.5 6048e5 λ /#-* e# Div, pow, sub, mul, giving the total mass decayed after a week 9e3> e# Is it OVER 9000! ? ``` [Answer] # Fourier, 51 bytes I have to admit that I don't fully understand this program... Mainly just a translation of TheNumberOne's Python code. ``` oI~M~NI~H604800000~G>H{1}{G/H^(M/2~Mi^~i)N-M>9000@o} ``` Note this is the first program that I've written for PPCG which uses `@`, the clear output function. [**Try it online!**](http://fourier.tryitonline.net/#code=b0l-TX5OSX5INjA0ODAwMDAwfkc-SHsxfXtHL0heKE0vMn5NaV5-aSlOLU0-OTAwMEBvfQ) [Answer] ## Actually, 20 bytes ``` 5╤:6048*/1½ⁿ1-*93╤*< ``` [Try it online!](http://actually.tryitonline.net/#code=NeKVpDo2MDQ4Ki8xwr3igb8xLSo5M-KVpCo8&input=MTgwMDAKNjA0ODAwMDAw) Explanation: ``` 5╤:6048*/1½ⁿ1-*93╤*< 5╤ 10**5 :6048 6048 * 6048*10**5 (milliseconds in 1 week) / divide by half-life 1½ⁿ (1/2)**(^) 1- 1-(^) (% of sample decayed after 1 week) * multiply by sample mass (mass decayed after 1 week) 93╤* 9*10**3 (9000) < is 9000 < sample mass decayed? ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 19 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` 9E3≤⊣-⊣×.5*6048E5÷⊢ ``` `9E3≤` is 9000 smaller than or equal to `⊣-` the left argument (mass) minus `⊣×` the left argument times `.5*`  ½ to the power of `6048E5÷⊢` 604800000 divided by the right argument (half-life) No need for parentheses, as APL is strictly right-to-left. [TryAPL online!](http://tryapl.org/?a=f%u21909E3%u2264%u22A3-%u22A3%D7.5*6048E5%F7%u22A2%20%u22C4%20f/%A8%288000%2040000%29%2870000%20800%29%2818000%20604800000%29%2818000%20604800001%29%2818000%20604799999%29%281%201%29%28100000%201%29%281000000000%201000000000%29&run) ]
[Question] [ You will be given a (possibly empty) string containing brackets (`[{()}]`) and any other characters (`A`-`Z`, `a`-`z`, `0`-`9`, punctuation). You need to check if it adheres to the following rules: * Non-bracket characters are ignored. * Every open bracket `[{(` has a closing bracket `)}]`. So `[](` is not allowed. * Brackets are nested properly. `[(])` is not allowed. * Curly brackets cannot contain square brackets within them. Simple brackets cannot contain either curly or square brackets within them. So `[({})]`, `[{[]}]` and `({})` are not allowed. Brackets can be nested with similar brackets, so `[[{((()))}{{(())}}]()]{()}` is allowed. Output is a single truthy/falsey value as per your choice. **Shortest code wins.** --- **Test cases** `b[[a{(/)}(())+={{}-}],]` -> Valid `([h][e][l][l][o])` -> Invalid `[///[{(\/(arg()))}1{{((-)-2)}}]()]{()}` -> Valid `hi` -> Valid [Answer] ## [Retina](https://github.com/mbuettner/retina), 84 bytes ``` ^([^][}{)(]|()\(|(?<-2>)\)|(?!\2)((){|(?<-4>)}|(?!\4)(()\[|(?<-6>)])))*$(?!\2|\4|\6) ``` [Try it online.](http://retina.tryitonline.net/#code=bWBeKFteXVt9eykoXG5dfCgpXCh8KD88LTI-KVwpfCg_IVwyKSgoKXt8KD88LTQ-KX18KD8hXDQpKCgpXFt8KD88LTY-KV0pKSkqJCg_IVwyfFw0fFw2KQp2YWxpZAptYF4oPyF2YWxpZCkuKgppbnZhbGlk&input=W1t7KCgoKSkpfXt7KCgpKX19XSgpXXsoKX0KW3soKX1dCmJbW2F7KC8pfSgoKSkrPXt7fS19XSxdClsvLy9beyhcLyhhcmcoKSkpfTF7eygoLSktMil9fV0oKV17KCl9CmhpCgpbKF0pCihbKV0KWyh7fSldClt7W119XQooe30pCihbaF1bZV1bbF1bbF1bb10p) This is a fairly straight-forward (but golfed) extension [of the basic parentheses-checking .NET regex](https://stackoverflow.com/questions/17003799/what-are-regular-expression-balancing-groups/17004406#17004406). While this is quite possible with balancing groups, [Perl's recursion definitely has the edge here](https://codegolf.stackexchange.com/a/65569/8478). However, either approach is beaten by ditching the elegance of a single regex match in favour of reducing the input gradually via repeated substitutions, [as Digital Trauma's sed answer does](https://codegolf.stackexchange.com/a/65567/8478). This can be implemented in 34 bytes in Retina, but I'm hesitant to post the code myself, as I didn't come up with the idea. [Answer] # Retina, 34 Firstly, credit where credit is due: * @ןnɟuɐɯɹɐןoɯ who [first posted this approach](https://codegolf.stackexchange.com/a/65545/11259). * @MartinBüttner who [suggested this exact answer](https://codegolf.stackexchange.com/questions/65526/bracket-balancing#comment158702_65567) but was too good of a sportsman not to post it himself. I independently (later) came up with [the same approach in sed](https://codegolf.stackexchange.com/a/65567/11259), so I hope I'm not treading on any toes ([big](http://meta.codegolf.stackexchange.com/questions/5828/the-many-memes-of-ppcg/5844#5844) or otherwise) by posting this: ``` [^][(){}] +`\(\) +`{} +`\[] ^$ ``` So now with a `sudo apt-get install mono-complete` and `git clone https://github.com/mbuettner/retina.git` I have a working retina on my Ubuntu VM. Here's the test output: ``` $ while read; do echo "Input: \"$REPLY\", Ouput: $( mono Retina.exe -s brbal.ret <<< "$REPLY" )" ; done < ../brbal.txt Input: "[[{((()))}{{(())}}]()]{()}", Ouput: 1 Input: "b[[a{(/)}(())+={{}-}],]", Ouput: 1 Input: "[///[{(/(arg()))}1{{((-)-2)}}]()]{()}", Ouput: 1 Input: "hi", Ouput: 1 Input: "", Ouput: 1 Input: "", Ouput: 1 Input: "([h][e][l][l][o])", Ouput: 0 Input: "[](", Ouput: 0 Input: "[(])", Ouput: 0 Input: "[({})]", Ouput: 0 Input: "[{[]}]", Ouput: 0 Input: "({})", Ouput: 0 $ ``` [Answer] # Sed, 53 ``` s/[^][(){}]//g :;s/()//;t :b;s/{}//;tb :c;s/\[\]//;tc ``` Here I am claiming that since `sed` does not really have a concept of truthy/falsey, then I am defining the empty string to mean truthy and all other strings to mean falsey. If that is not acceptable, then we can add a couple of lines, thus: # Sed, 66 ``` s/[^][(){}]//g :;s/()//;t :b;s/{}//;tb :c;s/\[\]//;tc /./c0 /^$/c1 ``` This outputs 0 for false and 1 for true. [Answer] # CJam, ~~27~~ 26 bytes ``` "(){}[]"q1$f&_,@2/e*{/s}/! ``` This prints **1** (truthy) or **0** (falsy). [Try it online!](http://cjam.tryitonline.net/#code=Iigpe31bXSJxMSRmJl8sQDIvZSp7L3N9LyE&input=W1t7KCgoKSkpfXt7KCgpKX19XSgpXXsoKX0) or [verify all test cases.](http://cjam.tryitonline.net/#code=cU4vewogICIoKXt9W10iUTEkZiZfLEAyL2Uqey9zfS8hCk59ZlE&input=W1t7KCgoKSkpfXt7KCgpKX19XSgpXXsoKX0KW3soKX1dCmJbW2F7KC8pfSgoKSkrPXt7fS19XSxdClsvLy9beyhcLyhhcmcoKSkpfTF7eygoLSktMil9fV0oKV17KCl9CmhpCgpbKF0pCihbKV0KWyh7fSldClt7W119XQooe30pCihbaF1bZV1bbF1bbF1bb10p) ### How it works ``` "(){}[]" Push that string. q Read all input and push it on the stack. 1$ Copy the bracket string. f& Intersect each input character with the bracket string. This pushes an array of singleton and empty strings. _, Get the length of the array (L), i.e., the number of characters in the original input. @ Rotate the bracket string on top of the stack. 2/ Split it into ["()" "{}" "[]"]. e* Repeat each character pair L times. { }/ For each character pair. / Split the string on the stack at occurrences of that character pair. This dosn't work properly the first time, since there's a string array on the stack. s Flatten the resulting array of strings. ! Apply logical NOT. ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 43 chars / 62 bytes ``` !Մ(Մ(Մ(ïċ/⁅⬮[\]{}]⌿),`⬮`,⬯),`{}`,⬯),`[]`,⬯) ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=%28[h][e][l][l][o]%29&code=!%D5%84%28%D5%84%28%D5%84%28%C3%AF%C4%8B%2F%E2%81%85%E2%AC%AE[%5C]%7B%7D]%E2%8C%BF%29%2C%60%E2%AC%AE%60%2C%E2%AC%AF%29%2C%60%7B%7D%60%2C%E2%AC%AF%29%2C%60[]%60%2C%E2%AC%AF%29)` Nope. --- However, if I use newly implemented features, I can get down to 28 chars / 47 bytes: ``` !ïċ/⁅⬮[\]{}]⌿)ė`⬮”ė`{}”ė`[]” ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~42~~ 37 bytes *Saved 5 bytes with a feature I didn't realize my own language had... Thanks for adding it, @Downgoat!* Japt really needs better RegExp support... ``` !Uo"()[\\]\{}" e"\\(\\)" e"\{}" e"\\[] ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=IVVvIigpW1xcXVx7fSIgZSJcXChcXCkiIGUiXHt9IiBlIlxcW10=&input=ImJbW2F7KC8pfSgoKSkrPXt7fS19XSxdIg==) ### How it works ``` // Implicit: U = input string Uo"()[\\]\{}" // Remove all non-bracket. e"\\(\\)" // Recursively remove all pairs of simple brackets. e"\{}" // Recursively remove all pairs of curly brackets. e"\\[] // Recursively remove all pairs of square brackets. ! // Return the Boolean NOT of the result. // (true for empty string, false for anything else) // Implicit: output last expression ``` [Answer] # C99, ~~226~~ ~~208~~ 207 Bytes This is my first time ever trying to golf something ``` #define S s[i] t(s,i)char*s;{int a[]={['[']=0,['{']=0,['(']=0};for(i=0;S*!(S=='{'&a['(']|S=='['&(a['(']|a['{'])|S==']'&(a['(']|a['{'])|S=='}'&a['(']);i++)a[S]++,a[S-S/90-1]--;return !(a['[']+a['{']+a['(']);} ``` Readable: ``` int t(char* s){ int a[265]={['[']=0,['{']=0,['(']=0}; for(int i=0;s[i]&&!((s[i]=='{'&a['(']>0)|(s[i]=='['&(a['(']>0|a['{']>0))|(s[i]==']'&(a['(']>0|a['{']>0))|(s[i]=='}'&a['(']>0));i++){ a[s[i]]++; a[s[i]-(s[i]/90+1)]--; } return !(a['[']+a['{']+a['(']); } ``` There is a buffer overflow but it doesnt seem to affect anything - I believe this is due to alignment. [Answer] ## Perl, 50 + 1 = 51 bytes ``` $_=/^((([^][)(}{]|\((?3)*\))|{(?2)*})|\[(?1)*])*$/ ``` Requires the `-p` flag and prints `1` for truthy and nothing for falsy results. I'm counting `-p` as one, because it can be combined with `-e`: ``` > perl -pe '$_=/^((([^][)(}{]|\((?3)*\))|{(?2)*})|\[(?1)*])*$/' ``` The code is basically just a plain regex match against the input, using Perl's nifty recursive regex feature. Thanks to Dennis for helping me test this and golf the Perl boilerplate. [Answer] # Python 3 : 120 bytes Building on [@Adnan's answer](https://codegolf.stackexchange.com/a/65539/32047), re proved shorter to use: ``` import re x=re.sub('[^[\](){}]','',input()) for i in('()','{}','[]'): while x.find(i)>=0:x=x.replace(i,'') print(x=='') ``` [Answer] # Python 3, ~~196~~ ~~170~~ ~~160~~ 154 bytes Awkwardly long, thanks to Mego for saving 6 bytes: ``` d=y="" for C in input(): for a in "[](){}":y+=C*(C==a) y=y.replace("()",d) x=y for r in y:x=x.replace("{}",d) for s in y:x=x.replace("[]",d) print(x==d) ``` ]
[Question] [ Let's play a one-player game called *jump the array*. To play, you only need an array of integers, say `a`. You start at some position `i`, and on each turn, you jump to a new position. On turn `n`, * if `n` is even, you jump to the absolute position `a[i] mod length(a)`, * if `n` is odd, you jump to the relative position `(i + a[i]) mod length(a)`. The array indexing starts at zero. You can count the first jump as turn `0` or turn `1`, which give a different game. Since the state space of the game is finite (your move is determined by your position and the parity of the turn number), you will of course eventually enter a loop of even length. Denote by `loop(a, i, b)` the length of this loop, when the first jump is counted as turn `b`. # Input A nonempty array `a` of integers to play the game with. # Output The maximum number `p` such that, when starting on some position `i` and counting the first turn as either `0` or `1`, you eventually enter a loop of length `2 * p`. In other words, your output is the number ``` max { loop(a, i, b)/2 : i in [0 .. length(a)-1], b in [0,1] } ``` # Rules You can give a function or a full program. The smallest byte count wins, and standard loopholes are disallowed. # Test cases ``` [0] -> 1 [-213] -> 1 [1,3,12,-1,7] -> 1 [2,3,5,7,9,11,13,17,19] -> 2 [-2,3,-5,7,-9,11,-13,17,-19,23,-27] -> 3 [0,2,5,4,-9,0,-1,1,-1,1,-6] -> 4 ``` [Answer] # Python - 157 ``` a=input() z=len(a) b=[] for i in range(z): s,c,t=[],"",0 while(c in s[:-1])-1:j=(i*t+a[i])%z;c=`t`+`i`;s+=[c];t^=1 b+=[len(s)-s.index(c)-1] print max(b)/2 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth): 28 character (Python 2: 116 character) ``` eSmhxtu+G%@Q+eG@QeGlQUQ]ddUQ ``` ## Usage: Try it here: [Pyth Compiler/Executor](https://pyth.herokuapp.com/) It expects a list of integers as input `[0,2,5,4,-9,0,-1,1,-1,1,-6]` ## Explanation: I noticed one important property of the function `loop`: For each `i` there is a `j`, so that `loop(a,i,0) == loop(a,j,1)` and vice versa. Therefore we only need to compute the values `loop(a,i,b)` for `b=0`. Proof: If the is a cycle `i -> j -> k -> ... -> z -> i` with `b = 0`, then there exists the cycle `j -> k -> ... -> z -> i -> j` with `b = 1`. Therefore a simple script can work the following way. Iterate over all `i` and try to reach `i` by iteratively computing `i = a[(i + a[i]) mod len(a)] mod len(a)`. Since this computation may ran into a cycle without `i`, we cancel the computation after `len(a)` steps. Then we print the maximum cycle. A **Python 2** implementation looks like this (**125 character**}: ``` a=input();A=len(a);m=[] for i in range(A): j=i for c in range(A): j=a[(j+a[j])%A]%A if i==j:m+=[c+1];break print max(m) ``` For the pyth implementation I used a little different approach. For each `i` I compute the list of positions, and look for `i` in this list. ``` eSmhxtu+G%@Q+eG@QeGlQUQ]ddUQ m UQ for each d in [0, ..., len(input)-1] compute a u ]d list G (using reduce), which is first initialized with G = [d] UQ for each H in [0, ..., len(input)-1]: +G append to G the value %@Q+eG@QeGlQ input[G[-1] +input[G[-1]] % len(input) (notice that list lookups in pyth work with modular wrapping) t remove the first value (which is d) x d and find the index of d in this shortend list (it's -1, if d is not in the list) h add 1 eS print the maximum (end of sorted list) ``` ## edit: Python 2: 116 characters @proud haskeller's solution was i few characters shorter than my Python solution, therefore I 'had' to shorten it a bit. ``` a=input();A=len(a);l=lambda j,i,c:c<=A and(c*(i==j)or l(a[(j+a[j])%A]%A,i,c+1));print max(l(i,i,0)for i in range(A)) ``` The difference is, that I calculate the number recursively instead of iteratively. [Answer] # Haskell, ~~120~~ 105 ``` f s|t<-l s=maximum[g$drop t$iterate(\i->s!!mod(i+s!!mod i t)t)i|i<-s] g(x:s)=l$0:fst(span(/=x)o) l=length ``` this generates an infinite list for each starting point (for golfing reasons we iterate over all values instead of all indexes, which are equivalent). then it calculates the cycle of each list (the cycle length of `xs` is `xs % []`). it uses @jakubes's observations about cycles. because it steps 2 steps at a time, we don't need to divide by 2 at the end. **Edit**: now using @MthViewMark's trick of dropping the first `n` elements to guarantee having a cycle with the first element. by the way, I managed to golf his algorithm to `112` characters: ``` l=length o(x:y)=1+l(takeWhile(/=x)y) j a|n<-l a=maximum$map(o.drop n.iterate(\i->mod(a!!mod(i+a!!i)n)n))[0..n-1] ``` [Answer] ## Haskell - 139 characters ``` l=length o(x:y)=1+l(takeWhile(/=x)y) j a=maximum$map(o.drop n.iterate(b!!))[0..n-1] where b=zipWith(\x y->mod(a!!mod(x+y)n)n)a[0..];n=l a ``` Examples: ``` λ: j [0] 1 λ: j [-213] 1 λ: j [1,3,12,-1,7] 1 λ: j [2,3,5,7,9,11,13,17,19] 2 λ: j [-2,3,-5,7,-9,11,-13,17,-19,23,-27] 3 λ: j [0,2,5,4,-9,0,-1,1,-1,1,-6] 4 ``` This makes use of @jakube's observation that you need only check half the starting values, while performing 2 step per iteration. [Answer] # Python, 160 ``` l=lambda a,b,c,d:(b,c)in d and len(d)-d.index((b,c))or l(a,(a[b]+[0,b][c])%len(a),~c,d+[(b,c)]) j=lambda a:max(l(a,b,c,[])for b in range(len(a))for c in(0,1))/2 ``` Function for answer is `j`. The recursive function `l` returns the loop length for a given array, start, and first turn, and the function `j` finds the max. [Answer] # Mathematica, ~~189 162~~ 161 bytes If anonymous functions are allowed - 161 bytes: ``` Max[l=Length;Table[b={};n=p;i=s-1;e:={i,n~Mod~2};While[b~Count~e<2,b~AppendTo~e;h=#[[i+1]];i=If[EvenQ@n++,h,i+h]~Mod~l@#];l@b-b~Position~e+1,{s,l@#},{p,0,1}]/4]& ``` Otherwise - 163 bytes: ``` f=Max[l=Length;Table[b={};n=p;i=s-1;e:={i,n~Mod~2};While[b~Count~e<2,b~AppendTo~e;h=#[[i+1]];i=If[EvenQ@n++,h,i+h]~Mod~l@#];l@b-b~Position~e+1,{s,l@#},{p,0,1}]/4]& ``` Running this on all the test-cases: ``` f /@ { {0}, {-213}, {1, 3, 12, -1, 7}, {2, 3, 5, 7, 9, 11, 13, 17, 19}, {-2, 3, -5, 7, -9, 11, -13, 17, -19, 23, -27}, {0, 2, 5, 4, -9, 0, -1, 1, -1, 1, -6} } ``` Results in: ``` {1, 1, 1, 2, 3, 4} ``` # Python 2, 202 bytes ``` def l(a,n,i): b=[] while not[i,n]in b:b.append([i,n]);i=(a[i]if n<1 else i+a[i])%len(a);n+=1;n%=2 return len(b)-b.index([i,n]) def f(a):print max([l(a,n,i) for n in[0,1]for i in range(len(a))])/2 ``` **[DEMO](http://repl.it/7RA)** This is nearly a port of my Mathematica answer. [Answer] # Mathematica, ~~113~~ 112 chars ``` l=Length;m=MapIndexed;f=Max[l/@ConnectedComponents@Graph@m[Tr@#2->#&,Part@@Thread@Mod[#+{Tr@#2,1}&~m~#,l@#,1]]]& ``` Example: ``` f /@ { {0}, {-213}, {1, 3, 12, -1, 7}, {2, 3, 5, 7, 9, 11, 13, 17, 19}, {-2, 3, -5, 7, -9, 11, -13, 17, -19, 23, -27}, {0, 2, 5, 4, -9, 0, -1, 1, -1, 1, -6} } ``` > > {1, 1, 1, 2, 3, 4} > > > [Answer] # ised 82 ``` ised '@1{0,2,5,4,-9,0,-1,1,-1,1,-6};@2{1};' '@{4 5}{(@3{:$1_x++x*@2{1-$2}:}2*#$1)::[#$1]};{1+?{:@5{$3::$5}=$4:}@::[2*#$1]_0}/2' ``` The first argument doesn't count into length (array initialization into `$1` and `b` initialization into `$2` - select the "game"). ]
[Question] [ The cardinality of the set \$\mathbb Q\$ of rational numbers is known to be exactly the same as that of the set \$\mathbb Z\$ of integers. This means that it is possible to construct a bijection between these sets—a mapping such that each integer corresponds to exactly one rational number, and vice versa. Provide such a bijection from \$\mathbb Z\$ to \$\mathbb Q\$. You may choose to use as the domain any contiguous subset of the integers instead of the whole of \$\mathbb Z\$. For example, you could instead choose a domain of \$\{\cdots,5,6,7\}\$ (integers \$\le 7\$) or \$\{0,1,2,\cdots\}\$ (like a 0-indexed infinite list), but not \$\{1,2,3,5,8,\cdots\}\$. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` ⌊d-‹Ė)1Ḟ:NY‹ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIpkLeKAucSWKTHhuJ46TlnigLkiLCIiLCIiXQ==) A completely different tactic, using an alternating form of the [Calkin-Wilf](https://en.wikipedia.org/wiki/Calkin%E2%80%93Wilf_tree#Breadth_first_traversal) sequence inspired by [Jordan's answer](https://codegolf.stackexchange.com/a/253718/100664). Append an `i` if outputting an infinite sequence is not allowed. ``` Ḟ # Generate a sequence... 1 # Starting with 1 -----) # Each value is the previous value n, put into the following... ⌊ # floor(n) d # 2 * floor(n) - # n - 2 * floor(n) ‹ # n - 2 * floor(n) - 1 Ė # 1 / (n - 2 * floor(n) - 1) Y # Interleave with :N # The sequence negated ‹ # Decrement every term to add a 0 ``` [Answer] # [J](https://www.jsoftware.com), ~~21~~ 16 bytes ``` **|1&(1%+-2*|)-~ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxQUurxlBNw1BVW9dIq0ZTtw4ivFmTKzU5I19BQydNU81OIdPK1KACIrNgAYQGAA) Uses the Calkin-Wilf generator. The domain is full \$\mathbb{Z}\$. `f(n) = CalkinWilf(n)` and `f(-n) = -f(n)` for `n>=0`. The input must be given as a bigint. ``` **|1&(1%+-2*|)-~ input: n, bigint | abs(n) &( )-~ repeat ^ times, starting from bigint zero: 1& 1%+-2*| 1/((1 + x) - 2 * frac(x)) ** multiply sign(n) to ^ ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~67~~ 50 bytes -17 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) This is the [Calkin-Wilf sequence](https://en.wikipedia.org/wiki/Calkin%E2%80%93Wilf_tree#Breadth_first_traversal) but mapped to the negative rationals for negative inputs, plus \$f(0) = 0\$. ``` F=->n{n<1?0:(m=F[n-1] n%2>0?1r/(1-2*m.ceil+m):-m)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN43cbHXt8qrzbAztDaw0cm3dovN0DWO58lSN7AzsDYv0NQx1jbRy9ZJTM3O0czWtdHM1a6E69TUM9PQMDQw09VITkzMUUvK5FBQKSkuKFZSUq-MNaxVs7RSUq92i4w1ja5W4UvNSINpgFgMA) ## Ruby, 40 bytes This is the Calkin-Wilf sequence for positive inputs/outputs only. ``` F=->n{n<2?1:1r/(2*(m=F[n-1]).floor+1-m)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWNzXcbHXt8qrzbIzsDa0Mi_Q1jLQ0cm3dovN0DWM19dJy8vOLtA11czVroeoVNQz19AwNDDT1UhOTMxRS8rkUFApKS4oV3KLjDWO5UvNSIAphFgAA) [Answer] # [R](https://www.r-project.org), ~~71~~ 66 bytes ``` f=\(x,n=abs(x))`if`(n,c(sum(m<-f(n-1))-2*m[2]%%m[1],x/n*m[1]),1:0) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY1BCoMwEEXvEhBmZILGbkpoNl4jCqahAcGkwSjYs3STLrrpjXqbUipd_bd5798fc37NZhmvwUxJPdfF8eO7daqDjYIy5wQb4jC6AQJZSKsHf-IOAheIvCm9bvqi8Fr0tFWh_AKSkDXupYM1CyQT43QDLmopavq_oW6koJ7SJSoLrGLEusBwV3P-7Qc) Outputs rational numbers represented as vectors of (*denominator*, *numerator*). --- # [R](https://www.r-project.org), 67 bytes ``` \(x,y=rle(intToBits(2*abs(x)+1))$l)sign(x)*head(c(y[1]-1,y[-1]),-1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZAxbsMgFIbVqQqnQEkHSLBqMlWRWNordEujiDo4IFNswYsbq8pJuqRDD9WepuA4SqYuwM_3v__B-_zyx9-b2wkuagdrqNellwUud64AU7t02yoPocfG7dQGJ0PPvGq8CsqB7CXUOJi3xqqLw9Unhq7DBSrFOZ-0TAu-yFkl8gWnH2hkSmKV24ImLU16pEVB2iVfTXVcZno5X7F0ohFVZ1QlVCVUDaiMIOPRyqooD1jZoHAjA6icpHI2vh8P5gNCvn-ltOJ7B2X28PP0QvasE94qYhw8148GAplP5WsgezrjlN5ZGszWRTXVSm5IQbqYlXHWpa6UZZwOUSvpggiyaWxHMh4_mbNzN4oiQxP8bkD_MzoJZKiPdnY9STo0OR5P-x8) Outputs rational numbers represented as [continued fractions](https://en.wikipedia.org/wiki/Continued_fraction). Works by calculating element i of the [Calkin–Wilf sequence](https://en.wikipedia.org/wiki/Calkin%E2%80%93Wilf_tree) using the [run-length encoding of the binary representation](https://en.wikipedia.org/wiki/Calkin%E2%80%93Wilf_tree#Breadth_first_traversal) of i. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes ``` ›"ƛȧ‹*[½₍⌊⌈Uvx∑;÷ȧ" ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oC6XCLGm8in4oC5KlvCveKCjeKMiuKMiFV2eOKIkTvDt8inXCIiLCIiLCItNFxuLTNcbi0yXG4tMVxuMFxuMVxuMlxuM1xuNCJd) A mess. Uses the Stern-Brocot sequence and works in theory... Given an integer, outputs a pair of integers. ``` ›" # [n, n+1] ƛ ; # Map to... [ # If .... ȧ‹ # |a| - 1 * # * a ½ # Then take a/2 ₍⌊⌈ # [floor(a/2), ceil(a/2) U # Uniquify (if even, just n/2) vx # Recurse on each ∑ # Sum ÷ȧ" # Take the absolute value of the second. ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~69~~ 67 bytes -2 bytes from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) ``` f=lambda i,m=1,n=1:i>3and f(i//2,m+i%2*n,n+~i%2*m)or(-~i*2%3*m-m,n) ``` [Try it online!](https://tio.run/##JYxBCoMwEEXXeopshBkdq9FNEdK7RKLtQDNK4sJuvHqa0t3778PbP8drk/G@h5RW87Z@dlYxeaNJjJ74MVpxagXuuoF8w9VQC0lz/cDjFqC9uB6qsfatJ8EUlVFxOQDLdQuKFYsKVp4LaNJ9j1NZnCbXsCz2wHIA08ySN51ZxZt1DjL9v/ciEBHTFw "Python 3.8 (pre-release) – Try It Online") Maps \$\{1,2,\ldots,\}\$. Represents fractions as pairs of integers; \$0\$ represented as \$(0,1)\$. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 44 bytes ``` f(n)=if(n<0,-f(-n),n,(1+f(n\2)^q=n%2*2-1)^q) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN3XSNPI0bTOBpI2Bjm6ahm6epk6ejoahNlAkxkgzrtA2T9VIy0jXEMjUhOpRS8sv0shTsFXQNTXQUQDhgqLMvBKgkJKCrh2QAJmpCVUNswkA) Using [the Calkin-Wilf sequence](https://en.wikipedia.org/wiki/Calkin%E2%80%93Wilf_tree) like other answers. --- ## [PARI/GP](https://pari.math.u-bordeaux.fr), 47 bytes ``` n->t=0;[t=(1+t^q--)^q|q<-2*binary(n)];t*sign(n) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN_XzdO1KbA2so0tsNQy1S-IKdXU14wprCm10jbSSMvMSiyo18jRjrUu0ijPT84BMqDa1tPwijTwFWwVdUwMdBRAuKMrMKwEKKSno2gGJNKBaTajqBQsgNAA) Starting from \$t=0\$. For each binary digit of the input \$n\$, take \$t=t+1\$ if the digit is \$1\$, and \$t=\frac{t}{t+1}\$ if the digit is \$0\$. Finally multiply the result with \$\operatorname{sign}(n)\$. --- ## [PARI/GP](https://pari.math.u-bordeaux.fr), 47 bytes ``` n->for(i=!t=0,abs(n),t=1/(1-t+t\1*2));t*sign(n) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN_XzdO3S8os0Mm0VS2wNdBKTijXyNHVKbA31NQx1S7RLYgy1jDQ1rUu0ijPT84BSUG1qID15CrYKuqYGOgogXFCUmVcCFFJS0LUDEmlAtZpQ1QsWQGgA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` NθF²⊞υιF↔θ⊞υ⁻Σ…⮌υ²⊗﹪§υ±²↨υ⁰‹θ⁰⪫⮌…⮌υ²/ ``` [Try it online!](https://tio.run/##dY1LDoIwEIb3nKJxNU0gIltWiBuMEKIn4DEKSWmhZYievhYTdOUkM4tv/kfTVbpRlbA2kyPNBQ01aph47N2VZhBxVpLpgHzWbyypjRI0o1P9vnkvycCNBkhfjcC0UyNccUFtEIj7LHJ7UlQLbCFXLQkFyZzJFp@ru8BH5QIj7lTHarX4LOTrxF6peznDBY2B6UM3dFa9/Hb8a3Vnt985k7XBIQxtsIg3 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of my JavaScript answer to [Output the nth rational number according to the Stern-Brocot sequence](https://codegolf.stackexchange.com/q/90232/). ``` Nθ ``` Input `n`. ``` F²⊞υι ``` Start with `0/1`. ``` F↔θ ``` Repeat `|n|` times. ``` ⊞υ⁻Σ…⮌υ²⊗﹪§υ±²↨υ⁰ ``` Calculate the next term of the sequence. ``` ‹θ⁰ ``` Output a `-` if the input was negative. ``` ⪫⮌…⮌υ²/ ``` Output the last two terms of the sequence, joined with `/`. Alternative implementation, also 37 bytes: ``` Nθ≔¹η≔⁰ζF↔θ«≔⁻⁺ζη⊗﹪ζηε≔ηζ≔εη»‹θ⁰Iζ/Iη ``` [Try it online!](https://tio.run/##VY3LCsIwEEXX9itCVxNIMV13VXQjWOkv9BFtISY2DxcRvz2OxFLcDNwz9zFMnRl0J2M8qYd3F3/vhYGFVllt7XxTUDIybYozElBdtSFQ91ZL7wS6KXllu5@lmZW30Eo84Ztl5Kh9L8UIjR691IlS5AKb1tSUilcp0uo7a82sHJyFtbAwwinChA6ddRA2ne/z/x9uVDEWJeexeMoP "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔¹η≔⁰ζ ``` Start with `0/1`. ``` F↔θ« ``` Repeat `|n|` times. ``` ≔⁻⁺ζη⊗﹪ζηε ``` Calculate the next term of the sequence. ``` ≔ηζ≔εη ``` Shuffle the terms into the desired variables. ``` »‹θ⁰ ``` Output a `-` if the input was negative. ``` Iζ/Iη ``` Output the current two terms, separated by `/`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes ``` \d+ $*#/1 +`#(?=1*/(1+))(\1*)(1*)/\3(1+) $1/$2$4 ^/ 0/ 1+ $.& ``` [Try it online!](https://tio.run/##Fcs5DgIxEETR/F9jDPKixu6xZwsQIZew0CBBQEKAuL8xQVVQpfd5fl/vezvY697qI2D8EJWwD/ZyVh@tBudsVe9sT6z5P2A0mtEUbpEU0a5Ox9ZEU6IXsiErsiAzMiEFycjYPxLKSKYwMbOwstFFlz8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Another port of my JavaScript answer to [Output the nth rational number according to the Stern-Brocot sequence](https://codegolf.stackexchange.com/q/90232/). ``` \d+ $*#/1 ``` Convert the absolute value of `n` to unary using `#`s, then append `/1` representing `0/1` in unary. ``` +`#(?=1*/(1+))(\1*)(1*)/\3(1+) ``` Match and consume one `#` each time, so that the replacement happens `n` times; look ahead and capture `b` as `$1` so that `a-a%b` and `a%b` can be calculated as `$2` and `$3`, and therefore also `b-a%b` as `$4`. ``` $1/$2$4 ``` Replace `a` with `b` and `b` with `a-a%b+b-a%b` i.e. `a+b-a%b*2`. ``` ^/ 0/ ``` Special case `0/`, since `0` in unary is the empty string. ``` 1+ $.& ``` Convert to decimal. [Answer] # [Python](https://docs.python.org/3.8/), 207 bytes. \$ \text{207 bytes, it can be golfed much more.} \$ Golfed version. [Try it online!](https://tio.run/##VY7BDoIwEETvfMXExKRVSShejBGO/AfRFpvYbbPUgyF8OwoSwbnt7L6ZDa9493Q8BR4Gw97BcH2N1lML64LniGo2ULeokps2aATJc4KPrAHhAvWdRrGOTyZkk6EfrV5WDsWIpkr@rInfIkeJbDlc5VRCHSAUUuQ7S1E4iT2cXBL@K1Zk6gbjGRaWwDU1WqhMzW8HHrPMprM9ihJdI6zsN3J4Aw) ``` from fractions import Fraction as F def g(n): if n < 1: return 0 else: m = g(n-1) if n % 2 > 0: return F(1, (1 - 2*int(m) + m)) else: return -m ``` Ungolfed version. [Try it online!](https://tio.run/##VY7NCsIwEITveYpBEBK10NSLiO2x71E00YD5YRsPUvrs0dZq69x2duebDc94825/CJSSJm@hqTlH410LY4OniHoyGLsojZo7cWR4y2g4nCA/0yBS8UEO@Wioe6vmlUU5RDMpftaYX6NAhXw@XHC@xVzuwCUyFBvjIrcCW1gxg/6bFoDMMqY9wcA4UOOuistcTu8HGmB61ZkeZYWu5kb0K8FSegE) ``` from fractions import Fraction def F(n): if n < 1: return 0 else: m = F(n-1) if n % 2 > 0: return Fraction(1, (1 - 2*int(m) + m)) else: return -m for i in range(101): print(f"{i} => {F(i)}") ``` ]
[Question] [ *Golfeek* is the working name of an esolang I'm occasionally working on. One distinctive feature of this language is that each statement is encoded as a sequence of bits rather than a sequence of bytes. Instead of just showing a long binary sequence, the 'gutter' of the source editor contains a representation of each statement in a more digest and (slightly) more readable format: [![example Golfeek source code](https://i.stack.imgur.com/C3S6e.png)](https://i.stack.imgur.com/C3S6e.png) ## Format * The binary sequence is always read from left to right. * It is first split into nibbles (groups of 4 bits) shown as uppercase hexadecimal between brackets. A space is inserted after each byte, provided that it's followed by another byte or a last lone nibble. *Example:* ``` [1,1,1,1,0,0,0,0,1,0,1,0] --> "[F0 A]" \_____/ \_____/ \_____/ ``` * If there are more than 14 nibbles, only the first 6 bytes are shown, followed by a space, followed by `..`, followed by the closing bracket. * If the number of bits is not a multiple of 4, the remaining bit(s) is/are appended as '0' or '1' right after the closing bracket. *Example:* ``` [0,1,1,1,1,0,0,1,0,1] --> "[79]01" \_____/ \_____/ \_/ ``` ## Your task Given a sequence of bits, return its representation in *Golfeek* format. ## Rules * The sequence of bits may be taken in any reasonable and non-ambiguous format. Please note that the sequence may contain leading zeros, which your format must be able to deal with. * You can assume that there will always be at least 4 bits in the input sequence, and therefore at least one nibble between the brackets. * The output must be a string (or a list of characters) that conforms exactly to the format described above, with uppercase hexadecimal and correct spacing. A trailing linefeed is optional. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). ## Test cases ### Input ``` 0101 00001 110101 10100111 101001111100 000000000000000 011110101101001110010011000111 11011110101011011011111011101111 11110101000110000001111011001110011100100110111000100000100 111101010001100000011110110011100111001001101110001000001001 1111010100011000000111101100111001110010011011100010000010010 ``` ### Output ``` [5] [0]1 [D]01 [A7] [A7 C] [00 0]000 [7A D3 93 1]11 [DE AD BE EF] [F5 18 1E CE 72 6E 20]100 [F5 18 1E CE 72 6E ..] [F5 18 1E CE 72 6E ..]0 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~36~~ ~~34~~ ~~33~~ 31 bytes ``` Ć4ô¤¨s¨Ch2ôJDg8@i6∍„..ª}ðý"[ÿ]ÿ ``` [Try it online!](https://tio.run/##yy9OTMpM/W9o6Pb/SJvJ4S2HlhxaUXxohXOG0eEtXi7pFg6ZZo86eh81zNPTO7Sq9vCGw3uVog/vjz28/7@S/X8DQwNDLgMgMOQyNARzQKSBoSGCARQ3ACtBAlxgCZB6mCoDCG0A1WsIVwBWYgg1CIpBCqCyUE0QfWCVUNMQRhpCjIUoAtpNgV6KLDY0AAA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` s4µLÐṀ©s14Ḅ‘ịØHUḢaȧ⁾..$ƊUs2KØ[j;ḟ®F ``` A full program which, given a list format of 1s and 0s, prints the result. **[Try it online!](https://tio.run/##y0rNyan8/7/Y5NBWn8MTHu5sOLSy2NDk4Y6WRw0zHu7uPjzDI/ThjkWJJ5Y/atynp6dyrCu02Mj78IzoLOuHO@YfWuf2////aEMdBTgyQCUNYGxkLpo4skZDDClcXDSTDTFsMcRmHYgRCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/7/Y5NBWn8MTHu5sOLSy2NDk4Y6WRw0zHu7uPjzDI/ThjkWJJ5Y/atynp6dyrCu02Mj78IzoLOuHO@YfWuf2/@HuLf4PdzQdbn/UtCby/391dfUYLgNDA0MuAyAw5DI0BHNApIGhIYIBFDcAK0ECXGAJkHqYKgMIbQDVawhXAFZiCDUIikEKoLJQTRB9YJVQ0xBGGkKMhSgC2k2BXoosNjQABhkA "Jelly – Try It Online"). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~112~~ 111 bytes ``` .{4} $& (.+) [$1] T`d`L`.*] B AB +`BA ABB A+(B*) $.1 T`d`L`1\d(?=.*]) B(.) $1 T` `_`\w.. (\[.{18})...+] $1..] ``` [Try it online!](https://tio.run/##pY0xCwIxDIX3/IobDmkthAQcXESus6PbXbHCObg4iOBw3G@vaRs99wu0Sfu@9/K8ve6Pa0o47WZoNw0YdLaBvuUA5zjGU8RtAA@dBxd9J11mZ/zWQousCA@jOR4EtOANipKFJl7i8EYEM/Q48X62iOiCiIghJWJiICkG5vLINzEvg/xTQf4KipD5L0W1k3r5BxSENUhPBlRVU/UVUtOWSK6xFZLdK7yrFjN9AA "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 1 byte thanks to @Grimmy. Explanation: ``` .{4} $& ``` Group the nibbles. ``` (.+) [$1] ``` Bracket the nibbles. ``` T`d`L`.*] ``` Change the bits used by the nibbles from `01` to `AB` to distinguish them from the spare bits. ``` B AB +`BA ABB ``` Convert from binary to unary. ``` A+(B*) $.1 ``` Convert from unary to decimal. ``` T`d`L`1\d(?=.*]) B(.) $1 ``` Convert `10-15` from decimal to hexadecimal. ``` T` `_`\w.. ``` Group pairs of nibbles into bytes. ``` (\[.{18})...+] $1..] ``` Truncate the output if there are more than 14 nibbles. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~129~~ ~~124~~ 113 bytes -5 thanks @tsh 11 more thanks @Arnauld ``` s=>'['+s.replace(/..../g,(x,i)=>(i<56?"9ABCDEF."[x=!s[59]|i<48?"0b"+x-9:7]||x+9:"")+(s[i+7]?i&4&&x-7?' ':'':']')) ``` [Try it online!](https://tio.run/##pZHfboMgFMbvfQrmhWCsFJJ2Tlc0W9e9hDGROexYTDViGi58d0eVtrvvCf/P7/tOcvjlZ66qXnZDeGq/xVSzSbEU5jBQuBddwyuB1tjE@rhCeiV9liK52z5nbvz2vv84fGI31@xJ5du4GOVu85K55MsNdBgnUTGOOogT1/UDpHIZREUmvY3n6TDKIIAJNKOAvj@deQ8GoYY9V0IBBkpCCXWICepQOl8uK6H0fjDvZEb@hTMnLvyVIstOrJbegBmh1sjOC2CzVrToZtK63S3pYrtApvYD2ocKU1Ji1TVyKJ3y1bm1Eddtf@DVD9KApaBqT6ptBG7ao/lFUCPtm77/AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 208 bytes ``` func[s][r: :rejoin b: parse s[collect[any[keep[4 skip]]copy t to end]]forall b[b/1: pick form debase/base r["0000"b/1]2 4]b: collect[foreach[x y]b[keep r[x any[y""]]]]if b/8[clear at b 8 b/7:".."]r["["b"]"t]] ``` [Try it online!](https://tio.run/##rY5NboQwDIX3nMLyAYakGqkjjtGt5UUSjEqhgEIqldNT8zMdZtpd6yiJnvP5vUQp5xcpibOqmKuPLtDIFAsoorz1dQe@gMHFUWCk0LethESum6gRGegMY1MPzKEfJkiQepCuZK766No28@Rzq9N1aEBb71CKd6PkywGR0GihIvwEZ9aYq72y4sIrfcLEfg3KoooldUJkrboCn18otOIiuAQeLtp4LvB0QlZnQo@MiXkeYt0lqACNNRazm9Q6amsfgEUba39rKWserA51fFlZXddJs93mh7P9RlfY7jH7vkd3bjfavNaZPeEWY7eoDbr72R9c/ukz1uD8BQ "Red – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes ``` [≔⪪S⁴θF›⁴L§θ±¹≔⊟θω≔⪫⪪↥⭆θ⍘↨²ι¹⁶¦² θ⎇‹²⁰Lθ⁺…θ¹⁸..θ]ω ``` [Try it online!](https://tio.run/##VU/BTgMhEL37FYTTbIINbBpj4qn2YGqq2aR6Mh7IirskBFigar8eB3Zb45AZXmaG9x79KEPvpMm5C9omoG@0ubvaxKgHCwdvdIKd9cd0SDgeoGFkjTnhzqcLBB6CkkkFWDOyV3ZII2zSzn6oH5gYeVYDDkE0GGSh7JyHCRm@/1QenT5LvXqvQi@jglnvSfpCdI@dxUCB0DKikUPcIDEjLSYldLE1f@NFBSvDCfYqRmj5xd1UHnTmGGF76o3ajq4KiNvCsVr9J6Hv9ILRb84Cg5fDuSil3qUlKjiXOq2Qz1u1ma@/zC8 "Charcoal – Try It Online") Link is to verbose version of code. ``` [ ``` Output the opening `[`. ``` ≔⪪S⁴θ ``` Split the input into nibbles. ``` F›⁴L§θ±¹≔⊟θω ``` Save the last slice if it's not a whole nibble. ``` ≔⪫⪪↥⭆θ⍘↨²ι¹⁶¦² θ ``` Convert each nibble into uppercase base 16, joining with alternate spaces. ``` ⎇‹²⁰Lθ⁺…θ¹⁸..θ ``` If the resulting string is greater than 20 characters then truncate it to 18 and add `..` otherwise output the string. ``` ] ``` Output the closing `]`. ``` ω ``` Output any left-over bits. [Answer] # [Perl 5](https://www.perl.org/) (`-p`), ~~91~~, 89 bytes -2 bytes thanks to Xcali++ ``` s/.{4}/sprintf"%X",oct"0b$&"/eg;$\=$';s/$\$//;s-.{12}\K...+-..-;s-..(?=.)-$& -g;$_="[$_]" ``` [Try it online!](https://tio.run/##pY3dCsIwDIXv9xRS6qZo00T0agwfwBcQnAyUKQPZxrq7sVe39k/n/QJp0uQ7J23ZvQ6a51mSpFpJGPajVG1X1f2DLc9s29x7hjceM1k@U4PxJFWS51zKVAkYaDfmJwDYCABhJ7A6ZrAWPF4IwxcZu/DiyrRGQorQBEVE7mNfJJoaM0eH/EXkFpb/UugrBi39AIdQMAppgbANIq9zZHCbLMnbesjcnqGddZjw3bR91dRKi/YD "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 50 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ò4 jJUÌʦ4 ®n2G uÃò mq "[]"i1WjT7 ¸h18WÊ?"..":P)+V ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8jQKakpVzMqmNAqubjJHIHXD8iBtcQoiW10iaTFXalQ3ILhoMThXyj8iLi4iOlApK1Y&input=WyIwMTAxIiwKICIwMDAwMSIsCiAiMTEwMTAxIiwKICIxMDEwMDExMSIsCiAiMTAxMDAxMTExMTAwIiwKICIwMDAwMDAwMDAwMDAwMDAiLAogIjAxMTExMDEwMTEwMTAwMTExMDAxMDAxMTAwMDExMSIsCiAiMTEwMTExMTAxMDEwMTEwMTEwMTExMTEwMTExMDExMTEiLAogIjExMTEwMTAxMDAwMTEwMDAwMDAxMTExMDExMDAxMTEwMDExMTAwMTAwMTEwMTExMDAwMTAwMDAwMTAwIiwKICIxMTExMDEwMTAwMDExMDAwMDAwMTExMTAxMTAwMTExMDAxMTEwMDEwMDExMDExMTAwMDEwMDAwMDEwMDEiLAogIjExMTEwMTAxMDAwMTEwMDAwMDAxMTExMDExMDAxMTEwMDExMTAwMTAwMTEwMTExMDAwMTAwMDAwMTAwMTAiXQotbQpbNV0KWzBdMQpbRF0wMQpbQTddCltBNyBDXQpbMDAgMF0wMDAKWzdBIEQzIDkzIDFdMTEKW0RFIEFEIEJFIEVGXQpbRjUgMTggMUUgQ0UgNzIgNkUgMjBdMTAwCltGNSAxOCAxRSBDRSA3MiA2RSAuLl0KW0Y1IDE4IDFFIENFIDcyIDZFIC4uXTA) ``` ò4 (Input as a string) partitioned on each 4 bits. jJ V = get n elements from last index and remove them UÌʦ4 n = is last element length != 4 ? ®n2G uÃò mq Convert each nibble to base 16, uà to uppercase, ò mq and join each pair. "[]"i1 Inserts between squares : WjT7 first 7 elements(removing them), ¸ joined with space. h18 Then replace characters at index 18 with : WÊ?".." '..' if not empty :P else empty string. )+V Finally appends remaining bits and outputs implicitly. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~194~~ ~~181~~ ~~191~~ 190 bytes Thanks to ceilingcat (-14 bytes) for the suggestions. Fixed an edge case (+10 bytes). The function takes the input string and builds up byte-sized representations a nibble at a time, outputting the results until the sixth byte, and changing the `[` to a space after the first byte output (if there is one). The buffer is reset after each output. After the sixth byte, nothing is output until the entire string is processed, but if the length exceeds 59 bytes (7 bytes + 3 bits), the stored representation changes to `..`, which is then output at the end. Excess bits that don't fit in a nibble are printed from the end of the input string. There is an edge case that I had to specifically check for, which is an input between 49 and 51 bytes (6 bytes + 3 bits), as an extra space would normally get printed before the ending bracket. ``` c,t;f(char*s){char u[4]="[";for(t=c=0;*s;c++>58?u[1]=u[2]=46:0)t+=t+*s++-48,c%4>2?u[c%8/4+1]=t+48+7*(t>9),t=0:0,c%8>6&c<48?printf(u),*(int*)u=32:0;printf("%s]%s",u+(c%8<1|c-48U<4),s---c%4);} ``` [Try it online!](https://tio.run/##pY/BcsIgEIbvPAWTThwISQuW2tSE@BQ9ZXKwaDQzGp1A2oO1j94USKztUWUG@Nn9/l1WRispu06GOimRXM@bQOGDvWGb80J4uZeUuwZpIQVNApVIQrKneNbmrBBtPi4En0wp1kRoEihCIh6H0ufZ2BDSjx84MZwmPCbPAdLZCw61oFNqmDibjGTK49m@qWpdohaHATIqwK14HE9pMsQ9XxW@8sKWIGNK2ac0PV5TjkMVRZHphZNjd1fVctMuljBVelHt7tcZ@BfaVG82BkxFuJ1XNXrfVQsMDwBCN6sZDBhtJ03gl5Lz2jbemrZwpHACy2a5RAr3DgjPX4MigwYyjEuU6KT2rVbI89zrCI4dZZQBahYDjLmHPSljZ2Hi1CF/FnAJy58o2t908LJfwCFsKDRsCwzZwdT7HDlUO5e08mKD/fSlHquvMl3bjPbnLV52k5l@y3IzX6ku@vgB "C (gcc) – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 48 bytes ``` 4co{L[4.<}ptl_FLjb2b62co)++sa7.>{6.+".."[+}if+]Q ``` [Try it online!](https://tio.run/##SyotykktLixN/f/fJDm/2ifaRM@mtqAkJ97NJyvJKMnMKDlfU1u7ONFcz67aTE9bSU9PKVq7NjNNOzbw/39DIDAAQQMDQxABpkFChmAGjADLgpkGEFVAEgA "Burlesque – Try It Online") ``` 4co #Split into nibbles {L[4.<}pt #Partition into those whose lengths >4 and those <4 l_FL #Take the remainder as a flat list jb2b6 #Convert the main block into base 16 (via binary) 2co)++ #Join as pairs sa7.> #Length greater than 7 { 6.+ #Take first 6 discarding remainder ".."[+ #Append ".." }if #If length > 6 +] #Append remainder bits Q #Prettify ``` ]
[Question] [ This challenge will have you [count "creatures"](http://cambolbro.com/games/palago/creature-counts/) in the tile game Palago. > > A creature is any closed shape that can be formed by Palago tiles of matching colour in a hexagonal grid. > > > The game Palago consists of tiles like this: [![Palago tile](https://i.stack.imgur.com/SuOrGt.png)](https://i.stack.imgur.com/SuOrGt.png) These tiles can be rotated \$120^\circ\$, \$240^\circ\$, or not at all and placed anywhere on a hexagonal grid. For example, here is a (red) creature that requires 12 tiles. [![Twelve tile creature.](https://i.stack.imgur.com/NNC5V.png)](https://i.stack.imgur.com/NNC5V.png) # Challenge The goal of this challenge is to write a program that takes an integer `n` as an input and computes the number of creatures (up to rotation and reflection) that require `n` tiles. The program should be able to handle up to `n=10` on [TIO](https://tio.run/). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins. # Example data The values should match the data found in the "Creature Counts and Estimates" section of the [creator's website](http://cambolbro.com/games/palago/creature-counts/). Namely ``` n | output ---+------- 1 | 0 2 | 0 3 | 1 4 | 0 5 | 1 6 | 1 7 | 2 8 | 2 9 | 9 10 | 13 11 | 37 12 | 81 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~578 ... 433~~ 431 bytes ``` f=(n,T=[B=[N=0,0,0,1,1]])=>!n||T.some(([x,y,q,m])=>B.some((p,d)=>m>>d&1&&((p=x+~-s[d],q=y+~-s[d+2],t=T.find(([X,Y])=>X==p&Y==q))?(q=t[3])&(p=D[d*3+t[4]])^p?t[f(n,T,t[3]|=p),3]=q:0:[0,1,2].map(t=>f(n-1,[...T,[p,q,-p-q,D[d*3+t],t]])))),s="2100122",D=Buffer("160).(9!'8 &$<%"))|n>1||[0,1,2,1,2,0].some((_,d,A)=>B[k=T.map(a=>[(h=n=>Math.min(...T.map(R=a=>a[A[(d+n)%6]]))-R(a))(0),h(3),(x=(a[4]+d*2)%3,d>2)*x?3-x:x]).sort()])?N:B[k]=++N ``` [Try it online!](https://tio.run/##LVBdT9swFH3nV5iKZr7NjZUPhLbCTUXF6/qA@gCyPIhws3YjTtJkUxDp/np3DbVl3U@fc@79Vfwtupf9rukjV9vN8ViSdLgmvSS9ohj9TTAxBig/d@O4Vl1dbaTUA75hi5XPL0@5Bi1HVZ7bIAkCjmkI/0WdtgZbevt0w9RgT2tV7pxllAd89AgPRE3wSNQCLGRLvc4MBPz/TttZFvb6kvl/NItel14c@vpIDWBmqJ3Hc@01pkZVRSN7yrkpSlArpdaoG1YZNVGLJyymZzA@2NEkTeI4SdMJ3tHyT1lu9nKSXMWg5LfzL19FcHEznQCMLk/G8ZPj48XmNPATWrz1C9C/eSTPXlCu5ZYc5d@LfquqnZNexkftnrha6FstbehgeuVlRPeyAJAx4FZmgHIgWfC0oZ2lMM3Q5inMhkUWDfPBALPuewkGFqs5UxoKw9WxrPfSCRLJtXDihm3GThiCeD8T4qV2Xf26Ua/1T/nsuy7e3UFEUc4ObwkOz3B9djj@Bw "JavaScript (Node.js) – Try It Online") (\$n=1\$ to \$n=13\$) ## How? ### Directions and tiles We use the following codes for the 6-direction compass and the tiles: [![directions & tiles](https://i.stack.imgur.com/mOXex.png)](https://i.stack.imgur.com/mOXex.png) We assume that the creature is blue. ### Connections We need a table to know which parts of the creature need to be connected to other tiles when we enter a given tile in a given direction: ``` | T=0 | T=1 | T=2 -----+-------+-------+------- d=0 | 0,4,5 | 1,2,4 | 4 d=1 | 0,3,5 | 1,2,3 | 3 d=2 | 0,3,4 | 0 | 0,1,2 d=3 | 3,4,5 | 5 | 1,2,5 d=4 | 2 | 2,3,4 | 0,2,5 d=5 | 1 | 1,3,4 | 0,1,5 ``` *Example:* If we enter a tile of type \$1\$ with direction \$5\$, we need to connect in directions \$1\$, \$3\$ and \$4\$: [![connections](https://i.stack.imgur.com/axS1S.png)](https://i.stack.imgur.com/axS1S.png) But the way the tiles are designed, there can't possibly be a single missing connection in a single direction. A consequence of that is that we can ignore one direction entirely and still be able to detect if the path is closed or not. By convention, we are going to ignore direction \$5\$. ``` | T=0 | T=1 | T=2 -----+-------+-------+------- d=0 | 0,4 | 1,2,4 | 4 d=1 | 0,3 | 1,2,3 | 3 d=2 | 0,3,4 | 0 | 0,1,2 d=3 | 3,4 | - | 1,2 d=4 | 2 | 2,3,4 | 0,2 ``` These updated sets of directions are first re-encoded as 5-bit integers, and then as ASCII characters with a fixed offset of \$+32\$: ``` | T=0 | T=1 | T=2 | T=0 | T=1 | T=2 -----+-------+-------+------- -----+-------+-------+------- d=0 | 17 | 22 | 16 d=0 | "1" | "6" | "0" d=1 | 9 | 14 | 8 d=1 | ")" | "." | "(" d=2 | 25 | 1 | 7 --> d=2 | "9" | "!" | "'" d=3 | 24 | 0 | 6 d=3 | "8" | " " | "&" d=4 | 4 | 28 | 5 d=4 | "$" | "<" | "%" ``` Once flattened, this gives: ``` D = Buffer("160).(9!'8 &$<%") ``` ### Coordinates To describe the positions of the tiles, we use cube coordinates with \$x+y+z=0\$: [![cube coordinates](https://i.stack.imgur.com/6R83f.png)](https://i.stack.imgur.com/6R83f.png) *Credits: [www.redblobgames.com](https://www.redblobgames.com/grids/hexagons/#coordinates)* It will make it easier to process rotations and reflections in the final step of the algorithm. ### Tile encoding The tiles are stored in a list, with no specific order. It means that we don't have to worry about some dynamic 2D allocation and we can easily iterate on the existing tiles. The downside is that, given specific coordinates, we need to `find()` the corresponding tile in the list. Each tile is stored as \$(x, y, z, m, t)\$ where: * \$(x, y, z)\$ are the cube coordinates of the tile as described above * \$m\$ is the 5-bit mask of directions that need to be connected * \$t\$ is its type (\$0\$, \$1\$ or \$2\$) ### Algorithm We start with a single tile of type \$1\$ at \$(0,0,0)\$, with a required connection in direction \$0\$: [![initial tile](https://i.stack.imgur.com/YNGas.png)](https://i.stack.imgur.com/YNGas.png) Therefore, this tile is encoded as `[0,0,0,1,1]`. At each iteration, we look for: * Tiles with missing connections: in this case, we successively try to complete the connection with each type of tile. * Tiles that are already connected but for which new connections need to be added because they have been reached in a different direction: in this case, we update the direction mask (with a bitwise OR) and force a new iteration. If all connections are valid *and* we have reached the requested number of tiles, we still need to test whether it is a new creature or just a modified version of an existing one: 1. We apply the following transformations: * We perform the 3 possible rotations by replacing \$(x,y)\$ with \$(x,y)\$ (no rotation), \$(y,z)\$ (120°) or \$(z,x)\$ (240°), and updating the types of the tiles accordingly. * We perform the 3 corresponding reflections by replacing \$(x,y)\$ with \$(y,x)\$, \$(z,y)\$ or \$(x,z)\$, and updating the types of the tiles accordingly. 2. For each transformation, we translate all tiles such that the bottom-right corner is always located at \$(0,0)\$. (The signs of the coordinates are inverted in the process, which technically leads to another reflection, but this is harmless.) 3. We sort the tiles according to their coordinates and types. (This sort is processed in lexicographical order, which is fine.) 4. We finally coerce the resulting list to a key string which can be compared with the other keys. 5. We abort as soon as a known key is matched, or store the new key and increment the final result if none of the transformations lead to a known key. ## Commented ``` f = (n, T = [B = [N = 0, 0, 0, 1, 1]]) => // abort if n = 0 !n || // for each tile in T T.some(([x, y, q, m]) => // for d = 0 to d = 4 B.some((p, d) => // if this tile requires a connection in this direction m >> d & 1 && ( // look for a connected tile t at the corresponding position (p, q) ( p = x + ~-s[d], q = y + ~-s[d + 2], t = T.find(([X, Y]) => X == p & Y == q) ) ? // if t exists, make sure that its direction mask is up-to-date (q = t[3]) & (p = D[d * 3 + t[4]]) ^ p ? // if it's not, update it and force a new iteration t[f(n, T, t[3] |= p), 3] = q : 0 : // if t does not exist, try each type of tile at this position [0, 1, 2].map(t => f(n - 1, [...T, [p, q, -p - q, D[d * 3 + t], t]])) ) ), // s is used to apply (dx, dy) s = "2100122", // D holds the direction masks for the connections D = Buffer("160).(9!'8 &$<%") ) | // stop here if the above some() was truthy or we have more tiles to add n > 1 || // otherwise, apply the transformations [0, 1, 2, 1, 2, 0].some((_, d, A) => B[ // compute the key k k = // by generating the updated tuples [x, y, type] and sorting them T.map(a => [ // transform the 1st coordinate (h = n => Math.min(...T.map(R = a => a[A[(d + n) % 6]])) - R(a))(0), // transform the 2nd coordinate h(3), // update the type (x = (a[4] + d * 2) % 3, d > 2) * x ? 3 - x : x ] ).sort() ] ) ? // if the key was found, just return N N : // if this is a new creature, store its key and increment N B[k] = ++N ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 480 417 bytes -63 bytes thanks to @Arnauld. Wow. ``` n=>(E=(x,y,d,k,h)=>V[k=[x+=1-(d%=3),y+=~d%3+1,d]]?0:(V[k]=1,h=H.find(h=>h[0]==x&h[1]==y))?(d^(t=2-h[2])?E(x,y,t)||E(x,y,h[2]*2):E(x,y,t+2)):[x,y,0],I=c=>c.map(([x,y,t])=>[x-g(0),y-g(1),t],g=p=>Math.min(...c.map(h=>h[p]))).sort(),S=e=>(V={},e=E(0,0,0))?(--n&&H.pop(H.push(e),S(),S(e[2]=1),S(e[2]=2)),++n):n-1||E[I(c=H)]||[0,0,0,++N,0,0].map(r=>E[I(c=c.map(([x,y,t])=>[-x-y,r?y:x,(r?t*2:t+1)%3]))]=1))(H=[[N=0,0,1]])&&N ``` [Try it online!](https://tio.run/##ZY9Pb6MwEMXv/RQcNmim/iNMbnQHTpHSw@ZSqRfLVSMgIdvWIMKuQEn61bNjUvWysuT39Dwz/s3v7d/tsewP3aB8W9XXHV095bAiGOUkK/kmG6T82b6RHQUZBdWClignQZ/VYimMrJwrkgy4wpGRDa317uAraChvbOKIxrixhnVCLKB6gYFS1djUYbGavxjwfL65kN6nmH3lIkXMbLCJk49UUl7qj20HMGeDYyw7qj0kTMNikDO5p47yX9uh0R8HD1rrW89M0zlE1Me2HwDlE9W85jOdLrKmFSSSTyBUysfxWndtB3z/OTZQc3FogJr5yHw7xpNCeMy8MryCfYSS1ujOZzsP47dNUDcD9JTfKv7fQY1qkn0xZaOEvhju02wQBhdLpg3fIazJ2g2FkcY5jOPNddf24COKzEPko5@swQiB0ekuisrWH9v3Wr@3e3gNVT9O/hIplbPZgcfLKz7cXa7/AA "JavaScript (Node.js) – Try It Online") Firstly, repect to Arnauld whose answer gave me the inspiration to dig deeper. I have tried hard to be original with my algorithms, although I intentionally changed some of my code to use the same variables as Arnauld so that the code could be more easily compared. ### Searching for empty hexes The search for creatures is: * Initialize list of tiles with tile 1 at 0,0 * Recursively: + Search for an empty hex that is needed to complete creature + If empty hex found - Add each type of tile 0,1,2 to empty hex and recurse + If empty hex not found - If creature is of correct size and is not already in zoo * Increment number of distinct creatures found by one * Add all rotations and reflections of creature to zoo The search for empty hexes uncovered an interesting symmetry. Arnauld discovered that one of the six directions could be ignored, but in fact three out of six can be ignored! Here is Arnauld's original direction and tile key: [![Arnauld's direction and tile key](https://i.stack.imgur.com/PLErR.png)](https://i.stack.imgur.com/PLErR.png) Imagine we start at tile A of type 1 at the blue dot. It seems that we have to recurse out in d=0 and d=5. However, whichever tile is placed in d=0, it will certainly have an exit in d=4, which will visit the same hex as exiting tile A in d=5. That is Arnauld's discovery, and it's what started me thinking. Notice that: * Every tile that has an exit in d=0 has an exit in d=5 * Every tile that has an exit in d=2 has an exit in d=1 * Every tile that has an exit in d=4 has an exit in d=3 * Every tile that can be entered from d=0 has an exit in d=4 * Every tile that can be entered from d=2 has an exit in d=0 * Every tile that can be entered from d=4 has an exit in d=2 This means that we only need to consider directions 0,2,4. Any exits in directions 1,3,5 can be ignored because the hexes reachable in directions 1,3,5 can instead be reached from an adjacent hex using directions 0,2 or 4. How cool is that!? ### Relabelled Directions So I relabel the directions and tiles like this (Arnauld's image edited): [![Simplified directions](https://i.stack.imgur.com/CAxjI.png)](https://i.stack.imgur.com/CAxjI.png) Now we have the following relationship between tiles, entries and exits: ``` | t=0 | t=1 | t=2 ----+-------+-------+------- d=0 | 0,2 | 1,2 | 2 d=1 | 0,2 | 0 | 0,1 d=2 | 1 | 1,2 | 0,1 ``` So exits are: d+t==2 ? (4-t)%3 : 2-t and 2\*t%3 ### Hexagonal Rotations and Reflections For rotations and reflections, I decided to try x,y [hexagonal axial coordinates](https://www.redblobgames.com/grids/hexagons/#coordinates-axial) instead of the x,y,z cube coordinates. ``` -1,2 0,2 1,2 2,2 0,1 1,1 2,1 0,0 1,0 2,0 3,0 ``` In this system, the rotation and reflection were simpler than I expected: ``` 120 Rotation: x=-x-y y=x t=(t+1)%3 Reflection: x=-x-y y=y t=(t*2)%3 ``` To get all the combinations I performed : rot,rot,rot,reflect,rot,rot ### Code (Original 480 byte) ``` f=n=>( // H:list of filled hexes [x,y,tile] during search for a complete creature // N:number of distinct creatures of size n // B:record of all orientations of all creatures already found H=[[0,0,1]],N=0,B={}, // E: find an empty hex required to complete creature starting in direction d from x,y E=(x,y,d,k,h)=>( x+=1-d, y+=1-(d+1)%3, // V: list of visited hexes during this search in E V[k=[x,y,d]] ? 0 : (V[k]=1, h=H.find(h=>h[0]==x&&h[1]==y)) ? // this hex is filled, so continue search in 1 or 2 directions (d==2-h[2] ? E(x,y,(4-h[2])%3) : (E(x,y,2-h[2]) || E(x,y,h[2]*2%3))) : [x,y,0] // return the empty hex ), // I: construct unique identifier for creature c by moving it so x>=0 and y>=0 I=c=>( M=[0,1].map(p=>Math.min(...c.map(h=>h[p]))), c.map(([x,y,t])=>[x-M[0],y-M[1],t]).sort() ), // A: add complete creature c to B A=c=>{ n==1&&!B[I(c)]&&( // creature is correct size and is not already in B N++, [0,0,0,1,0,0].map( // Add all rotations and reflections of creature into B // '0' marks a rotation, '1' marks a (vertical) reflection // rotation: x=-x-y y=x t=(t+1)%3 // reflection: x=-x-y y=y t=(t*2)%3 r=>B[I(c=c.map(([x,y,t])=>[-x-y,r?y:x,(r?t*2:t+1)%3]))]=1) ) }, // S: recursively search for complete creatures starting with hexes H S=e=>{ V={}; (e=E(0,0,0)) ? // e is a required empty hex, so try filling it with tiles 0,1,2 (--n && (H.push(e),S(),S(e[2]=1),S(e[2]=2),H.pop()), ++n) : A(H) // creature is complete, so add it to B }, S(), N ) ``` ### Code (Arnauld 417 byte) Arnauld kindly submitted a 63 byte saving that used tricks that took me quite some time to wrap my head around. Since it has many interesting edits, I thought I'd put his code below (I've added my comments) so that it can be contrasted with my version. ``` f=n=>( // E:find an empty hex required to complete creature starting in direction d from x,y E=(x,y,d,k,h)=> V[k=[x+=1-(d%=3),y+=~d%3+1,d]] ? 0 :(V[k]=1,h=H.find(h=>h[0]==x&h[1]==y)) ? (d^(t=2-h[2]) ? E(x,y,t) || E(x,y,h[2]*2) : E(x,y,t+2)) :[x,y,0], // I: construct unique identifier for creature c by moving it so x>=0 and y>=0 I=c=>c.map(([x,y,t])=>[x-g(0),y-g(1),t],g=p=>Math.min(...c.map(h=>h[p]))).sort(), // S: recursively search for complete creatures starting with hexes H S=e=> (V={},e=E(0,0,0)) ? (--n&&H.pop(H.push(e),S(),S(e[2]=1),S(e[2]=2)),++n) :n-1 ||E[I(c=H)] // creature is the correct size and has not been seen before // so record all rotations and reflections of creature in E[] ||[0,0,0,++N,0,0].map(r=>E[I(c=c.map(([x,y,t])=>[-x-y,r?y:x,(r?t*2:t+1)%3]))]=1) ) // This wonderfully confusing syntax initializes globals and calls S() (H=[[N=0,0,1]]) && N ``` ]
[Question] [ The first two MU-numbers are 2 and 3. Every other MU-number is the smallest number not yet appeared that can be expressed as the product of two earlier distinct MU-numbers in exactly one way. Here are the first 10 ``` 2, 3, 6, 12, 18, 24, 48, 54, 96, 162 ``` ## Task Given a positive number calculate and output the **n**th MU-number. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") competition so you should aim to make your source code as small as possible. [OEIS A007335](http://oeis.org/A007335) [Answer] # Pyth, ~~22~~ 21 bytes ``` @u+Gfq2l@GcLTGheGQhB2 ``` [Try it online.](https://pyth.herokuapp.com/?code=%40u%2BGfq2l%40GcLTGheGQhB2&input=9&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=%40u%2BGfq2l%40GcLTGheGQhB2&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0) 0-indexed. ### Explanation ``` @u+Gfq2l@GcLTGheGQhB2Q Implicitly append Q and read+eval input to it. hB2 Take the list [2, 2 + 1]. u Q Put the list in G and apply this Q times: eG Get last number in G. h Add one. f Starting from that, find the first T such that: cLTG Divide T by each of the numbers in G. @G Find the quotients that are also in G. l Get the number of such quotients. q2 Check that it equals 2. +G Append that T to G. @ Q Get the Q'th number in G. ``` [Answer] ## Haskell, ~~80~~ 77 bytes ``` l#(a:b)|[x]<-[a|i<-l,j<-l,i<j,i*j==a]=a:(a:l)#b|1<2=l#b ((2:3:[2,3]#[4..])!!) ``` [Try it online!](https://tio.run/##FcqxDsIgEADQ3a@4hg5gaBPBiXBfQhiOpI2HZ9O0Dg78O@rypveg87mI9C5KUyimpU@OU6LGcRJb/3Cslq8VkTJS@C0xqrRbdCiqXFbU2gUfkrM@q3Sf52yGwfQX8QYI@8HbG0ZYwfcv "Haskell – Try It Online") How it works ``` 2:3: -- start the list with 2 and 3 and append a call to # with [2,3] -- the list so far and #[4..] -- list of candidate elements l # (a:b) -- l -> list so far, a -> next candidate element, b -> rest c.el. | [x]<-[...] -- if the list [...] is a singleton list =a:(a:l#b) -- the result is a followed by a recursive call with l extended by a and b | 1<2=l#b -- if it's not a singleton list, drop a and retry with b -- the [...] list is [ i<-l,j<-l, -- loop i through l and j through l and whenever i<j, -- i<j and i*j==a] -- i*j==a a| -- add a to the list ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒcP€ḟ⁸ṢŒgLÞḢḢṭ 2,3Ç¡ị@ ``` A monadic link, 1-indexed. **[Try it online!](https://tio.run/##y0rNyan8///opOSAR01rHu6Y/6hxx8Odi45OSvc5PO/hjkUgtHMtl5GO8eH2Qwsf7u52@P//vzkA "Jelly – Try It Online")** ### How? ``` ŒcP€ḟ⁸ṢŒgLÞḢḢṭ - Link 1, add the next number: list, a e.g. [2,3,6,12,18,24] Œc - unordered pairs [[2,3],[2,6],[2,12],[2,18],[2,24],[3,6],[3,12],[3,18],[3,24],[6,12],[6,18],[6,24],[12,18],[12,24],[18,24]] P€ - product of €ach [6,12,24,36,48,18,36,54,72,72,108,144,216,288,432] ⁸ - chain's left argument, a [2,3,6,12,18,24] ḟ - filter discard [36,48,36,54,72,72,108,144,216,288,432] Ṣ - sort [36,36,48,54,72,72,108,144,216,288,432] Œg - group runs of equal elements [[36,36],[48],[54],[72,72],[108],[144],[216],[288],[432]] Þ - sort by: L - length [[48],[54],[108],[144],[216],[288],[432],[36,36],[72,72]] Ḣ - head [48] Ḣ - head 48 ṭ - tack to a [2,3,6,12,18,24,48] 2,3Ç¡ị@ - Link: number, i e.g. 7 2,3 - literal [2,3] [2,3] ¡ - repeat i times: Ç - call last link (1) as a monad [2,3,6,12,18,24,48,54,96] ị@ - index into with swapped @rguments (with i) 48 ``` [Answer] # [R](https://www.r-project.org/), ~~127~~ ~~118~~ ~~111~~ ~~108~~ ~~105~~ ~~100~~ ~~98~~ 90 bytes 8 bytes thanks to Giuseppe. ``` r=3:2;for(i in 1:scan())r=c(min((g=(r%o%r)[i:-1<i])[colSums(g%o%g==g*g)+g%in%r<3]),r);r[3] ``` [Try it online!](https://tio.run/##Dcg5DsIwEAXQ/p8ijaUZFgnHrElccgGWKkqBIjAjJQ6agCgQZze88ml636W70ulw3nP2UIlP@iT1rsjL26AkmcTMFmN7icSsvqVeIlHwpGYwyrUUc1tJw3U7dMdXP1L4f/A@TAJPg5FotHINz5RLrV2TvgwL5IADlsAKWAMbYAvsALtIPw "R – Try It Online") [Answer] ## CJam (32 bytes) ``` 4,{_2m*{~>},::*1$-$e`$0=|}qi*-2= ``` [Online demo](http://cjam.aditsu.net/#code=4%2C%7B_2m*%7B~%3E%7D%2C%3A%3A*1%24-%24e%60%240%3D%7C%7Dqi*-2%3D&input=9) with 0-indexing. I'm not sure there's much to be done beyond a trivial translation of the spec with one exception: by starting with a list of `[0 1 2 3]` (instead of `[2, 3]`) I save one byte immediately on initialisation and another two by being able to do `0=|` (adding just the new element because its frequency is `1` and is already in the list), but don't introduce any false elements because for every `x` in the list `0*x` and `1*x` are already in the list. [Answer] # [Python 2](https://docs.python.org/2/), ~~127~~ 118 bytes ``` n=input() l=[2,3] exec't=sorted(x*y for i,x in enumerate(l)for y in l[i+1:]);l+=min(t,key=(l+t).count),;'*n print l[n] ``` [Try it online!](https://tio.run/##FcpBCsMgEADAu6/wFo0SmvTW4EuCh5Bu6VKzil1BX2@b6zCp8TvS0js5pFRYaRHctti7F1DhGNh9Y2Z4qjo2@YpZoq0SSQKVE/LOoIK@uF0YNjTzw@s1GHciKbYfaE4Fw3o6YiHWdh1GEikj8X@T732@/QA "Python 2 – Try It Online") [Answer] # Mathematica, 154 bytes simple modification of the code found at oeis link ``` (s={2,3};Do[n=Select[Split@Sort@Flatten@Table[s[[j]]s[[k]],{j,Length@s},{k,j+1,Length@s}],#[[1]]>s[[-1]]&&Length@#==1&][[1,1]];AppendTo[s,n],{#}];s[[#]])& ``` [Answer] # [PHP](https://php.net/), 130 bytes 0-indexed ``` for($r=[2,3];!$r[$argn];$r[]=$l=min($m)/2){$m=[];foreach($r as$x)foreach($r as$y)($p=$x*$y)<=$l|$y==$x?:$m[$p]+=$p;}echo$r[$argn]; ``` [Try it online!](https://tio.run/##VY49D4JAEER7foXiFpyaaNDKY0NhKGy0sbtcCCEnRyKwWSkgfvz187QxdvMyeZkhSy5JyVJgmDvO2VDHfd1W0SvLj6fzYZ8JGUDBVYvhdh1Kd@k4AkYVLzdaToHVt9TSJ41wxaZuI2jEKhZ3aFBp6QVTlNZLk@IGg/jnUURACMPcp8T7DxjRY7qDRgHpBQLJpylt91tyM@K67fPPDyHdGw "PHP – Try It Online") Expanded ``` for($r=[2,3];!$r[$argn]; #set the first to items and loop till search item exists $r[]=$l=min($m)/2){ # add the half of the minimum of found values to the result array $m=[]; # start with empty array foreach($r as$x) # loop through result array foreach($r as$y) # loop through result array ($p=$x*$y)<=$l|$y==$x? # if product is greater as last value and we do multiple two distinct values :$m[$p]+=$p; # add 2 times or more the product to array so we drop 36 cause it will be 144 } echo$r[$argn]; # Output ``` # [PHP](https://php.net/), 159 bytes 0-indexed ``` for($r=[2,3];!$r[$argn];$r[]=$l=min(array_diff_key($m,$d))){$d=$m=[];foreach($r as$x)foreach($r as$y)$x<$y?${dm[$m[$p=$x*$y]<1&$p>$l]}[$p]=$p:0;}echo$r[$argn]; ``` [Try it online!](https://tio.run/##VU47C8IwGNz9FT4OacTBx2YaHcTBRRe3EkJoU1u07cenQ4PoX6/RRYQb7gF3RwV18YYK6jnmhg07avhe1ufotTOH42m/3QnZg@VzrYbz2VB2ecMRWCWL6VLLATj5hloGphWuqirryDJbb7Iyz83F@QjVFJkQ4oFMoVKJlqHE2bQIRX17Qyv@tRdoY/gNHlmVIIAU2gm8judj0BpX/QxeWKPVTD5dWjS/G92IuKzv5nNSyO4N "PHP – Try It Online") # [PHP](https://php.net/), 161 bytes 0-indexed ``` for($r=[2,3];!$r[$argn];$r[]=$l=min(array_diff($m,$d))){$d=$m=[];foreach($r as$x)foreach($r as$y)$x<$y?${dm[!in_array($p=$x*$y,$m)&$p>$l]}[]=$p:0;}echo$r[$argn]; ``` [Try it online!](https://tio.run/##VY49C8IwGIR3f4UfhyTSwY/NGB3EwUUXtxJCsK0NmPTl1aFF9K/X6iJudxw891BJ7WpDJfVy5oot51Tx3ceLeO3s4Xjab3dS9eD4EvVwNh2qtqhYgHU6TxZGDcDpdzSqS0bjqoOPwjG7xma@KARCgkxK@UCmEXRqVAfI3bnsIH13Qy3/eyNRr9Bs8MhCOvDRflkCpFFP0CQIcgxa42qenz9aTtUzP5fVT6QdEft4tx9Nqdo3 "PHP – Try It Online") [Answer] # Mathematica, 140 bytes ``` (t=1;s={2,3};While[t<#,s=AppendTo[s,Sort[Select[First/@Select[Tally[Times@@@Permutations[s,{2}]],#[[2]]==2&],#>Last@s&]][[1]]];t++];s[[#]])& ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 25 bytes ``` 3:i:"t&*9B#u2=)yX-X<h]2_) ``` [Try it online!](https://tio.run/##y00syfmf8N/YKtNKqURNy9JJudTIVrMyQjfCJiPWKF7zv0vIf0MuIy5jLkMDAA "MATL – Try It Online") ### Explanation ``` 3: % Push [1 2 3]. Initial array of MU numbers, to be extended with more numbers i: % Input n. Push [1 2 ... n] " % Do this n times t % Duplicate array of MU numbers so far &* % Matrix of pair-wise products 9B % Push 9 in binary, that is, [1 0 0 1] # % Specify that next function will produce its first and fourth ouputs u % Unique: pushes unique entries (first output) and their counts (fourth) 2= % True for counts that equal 2 ) % Keep only unique entries with count 2 y % Duplicate (from below) array of MU numbers so far X- % Set difference X< % Minimum. This is the new MU number h % Concatenate vertically horizontally to extend the array ] % End 2_ % Push 2 negated, that is, -2 ) % Get entry at position -2, that is, third-last. Implicitly display ``` [Answer] # [Perl 6](http://perl6.org), 96 bytes ``` {(2,3,{first *∉@_,@_.combinations(2).classify({[*] $_}).grep(*.value==1)».key.sort}...*)[$_]} ``` [Try it online!](https://tio.run/##Dc1RCsIgGADgq/wPI1Tkhy3qZQx2j7HEhgtpm6IuEPG9ztRbR@ki1neBzyq3nMsa4TBDVxJp@JGnWTsfgH2fr17wXuBk1qveZNBm86ShOC3Sez1HkgY2QiUyxZtTljB8yGVXXVfTzxvvKqI3LmREZHSoxJhLC15GWKX9fxwu9aktPw "Perl 6 – Try It Online") * `2, 3, { ... } ... *` is an infinite sequence where each element starting with the third is computed by the brace-delimited code block. Since the code block takes its arguments via the slurpy `@_` array, it receives the entire current sequence in that array. * `@_.combinations(2)` is a sequence of all 2-element combinations of `@_`. * `.classify({ [*] $_ })` classifies each 2-tuple by its product, producing a hash where the products are the keys and the values are the list of 2-tuples that have that product. * `.grep(*.value == 1)` selects those key-value pairs from the hash where the value (ie, the list of pairs having that key as a product) has a size of 1. * `».key` selects only the keys of each pair. This is the list of products that arise from only one combination of factors of the current sequence. * `.sort` sorts the products numerically. * `first * ∉ @_, ...` finds the first of those products that has not already appeared in the sequence. [Answer] ## JavaScript (ES6), ~~119~~ ~~118~~ 117 bytes A recursive function that takes a 0-based index. ``` f=(n,a=[2,m=3])=>a[n]||a.map(c=>a.map(d=>c<d&(d*=c)>m?b[d]=b[d]/0||d:0),b=[])|f(n,a.push(m=b.sort((a,b)=>a-b)[0])&&a) ``` ### How? At each iteration of ***f()***, we use the last term ***m*** of the sequence and an initially empty array ***b*** to identify the next term. For each product ***d > m*** of two earlier distinct MU-numbers, we do: ``` b[d] = b[d] / 0 || d ``` and then keep the minimum value of ***b***. The above expression is evaluated as follows: ``` b[d] | b[d] / 0 | b[d] / 0 || d -------------------+-----------+-------------- undefined | NaN | d already equal to d | +Infinity | +Infinity +Infinity | +Infinity | +Infinity ``` This guarantees that products which can be expressed in more than one way will never be selected. ### Formatted and commented ``` f = (n, a = [2, m = 3]) => // given: n = input, a[] = MU array, m = last term a[n] || // if a[n] is defined, return it a.map(c => // else for each value c in a[]: a.map(d => // and for each value d in a[]: c < d & // if c is less than d and (d *= c) > m ? // d = d * c is greater than m: b[d] = b[d] / 0 || d // b[d] = either d or +Infinity (see 'How?') : // else: 0 // do nothing ), // end of inner map() b = [] // initialization of b[] ) | // end of outer map() f( // do a recursive call: n, // - with n a.push( // - push in a[]: m = b.sort((a, b) => a - b)[0] // m = minimum value of b[] ) && a // and use a[] as the 2nd parameter ) // end of recursive call ``` ### Demo ``` f=(n,a=[2,m=3])=>a[n]||a.map(c=>a.map(d=>c<d&(d*=c)>m?b[d]=b[d]/0||d:0),b=[])|f(n,a.push(m=b.sort((a,b)=>a-b)[0])&&a) for(var n = 0; n < 10; n++) { console.log('MU[' + n + '] = ' + f(n)); } ``` [Answer] # [Haskell](https://www.haskell.org/), ~~117~~ ~~115~~ 113 bytes ``` n x=[a*b|[a,b]<-mapM id[1:x,x]] d x=minimum[a|a<-n x,2==sum[1|b<-n x,b==a]]:x l x|x<3=x+1:[2]|1>0=d$l$x-1 (!!0).l ``` [Try it online!](https://tio.run/##Jcs9CgMhEEDh3lO4YJEfDeumEyc3yAnEYsQskags2QSm8O5GSPnxeE/cX4@ce6@cwOEpNIcyeKsKbneeotOGJHnP4ugl1VS@xWFDq8YgF4B9WLfwdwBA7w2xzKmRvQKdtXGLb/o2QxRZkNJshcM0zcdL7gVThe2d6kesXPcf "Haskell – Try It Online") [Answer] # [Python ~~3~~ 2](https://docs.python.org/2/), ~~167~~ ~~139~~ ~~136~~ ~~133~~ ~~123~~ ~~121~~ ~~120~~ 118 bytes ``` a=[2,3];exec'p=[x*y for x in a for y in a if x-y];a+=min(q for q in p if p.count(q)+(q in a)<3),;'*input();print a[-2] ``` [Try it online!](https://tio.run/##Jck9DsMgDEDhq3gL5KcDUSfKSRCDFSWqhxoTEQlOTxS6Pb1Pav5GNq2h82Zeg93Lvg3ifBkrHPGEAsSAPes/6YCy1GBxcj9ilbqlx@QxeW3x4qySnlS/qD@rnu0wEsuVlbZyEmdAv5jQ2vsG "Python 2 – Try It Online") --- Thanks to @Mr.Xcoder and @LeakyNun for improvements! ]
[Question] [ Divide the first quadrant (including the positive x-axis, the positive y-axis, and the origin) into 1x1 grids, with each grid labelled by the coordinates of its bottom-left corner, as demonstrated below: ![](https://i.stack.imgur.com/61W6S.png) Note that each grid contains its boundaries and its vertices. Using mathematical symbols, the grid labelled (m,n) would represent the square `{(x,y) | m ≤ x ≤ m+1, n ≤ y ≤ n+1}`. --- Given a straight line in the form of `ax+by+c=0` with integers `a`, `b`, and `c`, and a grid represented by `(m,n)`, output whether the line passes through the grid, i.e. whether any point in the given grid is on the line. --- ``` a b c m n output 1 1 0 0 0 true 1 1 0 1 1 false 1 1 0 0 2 false 1 1 -3 0 1 true 1 1 -3 0 0 false 2 -1 0 1 1 true 2 -1 0 1 0 false 2 -1 0 0 2 true 2 -1 0 0 1 true 2 -1 0 1 2 true 2 0 -1 0 0 true 2 0 -1 0 1 true 2 0 -1 0 2 true 2 0 -1 1 0 false 2 0 -1 1 1 false 0 2 -1 0 0 true 0 2 -1 1 0 true 0 2 -1 2 0 true 0 2 -1 0 1 false 0 2 -1 1 1 false 1 0 -1 0 0 true 1 0 -1 0 1 true 1 0 -1 0 2 true 1 0 -1 1 0 true 1 0 -1 1 1 true ``` Please suggest more testcases in the comments. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Answer] # Python 3, 84 66 bytes First golf, first fail (maybe). Thanks to Rod for shaving off 18 bytes by using a function instead of direct input. ``` def f(a,b,c,m,n):f=-(a*m+c)/b;g=f-a/b;print(min(f,g)<=n<=max(f,g)) ``` [Try it online!](https://tio.run/##Hcc9DoAgDEDhqzi2WqLETeEwgBYZqMYw6OnxJ2/48o67bLuMtS4rNwyOPAXKJDixVeDa3AXs/RwtK/d6nEkK5CTAFNFYMTa76x@sDJo0DV9YHw) **Explanation:** Basically we calculate the value of the line function for m and m+1, if n is inbetween the values, then the list must pass through it at some point. Would be much better if the language had some simpler way to input multiple integers. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ż‘{Œpæ.ṠE¬ ``` [Try it online!](https://tio.run/##y0rNyan8///onkcNM6qPTio4vEzv4c4FrofW/H@4Y9OhnYcnpB2dFPaoac2hrQ93Tis2frhz1uHl@joPd67iOjqp5OHuLYfbgZLu//8bKigAkQEYlhSVpnLBBAyBMC0xpxghYqBghCyiawxWhdAEFjCAKjFS0IUbA1aCEEBXAjIXRYkBph64CiBP1xDhWoSAIboAmhZke2EiMB8aKCgYoRgLEzBEFzBCFzDAMAQl4FBda4juWkN01xoiuRZNAKIFAA "Jelly – Try It Online") ### Background Like other answers before mine, this relies on the fact that a straight line divides the plane into two semi-planes. The rectangle is either contained in one of these semi-planes (no intersection with the line) or intersects both semiplanes (and thus the line that separates them. ### How it works ``` ż‘{Œpæ.ṠE¬ Main link. Left argument: [m, n]. Right argument: [a, b, c] ‘{ Increment left; yield [m+1, n+1]. ż Zipwith; yield [[m, m+1], [n, n+1]]. Œp Cartesian product; yield [[m, n], [m, n+1], [m+1, n], [m+1, n+1]]. æ. Take the dot products with [a, b, c], mapping each [x, y] to ax+by+c. Ṡ Take the signs. E Test the signs for equality. ¬ Logical NOT. ``` [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` lambda a,b,c,m,n:min(0,a,b,a+b)<=-a*m-b*n-c<=max(0,a,b,a+b) ``` [Try it online!](https://tio.run/##ZZDNbsMgEITP8VNsLUVyUqiMe4viY3LtJVIvlSrs4sQSYAS4SZ7eBTf@I8IS7MfMsGt1t5dGZt1XlXeciuKHAkUFKpFAcidqmaTI1/S12OxzTLcCF1uJy30u6G1211ndMsjh5Laootz44uj3yOr7LlpdLzVnQNxpxd2VptfvWqrWJhtHjCPjq8i6SlCVsF/KEX8zitdO5nU6r5JR50FdgX7JrU9dKV1LC/GnbuQZmta6cKgaDWsTwxpMxG4lUxYOH8eD1o12nofjxIyFkhpmoGyE4syyuCMA7kv75WeLBkDc6geMJkk2J/i9V02mHqQPSQZ4jOklEwglPnchSZ89o8JVmEzdToCEILDM3x3IMGEKkC1iB0BCkIUgfQpZ/LhltyTsloTdklm3Afi3/AE "Python 2 – Try It Online") We can tell which side of the line a point is by the sign of `a*x+b*y+c`. The line passes through the square (counting touching) unless all four vertices `(m,n),(m,n+1),(m+1,n),(m+1,n+1)` are strictly on the same side of the line. We can plug these values in an extract out the constant `a*m+b*n+c` that appears in all four: ``` a*m+b*n+c a*m+b*n+c+a a*m+b*n+c+b a*m+b*n+c+a+b ``` So, the line passes through the square unless these four values are all positive or all negative. So, it suffices for their minimum to be `<=0` and maximum to be `>=0`. ``` min(a*m+b*n+c,a*m+b*n+c+a,a*m+b*n+c+b,a*m+b*n+c+a+b)<=0<=max(a*m+b*n+c,a*m+b*n+c+a,a*m+b*n+c+b,a*m+b*n+c+a+b) ``` Subtracting the common `a*m+b*n+c` from each part gives the code. A slightly longer approach is to check whether the set of signs (+,0,-) has length at least 2. **[Python 2](https://docs.python.org/2/), 62 bytes** ``` lambda a,b,c,m,n:len({cmp(a*m+b*n+c,-d)for d in(0,a,b,a+b)})>1 ``` [Try it online!](https://tio.run/##ZZBda4MwGIWv9Ve8Ewpa4zDuruDu2tvdFHYzGFEjFWIMSVxXxn67S1z9SokQ38dzTk4UN33peDbU@cfASFtUBAgqUIlaxA@M8vCnbEVI9m1c7HlcoqSK6k5CBQ0PU2SlJC6i3@gVD1r2FHI4m82vCVN2ONnd1/J28L3rpWEUsHnzmPkkyfWz4aLXYWSIMmQ@GGkztUSE9IswxJ6VYI2RWZ3M63DWWdDUIJ9ybVM9IRuuIXiXnabQ9dqEg227UwHsQPn0u6RCw/HtdJSyk8Zzd5yp0lASRRWUXSsY1TQYMIB50nHZu/kTwGaNF/QXSbYmycuoWkwjSO@SDJI5ZpQswJXY3I0kffTMCjMleGm7AOwCx7I@dyLTDVOAbBM7AeyCzAXpQ8jmx23bYrctdtviVVsH/Fv@AA "Python 2 – Try It Online") [Answer] # Mathematica, ~~60~~ 55 bytes ``` Solve[m#+n#2==-#3&&#4<=m<=#4+1&&#5<=n<=#5+1,{m,n}]!={}& ``` *-5 bytes thanx to @MartinEnder* input form > > [a,b,c,m,n] > > > [Answer] ## Batch, 66 bytes ``` @cmd/cset/a"q=%1*%4+%2*%5+%3,((-(q+%1)*(q+%2)&-q*(q+%1+%2))>>31)+1 ``` Explanation: We consider the values taken by the equation at the four corners of the cell. If the line does not intersect the cell, then all four values have the same sign, but if it does intersect the cell, then at least one value will be zero or the opposite sign. The comparison is simplified by multiplying pairs of opposite corners, then if both values are positive then the line does not intersect the cell. Some bit-twiddling then converts the multiplications into an overall result. [Answer] # [Python](https://docs.python.org/), 54 bytes ``` lambda a,b,c,m,n:abs(2*(a*m+b*n+c)+a+b)<=abs(a)+abs(b) ``` [Try it online!](https://tio.run/##ZZDNboMwEITP8BRbpEj8Vti9ReWYXHuJ1EulylDTIBmwbNM0T0/XNEBwZKRlP2bGu8irOfcdHeviYxSsLb8YsLRMq7RNuz0rdUjjkMVtUsZdUkUJS8rotbCcYYOljEajBg4FnLD4NRPaNkdbfaOue9@7nBvBgeCbJ/CTYpfPppODCSMkGslyYWqwa5kM@Q8TqXjWUjQoszpV1OGis6CpQT0VxqZ6UjWdgeBd9d039IPBcKh7BTsdwA60z38rLg0c3o4HpXqFnpvjxLWBimmuoepbKbjhwUgA8MmnY3fzZ0DwTAv6q4Tek@xlUq2mCeQ3CYVsiZkkK3AlNncjyR89iwK7jKzTroC4wLHc3zuTecMcgG5iZ0BcQF2QP4Rsftx2WuJOS9xpyd20Dvi3/AE "Python 2 – Try It Online") (Thanks to xnor for the testing script.) ### How it works The line goes through *m* + 1/2 + *x*, *n* + 1/2 + *y* if and only if *a*⋅(*m* + 1/2 + *x*) + *b*⋅(*n* + 1/2 + *y*) + *c* = 0 ⇔ 2⋅(*a*⋅*m* + *b*⋅*n* + *c*) + *a* + *b* = −2⋅*a*⋅*x* − 2⋅*b*⋅*y*. This is possible for some |*x*|, |*y*| ≤ 1/2 if and only if |2⋅(*a*⋅*m* + *b*⋅*n* + *c*) + *a* + *b*| ≤ |*a*| + |*b*|. [Answer] ## Mathematica, 50 bytes ``` -4<Tr@Sign[Tuples@{{#,#+1},{#2,#2+1}}.{##4}+#3]<4& ``` [Try it online!](https://sandbox.open.wolframcloud.com/) Takes `m, n, c, a, b` as input in that order. Explanation: `Tuples@{{#,#+1},{#2,#2+1}}` makes a list of the coordinates of the four corners of the square, then taking the dot product with `.{##4}` (which means `{#4, #5}`) and adding `+#3` computes `ax + by + c` for `x,y` at each corner. If the line passes through the point, this is zero; if the line is further from the origin, it's negative; and if the line is nearer to the origin, it's positive — therefore we check the `Sign`s of these four values. The line passes outside the square if and only if all four values are 1 or all four are -1, so we check that their sum is strictly between -4 and 4. (This answer is vaguely inspired by my answer to [this question](https://codegolf.stackexchange.com/a/116337/66104).) [Answer] ## Python 2, 147 110 bytes ``` def f(a,b,c,m,n): if b:d=sorted((-a*x-c)/float(b)for x in(m,m+1));return d[0]-1<=n<=d[1] return m<=-c/a<=m+1 ``` And a *huge* thanks to Leaky Nun! [TIO.](https://tio.run/##dZFBbsMgEEX3PsUsoR0Uxt2lZtsTdGd5gY1RLdk4IkRKT@86kZMm9kRILJ7efPhw@E0/Y8inybUevLBYY4MDBrnPoPNQ7505jjG1Tghl386qkTvfjzaJWvoxwhm6IAYc3knKz9imUwzgSl0pKkwojCupymDhQ2FUs7OFme3pELuQwPa9KDMvCAn1ZUkwBr7jqcU7nfcr/bL98QFrzLdYfVwGNiFXrJ/1HNVj@k2/Y16/nbrS9auUta0Xn8fEYzaEueHCV881z3OHLph4nPNYvwhn/ohtSnxT4pvSc9MN/g/JKjn9AQ) [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 71 bytes ``` (a,b,c,x,y)->(0<a?0:a)+(0<b?0:b)<=(x=-a*x-b*y-c)&x<=(0>a?0:a)+(0>b?0:b) ``` [Try it online!](https://tio.run/##hVTLboJAFN37FTckNmAHMth0o6Kbppum7cJl08UAg8EiQ5jBQBq/3V55SY1AMpCTOTPnPuDcPTsyUyQ83vs/5/CQiFTBHvesTIWRNVtOksyNQg@8iEkJ7yyMfycAYax4GjCPw6sQlw0AV4iIsxhcluovAi9xYARq5LbIa1HeosJYosQJH6mYwmAoCoEQzllnxCUeyUlhmGudrtiGLpjxiMhF5BorR88dk81y050Vpmc85LhD1@2xdXXsfEnwEqMupg5zFKEPByxJ36o0jHdf3yzdSaOqR3GpdJsALlq@cQUskrxM9pbHNe/lzadGQ6VZP0/vCKCo2c3gVuAfPyxQpdgvQMcD3L9PuxKDvD3CD@r3F3g9cO8bVbr9GV55e4Sfj/B0LIH@v2iwh/ZID@2RHto3PRzku/odS5ZeKU/7jbn9xtt@Y22/cXYNCtJMBZ4n3FPcr821LaTiB0tkykrQeSrQtencogH0vp/lAqZyGmukHQmkESU4K6zL3LlOC8dpyI32@aYttA@hAEFd1un8Bw "Java (OpenJDK 8) – Try It Online") Port of xnor's Python solution. ### Original solution, using Java's shape/line intersection built-in (108 bytes) ``` (a,b,c,x,y)->b==0?x<=-c/a&-c/a<=x+1:new java.awt.Rectangle(x,y,1,1).intersectsLine(x,c=(c+a*x)/-b,x+1,c-a/b) ``` [Try it online!](https://tio.run/##hVRLb6MwEL73V4yQsoKtITirXtKyve1lH5Xa42oPY@NEpNSOsNMSrfrb0zGQNE0DSH7J38w3D/i8wmeMzVrpVf64W29EWUiQJVoLv7HQ8P8CoNBOVQuUCn4Y09wACGNKhRoEVmFuyE0BMuhO4nCSzHtD3W7b6JqcX2lah44Ceb4FzQx2ITLBJKvZNoq/iyxLb@ubLJZT/OKXm6y@5HOtXmBF@Sb44pJ7JR3qZalC8mGc8ShpErV0b38V2t/LLJSX@LWOprFgxMBkjFMR7XwFPpWu3i6bZ1Pk8ERVhw@uKvTy7z/AammjrmSnrAs5Axpps9JYYGlVU9UpTmPWi8ff9hyu2vTj6RkCIo2PMzgl@IAPE7Qp9hOk4wHO@6fHFIM4H8EH@fsLfDc4941a3v4M33E@gs9G8HQsgf6/aLCHfKSHfKSH/KSHg/gx/5F2G7U01l7a2CpctNuJ7NnhuVD1muSp8r2mHrbWqafEbFyyJsm5RRhMZjl8mld2DhM70QHzkSgKRSB2Yt4zMv@QJP45@mAQQZYdbOAWgrufwRyCP8YBnbqaXndv "Java (OpenJDK 8) – Try It Online") ## Credits * -8 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ]
[Question] [ You know how you get a voicemail message and the person's connection wasn't great, and you're trying to figure out how to call them back, but you're not sure if that was a "5" or an "8" they said? That's this challenge. The good news is that the caller read off their number twice, but it's garbled in both places. Your program should take input like this: ``` 5551231234 / 5551231234 ``` Where the first ten digits are the first time the phone number is said in the voice mail and the second set are the second time it's said. Only...it'll look more like this: ``` 555?ABC1_36? / 55?522_1?234 ``` * A digit followed by a question mark means that that's the best-guess for that digit (e.g. "5?" means "probably a 5, compare with repeat"). * An underscore indicates a known missing digit, something too fuzzed by static to be deciphered at all. * Letters are just that: letters. Treat them as their respective digits + ABC -> 2, DEF -> 3, GHI -> 4, JKL -> 5, MNO -> 6, PQRS -> 7, TUV -> 8, WXYZ ->9 + All sample inputs use uppercase (you can safely omit a ToUpper() call) + If your language works better in lower case, you can freely use lowercase for the input and omit a ToLower() call. Just note that in your answer. You can additionally assume the following judgement calls: ``` 5? / _ -> 5 //5 is the best guess we have, use it 5? / 5? -> 5 //uncertain, but matching 5? / 4? -> ? //conflict 5 / 4 -> ? //conflict 5? / 4 -> 4 //solid information overrides possible value 5 / 4? -> 5 //solid information overrides possible value _ / _ -> ? //no information available ``` Additionally you can assume that all inputs will contain ten-digit phone numbers, not including the question marks. Inputs that aren't ten digits (e.g. `1234567 / 1234567`) can either be treated as unsolvable (falsey output) or throw an error. ### Input One line of characters `0-9A-Z _?/`, as described above. ### Output If it can be parsed to a single valid ten-digit phone number, output the phone number. Otherwise output some form of error indication (e.g. -1, false, or an empty line). Shortest wins, as per usual. Sample inputs: ``` 1234567890 / 1234567890 1234567890? / 1234567890 123456789_ / 1234567890 1234567890? / 123456789_ 1234567890 / 1234567890? 1234567890 / 123456789_ 123456789_ / 1234567890? 1234567890? / 1234567890? 1234567890? / 1234567891? 123456789_ / 123456789_ 555CALLUS1 / 5552255871 404_12?6039 / 4041?1560_9 _GETREVENGE / 16?36?_2838_ 1?691460_50 / 16_14609?50 61?08977211 / 612?897725?1 40?0INSTA__ / 8?00_NSTI?LL 3985_534?10 / 39?8?5053_10 7__7294?737 / 7797299?_37 28?897_384?1 / _8?89763861 271168090_ / 27116800?09 6802?148343 / 67?01148343 94_11628?2?6? / 9491162_47? 17?4285_689 / 1__26?52689 6_311?95_38 / 6731194?7?38 380?7DRAGON / 3807378?5?66 4?647_93236 / 5646?6?9__36 365?268898_ / 366267?7?984 GRATEDBATE / IRATEDBATE 5307_079?93 / ____8_____ 535_3_0255 / 52?5_3_024?5 55_____088 / 54?2397207?7? 6_48398_95 / _946?398?6_5? _0_312_3_1 / 81?53123?1?71 ____1_____ / 64?255?508?61 8427820607 / 6?424?8?__6?07 50_3707__6 / 52?8375?74?56 615___8255 / 62?526?983?2?1? __652618__ / 8365261__0 149___933_ / 1_9677?92?31 ___7?281562 / 3438?28154?2 5?7?7?___8?3?7?4 / 57_855837_ 605_272481 / 605427__81 86?569__731 / 88560?0?7721 1__91654?15 / 17?9?9165715 800NWABODE / 80069ABI?DE 8___9017_0 / 8_2494?12?9_ _024?5?91?470 / 304?17908?7_ 42510704_2 / 4_51070492 9338737_89 / 93_873PLUS 327762_401 / 327_MASH01 33093_2058 / 3309_12058 4061_33578 / 40619_3578 559_383197 / 559938_197 94_9746084 / 9459746_84 1_37655238 / 163POLKA_T _672FRIZZY / 767237499_ 8_76318872 / TIP63188_2 51_8404321 / 5178404_21 358_030314 / 358603_314 2597_85802 / 25979_5802 77141_1408 / 7714_91408 330858_457 / 330_586457 4686079_39 / 46_6079239 86457508_6 / 8_45750826 523226626_ / _23BANNANA _ISSY_ISSY / 44__9548?79? 6?00B_YJILT / 800289KILL? 2?52803___0 / 1526?0390?61? FI?ND___T?HE / EAS?T?EREGGS? 0_231?95_38 / 0723194?7?38 0?647_39236 / 0646?6?3__36 025?267798_ / 06?6265?9?984 0061_33578 / _0619_3578 ``` I've only insured that every possible edge-case is covered (the first 11 entries), but other than that, it's pretty much random. **Update** Four entries at the bottom added with leading zeros (at Jonathan Allan's suggestion). Correct output for the sample inputs: > > <https://pastebin.com/gbCnRdLV> > > > Based on the output from [Jonathan Allan](https://codegolf.stackexchange.com/a/117357/47990)'s entry (the formatted output was ideal). [Answer] # [Python 2](https://docs.python.org/2/), ~~314~~ ~~307~~ 274 bytes ``` lambda s:g(*''.join(q<n<"["and`(int(n,36)-4-(n>"R")-(n>"Y"))//3`or n for n in s).split(" / ")) def g(a,b,s=str.startswith): if b:c,d,e,f=a[0],a[1:],b[0],b[1:];b=(c==e and[c,q][c=="_"]or"_"in c+e and min(c,e)or[q,c,e][s(f,q)-s(d,q)])+g(d[s(d,q):],f[s(f,q):]) return b q="?" ``` [Try it online!](https://tio.run/nexus/python2#jVZbb1pHEH73rzg6L4EGO3u/uCEjXBOHhpLI0FYOtabYhtRVgmOgaqtsfnv6zZI2T5aKpXP2O7M78811ver/8vnd4v3VzaLZHr/tfPPo0dHvd7frzv3T9dN23i7WN792bte7zrpnQ/fQHXbWz9rztlvfF223@@SJ/fVu06ybVX3erptt92j74d3trtM2TxrsOLhZrpq3nUXvqrftb3ebo@1usdlt/7zd/dY9PmhuV83V8XXvprfsrfqLubrsLeb6@LJ3JcsrWX571e9c9/vLBmTm1737yzlQy@3l3QZPWLx@XGXNe/C@7i27d5v5fQ@Ly/m2s@rddw@3nRu8LruP33Zu5nsAC6sv4uPL7kGzWe7@2Kybq4P7fkvt591yu9v2W22s8yGmrODLV1C@LukBAf@vA1wesEAPCPghC/Qgpwclmh5QxsV7/91gPP5xqvEdwBjvU9TFKcfaUFA2QwCkSfugOBc@G87Ohz8NJ2dDURXIBmKTbAJjClk77PLVlcACMnlVgiaVcoxGi50AzRV5EkukRpPpbMBCLZFSDDSi8bjYnDx760iLPpspQZe3rFWJzNFkR9FGiGLMQJnYxmKS6GabcAwirjDYFHQxUeuQVFZi6QuA9VzwNqRdss4KvUhK71HJCIMO0IlYSEyzy4LZRcQ0kjNgGJLESDObQN4AlcBWa8oeLKo@IOFKNhWbFMXT88HZq4n4lBQ8gFsUQnEUXORsjQ2SjOACbGZmG4oNnqA55STUbQgGJCPl5MrZ@WA2PD3BA5LRf6B4qyKrmCmLT4xfkgdSbsGLkWcxYkiAMo48aqFuUElIe0fGIqpK7MAhhAPGsxziDGZAFNhTYQVnDZRItJMmD2RJE4pItOmqU6IAhd4jgTinS3ImJqOCkvQFxNEhucyBVCweGiPIc9gzTDZ6imAYUEfCMe3JByPhRhAssoMaxwFgnfaFZCuAO0U7BBFxtbX2OYeIyBmylWAkk1DZRsLqbKoITAss4k@MkcXCCZXICd1hI5egPJtoXKrlrDy8wU64hQoIsIaMC4eEliHkG3VfQCXrAN1auKN2kBngqH1BFU5@Hpy8OpUUAoQ8OBnR6bBIxrLSyKMI2DhUEXoHfbtPGTSQi7U5FCQxI7hg54zXKqKDxSvHe5BNQQgSyo1rvWbLAK/R@sWaGKWmlZAG4B8G0xdKF2sVdhnlpSAEYCQAoGURWGt9THU2BJ1ZAAoIi2R1jnWY5IyhACBNlCNGQXK1g7wARulCSQyYObVLdLCvX41fDnhWOETz/Hz05s2F9DaAjS7D6cRoZJ1SFL9mo9cVMHKloU05a@oQ01EAI@TWJ1ZWWS12ATDNUKuuGDBAKtH0MgcAMgsoMWqnMbRUqjNFg7YAiQN2s/NxHwfsDgDFBajE4f2MDCwATVOqFIVeC7ieAzChwFNjpHelENnYk8FkMpgMCo@m04v6ED0OOfcOiczoO4zDE774fjSe7UvDpPxyNB5TkdpP8IdrbWhpBMxqhd6i8nxEk1NIZvRCKmo4mNKMhufDs7MptQcHcoHLtSd3eL3@/r3GSyv3NH67zd/Hm/6qI9Ju/bL863r5YYeP7XCzwXVcP37Y4B@Gpv14bPKnw2fNx0/tEXS/X@zqwd6m@/kf "Python 2 – TIO Nexus") [Answer] # Python 3, ~~549~~ ~~530~~ ~~509~~ ~~453~~ ~~449~~ ~~410~~ ~~406~~ ~~394~~ ~~393~~ 391 bytes I'm sure this can be improved, but it's a start: ``` def f(e,z,q="?",u=str.isnumeric): if e+z in(e,z):return"" o,O,t,T,*x=e[0],e[1:2],z[0],z[1:2],e[1:],z[1:] if"?"in o+t:return f([e,x[0]][o==q],z) if u(o): if u(t):return t+f(*x)if O==q!=T else o+f(*x)if o==t or T==q!=O else 1 return o+f(*x) if u(t):return t+f(*x) def g(s): for a,b in zip(map(chr,range(65,91)),"2223334445556667777888999"):s=s.replace(a,b) return f(*s.split(" / ")) ``` I'm using `str.translate` for the letters, and a wrapper function `g` to make the inputs in the format in which I want them. The actual function `f` is recursive, and will fail for ambiguous inputs. I still have lots of repititions in there though, so I'm sure there's lots of room for improvement. Improvements: * saved 19 bytes by combining conditions * saved 21 bytes with ternaries * saved 56 bytes using a dictionary comprehension instead of the manual dictionary, thanks to @TuukkaX * saved 4 bytes by switching to the method suggested by @ovs, with @TuukkaX's improvement * saved 38 bytes with improvements from @ovs (and the last removable whitespace removed) * saved 4 bytes by putting defining `str.isnumeric` in a keyword argument * saved 12 bytes with combined comparison operators (e.g. `T==q!=O`) * saved 1 byte by turning `not(e or z)` into `e+z in(e,z)`. * saved 2 bytes by saving the frequently used `(E,Z)` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 84 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +4 bytes - I think it should probably behave the same in all cases, so I've converted the keypad lookup integers back to digit-characters using `+49Ọ`. ``` ”?e‘ḣ@µ”_eḤ‘ẋ@ ;Ṃµ68DṬ+3RØAṁẇ@€FT+49Ọȯµ€Fṡ2i”?Ḃ$ÐḟÇ€ ḟ⁶ṣ”/Ç€ZLÐṂ€Q€LỊ$ÐfF€Ḣ€ḟ”_µL⁼⁵ȧ ``` A function which takes the string in the specified format and returns the phone number as a list of character or zero if invalid. As a program this is printed as if it were a string. The way it works they could repeat the number more times (e.g. `"123456789_ / 123456789_ / 1234567890"`) ...or even only say it once, and the logic defined will apply. **[Try it online!](https://tio.run/nexus/jelly#@/@oYa596qOGGQ93LHY4tBXIi099uGMJSGBXtwOX9cOdTYe2mlm4PNy5Rts46PAMx4c7Gx/uand41LTGLUTbxPLh7p4T64H6gNyHOxcaZYKMe7ijSeXwhIc75h9uB4pzARmPGrc93LkYKKcPForyAUrvbAKyAoHY5@HuLqD6NDcg@@GORWByPsghh7b6PGrc86hx64nl////V3IPcgxxdXECEgr6Cp5wjhIA)**, or see [all the sample inputs](https://tio.run/nexus/jelly#jVSxbhxHDO3nK1y4cwDPDGc4M0hBraLT@eLLSbm7JJAbVg6Qv7DUCEhSpHQTGIkDuDHgJgp0Viqp0W/s/YjyOBfE1QGRoNW@5Qz5SD7yYfvqV3m5ffV6vH57cHsFpC/H6z/sw8efDtzn4@bi9orr0bh5/4SWd6@HcXM@frw82F68P14/SW28@fn@A@4Bjpvf4g/mbry@eHz3y3j95u4S3x1etud/jZu3sD3tn17MYd5c4O1r/M3Hmx9x/vtjvI/Xv/fnGyNyezXfnv@9Pb@6f/dwd3n/Ad@8G2/@/Ozu8jFOTR8eQqSUudTmHz199Am4T6@yx6D/64K6PRFkj0H3RZC9nPZaguxxpi7n/MUwn3@zCvgOEGPOtQSXfNIQhT01GICChMxem9PpZL2cfDtZTCfmioVYNFaqYCzcQsKp3FNhNdAke8dBfG2lxGBxGJ47ymKRxM8Wq/WgRq2K9wo0k/ncUatZMyUJ5o@aVPjKpMG7olpiS1KowFRKA2qiVFys5lup4hpM2iFT5eBiCYGrb94i/QsQvTn8jxJSpURGr4gPO@QayhAYPlELq2lLzbCmgpoWSREMuVqNgmpkyRHIsVII0jJYdH9AxlWoOqpeytFymJ4sLKfqkQHSEmaXhFPRRpHYmsGJEbOpEjviLPBcWzXqxBxBskiryU2Xw3pydIgHLLP/gMvki/rSpFlOip9qD7ScwEs9Gm1RouxQkgwx9BO@GuucJBLK6i0QMkI9EL3ZJW2gBiSsWZx6ZBvhxMpdg2QgkiBQkXkL3aeVAQ5zRgdxL7iaYqnRs7f@MQqZ0F1VFl9chscC9so7hpVKlgKGDCEZx7ojz9HqjSoQ2gOR4wJwqDslUQdIx4WEKqKw1MWvjQtKF4U6wSKxQtrR6pqodgSmDhHxa8GE8JKMStGK8aCijn3WWGKqXc8@IxucRFqQACMaWm4cKmZG0HAI34FKCwzfwbhDPGgNcAnZQYaL74bDkyPrIQC34XAmRxNnLWs@oJFm0JggIwwPBnfXMniQVPp0eFhKQ3HBLsUcfMEIW1ZJd6BFhxJU6E27YBspwClm31EsxUTtjTSAfjWsnvngiDxORZ9NEAawEwAwsygsUS61LwcOTQ1AQHipFFrp26Q1bAUAm6JWsAtq6iOUDSi0CyeFsXT6mASm05P580HXTrnE4@XsxYszG24AKqkh6aqY5FBrsbzWs9MOFL0K8OYTxb7FQjGgKDnlqp48BYsLgHUGrSYXwQCtxNTbIgBoasCVElLA1vK1L5UA2gasDjitKZddHXCaAVxiuMTl3ZJkNYChcd0KoXcB93sAkR0yjdGG14SokQ6HxWJYDE5nq9VZf5ifhJ7nhEY2zB324aGefTmbr3fSiLU9n83n4kz7Fflo10awQcCy9pgtccczWRzBspZnpqjJsJK1TJaT6XQl/wA). ### How? ``` ”?e‘ḣ@µ”_eḤ‘ẋ@ - Link 1, helper to vary the length of a 2-slice: list s ”? - literal '?' e - exists in s (1 or 0) ‘ - increment (2 or 1) ḣ@ - head with reversed @rguments (s or s[:1] - removes 2nd value if not '?') µ - monadic chain separation, call that t ”_ - literal '_' e - exists in t (1 or 0) Ḥ - double (2 or 0) ‘ - increment (3 or 1) ẋ@ - repeat t that many times (t*3 or t - [`_`]->['_','_','_']) ;Ṃµ68DṬ+3RØAṁẇ@€FT+49Ọȯµ€Fṡ2i”?Ḃ$ÐḟÇ€ - Link 2, reformat a phone number: char list of [0-9][A-Z], p ; - concatenate p with Ṃ - minimum of p - (?<_<0<1<...<9<A<...<Z - never "?" however, since it only follows a digit.) - - this is simply to make a 2-slice with the last character on the left, as used at the very end of this link. µ - monadic chain separation call that q µ€ - monadic chain separation, for €ach v in q do: 68 - literal 68 D - cast to a decimal list - [6,8] Ṭ - untruth - [0,0,0,0,0,1,0,1] +3 - add 3 - [3,3,3,3,3,4,3,4] R - range - [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3,4],[1,2,3],[1,2,34]] ØA - uppercase alphabet - ABCDEFGHIJKLMNOPQRSTUVWXYZ ṁ - mould like the range ^ - [ABC,DEF,GHI,JKL,MNO,PQRS,TUV,WXYZ] ẇ@€ - sublist v exists in that? for €ach, with reversed @rguments F - flatten (e.g. 'E' -> [0,1,0,0,0,0,0,0]; '4' -> [0,0,0,0,0,0,0,0] T - truthy indexes (e.g. 'E' -> [2]; '4' -> []) +49 - add 49 Ọ - cast to character ȯ - or (e.g. 'E' -> [3]; '4' -> '4') F - flatten ṡ2 - all slices of length 2 Ðḟ - filter discard if: $ - last two links as a monad: i - first index of ”? - literal '?' (first index returns 0 if none exists) Ḃ - mod 2 (so this filter discards pairs starting with '?') Ç€ - call the last link (1) as a monad for €ach slice ḟ⁶ṣ”/Ç€ZLÐṂ€Q€LỊ$ÐfF€Ḣ€ḟ”_µL⁼⁵ȧ - Main link: string (or char list) s ḟ - filter discard any: ⁶ - literal ' ' ṣ - split on: ”/ - literal '/' Ç€ - call the last link (2) as a monad for €ach Z - transpose ÐṂ€ - filter, for €ach, keep items with minimal: L - length Q€ - de-duplicate €ach Ðf - filter keep items with: $ - last two links as a monad: L - length Ị - insignificant? (=1 effectively here) F€ - flatten €ach Ḣ€ - head €ach ḟ - filter discard any of: ”_ - literal '_' µ - monadic chain separation, call that r L - length(r) ⁵ - literal 10 ⁼ - equal? ȧ - and r (0 if r did not result in a 10-digit list, else r) ``` [Answer] ## JavaScript (ES6), ~~180~~ ~~190~~ 188 bytes *Edit: ~~+10~~ +9 bytes to comply with the falsy output rule* --- Takes the two input strings in currying syntax `(a)(b)`. Returns either `false` or a string representing the guessed phone number. ``` a=>b=>!(s=(F=a=>a.match(/(.\??)|_/g).map(([x,y])=>(x<=9?++x:parseInt(x,36)*.32-(x>'Y'))|(x!='_'&!y)*16))(a).map((x,i)=>(x=(d=x^(y=F(b)[i]),x>y)?x:y)&&(d&16|!(d%x))?--x&15:a).join``)[10]&&s ``` ### How it works **Step #1 - Parsing the input strings** We first define the `F()` function which translates a string into an array of integers by applying the following rules: * the underscore is converted to ***0*** * a digit ***N*** or an equivalent letter is converted to ***(N+1) OR 16*** (e.g. "2" → 19, "R" → 24) * a digit ***N*** or an equivalent letter followed by an interrogation mark is converted to ***N+1*** (e.g. "2?" → 3, "R?" → 8) Which can be interpreted the other way around as follows: * ***0*** → *unknown* * **[ *1 .. 10* ]** → *unreliable* * **[ *17 .. 26* ]** → *reliable* We apply `F()` to both `a` and `b`. This gives us a pair of integers ***(x, y)*** for each digit in the phone number, corresponding to the two possible interpretations. **Step #2 - Guessing the digits** For each pair ***(x, y)***, we compute: * ***d = x XOR y*** * ***x = MAX(x, y)*** → *reliable values are always preferred to unreliable ones* If ***x == 0***, it means that both inputs are underscore characters. So, the digit is unknown in this case. If ***x != 0***, we can safely deduce the digit if one of the following conditions is true: ``` condition | interpretation ----------------+------------------------------------------------------ (d AND 16) != 0 | one input is unreliable and the other one is reliable d == 0 | both inputs are identical d == x | one input is an underscore ``` The last two conditions can be merged with `!(d % x)`. Hence the final formula: ``` x && (d & 16 || !(d % x)) ``` If true, we convert ***x*** back to the guessed digit by computing ***(x - 1) AND 15***. ### Test cases (Only the 50 first ones because the console snippet can't support more output history.) ``` let f = a=>b=>!(s=(F=a=>a.match(/(.\??)|_/g).map(([x,y])=>(x<=9?++x:parseInt(x,36)*.32-(x>'Y'))|(x!='_'&!y)*16))(a).map((x,i)=>(x=(d=x^(y=F(b)[i]),x>y)?x:y)&&(d&16|!(d%x))?--x&15:a).join``)[10]&&s console.log(f('1234567890')('1234567890')) console.log(f('1234567890?')('1234567890')) console.log(f('123456789_')('1234567890')) console.log(f('1234567890?')('123456789_')) console.log(f('1234567890')('1234567890?')) console.log(f('1234567890')('123456789_')) console.log(f('123456789_')('1234567890?')) console.log(f('1234567890?')('1234567890?')) console.log(f('1234567890?')('1234567891?')) console.log(f('123456789_')('123456789_')) console.log(f('555CALLUS1')('5552255871')) console.log(f('404_12?6039')('4041?1560_9')) console.log(f('_GETREVENGE')('16?36?_2838_')) console.log(f('1?691460_50')('16_14609?50')) console.log(f('61?08977211')('612?897725?1')) console.log(f('40?0INSTA__')('8?00_NSTI?LL')) console.log(f('3985_534?10')('39?8?5053_10')) console.log(f('7__7294?737')('7797299?_37')) console.log(f('28?897_384?1')('_8?89763861')) console.log(f('271168090_')('27116800?09')) console.log(f('6802?148343')('67?01148343')) console.log(f('94_11628?2?6?')('9491162_47?')) console.log(f('17?4285_689')('1__26?52689')) console.log(f('6_311?95_38')('6731194?7?38')) console.log(f('380?7DRAGON')('3807378?5?66')) console.log(f('4?647_93236')('5646?6?9__36')) console.log(f('365?268898_')('366267?7?984')) console.log(f('GRATEDBATE')('IRATEDBATE')) console.log(f('5307_079?93')('____8_____')) console.log(f('535_3_0255')('52?5_3_024?5')) console.log(f('55_____088')('54?2397207?7?')) console.log(f('6_48398_95')('_946?398?6_5?')) console.log(f('_0_312_3_1')('81?53123?1?71')) console.log(f('____1_____')('64?255?508?61')) console.log(f('8427820607')('6?424?8?__6?07')) console.log(f('50_3707__6')('52?8375?74?56')) console.log(f('615___8255')('62?526?983?2?1?')) console.log(f('__652618__')('8365261__0')) console.log(f('149___933_')('1_9677?92?31')) console.log(f('___7?281562')('3438?28154?2')) console.log(f('5?7?7?___8?3?7?4')('57_855837_')) console.log(f('605_272481')('605427__81')) console.log(f('86?569__731')('88560?0?7721')) console.log(f('1__91654?15')('17?9?9165715')) console.log(f('800NWABODE')('80069ABI?DE')) console.log(f('8___9017_0')('8_2494?12?9_')) console.log(f('_024?5?91?470')('304?17908?7_')) console.log(f('42510704_2')('4_51070492')) console.log(f('9338737_89')('93_873PLUS')) console.log(f('327762_401')('327_MASH01')) ``` [Answer] # [Perl 5](https://www.perl.org/), 211 bytes ...without indentation and \n newlines ``` @i=map{y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/22233344455566677778889999/;$_}split' / ',shift; print map{ $_=join'',map{s,(\d\??|_),,;$1}@i; /((\d)\??\2\??|(\d)\??_|_(\d)\??|(\d)\d\?|\d\?(\d))$/;$2//$3//$4//$5//$6//'?' }1..10 ``` [Try it online!](https://tio.run/nexus/perl5#LY5pa8JAEIb/Sj4srIHFMbvZ7ZYg0VqPai@PHkpgEErpitrQ5Is0@e3pbHXgHeZ5hzmanusetvnvCfo3g9vhaDy5m87uHx6fnueL5erl9e19vQEppVIqjmOttTHmisJae00BCcO6yPeu5AEEXBRf7rNM8h93LAO/lmF39@2OnAtPhWhlH1maVhgKkbCo7rkEWuSFZGbSdy6AFV6qs0NTlU8eQkZXJQBTpJikSQaAp7yO2u2o0zQNotHSRBaR3rLqHxA7fw "Perl 5 – TIO Nexus") [Answer] # Retina, ~~150~~ ~~140~~ 136 bytes *Saved a few bytes thanks to Kritixi Lithos* ``` T`?L`#22233344455566677778889 ./. (?<=(\d)(\w#?){9}).#|.#(?=(\w#?){9}(\d)(?!#)) $1$4 # _(?=.{9}(.))|(?<=(.).{9})_ $1$2 ^(\d*)\1$|.* $1 ``` [Try it Online!](https://tio.run/nexus/retina#jZAxDoMwDEV3n4IqVIo7BGKSEKQiq@rQha3thhqG3qEDcHYaGMoUqZ78/exvy0d5G5bHwN0giKiqKmOMtdY5V8fw3jeQTQWA5HMr@zfK/iMYx2ZGJSYlJLe/yob5IBAh17kBARAiVytSiNNmoXDVGNYWglecOWGv8yhBjVTOsCyaKmNd7ZsyK7JdwJ5yAoS/BgIkNnAChNQGTt6UJJoTZgHi26@XrnvedaxHQWStr/UX) **Explanation:** The first line transforms all `?` in the input into `#` and all letters into their numeric equivalents. We then remove the spaces and `/` from the input. The next two lines take care of "guess vs. certainty" cases (eg. `5? \ 4` would be replaced by `4 \ 4`). After removing all `#`s, lines 8 and 9 deal with "number vs. `_`" cases (`_ \ 3` becomes `3 \ 3`). Then, if both halves of the string match, we keep the first 10 digits. Otherwise, the phone number is invalid so we remove everything. Alternative 160-byte solution that works for phone numbers of arbitrary length (and equal size): [TIO](https://tio.run/nexus/retina#jZHPCgIhEIfv8xQLbqAbWI5/1j1JdOiyt@oW6qF3CGnffZui2i5CguD8Pr8ZwRU/5PmUw6YZMysFEbXWxhhrrXOup@W9H@CeI5t4EQxaBVEyLrsi@OVK@yY7QWmrW4T4jYp4XSKCRMhJi/IjiBzf0ZOpKYmPZEgqk1wX2cE8K9TGut4P22bTLAUsx1AB6S8hQWVCqIBUmxCqb6oSFSrNEtA37HfjeD4qyqlAtNb36gE) [Answer] # PHP, ~~251~~ 236 bytes ``` for(;a&$c=preg_replace(["#[^_?](?!\?)#","#_#"],["$0k","?<"],join("-",$argv))[++$i];)${$k+="-"==$c}.=$c<_&$c>=A?0|(ord($c)-($c>W)-($c>P)-59)/3:$c;for(;$c=${1}[$k+1];)echo($n=${1}[$k])==($m=${2}[$k++])|($b=${2}[$k++])!=$c?$c>$b?$n:$m:"?"; ``` takes input from command line; run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/04a59afca05afaa35a9e162e14903f23dba7dd41). **breakdown** ``` # A: transform input # 2. replace single chars with two-character chunk and make sortable: # replace "_" with "?<", append "k" to everything else not followed by "?" for(;a&$c=preg_replace(["#[^_?](?!\?)#","#_#"],["$0k","?<"],join("-",$argv))[++$i];) # (unknown "<" < unsure "?" < certain "k") ${$k+="-"==$c}.= # if "-", next argument $c<_&$c>=A # if letter ?0|(ord($c)-($c>W)-($c>P)-59)/3 # then translate to digit :$c # else don´t ; # B: evaluate for(;$c=${1}[$k+1];) # loop through arguments: $c=command 2 echo ($n=${1}[$k]) # $n=digit 2 == # if digits are equal ($m=${2}[$k++]) # $m=digit 3 | ($b=${2}[$k++]) # $b=command 3 !=$c # or "commands" are not ?$c>$b?$n:$m # then get the one with the more definitive "command" :"?" # else conflict/unknown ; ``` **golfings** * `preg_replace` first: -8 bytes * `join`: -2 * `$$k` instead of `$t[$k]`: -5 [Answer] # PHP, 200+8 bytes inspired by [Arnaulds solution](https://codegolf.stackexchange.com/a/117360/55735). ``` for($s=join($argv);$c=ord($s[$i++]);$i+=$x)$t[]=$c>90?63:15&($c<65?$c:($c-($c>80)-($c>87)-59)/3)|16*$x="?"==$s[$i];for(;$p++<10;)echo chr(($e=$t[$p]^$d=$t[$p+10])&48|!(15&$e)?min($t[$p],$d)&15|48:63); ``` takes input from command line arguments; run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/e775054aa7d1a3e13130a91af78f19a597bf569d). *modifications to comply with the error output restriction:* (print `X` for an incomplete number): * remove `|48` (-3 bytes) * replace `echo chr(...);` with `$r.=...;echo$r>1e10?X:$r;` (+11 bytes) **breakdown** ``` for($s=join($argv);$c=ord($s[$i++]); # loop through characters of arguments $i+=$x) # skip "?" $t[]= $c>90 # if "_" ?63 # then 32+16+15 : # else 15&( # lower 4 bits of $c<65 # if digit ?$c # then digit :($c-($c>80)-($c>87)-59)/3 # else letter mapped to digit ) |16*$x="?"==$s[$i] # if next char is "?", add 16 ; for(;$p++<10;)echo chr( # loop through translated arguments ( $e=$t[$p]^ # 2. $e=difference $d=$t[$p+10] # 1. $d=char from 2nd argument )&48 # if certainties differ |!(15&$e) # or digits do not ?min($t[$p],$d)&15|48 # then pick the more definite digit (15|48 -> "?") :63 # else "?" ); ``` **golfings** * work around `preg_replace_callback` (-10 bytes) * rely on 10 digit input (-9) * and additional golfing (-8) * removed `join` delimiter (-7) * moved `$x` assignment to the end (-2) [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 173 bytes ``` sub t{$_=pop;y/A-Z/22233344455566677778889999/;/_|\d\??/g}@e=m|\S+|g;@a=t$e[0];$_=join"",map{$_.=shift@a;s/^(.+)\1$/$1/||s/_//||s/..../_/||s/.\?//;$_}t$e[2];s/\?//;$_ x=!/_/ ``` [Try it online!](https://tio.run/##jY5BbsIwEEX3nCJFWVDRZGInDkGW5XCArroDUytVU5oKiFWnEqjm6jUDQmJlqX/jP/4zb8a031vmvf15i4bfWAvTG36ERbIESmme50VRMMbKspyhqqqao4CDdupdSQmbU92KnVMvU7fhdSOGuF1la46gr77bj8dPu8YgNhX2s/sY6oZbeJ2k00dFYogJOGdBw/VJUeivVkkAZJwuNLrGmdtHdBAP2OM9oXnBylk1zyKI7sXobmUg0P8a0KPABhkIdGiDDN4UTIgMwPRfb4au31ufPLM0I5lPzPYM "Perl 5 – Try It Online") ]
[Question] [ Write a regex that works in at least 2 regex flavors (or versions), and match a different string in each flavor (or version) it is running in. The strings to be matched in this challenge are the first words of the Ubuntu code names, which are listed below. Your regex has to match from the top of the list. That is, if your regex works in 3 flavors, it has to match `Warty` `Hoary` and `Breezy`, and not others. ``` Warty Hoary Breezy Dapper Edgy Feisty Gutsy Hardy Intrepid Jaunty Karmic Lucid Maverick Natty Oneiric Precise Quantal Raring Saucy Trusty Utopic Vivid Wily Xenial Yakkety Zesty 17.10 18.04 18.10 19.04 19.10 ... ``` If your regex works in more than 26 flavors, you can match the Ubuntu version numbers instead. Starting from 17.10, for each new flavor, change the second number to 10 if it was 04, and increment the first number and change the second to 04 otherwise. In each flavor, your regex should match only the supposed string and nothing else (not limited to the code names). Trailing newlines doesn't matter. That means your regex could either match only the string without the trailing newline, match only the string with the trailing newline, or match both. And it doesn't have to be consistent in different flavors. You can assume the input is in printable ASCII (except for the trailing newline, if there is one). Your score is (the length of your code+10)/((number of flavors)^2). Lowest score wins. [Answer] ## 87 bytes, 5 flavours, (87+10)/25 = 3.88 ``` ^(((?=W)[[:word:]&&]art|Ho(?=a)\ar|Bre(?=ez)[]e]\z|E(?=dg)[[d]]g)y|(?=Da)[D-[E]]apper)$ ``` I've gone with the easy to test flavours for now, which are: * [Regex101](https://regex101.com/): PCRE (PHP), Javascript, Python * [Regex Storm](http://regexstorm.net/tester): .NET * [Rubular](http://rubular.com/): Ruby The general structure is `^((...)y|...)$`, i.e. factoring out the trailing `y`s and adding anchors. ### Warty (PCRE) ``` (?=W)[[:word:]&&]art ``` In PCRE and Ruby, `[[:word:]]` is a POSIX character class matching a word character — in other flavours you get a `[[:word:]` character class then literal `&&]`, which fails the `(?=W)` assert. To make Ruby fail, `&&` is used to intersect the POSIX class with nothing, whereas in PCRE `&&` has no special meaning. ### Hoary (Javascript) ``` Ho(?=a)\ar ``` For whatever reason, Javascript is the only flavour out of the bunch where `\a` is a literal `a` — in other flavours it matches the bell character (ASCII 7). ### Breezy (Python) ``` Bre(?=ez)[]e]\z ``` In Python and Javascript, `\z` is a literal `z` — in the other flavours it is equivalent to the `$` end of string anchor. To make Javascript fail we use the char class `[]e]`, which is an empty char class `[]` then literal `e]` in Javascript, and a two-char class `[]e]` in Python. ### Dapper (.NET) ``` (?=Da)[D-[E]]apper ``` In `.NET`, `[D-[E]]` is a set difference, removing the set `[E]` from `[D]`. In PCRE, Javascript and Python, we have the class `[D-[E]` then a literal `]`. Ruby's a little different, but for some reason it parses as a class `[D-[E]]` which only matches `E`, and I have yet to figure out why... ### Edgy (Ruby) ``` E(?=dg)[[d]]g ``` Ruby allows char classes inside char classes, so `[[d]]` is actually equivalent to `[d]`, or just `d`. In the other flavours, we have `[[d]` then a literal `]`. ]
[Question] [ # Alphabetize Integers For a given set of numbers, put them in alphabetical order when they are spelled out (i.e. 1: one, 2: two, 90: ninety, 19: nineteen). Your code should work for the range `[-999999, 999999]`. Output must have a delimiter between numbers. A space will work, as will a space and a comma as shown in the examples below. Input can be an array of integers, a string of delimited numbers, or however you see fit. All integers are assumed to be unique. Numbers are not hyphenated for the purposes of this challenge and spaces are alphabetized before any other characters. Negative numbers are assumed to be expressed by using the word `minus`. For example, `four` would precede `four thousand` and the number `-40` would be sorted using the string `minus forty`. Assume all numbers will be solely comprised of number words and no conjunctions (e.g. use `two thousand forty two` instead of `two thousand and forty two`). --- ## Test Cases **Single Digit Integers:** Input: ``` 1, 2, 3, 4, 5 ``` Output: ``` 5, 4, 1, 3, 2 ``` **Multiple Digit Integers:** Input: ``` -1002, 5, 435012, 4, 23, 81, 82 ``` Output: ``` 81, 82, 5, 4, 435012, -1002, 23 ``` **Spaces between words, no hyphens, commas or "and":** Input: ``` 6, 16, 60, 64, 600, 6000, 60000, 60004, 60008, 60204, 60804 ``` Output: ``` 6, 600, 6000, 16, 60, 64, 60000, 60008, 60804, 60004, 60204 ``` Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins. No loopholes allowed! [Answer] ## Inform 7, ~~214~~ ~~201~~ 118 bytes [Inform 7](http://inform7.com/) is an absolutely terrible language for golfing, so I wanted to give it a chance here. Indentation should use tab (`\t`) characters, but HTML doesn't like those. Conversely, Inform doesn't like spaces for indentation, so you'll have to replace the spaces with tabs if you copy-paste the code from here to test it. Or just copy-paste from the Markdown source instead. Golfed: ``` To X: repeat through Table 1: now Q entry is "[R entry in words]"; sort Table 1 in Q order; say "[R in Table 1]". ``` Input should be an Inform table, like so (with `\t` between the columns): ``` Table 1 R (number) Q (text) -1002 5 435012 4 23 81 82 ``` Output: > > 81, 82, 5, 4, 435012, -1002, 23 > > > This function runs through the table once, adding a textual representation of each number in a new column. Then it sorts the table rows according to the text column; in Inform, strings are sorted lexicographically. Finally, it prints out the original column in the new order. Conveniently, Inform 7's ["crude but sometimes useful"](http://inform7.com/learn/man/WI_16_4.html) format for printing out table columns turns out to be comma separated, exactly as requested. Ungolfed, with boilerplate showing how to call the function: ``` To print the numbers in alphabetical order: repeat through the Table of Sortable Numbers: now the name entry is "[the index entry in words]"; sort the Table of Sortable Numbers in name order; say "[the index column in the Table of Sortable Numbers]". Table of Sortable Numbers index (number) name (text) -1002 5 435012 4 23 81 82 There is a room. When play begins: print the numbers in alphabetical order. ``` [Answer] # JavaScript (ES6), ~~189~~ ~~179~~ 186 bytes ``` let f = a=>a.sort((x,y)=>!x-!y||(X=q(x),Y=q(y),X>Y)-(X<Y),q=n=>n<0?"L"+q(-n):n>999?q(n/1e3)+"Z"+q(n%1e3):n>99?q(n/100)+"K"+q(n%100):n>19?" cYHFVSCO"[n/10|0]+q(n%10):"0PdaIGTQAMWDbXJEURBN"[n|0]) let g = a => console.log(`[${f(a)}]`) g([1,2,3,4,5]) g([-1002,5,435012,4,23,81,82]) g([0,1000,1100]) ``` ``` <input id=I value="1 2 3 4 5"><button onclick="g(I.value.match(/\d+/g)||[])">Run</button> ``` The basic idea is to convert each input number into a short string that's in the correct lexographical position compared to all other number-string pairs. Here's the dictionary used: (Don't run the snippet; it's just used to hide the long list.) ``` A eight B eighteen C eighty D eleven E fifteen F fifty G five H forty I four J fourteen K hundred L minus M nine N nineteen O ninety P one Q seven R seventeen S seventy T six U sixteen V sixty W ten X thirteen Y thirty Z thousand a three b twelve c twenty d two ``` This creates a very concise way of mapping each number to its lexographically correct position. That's what the recursive `q` function does: ``` q(-X) => "L" + q(X) q(XYYY) => q(X) + "Z" + q(YYY) q(XYY) => q(X) + "K" + q(YY) q(XY >= 20)` => " cYHFVSCO"[X] + q(Y) q(X) => "0PdaIGTQAMWDbXJEURBN"[X] ``` The `0` at the beginning of the string is to ensure that e.g. 100 (`one hundred`, converted to `PK0`) is sorted before `101` (`one hundred one`, converted to `PKP`). This creates an odd scenario where 0 (`zero`) is sorted to the front of the array, so to get around this, in the sorting function we first sort any zeroes to the right with `!x-!y||(...`. [Answer] # Mathematica, 67 bytes ``` SortBy[#,#~IntegerName~"Words"~StringReplace~{","->"","-"->""}&]& ``` Unnamed function taking a list of integers as its argument and returning a list of integers as its value. `#~IntegerName~"Words"` is a built-in that changes an integer to its name in English. `IntegerName` sometimes has commas and hyphens in its output, so the `StringReplace` call gets rid of those. (Sadly the hyphen is actually the 3-byte character, 8208, in UTF-8.) Then `SortBy` sorts the original list alphabetically according to the value of the modified integer name. A nice coincidence: `IntegerName` uses `negative` instead of `minus` in its output—but no word appearing in the names of any of the allowed numbers is alphabetically between those two words, so no replacement is needed! (Hat tip to ngenisis for reminding me of `Sortby`.) [Answer] # Bash + GNU utils + bsdgames, 52 * 4 bytes saved thanks to @izabera. ``` sed 's/.*/echo `echo &|number`:&/e'|sort|sed s/.*:// ``` I/O is newline-delimited lines. * The first sed expression replaces each numerical number with a shell command that outputs the word form of the number (as given by the [bsdgames `number`](http://wiki.linuxquestions.org/wiki/BSD_games) utility), followed by a `:` then the numerical form of the number. * This is then `sort`ed. * Then the second `sed` strips leading characters up to and including the `:`, leaving the numerical form sorted as required. `number` correctly handles "minus", and its output is close enough to the specificed format that the `sort` works as required. It does output "fourty-four" instead of "fourty four", but this shouldn't matter from the sorting perspective. The bsdgames package may need installation: ``` sudo apt-get install bsdgames ``` The `sed` and `sort` utilities are almost certainly already in your distro. [Answer] # Python + inflect, ~~97~~ ~~91~~ 89 bytes ``` from inflect import* a={x:engine().number_to_words(x)for x in words} sorted(a,key=a.get) ``` Used the `inflect` library to transform the `words` array of integers into their phonetic/string representation. Stored into a dictionary of k/v pairs where the keys were the numeric representation and values were the string representation. Returned the list of keys as sorted by values. EDIT: Saved 5 and 3 bytes, thanks to ETHproductions and Alex.S! [Answer] # Mathematica, 30 bytes The answer below outputs a pure function which will take a list of integers as an input and sort them by their alphabetic name. Just what the doctor ordered ;) ``` SortBy[#~IntegerName~"Words"&] ``` Here is the ungolfed version: ``` SortBy[IntegerName[#, "Words"]&] ``` And here is an example usage: ``` SortBy[#~IntegerName~"Words"&][{0,1,2,3,4,5,6,7,8,9,10}] ``` Which could also be written as ``` SortBy[#~IntegerName~"Words"&]@{0,1,2,3,4,5,6,7,8,9,10} ``` They produce identical outputs - in mathematica, `f[x]` is equivilant to `f@x`. ``` Outputs: {8, 5, 4, 9, 1, 7, 6, 10, 3, 2} ``` There is a much longer answer that another user posted in Mathematica. That answer tries to correct for some small differences between the way mathematica alphebatizes numbers to better conform to the way the OP stated numbers should be alphebatized, however the things they correct for don't affect sorting order, and my answer outputs identically to theirs: ``` MyF = SortBy[#~IntegerName~"Words"&]; TheirF = SortBy[#, #~IntegerName~"Words"~ StringReplace~{"," -> "", "-" -> ""} &] &; MyF[Range[-999999, 999999]] == TheirF[Range[-999999, 999999]] (*Outputs True*) ``` [Answer] # Common Lisp, 113 bytes No external libraries necessary. ``` (print(mapcar #'cdr(sort(loop for i in x collect(cons(format()"~r"i)i))(lambda(y z)(string-lessp(car y)(car z)))))) ``` Output if `x` is `'(1 2 3 4 5)`: ``` (5 4 1 3 2) ``` ]
[Question] [ Let me tell you about a simple number system. (which I made up just for this challenge) This system contains the functions `()`, `[]`, `{}`, and `<>`. ## 1. `()` When `()` is given no arguments, it evaluates to `0`. When `()` is given one or more arguments, it evaluates to the sum of the arguments. ## 2. `[]` When `[]` is given no arguments, it evaluates to `-1`. When `[]` is given one or more arguments, it evaluates to the first argument minus the sum of the other arguments. # 3. `{}` When `{}` is given no arguments, it evaluates to `1`. When `{}` is given one or more arguments, it evaluates to the product of those arguments. # 4. `<>` When `<>` is given no arguments, it evaluates to `1`. When `<>` is given one or more arguments, it evaluates to the first argument integer divided by the product of the other arguments. ## Your task Given a string that contains a valid number (that means brackets are balanced, no division by 0s, etc.) in this simple number system, print its value. ## Test cases ``` () -> 0 (()()) -> 0 ([][]) -> -2 ({}<>) -> 2 ({}[]) -> 0 [] -> -1 [[][]] -> 0 [()<>] -> -1 {()} -> 0 {([]<>)} -> 0 ``` Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins. [Answer] # Haskell, ~~357~~ ~~306~~ ~~277~~ ~~251~~ ~~228~~ ~~224~~ ~~188~~ ~~185~~ 180 bytes A token-based parser with an explicit stack. `(%)` takes a token stack and a character and either pushes (opcode,defaultnumber) or (0,number) for `({[<`, or pops topmost numbers and one opcode and pushes the answer for `)}]>`. Opcodes are encoded by a ascii enumeration hack. Kudos to @ChristianSievers for his great [answer](https://codegolf.stackexchange.com/a/100819/60340) that I borrowed some ideas from. One-liner! ``` s%c|elem c"([<{",g<-div(fromEnum c)25=(g,[0,0,1,-1,1]!!g):s|(a,(o,n):b)<-span((==0).fst)s=(0,[foldr1(flip$[(+),quot,(-),(*)]!!(o-1))$snd<$>a,n]!!(0^length a)):b snd.head.foldl(%)[] ``` Now with less error-handling! Usage: ``` *Main> map (snd.head.foldl(%)[]) ["()","(()())","([][])","({}<>)","({}[])","[]","[[][]]","[()<>]","{()}","{([]<>)}"] [0,0,-2,2,0,-1,0,-1,0,0] ``` Thanks @ChristianSievers for saving 14+3 bytes! Thanks @Zgarb for saving some+4 bytes! [Answer] # Python 2, ~~292~~ ~~265~~ ~~248~~ ~~235~~ ~~223~~ ~~206~~ 204 bytes ``` r=reduce s=input() for n in')]}>':s=s.replace(n,'),') for a in'(*x:sum(x)','[a=-1,*x:a-sum(x)','{*x:r(int.__mul__,x,1)','<a=1,*x:r(int.__div__,x,a)':s=s.replace(a[0],'(lambda %s)('%a[1:]) print eval(s)[0] ``` Replaces all brackets with a lambda that does what the bracket does, then evaluates the resulting Python code. Requires its input surrounded by quotes, like `'[<><>([]{})]'`. This program stores the type of bracket as the first character in each string in the `for`, and everything after the keyword `lambda` as the rest. It then uses the first character to substitute; the rest of it is combined into a lambda like `(lambda*x:sum(x))()`. [Try it on Ideone!](http://ideone.com/7tilTl) [Answer] # [PEG.js (ES6)](http://pegjs.org/online), 132 bytes ``` x=a:[([{<]b:x*[)\]}>]{var x='([<'.indexOf(a) b.length^1||b.push(0) return~~eval(b.length?b.join(('+-/'[x]||'*')+' '):~-('10'[x]||2))} ``` Should be fixed now. # Explanation More readable: ``` x=a:[([{<] b:x* [)\]}>] { var x='([<'.indexOf(a) b.length^1||b.push(0) return ~~eval( b.length? b.join(('+-/'[x]||'*')+' ') :~-('10'[x]||2)) ) } ``` PEG.js is an extended version of Javascript specifically made for parsing. It's VERY strict, which is why I had to use `var`. In addition, there seems to be a bug with brackets inside strings, which bloated the code significantly. To start, we define a rule `x` that matches any bracket `a` that may or may not contain multiple expressions that matches rule `x`. For each match to rule `x`, we push a 0 to the array of the inner match `b` if `b`'s length is 1. If `b`'s length > 0, then we find the index of `a` in `([<` and get a character from `+-/` using that index. If the result is undefined (meaning that `a` was `{`), then we turn the result into `*`. Finally, we tack on a space and join `b` with the result. If `b`'s length = 0, then we find the index of `a` in `([<` and get a character from `10` using that index. If the result is undefined (meaning that `a` was `{` or `<`), then we turn the result into 2. Finally, we simply decrement. At the end, we can just evaluate the expression and floor the result. [Answer] # Perl, 113 + 2 = 115 bytes Run with `-lp` (2 byte penalty). ``` /\W/,eval"sub $`\{\$#_?(shift)$&&$'1}"for qw'a+a:1- b-a:- c*c: d/c:';y/([{</a-d/;s/\W/0),/g;s/\pL\K/(/g;$_=eval ``` More readable (note: this "more readable version" won't actually run, because I put comments in places they aren't syntactically allowed): ``` # -p option: read a line of input into $_ at program start # -l option: remove the final newline whenever reading do { # for each element of a list, given later: /\W/; # place an initial identifier in $`, the next character in # $&, and the rest of the element in $' eval qq{ # then evaluate the following template, with substitutions: sub $` { # define a subroutine named $`, that does this: \$#_ ? # if there is more than one argument (shift) # then return the first argument $&-ed with $& &$' # the result of a recursive call with the tail of the arguments # else (the "else" is a colon taken from $', not the template) 1 # return (the remainder of $' applied to) 1 } } } for qw' # specify the list by splitting the following on whitespace: a+a:1- # a(head,tail) = len(tail>1) ? head+a(tail) : 1-1 b-a:- # b(head,tail) = len(tail>1) ? head-a(tail) : -1 c*c: # c(head,tail) = len(tail>1) ? head*c(tail) : 1 d/c: # d(head,tail) = len(tail>1) ? head/c(tail) : 1 '; y/([{</a-d/; # replace ( [ { < with a b c d in $_ s/\W/0),/g; # replace whitespace, punctuation in $_ with the string "0)," s/\pL\K/(/g; # place a ( after (\K) each letter (\pL) in $_ $_=eval # evaluate $_ as a Perl program, storing the result back in $_ # -p option: print $_ to the user at program end # -l option: output a newline whenever printing ``` The basic idea is that we're converting an input like `[()<>]` to the Perl program `b(a(0),d(0),0),` via text processing; Perl's just fine with the trailing comma. Earlier, we defined the functions `a`, `b`, `c`, `d` to have the same effect as the `()`, `[]`, `{}`, `<>` constructs from the language we're implementing; they each disregard their last argument (the 0 at the end), which is included to ensure that all input parses correctly, and work using the implementation commonly seen in functional programming where the head and tail are processed separately. Because `b(e,f,g,0)` means `e-f-g`, i.e. treats its first argument specially, whereas `a` treats its arguments symmetrically (`a(e,f,g,0)` means `e+f+g`), we implement `a` recursively and `b` via calling `a`. `c` and `d` have a similar relationship. All four of these functions are very similar, so we generate them at runtime rather than implementing them separately; we store a template that applies to all four functions in a string, then generate the functions by substituting characters into the template. Because Perl `/` does floating-point division, the implemented `{}` does too. I'm assuming that either this is not a problem in its own right, or `-Minteger` (selecting a language variant where all arithmetic operations are integer operations) is free, because otherwise I'd have to spend extra bytes writing an integer division in Perl, which doesn't seem to be what the problem is fundamentally about. (I think you'd have to spend four bytes changing `(shift)` to `int+(shift)`; I haven't tested this.) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 94 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) `o←{(⊂(1⊃⍵),⍺⍺⊃⍵),2↓⍵}⋄u←{(⊃⍵,⍺⍺1)⍺⍺⍵⍵/1↓⍵}⋄⍎⍕'+/o' '-u+o' '×/o' '÷u×o' '(⊂⍬),'[')]}>'⍳⌽⍞],'⊂⍬'` uses `⎕IO←0` replaces `)]}>` with a function call that takes a stack, applies an operation on its top frame, deletes it, and appends the result to its next frame (monadic operator `o` is used for that; dyadic operator `u` handles the more complicated cases of `-` and `÷`) replaces `([{<` with code that adds a frame to the stack (`(⊂⍬),`) executes the resulting expression (reversed, to match APL's order of execution) with an initial stack of one empty frame (`⊂⍬`) [Answer] # Octave, ~~215~~ ~~206~~ 198 bytes ``` S='sum(x(:))-sum(x(2:end))';Y='(@(x)isempty(x)';c=']) ';[~,~,u]=unique(['()<>[]{}',input('')]);eval([{'sum([',c,[Y,'+fix((',S,')/prod(x(2:end))))(['],c,[Y,'*-1+',S,'*2)(['],c,'prod([',c}{u(9:end)}]) ``` [try it online](http://rextester.com/FTYGI10819) [Answer] # PHP, ~~315~~ ~~300~~ ~~285~~ ~~258~~ ~~250~~ 244 bytes ``` for($s=$argv[1];$r=!$r;)foreach(["(+)1","[-]0","{*}2","</>2]as$p)if(preg_match("#$e$p[0]([-_\d]*)$e$p[2]#",$s,$m)){if(""==$v=strtok($m[1],_))$v=$p[3]-1;while(""<$n=strtok(_))eval("\$v$p[1]=$n;");$s=strtr($s,[$m[$r=0]=>_.$v]);}echo substr($s,1); ``` replaces sub-expressions with underscore+value; loop breaks when iteration made no replacement. 19 years since I first met C, 17 years working with PHP; this is the first time that `strtok` makes sense ... helping to save 24 bytes! **breakdown** ``` for($s=$argv[1]; // take input from argument $r=!$r;) // toggle $r; loop until no replacement has taken place foreach(["(+)1","[-]0","{*}2","</>2]as$p) // loop through operations if(preg_match("#$e$p[0]([-_\d]*)$e$p[2]#",$s,$m)) // find a match { if(""==$v=strtok($m[1],_)) // init $v with first token from sub-match $v=$p[3]-1; // if no token, init with default value while(""<$n=strtok(_)) // loop through tokens eval("\$v$p[1]=$n;"); // operate $s=strtr($s,[$m[$r=0]=>_.$v]); // reset $r; replace match with underscore+value } echo substr($s,1); // print result ``` [Answer] # ES6 (Javascript), ~~250~~, ~~171~~, ~~154~~, ~~149~~, 147 bytes A pure Javascript version. "Metaprogramming" (like most other answers here), converts input program text into a corresponding Javascript program, by applying a number of direct text substitutions to it (i.e. keeping the program structure as is). Can probably be golfed further. *UPDATE (v2.1)* * Minus two bytes (removed parenthesis in the ternary expression) * Golfed 5 more bytes off, by using variable for result extraction, and getting rid of extra "[]" *UPDATE (v2)* Just realised that pending commas in ES arrays are totally valid, so the whole comma normalization code could be removed. Also followed an excellent advice by @Titus, on optimizing the alphabet lookup. *UPDATE (v1)* Removed duplicate "replace" alias. *UPDATE (v1)* * Use a better alphabet: ()=>1+ []=>0 {}=>2\* <>=>2/ (each char can be directly re-used as a value or operator) * Replaced reduce() with replace() (alphabet mapping) * Merged constant inlining, open and closing bracket processing into one step **Golfed (v2.1)** ``` s=>eval("o="+s.replace(/./g,r=>"2+1-3*3/"["()[]{}<>".indexOf(r)]).replace(/\d\D?|\D/g,r=>r[1]?r[0]-2+",":r*1?'([':`].reduce((r,a)=>r${r}a)),`)+"o ``` **Golfed (v1)** ``` (s,A="(2)+[1]-{3}*<3>/")=>eval(s[R="replace"](/./g,r=>A[A.indexOf(r)+1])[R](/\d\D?|\D/g,r=>r[1]?r[0]-2+",":(r[0]*1?'([':`].reduce((r,a)=>r${r}a)),`))[R](/,(\])|,$/g,"$1")) ``` **Golfed (v0)** ``` ([...s],A="(a)b[c]d{e}f<g>h",R="replace")=>eval(s.reduce((r,c)=>r+=A[A.indexOf(c)+1],'')[R](/ab|cd|ef|gh/g,r=>({d:-1,b:'0'}[r[1]]||1) + ',')[R](/[aceg]/g,"([")[R](/[bdfh]/g,r=>`].reduce((r,a)=>r${"+*-/"["bfdh".indexOf(r)]}a)),`)[R](/,(\])|,$/g,"$1")) ``` **Explained (v0)** ``` //BEGIN //s - input text, A - alphabet, R - "String.replace()" alias E=([...s],A="(a)b[c]d{e}f<g>h",R="replace")=>eval( //Replace input alphabet by a more friendly one, to avoid too much escaping and quoting // () - ab, [] -cd, {} - ef, <> - gh s.reduce((r,c)=>r+=A[A.indexOf(c)+1],'') //Replace no-arg invocations with a corresponding constant value // () => 0, [] => -1, {} => 1, <> => 1 [R](/ab|cd|ef|gh/g,r=>({d:-1,b:'0'}[r[1]]||1) + ',') //Replace opening brackets with "([" [R](/[aceg]/g,"([") //Replace closing brackets with "].reduce(...))," //An arithmetic operation to apply (+-*/) is chosen based on the bracket type //and is substituted into the template [R](/[bdfh]/g,r=>`].reduce((r,a)=>r${"+*-/"["bfdh".indexOf(r)]}a)),`) //Strip excessive commas [R](/,(\])|,$/g,"$1") ); //END: eval() the result Example: E("{([]<>()<>{})(<><>)}") => eval("([([-1,1,0,1,1].reduce((r,a)=>r+a)),([1,1].reduce((r,a)=>r+a))].reduce((r,a)=>r*a))") => 4 ``` **Test** ``` E=([...s],A="(a)b[c]d{e}f<g>h",R="replace")=>eval(s.reduce((r,c)=>r+=A[A.indexOf(c)+1],'')[R](/ab|cd|ef|gh/g,r=>({d:-1,b:'0'}[r[1]]||1) + ',')[R](/[aceg]/g,"([")[R](/[bdfh]/g,r=>`].reduce((r,a)=>r${"+*-/"["bfdh".indexOf(r)]}a)),`)[R](/,(\])|,$/g,"$1")) T=(s,a)=>{ console.log(s,r=E(s),r==a?"OK":"NOT OK"); } T("()",0) T("(()())",0) T("([][])",-2) T("({}<>)",2) T("({}[])",0) T("[]",-1) T("[[][]]",0) T("[()<>]",-1) T("{()}",0) T("{([]<>)}",0) ``` **Test Output** ``` () 0 OK (()()) 0 OK ([][]) -2 OK ({}<>) 2 OK ({}[]) 0 OK [] -1 OK [[][]] 0 OK [()<>] -1 OK {()} 0 OK {([]<>)} 0 OK ``` [Answer] ## Haskell, ~~184 179 172 161 160 159 151 148~~ 145 bytes ``` s%(c:i)|elem c")}]>"=([1?(*),sum,1?quot,(-1)?(-)]!!mod(fromEnum c)5$s,i)|(r,j)<-[]%i=(s++[r])%j [v]%e=(v,e) (v?_)[]=v (_?o)s=foldl1 o s fst.([]%) ``` Recursive descent, threading the input because Haskell. As usual, the last line is not a definition, but states the function that solves the problem. So to test, put the lines except the last one in a file, load it and do something like this: ``` *Main> fst.([]%) $ "{([][][])([][])}" 6 ``` Thanks to @Zgarb for inspiration and a lot of detailed hints, and to @Angs for inspiration from his solution and further hints. It wasn't specified how division should behave with negative integers. Anyway, repeatedly using `div` seems wrong, as it is not the same as using `div` once with the product of the remaining values. Now using `quot`, I get the same results for `<{}([][])[]>`and `<{}{([][])[]}>`. For nice, almost readable code look at the first version. The intermediate versions contain all kinds of nice and intimidating code and help understand this version. [Answer] ## JavaScript (ES6), no `eval`, 156 bytes ``` f=s=>s==(s=s.replace(/(.) ?([- \d]*)[\]})>]/,(_,c,s)=>` `+(s?s.split` `.reduce((l,r)=>c<`<`?l- -r:c<`[`?l/r|0:c<`{`?l-r:l*r):c==`[`?-1:c==`(`?0:1)))?+s:f(s) ``` Explanation: The regexp finds the first unprocessed closing bracket, and matches the (presumably) corresponding opening bracket and any arguments in between. The arguments are split and reduced according to the operation (sadly '(' and '[' are not the optimal pair for `+` and `-`), or if there are no arguments then the appropriate value is calculated (again the matching of characters to values is suboptimal from my point of view). The result is then substituted in with a leading space so as to separate it from other results. The function then calls itself recursively until there are no more changes to make, in which case it returns the resulting value. Example: ``` [()<>] [ 0<>] [ 0 1] -1 ``` ]
[Question] [ [Befunge](https://esolangs.org/wiki/Funge-98) is a 2-dimensional programming language, with an instruction pointer (IP). In Befunge-98, the `;` character tells the IP to skip characters up until the next `;` (Let us call it skipping mode when the IP is skipping characters). Here is an example: ``` "This part is read into the stack" ; this part is not ; @ ``` I would like to generate a `w` wide, `h` high comment outline for a Befunge-98 program. This means that an IP in normal mode (not in string mode nor in skipping mode) should enter the comment, skip over the comment and then exit in normal mode, no matter which row or column it arrives from. Additionally, the outline must be at most one character thick. That is, the bounding box of the entire comment (including outline) must be no more than `w+2` wide and no more than `h+2` high. ## Example If `w = 5, h = 3` then a valid comment outline would be: ``` ;;;;;; ; ; ; ; ; ; ;;;;;; ``` Note that this would not be a valid comment outline: ``` ;;;;;;; ; ; ; ; ; ; ;;;;;;; ``` This is because in the first column, the IP would enter in normal mode, but exit in skipping mode, potentially skipping crucial code. (The same thing would happen in the 7th column, 1st row and 5th row) This is not valid either: ``` ``` This would result in the comment being interpreted as code. ## Challenge Write a program or function that, given a width and height as input, outputs any valid Befunge-98 comment outline for that size. The width and height are guaranteed to be at least 1. * You must output in spaces, semicolons and line breaks, unless your chosen programming language is unable to * You may have trailing whitespace, however they can only be spaces and line breaks * Each line may have trailing spaces * You may alternatively take input as `w+2` and `h+2` instead of `w` and `h` + You may also mix between the two e.g. you can input `w+2` and `h` * As stated above, the width of the outline must be at most 1 * There must be a `w` by `h` area inside the outline made of only spaces ## More examples `w = 2, h = 2` ``` ;;;; ; ; ; ; ;;;; ``` `w = 3, h = 2` ``` ;;;; ; ; ; ; ;;;; ``` `w = 2, h = 3` ``` ;; ; ; ; ; ; ; ;;;; ``` `w = 5, h = 1` ``` ;;;;;; ; ; ;;;;;; ``` [Answer] # [Python](https://www.python.org), ~~93~~ ~~89~~ ~~85~~ ~~79~~ ~~74~~ 73 bytes ``` lambda w,h:';'*(w|1)+(';\n;'+' '*w)*h+';\n'+h%2*' '+';'*(w+~h%2+~(w^h)%2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3PXMSc5NSEhXKdTKs1K3VtTTKaww1tTXUrWPyrNW11RXUtco1tTK0QXx17QxVIy2gkDZEoXYdkK9dp1Eel6GpaqQJMfAWo2RicXFqUYlCmoaRjpGmXnFJUWaBhqaCra1CDJeSkhKXNRBwWSsowAgQFygOU8jFhaTfmAj9IELB2loBhyHGeB2hACetcRthitMdUENgxiDTClB5JCMhIbRgAYQGAA) -7 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) and [bsoelch](https://codegolf.stackexchange.com/users/118682/bsoelch). The last row is built from four parts: 1. a space if the height is odd 2. `w` semicolons 3. one additional semicolon if `h` is even 4. one additional semicolon if `w` and `h` have the same evenness. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` aþ¬So1;Ʋ€ZṚƊ4¡ị⁾; Y ``` A dyadic Link that accepts \$w\$ on the left and \$h\$ on the right and yields a list of characters (or a full program that prints the result). **[Try it online!](https://tio.run/##AS0A0v9qZWxsef//YcO@wqxTbzE7xrLigqxa4bmaxoo0wqHhu4vigb47IFn///81/zQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/x8L5Da4LzDa2PbXrUtCbq4c5Zx7pMDi18uLv7UeM@a4XI/2YPd043Ojrp4c4ZOoeX60eClWUB5Q5tO7TtPwA "Jelly – Try It Online"). ### How? ``` aþ¬So1;Ʋ€ZṚƊ4¡ị⁾; Y - Link: integer, W; integer, H þ - [1..W] table [1..H] with: a - logical AND ¬ - logical NOT -> W×H zeros ¡ - repeat... 4 - ...times: four Ɗ - ...action: last three links as a monad: € - for each Row: Ʋ - last four links as a monad: S - sum {Row} 1 - one o - {sum} logical OR {one} ; - {that} concatenate {Row} Z - transpose } Ṛ - reverse } - rotate a quarter ị⁾; - index into "; " (1-based and modular) Y - join with newline characters ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~22~~ 21 bytes ``` F⁴«§; ⁺ι⁺ⅈⅉ×;I§⟦θη⟧ι↷ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw0RToZqLM6AoM69Ew7HEMy8ltUJDyVpBSUchIKe0WCMTSkdoaOooRGpoAoE1THlIZm5qMVAxUK1zYjFCe3ShjkJGrI5CJkx1Zll@SVBmekaJBpBb@/@/sYLxf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⁴« ``` Loop over the four sides of the rectangle. ``` §; ⁺ι⁺ⅈⅉ ``` Output a space if the sum of the previous dimensions is odd but a semicolon if it is even. ``` ×;I§⟦θη⟧ι ``` Output the appropriate number of semicolons. ``` ↷ ``` Pivot 90° so that the next iteration draws the next side of the rectangle. (Would have saved 4 bytes to input the width and height as a tuple instead of separate values.) [Answer] # [Rust](https://www.rust-lang.org), ~~109~~ ~~100~~ ~~129~~ ~~120~~ ~~113~~ ~~112~~ 108 bytes -4 bytes thanks to @corvus\_192 Is this what people mean when they say Rust's syntax is unreadable? ``` |w,h|{let r=str::repeat;r(";",w|1)+&r(&(r(";\n;",1)+&r(" ",w)),h)+";\n"+&r(" ",h%2)+&r(";",w+!h%2+!(w^h)%2)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=tZJRasMwDIbZq0-hGlqsxlupS2HE9BR7TD0Iw1kCXVYcZ4GlOcle8rAdajvNlLgj3QH6EkW_fumTwB-frq58_3PjshJe0qIUyFo4WA8Z7NhqyU6NzE9c8ztnjzb1ojmtMVoIrvflJA4Sh8mD-PebYzRY-b96PldDw0V_NM7FQGsHvNtV3sVxMGhHQC4D24mFcOcFZBBotiSonGhBC6DQnCRNpGRjJMW1VsYkzVyZhCwGu2uCGzpuQXa1FDM6M0dKiLhcfdU-u73_PlyVPaM0Iu5jjqR3Z2avGRuA3lb-Ka1sFUMi6qp4t3L8ot4a2JGmpEIJFDZD2IRsSxuMYYOGBmWvDgTdgFCU00RoGYwP6S091DaGB--K8pmGZqNXU_VIip8J3o6Wbl_SFVToGDvv2fch_gI) At the end of the program, I have to calculate the number of semicolons to output for the last line. This forms a decision tree that can be visualized in the following table: | w | h | result | | --- | --- | --- | | odd | odd | w + 1 | | odd | even | w + 1 | | even | odd | w | | even | even | w + 2 | First, I used an actual array and indexing with `n%2` to get the result, but this takes too many characters. ~~I have now converged to `w+(w&1)+2*(!(w|h)&1)` (first taking `w`, adding `1` if `w` is odd and then adding 2 if both `w` and `h` are even), but this can't be optimal.~~ ~~I have now converged to `w+(!h&1)+(!(w^h)&1)` (first taking `w`, adding `1` if `h` is even and then again adding 1 the parity of `w` and `h` is equal, but that also can't be optimal. Just look at the amount of parens!~~ `w+!h%2+!(w^h)%2` seems to be the best option. Completely forgot about precedence whoops [Answer] # [J](https://www.jsoftware.com), 53 53 41 36 35 31 30 26 24 bytes ``` '; '{~1=3|+/&(3,$&5,2&|) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsUPdWkG9us7Q1rhGW19Nw1hHRc1Ux0itRhMifdNJkys1OSNfwUQhTcEYzASaCRYxBoqYYIiYooiAdJlATFqwAEIDAA) Finally found a decent approach based on an addition table of the appropriate lists. Say our `m rows x n cols` input is `1 x 3`, which represents the dimensions of the inner box. We construct lists for each dimension of an addition table as follows: ``` going down: Initial number is always 3, followed by m 5s, followed by.... v 3 5 1 <-- Final number is 1 since m = 1 is odd. Otherwise would be 0. going across: 3 followed by n=3 fives v 3 5 5 5 1 <-- Final number is is 1 again, since n=3 is odd ``` Let's see what happens when we make a addition table: ``` | 3 5 5 5 1 --+-------------- 3 | 6 8 8 8 4 5 | 8 10 10 10 6 1 | 4 6 6 6 2 ``` Next we mod by 3, and check if the result is 1, which it will be only for cells that should be a space: ``` 0 0 0 0 1 0 1 1 1 0 1 0 0 0 0 ``` And finally convert to spaces/semicolons: ``` ;;;; ; ; ;;;; ``` This procedure gives the correct result for all 4 possible even/odd combos. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` «';Ž9¦S.ΛIÉ©нi¨}®θið®OÉǝ}®Oi¦ ``` Can definitely be golfed by using a different approach.. Input as pair \$[w+2,h+2]\$. [Try it online](https://tio.run/##ATwAw/9vc2FiaWX//8KrJzvFvTnCplMuzptJw4nCqdC9acKofcKuzrhpw7DCrk/DicedfcKuT2nCpv//WzcsNV0) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GpeSZV1BaYqWgZK/DpeRfWgLh6Pw/tFrd@uhey0PLgvXOzfY83Hlo5YW9mYdW1B5ad25H5uENh9b5H@48PhfI9c88tOx/rc6hbfZcIPO4yjMyc1IVilITUxQy87hS8rkUFPTzC0r0IdZCKTSX2CiogNXmpf6PNtExieWKNgWTJjqmYDaQBAA). **Explanation:** Step 1: Create a \$w+2\$ by \$h+2\$ box of `;`, filled with spaces: ``` « # Merge the (implicit) input-pair to itself: [w+2,h+2,w+2,h+2] '; '# Push character ";" Ž9¦ # Push compressed integer 2460 S # Convert it to a list of digits [2,4,6,0] .Λ # Use the (modifiable) Canvas builtin with these three arguments ``` [Try just step 1 online.](https://tio.run/##yy9OTMpM/f//0Gp166N7LQ8tC9Y7N/v//2hzHdNYAA) Step 2: Do the following actions based on whether the \$w\$ and \$h\$ are odd: | \$h\$=even,\$w\$=even | \$h\$=even,\$w\$=odd | \$h\$=odd,\$w\$=even | \$h\$=odd,\$w\$=odd | | --- | --- | --- | --- | | Do nothing | Insert a space at index 1;Remove the first character*†* | Remove the first character*†*Remove the last character | Insert a space at index 0;Remove the last character | *†*: Removing the first character of the multiline string basically empties the top-right corner. Combining those actions, we have the following three things to do: | Remove the first character*†* | Remove the last character | Insert a space at index \$((w+h)=odd)\$ | | --- | --- | --- | | If \$w+h\$=odd | If \$w\$=odd | If \$h\$=odd | Which translates to the following code: ``` I # Push the input-pair again É # Check for both whether they're odd (1 if odd; 0 if even) © # Store this pair in variable `®` (without popping) н # Pop and push the first item i } # If w is odd: ¨ # Remove the last character of the box ® # Push pair `®` again θ # Pop and push its last item i } # If h is odd: ð # Push a space character " " ®O # Push the sum of pair `®` É # Check if this sum is odd ǝ # Insert the space at that (0-based) index ®O # Push the sum of pair `®` yet again i # If this sum is 1 (so either w or h is odd, and the other is even): ¦ # Remove the first character of the box† # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine to understand how the Canvas builtin `Λ` works.](https://codegolf.stackexchange.com/a/175520/52210) [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž9¦` is `2460`. [Answer] # [Ruby](https://www.ruby-lang.org/), 66 bytes ``` ->w,h{(a="; "*w*h)[w+h]+?;*w+a[h]+" ;#{' '*w};"*h+" "+a[w]+?;*-~w} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165cJ6NaI9FWyVpBSatcK0Mzulw7I1bb3lqrXDsxGshS4rJWrlZXUNcqr7VW0soA8pWAEuVgJbp15bX/uQqKMvNKFNL0khNzcjSMdIw0gWq4lNCFjbEJG@MSxm6IAU7lBppc/wE "Ruby – Try It Online") We use "; " repeated (`w` \* `h`) times to get the character at the corners (by indexing) without using reminder operations. The character at the top left corner is `;` if both or none of `w` and `h` are odd so we add them together, that's why we need a loooong "; ; ; ..." string [Answer] # [JavaScript (Node.js)](https://nodejs.org), 96 bytes ``` f=(x,y,h=y++,w=x++)=>~x?f(x-1,y,h,w)+' ;'[(Y=y>h|!y)^(x>w|!x)|Y&!x*h+!y*w+1]:y?f(w,y-1,h)+` `:'' ``` [Try it online!](https://tio.run/##fcvdCoIwFADg@55iu2mbZwbqnTF7DukHxbQV4iKjnQPSqy@7C6KuP75L/ajH5na@3uPBHdsQOiNRk7aGALQ3CKBM8cRNJzFO3qC9AsHWYitLQ4WdOKmDxMJPHNVULjlGFjhFHpJ9TnPzmuZoFVSLKhciNG4YXd@ueneSnUw1SxUDJnaDUIsvy35Z9udlny@8AA "JavaScript (Node.js) – Try It Online") [Answer] # [sed](https://www.gnu.org/software/sed/) `-E`, 158 bytes Input is taken as `51` for w=5 and h=1. The first line adds a cheat sheet to teach `sed` counting down (of course you'd need some extra bytes for comments larger than 9) and produces the solution for w=1/h=1. Then the `w` loop adds two `;` and one while counting down the first field. The `h` loop duplicates a line with a whitespace while counting down the second field. The next-to-last line adds a semicolon for a odd number of them. Not very slim, but probably the best to achieve with `sed`. ``` s/$/987654321\n;;\n; ;\n;;\n/ :w s/^(.)(..*\1(\S).*;;)(.* )(.*;)/\3\2;\4 \5;/ tw :h s/^.(.)(.*\1(\S).*)(\n.* ;)/-\3\2\4\4/ th s/(\n(;;)+)(;\n)/\1;\3/g s/.*1// ``` [Try it online!](https://tio.run/##PY09DsIwDEZ3n6IDQxLUWE5SfuqZE7BaTKDCkiKlqLcnOCAx2LLl9z6X27Wf8qvWghs8Hva7IcVAkpm1Ov4NCOMKBS/GW@O9EzJytt4x6@q61tiiRAksqZOBEZYVxntT/Nf5K9ZIVkXxvvGSJCncSD0YDdxaow81jVgiTnrwjhBrJYIQIESIAQZ6z8/lMedS@9MH "sed – Try It Online") ]
[Question] [ # Context From Wikipedia: A polyomino is a plane geometric figure formed by joining one or more equal squares edge to edge. one-sided polyominoes are distinct when none is a translation or rotation of another (pieces that cannot be flipped over). Translating or rotating a one-sided polyomino does not change its shape. In other words, a one sided polyomino reflected across its x or y axis is not the same as the original polyomino, but a one sided polyomino that is rotated is still considered the same polyomino # Task Given a number n, find how many different unique one sided [polyominos](https://en.m.wikipedia.org/wiki/Polyomino) can be created using n number of blocks # Input Take integer n as input for the number of blocks that exist in the polyomino # Output An integer of the amount of unique one sided polyominos that can be generated # Examples in -> out 4 -> 7 5 -> 18 6 -> 60 7 -> 196 More test cases can be found on the [Wikipedia](https://en.m.wikipedia.org/wiki/Polyomino) page and [OEIS](https://oeis.org/A000988) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~39~~ 37 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Soon to be crushed by MATL and, quite possibly, APL ``` p`œc⁸ḣ1ạ§ỊẸʋƇ@;QɗƬƊṪṢƊƑƇŒṬZṚŒṪƲƬṂ$€QL ``` **[Try it online!](https://tio.run/##AVYAqf9qZWxsef//cGDFk2PigbjhuKMx4bqhwqfhu4rhurjKi8aHQDtRyZfGrMaK4bmq4bmixorGkcaHxZLhuaxa4bmaxZLhuarGssas4bmCJOKCrFFM////NQ "Jelly – Try It Online")** (It's pretty slow - a(6) took ~30 minutes locally!) To see them instead [try this](https://tio.run/##y0rNyan8/78g4ejk5EeNOx7uWGz4cNfCQ8sf7u56uGvHqe5j7Q7WgSenH1tzrOvhzlUPdy461nVs4rH2o5Me7lwT9XDnLBBj1bFNx9Y83Nmk8qhpTSBYBshwB@KsR437Dm07tO3///8mAA "Jelly – Try It Online") (`L` -> `ŒṬ€G€j⁾¶¶`). ### How? Builds all index lists, where each represents the locations of `1`s on a grid of `1`s and `0`s, up to those for a square of side `n`, filters for those that have their `1`s fully connected, then selects the "minimal" of each after any amount of rotation + vertical translation, and finally de-duplicates and yields the length. ``` p`œc⁸ḣ1ạ§ỊẸʋƇ@;QɗƬƊṪṢƊƑƇŒṬZṚŒṪƲƬṂ$€QL - Link: integer, n A....B..................C............ - break down below A: p`œc⁸ - Get all ways to have n 1s on an n*n grid as multidimensional indices ` - use n as both arguments of: p - Cartesian product -> all pairs of [1..n] - these are in sorted order ⁸ - chain's left argument, n œc - combinations (no replacement) - ...and so each of these are in sorted order B: ḣ1ạ§ỊẸʋƇ@;QɗƬƊṪṢƊƑƇ - Keep only the fully-connected ones (call input "All") Ƈ - filter keep those for which: Ƒ - is invariant under: Ɗ - last three links as a monad: Ɗ - last three links as a monad: 1 - one ḣ - head to index - i.e. [firstPair] (initial "Current") Ƭ - collect up while distinct, applying: ɗ - last three links as a dyad - i.e. f(Current, All): @ - with swapped arguments - i.e. f(All, Current): Ƈ - filter keep those (of All) for which: ʋ - last four links as a dyad - i.e. f(All, Current): ạ - absolute difference (vectorises) § - sum each Ị - insignificant? (effectively "in (0,1)?") Ẹ - any? - i.e. any are neighbours/same? ; - concatenate (the result with Current) Q - deduplicate (-> Current for the next Ƭ-loop) Ṫ - tail Ṣ - sort C: ŒṬZṚŒṪƲƬṂ$€QL - Count the distinct results € - for each: $ - last two links as a monad: Ƭ - collect up while distinct, applying: Ʋ - last four links as a monad: ŒṬ - 2d array from multidimensional indices Z - transpose Ṛ - reverse (transpose + reverse = rotate 1/4 anti-clockwise) ŒṪ - truthy multidimensional indices Ṃ - minimum Q - de-duplicate L - length ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~269 ... 243~~ 239 bytes Rather slow for \$n\ge7\$, but it does find \$a(8)=704\$ in a bit more than 2 minutes on my laptop. ``` f=(n,m=[...o=Array(w=n)],i=c=0)=>n?m.map((r,y)=>m.map((_,x,[...m])=>!i|1<<x&~r&(m[y+1]|r/2|r*2)&&f(n-1,m,m[y]|=1<<x)))|c:[0,0,0,0].some(_=>o[M=(m=m.map(a=(_,y)=>m.map(b=(v,x)=>a|=b|=(v>>y&1)<<w+~x)|b)).flatMap(v=>v/(a&-a)||[])])?0:o[M]=++c ``` [Try it online!](https://tio.run/##ZY3RaoNAEEXf@xd9WWbqulHbphAcQz8gXyBLWK0Wg7sb1mAUlvy63bSFUmSezpk7c09qVEPtuvMlNvajWZaWwHBNpRDC0rtzaoYrGZS8o5oSpMLstdDqDOD4HPAXjnzi9xstg3vsfJrnE7s5Brqco1R6t8m8e8qQsRZMnHLNw0J6uucQ0de7MuHfI8VgdQNHKmx5IND006AodPwVVgQjnwIqT5UPUBQzSzHPr9FtQl8hirZXl0OIjlSMG1AsVuh9KVHiPtmF35KiqF5qawbbN6K3n9BCivjw32Qr87wyLyvzujLblXlDXL4A "JavaScript (Node.js) – Try It Online") ## How? ### Building the \$n\$-polyominos We store the polyomino in an array \$m[\:]\$ of \$n\$ bitmasks and build all possible shapes recursively. At each iteration, a new cell adjacent to an existing cell is added. ``` m.map((r, y) => // for each bitmask r at position y: m.map((_, x, [...m]) => // for each position x, using a copy of m[]: !i | // always set this cell if this is the 1st iteration 1 << x & // otherwise, the x-th bit ~r & // must not be already set in the current row ( // and one of the following conditions must be met: m[y + 1] | // - the x-th bit is set in the next row r / 2 | // - the (x+1)-th bit is set in the current row r * 2 // - the (x-1)-th bit is set in the current row ) && // if truthy: f( // do a recursive call: n - 1, // decrement n m, // pass the copy of m[] m[y] |= 1 << x // set the bit at (x, y) ) // end of recursive call ) // end of inner map() ) // end of outer map() ``` ### Applying the rotations and translations When we have enough cells, we apply all 4 possible rotations to \$m[\:]\$, discard the empty rows and translate it horizontally so that it's 'right-justified'. We store the encountered shapes in the object \$o\$ and the number of distinct shapes in \$c\$. ``` [0, 0, 0, 0].some(_ => // repeat 4 times: o[ // we will ultimately test this entry in o M = ( // save the final matrix in M[] // 1) rotate m = m.map(a = // starting with a zero'ish, (_, y) => // for 0 <= y < w: m.map(b = // starting with b zero'ish, (v, x) => // for each bitmask v at position x in m[]: a |= // update the global bitmask: b |= // update the row bitmask: (v >> y & 1) // extract the y-th bit from v << w + ~x // and set the (w-x-1)-th bit in b accordingly ) | b // end of inner map(); yield b ) // end of outer map() ) // 2) translate and crop .flatMap(v => // for each bitmask v in m[]: v / (a & -a) // right-shift v by the position of the LSB of a || [] // discard this row if it's empty ) // end of flatMap() ] // end of lookup ) ? // if at least one shape was already encountered: 0 // do nothing : // else: o[M] = ++c // save the new shape in o and increment c ``` [Answer] # [R](https://www.r-project.org), ~~180~~ 168 bytes ``` f=\(n,o={},v=0,u=0,`:`=c,`~`=sort,`?`=diff){for(j in u)F=F+`if`(length(p<-~j:o)<n,f(n,p,v,setdiff(c(u=u[-1],j+-1:1i:1:-1i),v<-j:v)),2^(-any(?p-~-p)-any(?p-~p*1i))/n);F} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY9NCsIwEEav0uWMzqBxpbGhu17CHyJqNEXSUJOCiL2IG10IXsGjeBtbRBcDA_O-4X3Xe3W7PWIwPH4_jZqDo1KdL1SrIcV2tNRqTbrR6lhWgXSm1cYag2dTVlAk1iURc5X3tTUaDlu3C3vwKTeFLDF1ZNp_nmo6bkMXgzVEFWcsFlT0WUhhpZAsLFKdciFrRBotgVfuBJnnhj3-d99rMRw4nOaXr--rU7CdgpATTHxlXQADLfW9_3p9AA) How about a golfy implementation of a more or less real world algorithm of counting polyominoes? This code is a variation of Redelmeier's method published back in 1981 ([link](https://doi.org/10.1016%2F0012-365X%2881%2990237-5)). Obviously, here lots of speed optimizations have been sacrificed in favor of golf, but it still manages to calculate all \$n\$ up to 9 in about 17 s on TIO (and even finishes \$n = 10\$ when run alone), yet allowing for a quite nice byte count. ### Explanation The method works by performing a recursive depth-first search up to the indicated length \$n\$. The key point is that we never store the list of found polyominoes. Instead, we check for symmetries, and if the current polyomino is symmetric, add only a fraction of the score, so that the total of all polyominoes having the same unique shape would add up to 1. The algorithm starts by initializing the parent polyomino \$o\$ as empty (`NULL`), the set of visited cells \$v\$, and untried cells \$u\$ containing only the origin. The coordinates of the cells are represented by complex numbers. `for(j in u)` - Iterate through the untried set. At each iteration, the current cell is \$j\$. `u<-u[-1]` - Remove the current cell from the untried set. `v<-c(j, v)` - Add it to the visited set. `p<-sort(c(j, o))` - Grow the current polyomino \$p\$ by adding \$j\$ to the parent \$o\$. Sort for later use. `if(length(p)<n)` - If the polyomino has not yet reached the maximum length, `f(n,p,v,...)` - Invoke the recursive call with modified arguments. The new untried set (`...`) is constructed as follows. Add new neighbors to the untried set. When we are at the origin, the next iteration will involve the cells labeled `1-4` in the scheme below. However, the new neighbors exclude already visited cells, therefore when enumerating neighbors for cell `1`, only the cells `5-7` will be added, as the origin had already been visited. ``` . . . . . . . . . 6 2 . . . . 5 1 0 3 . . . . 7 4 . . . . . . . . . . ``` So, the new untried set is defined as \$u \cup\ \{j-1,j+i,j+1,j-i\} \setminus v\$. If the length \$n\$ has already been reached, count the polyomino and return. `2^(-any(diff(p-sort(-p)))-any(diff(p-sort(p*1i))))/n` - This is our symmetry evaluation. As we are interested in one-sided polyominoes, luckily, only two checks corresponding to 90 and 180 degree rotations are needed, no reflections involved. The rotations with complex numbers are very simple (\$ \times i\$ for 90 degrees, and \$ \times -1\$ for 180 degrees), but then we need to align the shapes to compare them. For this purpose, we sort the polyomino cells, and subtract one from another. If both represent the same shape under different translations from the origin, the resulting vector will consist of identical entries, so that all `diff` will be zero. Now, if a polyomino is invariant under 180 degree rotation, we will encounter this shape twice, so that gains a multipler of \$1/2\$. If it is also invariant under 90 degree rotation, we will find it 4 times, and the multiplier becomes \$1/4\$. In Redelmeier's work, there are additional restrictions disallowing inclusion of certain cells, in order to guarantee that each different rotation ("fixed" polyomino) we be counted exactly once. But these checks take precious bytes, so we skip them. In our case, each fixed polyomino is counted \$n\$ times - once for every possible starting point. So, we can handle this simply by dividing the result by \$n\$. Finally, we make use of heavy operator overloading to turn the code into a lunatic mess for some rather modest byte savings. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~216 214~~ 204 bytes ``` ->n{*h=1,1i,-1,-1i;z=[[0i]];(r,*z=z;r.map{|c|h.map{|v|(r!=k=r|[c+v])&&(w=h.map{|y|(x=k.map{|v|v*y}).map{|g|g-x.map(&:real).min-1i*x.map(&:imag).min}.sort_by &:rect})-z==w&&z<<w[0]}})until z[0][-n];z.size} ``` [Try it online!](https://tio.run/##NY1LCoMwGISvYjchWhN02dq/FwmhqPgItlbiK8bk7FarwixmvhkY2SfTksNCnvXslRD6ofBJuEpEGhgLBOcRlr6nQUeSfuJmNqkpdzMYLC9QgTQsvQ7cRQiPcHSTwQqqczd4k3X3UJiCqM1idJdZ/F6xqNc774TiExd/aGn7ld0rmZxtmXbWJRpgREg/HiMLuLVuX3fi7eg1MFLzSNNW6MwuOKT0dvwp0zhM@TlTnNvlBw "Ruby – Try It Online") ~~5.5 seconds for n=8 on TIO.~~ ~~**Update:** 41 seconds for n=9 on TIO~~ **Harder Better Faster Shorter:** 36 seconds for n=9 on TIO Still golf-in-progress, the explanation refers to a previous version, the concept is still the same. ### How (more or less): ``` ->n{z=[[0+0i]] ``` This initializes the list of polyominos. Instead of a matrix, I will use a list of complex numbers (with integer real and imaginary part). The first entry is the monomino (0,0) ``` (r,*z=z; ``` The main loop: get a single n-omino from the list and build all possible (n+1)ominos from there: ``` 4.times{|v|r.map{|c| ``` We need to iterate on all squares of `r` 4 times (add a new square on all sides) ``` (k=[*r,e=c+1i**v])==k|[]&& ``` First check: if we have duplicate squares, we can discard this piece. Otherwise, continue. ``` (w=4.times.map{|y| ``` Check all possible rotations ``` (x=k.map{|v|v*1i**y}) ``` To rotate a piece 90 degrees, multiply all squares by `i` ``` .map{|g|g-x.map(&:real).min-1i*x.map(&:imag).min} ``` Then translate it so that it starts from (0,0). ``` .sort_by(&:rect)})-z==w&& ``` Sort the squares inside all 4 rotations, check if at least one is already contained in `z` ``` z<<w[0]}}) ``` If not, add the first rotation to `z` ``` until z[0][-n] ``` Repeat until the first piece in the list has size `n` ``` ;z.size} ``` The size of `z` is the final result. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 632 bytes *Finds a(9)=2500 in 30 seconds* ``` J=Length;Q=First;s@n_:=(p=m@{{0,0}};Do[p=S[Flatten[m@#&/@p,1]],n-2];If[n<3,1,J@p]);m@b_:=(A=B={};Do[(A=If[(X=MemberQ)[b,b[[i]]+#],A,(H=Append)[A,b[[i]]+#]])&/@{{0,1},{1,0},{-1,0},{0,-1}},{i,J@b}];A=Complement@A;Table[B=H[B,H[b,A[[j]]]],{j,J@A}];B);S@q_:=Module[{s,b,u,L,V,U,f},f={};Do[s=q[[j]];b=g[q[[j]]];u=Sort[(#-Q@b)&/@q[[j]]];{L,V,U}=v@u;f=If[Or@@(X[f,#]&/@{u,Sort[(#-Q@g@L)&/@L],Sort[(#-Q@g@V)&/@V],Sort[(#-Q@g@U)&/@U]}),f,H[f,u]],{j,J@q-1}];f];g@h_:=(o=(W=Select)[h,Last@#==(Min[Last@#&/@h])&];W[o,Q@#==(Min[Q@#1&/@o])&]);v@p_:=(x=y=z={};Do[x=H[x,{T=Last[p[[i]]],-(R=Q[p[[i]]])}];y=H[y,-{R,T}];z=H[z,{-T,R}],{i,J@p}];{x,y,z}) ``` [Try it online!](https://tio.run/##VVFta9tADP4rg8CwmUzi7dN2E5zTUrKSsDlvLRzHsNtz7BKfnfhckhz@7Z4uaVZ6X07So0d6JJWJyVWZmOIp6ft7nCq9MTmL8a7YN4Y1XP/9gV6NJbd2BKOuY7eVqHEh7raJMUqLkg8@D3kNoZSgg6@S/cqE/vkNQrjntfRZyVNXIcIx2jOZTErxHnGmylTtY1@kkApRSPllICECb4JRXSv97IvoHZA@dXESwg5sSELABpdvBEHY0V9Qw7STLMKbqqy3qlTa8Igtk3SrxBgnYgwTahUJ8SLpgX0hQkSEsc8WfEciZ9VzS7m2gRRamMIaVpB1kL0Jb3B35rIUN@JiStbiotob4Q2CmKdO4xWwZ36Hr7xlmZv4955z71FkMJBulBbeiRs@ddSp/BBbu9j6Y2zlYivZ@ZDRNBm010F2tATJMsk2PHf7rtB7wIXaqifjixymSWP4ANGbFVpcHCqU01YlexAVxP9BskKCKgf57JXXrtoBj3h6W8OBVnkAu0RXRtTnA0kIvDnGV88nKUdKO0Jg57Ak70TeiU62hHknL7eqKWwPcIRT5/d/9oU2n4a8GfJ5ojeKf@/7fw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~75~~ 72 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Should have been 1 byte less by replacing `})}€ê` with `}){}`, but the many nested maps/loops cause a bug in 05AB1E here (`})ê}` and `})}€{` also doesn't work strangely enough..) ``` 1ÝInãʒOQiyƶIô©Δ2Fø0δ.ø}2Fø€ü3}®Ā*εεÅsyøÅsM}}}˜Ùg<]εIô2Føʒà}}4FDíø})}€êÙg ``` Extremely slow brute-force, so is only able to output up to \$a(4)\$ on TIO. [Try it online](https://tio.run/##yy9OTMpM/f/f8PBcz7zDi09N8g/MrDy2zfPwlkMrz00xcju8w@DcFr3DO2pBzEdNaw7vMa49tO5Ig9a5ree2Hm4trjy8A0j61tbWnp5zeGa6Tey5rUC9IMWnJh1eUFtr4uZyeC1Qu2YtSPMqoJL//03@6@rm5evmJFZVAgA) or [verify the first few results](https://tio.run/##yy9OTMpM/W9ybJKfvZLCo7ZJCkr2focnhCr9Nzw8NyLv8OJTkyKK/SMCMyuPbYs4vOXQynNTjNwO7zA4t0Xv8I5aEPNR05rDe4xrD6070qB1buu5rYdbiysP7wCSvrW1tafnHJ6ZbhN7bitQL0jxqUmHF9TWmri5HF4L1K5ZC9K8Cqjkv5JemM7//7q6efm6OYlVlQA). **Explanation:** Step 1: Create all possible \$n^2\$-sized list using `0`s and `1`s, consisting of \$n\$ amount of `1`s: ``` 1Ý # Push pair [0,1] In # Push the squared input ã # Cartesian power ʒ # Filter this list of lists by: i # If O # the sum of the current list Q # is equal to the (implicit) input-integer: # Continue with the check in step 2 below # (implicit else: implicitly use the implicit input for the filter; # this is only truthy for edge case n=1, which fails step 2 due to the `ü3`) ``` [Try just this first step online](https://tio.run/##yy9OTMpM/f/f8PBcz7zDi09N8g/8/9/kv65uXr5uTmJVJQA) (without trailing `i`). Step 2: Filter it further to only keep single polynominos, using a flood-fill approach: ``` y # Push the current list again ƶ # Multiply each value by its 1-based index Iô # Convert the list to an input-by-input block © # Store this block in variable `®` (without popping) Δ # Loop until the result no longer changes to flood-fill the matrix: 2Fø0δ.ø} # Add a border of 0s around the matrix: 2F } # Loop 2 times: ø # Zip/transpose; swapping rows/columns δ # Map over each row: 0 .ø # Add a leading/trailing 0 2Fø€ü3} # Convert it into overlapping 3x3 blocks: 2F } # Loop 2 times again: ø # Zip/transpose; swapping rows/columns € # Map over each inner list: ü3 # Convert it to a list of overlapping triplets ®Ā # Push matrix `®` and convert all its positive values back to 1s * # Multiply each 3x3 block by this matrix of 0s/1s (so 0s will remain 0s) εεÅsyøÅsM # Get the largest value from the horizontal/vertical cross of each 3x3 block: εε # Nested map over each 3x3 block: Ås # Pop and push its middle row y # Push the 3x3 block again ø # Zip/transpose; swapping rows/columns Ås # Pop and push its middle rows as well (the middle column) M # Push the flattened maximum of the entire (scoped) stack, # which is the flattened maximum of the cross of the current 3x3 block }} # Close the nested map }˜ # After the flood-fill loop: flatten the block to a list Ù # Uniquify its values g # Pop and push its length < # Decrease it by 1 to account for the 0s # (only 1 is truthy in 05AB1E, so only single islands remain) ] # Close both the if-statement and filter ``` [Try just the first two steps online.](https://tio.run/##yy9OTMpM/f/f8PBcz7zDi09N8g/MrDy2zfPwlkMrz00xcju8w@DcFr3DO2pBzEdNaw7vMa49tO5Ig9a5ree2Hm4trjy8A0j61tbWnp5zeGa6Tez//yb/dXXz8nVzEqsqAQ) Step 3: Convert each valid lists to matrices, and slash of any rows/columns of 0s to have the actual polynominos: ``` ε # Map over each inner list Iô # Convert it to an n-by-n block 2F # Inner loop 2 times: ø # Zip/transpose; swapping rows/columns ʒ # Filter this list of rows by: à # Get the maximum of the row (so if it only contains 0s, it'll be removed) } # Close the filter } # Close the inner loop ``` [Try just the first three steps online.](https://tio.run/##yy9OTMpM/f/f8PBcz7zDi09N8g/MrDy2zfPwlkMrz00xcju8w@DcFr3DO2pBzEdNaw7vMa49tO5Ig9a5ree2Hm4trjy8A0j61tbWnp5zeGa6Tey5rUC9IMWnJh1eUFv7/7/Jf13dvHzdnMSqSgA) Step 4: Remove all duplicated rotations, by converting each polynomino to a quartet of its four sorted rotations, and then uniquify that list of quartets. ``` 4F # Inner loop 4 times: D # Duplicate the current polynomino-matrix íø # Rotate it 90 degrees counterclockwise: í # Reverse each inner row ø # Zip/transpose the matrix; swapping rows/columns }) # After the loop: wrap the four rotations on the stack into a list # Explanation if the 05AB1E bug mentioned at the top wasn't present: { # Sort the quartet of rotations }Ù # After the map: uniquify the list of polynomino-rotations # Actual explanation with bug: }€ # After the map: open a new map: ê # Sort and uniquify each quartet Ù # After the map: uniquify the list of distinct polynomino-orientations ``` [Try just the first four steps online.](https://tio.run/##yy9OTMpM/f/f8PBcz7zDi09N8g/MrDy2zfPwlkMrz00xcju8w@DcFr3DO2pBzEdNaw7vMa49tO5Ig9a5ree2Hm4trjy8A0j61tbWnp5zeGa6Tey5rUC9IMWnJh1eUFtr4uZyeC1Qu2YtSPOqwzP//zf5r6ubl6@bk1hVCQA) Step 5: Get the amount of unique polynominos left, and output it as result: ``` g # Pop and push the length # (which is output implicitly as result) ``` [Answer] # Python, ~~396~~ 319 bytes saved 77 bytes thanks to @Deadcode Modified from [@Kirill L.'s answer](https://codegolf.stackexchange.com/a/200161/110802). The golfed version, [Try it online!](https://tio.run/##hZDBboQgEIbP@hQcB4WttDd3ufoSxoOJ0GLcgSCY@PR26KHdW/8DGf7MfDP5w5m@PH5cl3sGHxPD/Awnm3eGoV6MZRZQeD1O4tBjN4lcXt7X1aC7urI@spU5ZJmcKuidCGYB347rxMlxlm0GIfAH9lnnUfXTnTjr1B73odWFHcQhNrcn2E2CzG8ZncefD4bbHON8wsrb33qUSqhVKCEVreCyNB6cRNvMtpuesPDeNCBnPAticdb@oQKXVJczQb6YpH/7X7xGrWXkDWlrNClHZMNVssCSRZzx0wCd2VFOjBSiwwTRZ1yA2DR5fQM) ``` import numpy as np def f(n,o=[],v=[0],u=[0]): F=0 for j in u: p=sorted(o+[j]) if len(p)<n:u=u[1:];v=[j]+v;F+=f(n,p,v,list(set(u).union(set(np.array(j)+np.array([-1,1j,1,-1j]))-set(v)))) else:F+=(2**(-any(np.diff(np.array(p)-np.sort(-np.array(p))))-any(np.diff(np.array(p)-np.sort(np.array(p)*1j))))/n) return F ``` The ungolfed version: ``` import numpy as np def f(n, o=None, v=None, u=None): if o is None: o = [] if v is None: v = [0] if u is None: u = [0] F = 0 for j in u: p = sorted(o + [j]) if len(p) < n: u = u[1:] v = [j] + v F += f( n, p, v, list(set(u).union(set(np.array(j) + np.array([-1, 1j, 1, -1j])) - set(v))) ) else: var1 = any(np.diff(np.array(p) - np.sort(-np.array(p)))) var2 = any(np.diff(np.array(p) - np.sort(np.array(p) * 1j))) F += (2 ** (-var1 - var2) / n) return F expected = [] for n in range(1, 10): expected.append(round(f(n))) print(expected) ``` ]
[Question] [ Very recently, I changed my SE username because I made this account some years ago and wanted to get back into asking questions. However, I’m still planning to post questions and potentially earn votes. We can imagine a site that has some issues dealing with name changes. The problem: given a list of names, reputation changes, and name changes, can you create a leaderboard of reputation? **Assume everyone's reputation starts at 0.** Input comes in any reasonable format, and has two forms: a *name change* `<String, String>` and a *rep change* `<String, Number>`. What does *any reasonable format* mean? When I write questions, it usually means the input can be rearranged or repackaged to work with the way your language takes in input (do you want a list of pairs? two lists? a string? that’s all fine) as long as it doesn’t add information or otherwise offload some of the computational work onto the human. Name changes change a person’s username to any username *not currently in use.* For example, if A changes name to D, and B changes name to C, D (previously known as A) could still change their name to A or to B, even though these names have been used before. However, at any given moment the set of names are unique. Rep changes represent something like getting up/down votes on a post, receiving a bounty, etc. All rep changes are guaranteed to be integers. They might come in the form <“Bob”, 5> or <“Alice”, -53000>. At the end, you must output all usernames that are currently in existence, and their rep counts, in descending order. Test case: ``` Alice 5 Bob 7 Bob John John 113 Alice Cheryl Daniel 13 John Alice Alice 12 ``` Result: ``` Alice 132 Daniel 13 Cheryl 5 ``` Test case, suggested by Unrelated String: ``` Jimmy Adam Donald 12 Amelia -11 ``` Result: ``` Donald 12 Adam 0 Amelia -11 ``` Test case: ``` CodegoLfer65 12 Bluman 9 CodegoLfer65 n4me n4me -3 ``` Result: ``` Bluman 9 n4me 9 (note: these two can be in either order) ``` Usernames are composed of only [A-Za-z0-9], i.e. alphanumerics. However, the input will not be a number in your language. This means usernames like `144`, `015`, `0x0F`, `1e7` will not appear in the input. Numbers such as `1/3`, `2.8` do not appear due to the character specification in the first place. This question seems heavy on data structures, so golfing languages may not perform as well. Maybe other languages will have a fighting chance? Scoring is by lowest number of bytes, i.e. tag:code-golf . [Answer] # [Python 3](https://docs.python.org/3/), 115 bytes ``` def f(l): r={} for n,m in l:q=m*0!=0;r[[n,m][q]]=r.pop(n,0)+[m,0][q] return sorted(r.items(),key=lambda i:-i[1]) ``` [Try it online!](https://tio.run/##VY69bsMgFIV3nuJ2AloSmVpRJVcMSTvlFRADqbGMyo9D6GBVfXaXkFRyt3OOvu/qTnMeY2iXpTcDDMTRDkES3z8IhpggMA82gOvOwj82D6J5TVKWUcmzUiJtpziRwBr6JD1rrmORTf5KAS4xZdOTtLXZ@Auh7NPMwml/6jXYbmMlV3SZkg2ZDEQiiffOfhjMYKdYaYd4KvlllfExjgHXoSYGnLe1/pn4bTRpdjfmXQdr3JVq184d/ufxZ4UUpWj9zdF6P1e@1/5@MQbt@htfdW@c1aVvOC9DubD8Ag "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~102~~ ~~101~~ ~~95~~ ~~94~~ ~~93~~ 90 bytes ``` ->c{l={};c.map{|a,b|x=l[a]||0;b*0!=0?(l[b],l[a]=x,p):l[a]=x+b};l.compact.sort_by{|a,b|-b}} ``` This takes input in the form of a list of `["name", "new_name"/score]` pairs. And it outputs in an ordered list of `["name", score]` Golfy Tricks * I used `p` with no args to get a `nil` value. * ~~I used `String===b` instead of `b.is_a?String`~~ * ~~I used ~~`b!=b.ord`~~ `b.ord!=b` to find out if it's a string or not. See [`String.ord`](https://ruby-doc.org/core-2.4.0/String.html#method-i-ord) and [`Integer.ord`](https://ruby-doc.org/core-2.5.0/Integer.html#method-i-ord)~~ * I'm using `b*0!=b` to check if it's a string or not. * For some reason, `b.ord!=b` means that I don't need a space between the `?` ternary operator and the following `(`, but if I swap it to `b!=b.ord`, then another whitespace is needed. * I sorted by `-b`, rather than by `b` and then reversing (d'oh!) ## [Try it online!](https://tio.run/##pZHfaoMwGMXvfYosV@0WRefc2MSNtbsqewORkcRYhcSIbaGiPruLf9vZMQbNVc6PL@fk8OUHUjQR8ECjv9KSe2XtUkPgrKwwItXR4z4Oqsp0ya1545lvC@6TALXQO6Js@dLf7kjtcoNKkWG6N3Yy33@RonfQSV03NMbplu1Uiq8BdXz4zhPKIAJOgAaykkTpp5mGGxmncIKdQsCy7AmNTnAds7zgp9kPnCaMt9P2/P3w6MLDulco0DIQGRRzvhj@vdS0ywabRIii8wqxOEuVKebh6DXYC8YTrJhuWf8PWMuQbeVnxPJH56ffih8Ebns8T2g2DNMHcdavUyrevrreiK9u16/X@XvdPbTM322bbw "Ruby – Try It Online") Edit: Thanks to [Veskah](https://codegolf.stackexchange.com/users/78849/veskah), for pointing out some problems this solution was missing. Somehow adding a temporary variable to hold `l[a]||0` has shortened the code by a byte. Edit: Thanks to [G B](https://codegolf.stackexchange.com/users/18535/g-b), for suggesting `b*0!=0` instead of `b.ord!=b`, which also allowed me to get rid of the space before the `?`, saving 3 characters. [Answer] # [PHP](https://php.net/), 111 bytes ``` for(;$n=$argv[++$i];+$r&&$a[$n]+=$r)if(!+($r=$argv[++$i])&&$a[$r]=+$a[$n])unset($a[$n]);arsort($a);print_r($a); ``` [Try it online!](https://tio.run/##bVDLbsMgELzzFTRCsRHOwY2qHqhV9XHKLzgoog4JSBistVPJqvrtro2txKm8B7QzzAzLVrrqXl4rXSFEGlU3Nc5wjnBf4zlU9GZNoaIER09RcmPf/dfAPS9wO6/dnB4xjtJ0O6evuR9aQWvnV5/SGWWDZ7uUNFkXstLHiRbJ/3/sTFm2wX2U5d1r3kl7vHOPoaWyRg78Jk1vsYIjdPKgZKFxPK1N1jh0FP8EGZFw/u6XKQFkeygVnFWcu4u1IpmEvOszYk5cFrQ5Y8QIzgis10TmxAmWEaDmFD@wmMBcREcFiIyNSnpxtWriCXAJtYcBUl6Bcc0BQt8Nc6lCe7zau8219m7Fw8hTiKF3sDei3@4P "PHP – Try It Online") Inputs are command arguments (`$argv`) as a plain list like: `Alice`, `5`, `Bob`, `7`. Every item is a separate argument. ### Commented ``` for(; $n=$argv[++$i]; // $n is set to the first parameter (name) for each event +$r&&$a[$n]+=$r) // at the end of each iteration if $r is a number // add it to reputation of $n if( !+( $r=$argv[++$i] // $r is set to the second event parameter (name or reputation change) )&& $a[$r]=+$a[$n]) // if $r is a name, transfer reputation of $n to $r unset($a[$n]); // and remove $n from $a arsort($a); // after the loop, sort $a by its values in descending order print_r($a); // print $a as string ``` --- # [PHP](https://php.net/), 98 bytes This one shows non-existing users too (at the end of the list), but shows nothing as their reputation. ``` for(;$n=$argv[++$i];arsort($a))+($r=$argv[++$i])?$a[$n]+=$r:[$a[$r],$a[$n]]=[+$a[$n]];print_r($a); ``` [Try it online!](https://tio.run/##bZDfaoMwFMbv8xShBFS0F66MwTIp@3PVV0hDyWzWBGIiRzuQsWd3Jkqrw3MRzvnlfN85Sa3q/mVfqxoh0sqmbXCBGcJDjKeP6NXoUkYZjh6j7E7f3KdnTyvs4JSd47HGUZ7v5vjm@64kdGZ@9SGsliZodmtOk3TFK3@YMM/@v@Ogq6oL6rOoFtOcFea8UI@mlTRaeL7N87stpwh9OZCiVDievk00OGQJ/gltRMDle/hMASC6UyXhImNmr8bwbGqk/eARU2KL0MvSlGhOBTQO2piIJEljAvO7ZE8EI5anBYFn5nPg2Yh4wdIpozVo257AW9DeryJL5fDmaLe3ONoNDVtebSOHYTpZlIMQ/fZ/ "PHP – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 65 bytes ``` {(>x)!x@>x}(0#`!0){(n;a):y;$[`i~@a;@[x;n;+;a];@[x;a;:;0^x@n]_n]}/ ``` [Try it online!](https://ngn.bitbucket.io/k#eJxVjd1qAjEQhe99CqW9yCDipmqlOyCr9kr6BrI2o5vVQDIBoZBF7LN3k7WiV3N+vsPU+UUsAgxCsQhXkb2oQQYXwUiQN/i6Vea3ICy2ARmHSGWShDlmu1Bw+c3lddzr1X0h1NKag8YZYF+old/j/K7Uxp84uShQykky3UCtT/rc2JR8Ehtt8dYnuKMeePkG0D3cGOeaFqjIAbZjz2Sr2Ldm6bQ1hCMp/+m1r/TRf9X6/D67QSv744jxI+qnWvHU6ZjGi6MJwB8+Rlcl) Input is taken as a list of pairs; user names are symbols (rather than strings). * `(0#`!0){...}/` set up a reduce, seeded with an empty dictionary (mapping symbols to integers) that tracks the active usernames and their respective reputation scores * `{(n;a):y;...}` destructure the next pair into its `n`ame and `a`ction * `$[`i~@a;...;...]` check whether or not the `a`ction is an integer (representing a reputation change) or not * if the action was a reputation adjustment... + `@[x;n;+;a]` add the reputation change to that user (if this is the first time the username appears, use `0` as the fill element) * if the action was a username change... + `@[x;a;:;0^x@n]` carry over the reputation from the previous name to the new name (if the prior name didn't have any reputation or name changes yet, set its reputation to 0) + `..._n` delete the old user name from our reputation tracker * once done handling the reputation/name changes... + `{(>x)!x@>x}` sort the users by their reputation, descending (outputting both the username and their "final" reputation) [Answer] # [Pip](https://github.com/dloscutoff/pip) `-rS`, ~~71~~ 53 bytes ``` {IaNI@ZllPB[a0](lY@Zl@?a1)+:bI+bNEb(ly0):b}MUg^sRVSNl ``` [Try it online!](https://tio.run/##K8gs@P@/2jPRz9MhKicnwCk60SBWIycSyHGwTzTU1LZK8tRO8nNN0sipNNC0Sqr1DU2PKw4KC/bL@f/fMSczOVVB15TLKT9JwRxMeuVn5HGBCAVDQ2Mux5yc1DwF15T0xCIuiGLnjNSiyhwul8S8zNQcBaASsFqwHFSFodF/3aJgAA "Pip – Try It Online") I'm gonna golf this some more before writing a thorough explanation. The basic idea: * Keep a list of [name score] pairs in `l` * Loop through the lines of input, split on spaces, using `MU` (for each line, the first item is `a` and the second item is `b`): + If `a` is not one of the names in `l`, append `[a 0]` to `l` + Add `b` to the score in `l` associated with the name `a` (if `b` is a name, this adds 0\*) + If `b` is not a number, change the name `a` in `l` to `b` * Once the loop is done, sort `l` in descending numerical order (since all the names are 0 in numeric context\*, this sorts by the scores) \* Assuming that no names start with a digit, which I argue is the best Pip-specific interpretation of ["whatever the input is, it won't be able to be parsed as a number."](https://codegolf.stackexchange.com/questions/195022/whos-who-in-the-name-change-game/226382#comment464627_195022) [Answer] # [Haskell](https://haskell.org), 253 bytes ``` import Text.Read import Data.List m l(k,d)=maybe((d,o):n)(\a->(k,a+o):n)(readMaybe d)where o=maybe 0id(lookup k l);n=filter(\(x,_)->x/=k)l f v=sortBy(\(_,x)(_,y)->compare y x)$filter(\(x,y)->maybe("",0)id(find(\(a,_)->a==x)r)==(x,y))r where r=foldl m[]v ``` The function takes a list of String pairs and returns a list of `(String, Int)` pairs ## Full programme, **355 bytes** ``` module Main where import Text.Read import Data.List m l[k,d]=maybe((d,o):n)(\a->(k,a+o):n)(readMaybe d)where o=maybe 0id(lookup k l);n=filter(\(x,_)->x/=k)l main=getContents>>= \c->let r=foldl m[]$map words$lines c in putStr$unlines$map(\(x,y)->unwords[x,show y])$sortBy(\(_,x)(_,y)->compare y x)$filter(\(x,y)->maybe("",0)id(find(\(a,_)->a==x)r)==(x,y))r ``` The programme takes input as specified in the testcases via STDIN ## [Try it online!](https://tio.run/##TZDBasMwEETv/ool@GBRJ01aSqFFhiY5lebS9paEoFhKLbySjCwT@etdWW6glwHtvF1mVLG2FojDoAzvUMCOSQ3XSliRSNUY6@BbeLf4FIzfBlvm2OJDti5RgPs650eqWH8WWcZzQ140yQ5sXmR1zu6mpw3Lu5EATuJpMNMGLCXP0Ji6a6AGJK@aXiQ6YbND5vMTmRf@ntYEExVS0R/hNkY7oV1bFBQO5bxA4cDSi0GOoPbHVLEGrsbyNkWpRQslhDZN576cTTsdZyMTz/fhfKcjvfd5W5kr9EeStqHiug/EKfckyIiVRjUsxO7Bk/RfwtGbqs9m@ZKEMhepebBYDM8o9cQSSiNK7DC8oSwFPCVrc4bnqO@m0skosFo9JpO/CX/UY7JlWgqEMI5@9P6I1cMv "Haskell - Try it online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 118 bytes ``` a=>a.flatMap(v=>([p,q]=v,u=a[p])?(q+-q?a[a[u[0]=q]=u,p]=0:u[1]+=q,[]):[q+-q?a[q]=[q,0]:a[p]=v]).sort((a,b)=>b[1]-a[1]) ``` [Try it online!](https://tio.run/##VZFbT8IwGIbv9yt6YUIbusFENM50hMONRP0DtYZvrIOZHnYO/HrsJiR68y55n@f90mTf0EG9r/Ki8Y1N5SVjF2AxBJmC5h0K3LEY84KWgnW0ZcALQRa4HPvlAjjwlk8Fc6ylhWDTqOWhGLOSckEifpUc5SWdiqjfsk6QoLZVgzHQhLA4cQsfXJBLI@sGMVQjFqO9NbVVMlD2gDNcB02Va@yWhcobPPo0IxJo97hT755uNRqR3xrzEz0Ld919J1/@4jMd302C/j4@k8VHqxNZBQVUtXw1rqLhlETOJ@TFG6Sdt1T5XqK5t7IJehpya4/G6wOF4ezK10dZnZW3AZNLhVw98IFdjfDe25Hb0W2u9RktU9DexhpQaY@XWqockB@Gf8y1@xMH@5bJ6nHeSyvVajDo@T8wD1p6fSB/5saXHw "JavaScript (Node.js) – Try It Online") Expect input `([string, string]|[string, number])[]` type. `q+-q` is used to test whether `q` is a number or string. if `q` is number, `q+-q` will be falsy. If `q` is string, `q+-q` will be truthy. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 48 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¯svИy`Uk;©di®èX.ïi`X+‚ëy`:}®ǝëX.ïiyëX¾‚}ª]Σθï}R ``` Input as a list of pairs. [Try it online](https://tio.run/##yy9OTMpM/f//0PrissMTTs@pTAjNtj60MiXz0LrDKyL0Dq/PTIjQftQw6/DqygSr2kPrjs89vBosXAmkD@0DytQeWhV7bvG5HYfX1wb9/x8dreSYk5mcqqRjGqsTreSUn6SkYw5nKXnlZ@Qpgbhgho6hoTGIA9Wh5JyRWlSZA5Z3SczLTM0BqjBGqIaqQ9JhaBQbCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLj/T@0vrjs8ITTcyoTQrOtD61MyTy07vCKCL3D6zMTIrQfNcw6vLoywar20Lrjcw@vBgtXAulD@4AytYdW1daeW3xux@H1tUH/dQ5ts/8fHR2t5JiTmZyqpGMaqxOt5JSfpKRjDmcpeeVn5CmBuGCGjqGhMYgD1aHknJFaVJkDlndJzMtMzQGqMEaohqpD0mFoFBurowC00yszN7cSpCIlMReiPz8vMScFrAKkPDc1JzNRSUfX0JB0DSAuSJUOeXqhqmGanfNTUtPzfdJSi8xMYTqcckpzE4EetARxUBUo5ZnkQrwMZujoGkPNAYenKZaQBXMNDaDKEAEFCTWwFIyp5JNYWpQK0QZhgtVaxMbGAgA). **Explanation:** ``` ¯ # Start with an empty list: [] sv # Loop over each input-pair `y` Ð # Triplicate the current list ˜ # Flatten it y` # Push the key and value of the current item `y` separated to the stack U # Pop the value, and store it in variable `X` k # Get the index of the key in the flattened list ;© # Halve it, and store it in variable `®` (without popping) di # If this index/2 is non-negative (>= 0): ®è # Get the `®`'th pair from the current list X.ïi # If `X` is an integer: ` # Push the key and value of the indexed pair separated to the stack X+ # Add `X` to the value ‚ # And pair the key and this new value back together ë # Else (it's a rename): y` # Push the key and value of the current item `y` separated to the stack : # And replace key with value in the indexed pair } # After the if-else: ®ǝ # Insert this modified pair at index `®` back into the list ë # Else (the current key doesn't exist yet): X.ïi # If `X` is an integer: y # Simply use the current item `y` ë # Else: X¾‚ # Pair `X` with 0 } # After the if-else: ª # Append this new pair to the list ] # After the loop: Σ } # Sort the resulting list in ascending order by: θ # The last item of each pair (the values) ï # Casted to an integer (because the `:` might have made it a string) R # And then reverse this sorted list to make it descending # (after which it is output implicitly as result) ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html) (with shell callout to "sort"), 105 bytes ``` b=$1,d=$2{g=f[b]=d+0==d;f[d]=!g;g?m[b]+=d:m[d]=0+m[b]}END{for(n in m)if(f[n])print n" "m[n]|"sort -k2rn"} ``` [Try it online!](https://tio.run/##VYnLCoJAFED38xW3wYVigk4ZlFyCHrvoB8SFMs4gNndiMlqY3z7pss2Bc0796b1vMMjWEgMxalRlU6GMU0RZqFJWuNKFPpq5xigPZilpvOh0vV9GZV1I0BGYqFOhKqmKnq6jAYgDN7N@@cu6AZJeOOKT92crW21vqnW7HDLBTo@3qQn27G/Q1rRsASSbHw "AWK – Try It Online") This one builds two arrays, one with the score for a give name, and one that's a boolean flag indicating if a name is active or not. At the end, the code prints the reputation scores for all the active accounts and pipes those lines to a `sort` call. Sorting things in AWK is a nightmare... Here's a description of the components. ``` b=$1,d=$2{ } ``` This test/code-block runs for each input line. The `b=$1` and `d=$2` are just a shortcuts for positional variables used repeatedly in the code. The first one is always truthy, so the code block runs even if the reputation is `0`. ``` g=f[b]=d+0==d; ``` The first expression sets the "is an active account" flag (the `f[]` array) to true or false depending on whether or not the second token on the input line is a number. The test `d+0==d` catches that since AWK converts a non-numeric string to `0` if you try an use it as an integer in a mathematical expression. And `g` is set just to shorten the code when `f[b]` is needed later. ``` f[d]=!g; ``` The "is an active account" flag for the second token is the opposite of the value computed for the first token. That will set some garbage entries for input lines that have a numeric reputation as the second token, but they will be ignored. ``` g?m[b]+=d:m[d]=0+m[b] ``` This ternary sets increments the reputation counter (the `m[]` array) for the first token if we got a numeric second token. Otherwise it sets the reputation token for the second token to the reputation token of the first token. In other words, it copies the reputation to the new name. ``` END{for(n in m)if(f[n])print n" "m[n]|"sort -k2rn"} ``` Once all the input lines have been handles, the code loops through all the names in the reputation array `m[]` and for any that are active users per the `f[]` array, it prints the name and final reputation. The `sort -k2rn` command sorts the whole set and prints the output. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 132 bytes ``` /.* -?[0-9]/{a[$1]+=$2} !/.* -?[0-9]/{a[$2]=a[$1]+0;delete a[$1]} END{PROCINFO["sorted_in"]="@val_num_desc";for(k in a)print k,a[k]} ``` [Try it online!](https://tio.run/##XcpPT8JAEIfh@3yKseGgaIUtoiGk0dJqIjFgvDabZmUH2XT/mKVoCOlnr7Zw0cubzO8Z8V02zeC6j@F9PgwnfHAQeY/xy7gX1XD2HyIeH3k4laSpIuzOGh4X2eH1bZk@L56WebB1viJZKBvwOHj4ErqwO1NI2q6C6dr58xKVRXHx6ZWtsLwSecnrpkm0WhGOYebe8a7r3G0stEHGRnD0dEN@ryETVpHG37nzzk4fLIK5MmaPiRQGMmeFlu2YGNJKYMgYpE7Sh3tZk78dtzTTOyMsTv6CvTEEbTAcwQ8 "AWK – Try It Online") We're careful to `+0` to make sure the new name has reputation. The hardest part of this problem is printing the list out sorted by values. Thankfully, GNU Awk has an array called `PROCINFO`, and by writing the special value `"@val_num_desc"`, the array will be `num`erically sorted in `desc`ending order by `val`ue. [Answer] # [Perl 5](https://www.perl.org/) `-a`, 114 bytes ``` $_=pop@F;/^-?\d+$/?$k{$F[0]}+=$_:($k{$_}=$k{$F[0]}+0,delete$k{$F[0]})}{say"$_ $k{$_}"for sort{$k{$b}-$k{$a}}keys%k ``` [Try it online!](https://tio.run/##RYpNC8IgAEDv@xUyDIpl02CXQtYgdgj6BX2IQ4MxnTK9yPCvZ4ygTo/3eFZOqkoJMmqNPbXH8onquyhgWcNhhu0NP2JBITusF2WR/iveCqmkl7@yibPjIYcMfN/8ZSbgzOTnxbuIFvAYBxncakjp0msdQCO4zs5m5EoAss8aLVXPASLkbazvzegSulY7THBC/AM "Perl 5 – Try It Online") [Answer] # Java 10, ~~166~~ 251 bytes ``` import java.util.*;a->{var r=new HashMap<String,Long>();for(var l:a)if(l[1].matches("-?\\d+"))r.merge(l[0],new Long(l[1]),Long::sum);else{var t=r.remove(l[0]);r.put(l[1],t==null?0:t);}return r.entrySet().stream().sorted(Map.Entry.comparingByValue());} ``` +85 bytes because I hadn't noticed the output should be sorted by value.. >.> Input as a 2D list of Strings, output as a sorted stream of key-value pairs. [Try it online.](https://tio.run/##tZRdT9swFIbv@yuOchWvxDRj3URCQcCQNgTsAmk3pRcmcRszf0S206lC/e2d7bSMBLZJ09aLNj7nPc/56HEeyJIkD@W3DRO10hYe3Bk3lnH8Jof9fRimh2AV2IrC/crSpFCNtIOCE2PgmjD5OABg0lI9JwWFG3@EZxBjNSUC34afo2tS4wtp9erIGZhc7F0puTg@hiJuz9PZdAYE5Q6yHrgvY4llBdyAhAlsSHL8uCQa9ETS7/CJmMrxOqQY5XOlYy/iGUFsHvNpOsOC2KKiJo6Sk7u7chghpLGgekGdezTb8zQfHsQokLLMNALllBsaUtqJxpoKtWxDUK5x3dgQsGcnE9lwfjLKLMrXmtpGS9CY@j5vqY3Rdgj@wU2YlvHTGHChRE18/Werr4Q3NEYOscl973Vzz13v2xEsFStBuHk/TcrNqR22pcbG0akTUxjfySgY/WcYnal7@PDSdKkq2bV6C6TpQdfaMs8rqle86/lIJKMc@gEBE6JeA6Vvo/DX7kq@ZEKs4LQkogdXkvDSyXsQQTkjkKTpP8L07A4A/wfdYnrsc1XShbqaU/1@/IJ0xhtBJBx2rZ0Q@U70puwtkBxEL@5PWJ6QtV0eMNvVuV0ZSwVWjcW1c1gu4@izdJudwa7YVyRm59ptImeSGndDDTY1Z643V1dP41TMg53KX7etOQRiTuXCVk7Shvgb7BIBm4xyYEfPNe48HKJty4E3ZTOHDBr3uMv/u@p/7Ym@NLbTu8RFHLIg7Iq6IEUV/wzLsm3cX6VKIvc@qSmx8XiE/kBYD9abHw) **Explanation:** ``` import java.util.*; // Required import for Map and HashMap a->{ // Method with 2D String-array as parameter // and a Stream of String-Long KeyValue-pairs as return-type var r=new HashMap<String,Long>(); // Map, starting empty for(var l:a) // Loop over the lines of the input: if(l[1].matches("-?\\d+")) // If the second part is an integer: r.merge(l[0], // Use the first part as key new Long(l[1]), // Convert the second part to an integer Long::sum); // And sum it with a potential existing value for this key else{ // Else (it's a rename): var t=r.remove(l[0]); // Remove the first part from the map; // store the current value (of null if not present) in `t` r.put(l[1], // Use the second part as new key r.remove(l[0])); // And remove the first part from the map, // which will return the current value // (or null if not present) return r // Return the Map as result .entrySet().stream() // after we've converted it to a steam of KeyValue pairs, .sorted(Map.Entry.comparingByValue());} // and sorted it by value ``` ]
[Question] [ # The Challenge In this challenge, you specify a *source language* `S` and a *target language* `T`. Your task is to write the following program `P` in the language `S`. If a valid program `Q` in the language `T` is given as input to `P`, it will output a valid program `R` in the language `T` which takes no input and outputs `Q(R)`, that is, the program `Q` applied to the source code of `R`. *In addition*, you should present in your answer a nontrivial example program `Q` (the more interesting, the better, although you score no points for this), the resulting program `R`, and the output of `R`. This is code-golf, so the shortest code for `P` wins. In other words, this is a challenge about writing a "universal quine constructor" that can create arbitrary types of generalized quines. # Clarifications * Your source and target languages may be identical. * The program `P` should take one string as input (from STDIN or equivalent), and output one string (to STDOUT or equivalent), as should every output program `R`. * The input programs `Q` should also transform a string to another string, but their form is more flexible: they can be string-to-string functions, code snippets that modify a variable with a certain name, snippets that modify the data stack if your target language has one, etc. You can also further restrict the form of the `Q`'s by stating that, for example, they may not contain any comments. However, you must be able to implement any computable string-to-string function as an input program `Q`, and you must *explicitly* state how they function and what further constraints you place on them. * The output program `R` should really be a (generalized) quine, so it must not read any input (user input, files etc.) unless `Q` does so. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are disallowed. # An Example Suppose I choose Python as my source language, and Haskell as my target language, and I further require that the input program should be a one-line definition of a `String -> String` function named `f`. If I give the string-reversing program ``` f x = reverse x ``` as input to my Python program `P`, it will output the source code of another Haskell program `R`. This program prints to STDOUT the source code of `R`, but reversed. If `P` is given the identity function ``` f x = x ``` as input, the output program `R` is a quine. [Answer] # Source = Target = CJam, ~~19~~ ~~17~~ 16 bytes ``` {`"_~"+}`)q\"_~" ``` This assumes that the input program `Q` (given on STDIN) is some CJam snippet which expects a string on the top of the stack and leaves another string on top of the stack. [Test it here.](http://cjam.aditsu.net/) ## Examples 1. The identity would just be an empty snippet, so leaving STDIN empty prints ``` {`"_~"+}_~ ``` Which is the standard quine, with an additional `+`. 2. To reverse a string in CJam, you can use `W%`, so putting that on STDIN, this yields: ``` {`"_~"+W%}_~ ``` which we can run to obtain ``` ~_}%W+"~_"`{ ``` 3. As a third example, say we use a snippet which intersperses a string with spaces: `' *`. Running `P` with that as input, we get ``` {`"_~"+' *}_~ ``` which in turn prints ``` { ` " _ ~ " + ' * } _ ~ ``` 4. It now also works if `Q` contains line breaks (although that's never necessary in CJam). Here is a program with a line break, which removes all line breaks from a string (in an unnecessarily convoluted way - split into lines, then join): ``` N/ "" * ``` This results in the following `R`: ``` {`"_~"+N/ "" *}_~ ``` which in turn prints ``` {`"_~"+N/""*}_~ ``` ## Explanation Let's look at the produced output first: The standard CJam quine is ``` {`"_~"}_~ ``` It works as follows: * Push the block `{`"_~"}`. * Duplicate it with `_`. * Execute the copy with `~`. * Now inside the block, ``` turns the first block into its string representation. * `"_~"` pushes the two characters of the source that are not part of the block (and hence missing from the string representation). * The two strings are printed back to back at the end of the program. In the basic quine the ``` is unnecessary, because if you just leave the block as it is, it's printed all the same at the end of the program. The output of my program `P` is a modified version of this snippet. First, I've added a `+` to the block, which concatenates the two strings into one string containing the entire source. Note that this will be true no matter what I do inside the block, because that will all get added to the string representation obtained with ```. Now I can simply put the program/snippet `Q` inside the block after the `+`, so that it can modify the source string before it is printed. Again, since `Q` goes inside the block, it will be part of said source string. In summary, `P` prints ``` {`"_~"+Q}_~ ``` Now, for how I go about constructing this output in `P`: ``` {`"_~"+} "Push the block without Q."; ` "Turn it into a string. This is shorter than writing a string right away, because I'd have to escape the quotes, and I'd need two quotes instead of one backtick."; ) "Pop off the last character (the brace) and push it on the stack."; q "Read input Q."; \ "Swap Q with the brace."; "_~" "Push the final two characters."; ``` The four strings are printed automatically (back-to-back) at the end of the program. [Answer] # Haskell expressions → Haskell expressions, 41 bytes ``` ((++)<*>show).('(':).(++")$(++)<*>show$") ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v8BWQ0NbW9NGy644I79cU09DXUPdCkhpaytpqiDJqChp/s9NzMxTsFVIyedSUCgoLQkuKfLJU1BRKFBQykxRQhXTyExB044pgmFKUWpZalFxKrpRUGF087ALYxiak5qXXpIBFi/KzCsBGQgRQjcPq@h/AA "Haskell – Try It Online") ### How it works `P $ "Q"` = `((++)<*>show).('(':).(++")$(++)<*>show$") $ "Q"` constructs `"R"` by 1. `(++")$(++)<*>show$")`: appending the string `")$(++)<*>show$"`, 2. `('(':)`: prepending the character `'('`, and 3. `(++)<*>show` (= `\x->x++show x`): appending a quoted version of that, resulting in `"R"` = `"(Q)$(++)<*>show$\"(Q)$(++)<*>show$\""`. `R` = `(Q)$(++)<*>show$"(Q)$(++)<*>show$"` works by 1. taking the string `"(Q)$(++)<*>show$"`, 2. `(++)<*>show`: appending a quoted version of that, 3. applying `Q` to that, resulting in `Q "(Q)$(++)<*>show$\"(Q)$(++)<*>show$\""` = `Q "R"`. (The parens around `Q` are necessary because `Q` might contain `$` just as easily as `R` does, and `$` is unfortunately right-associative.) ### Demo ``` λ> putStrLn $ ((++)<*>show).('(':).(++")$(++)<*>show$") $ "id" (id)$(++)<*>show$"(id)$(++)<*>show$" λ> putStrLn $ (id)$(++)<*>show$"(id)$(++)<*>show$" (id)$(++)<*>show$"(id)$(++)<*>show$" λ> putStrLn $ ((++)<*>show).('(':).(++")$(++)<*>show$") $ "reverse" (reverse)$(++)<*>show$"(reverse)$(++)<*>show$" λ> putStrLn $ (reverse)$(++)<*>show$"(reverse)$(++)<*>show$" "$wohs>*<)++($)esrever("$wohs>*<)++($)esrever( λ> putStrLn $ ((++)<*>show).('(':).(++")$(++)<*>show$") $ "length" (length)$(++)<*>show$"(length)$(++)<*>show$" λ> print $ (length)$(++)<*>show$"(length)$(++)<*>show$" 44 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) → [7](https://esolangs.org/wiki/7), 9 bytes ``` “ṚƓ^ṾṂ’³3 ``` [Try it online!](https://tio.run/##ASMA3P9qZWxsef//4oCc4bmaxpNe4bm@4bmC4oCZwrMz////MjQwNQ "Jelly – Try It Online") Q is a 7 function (i.e. that doesn't look beyond the top stack element, and does I/O via the stack), and is given as a command-line argument. ## Explanation ### The 7 program The universal quine constructor in 7 that I use here is: ``` 717162234430…3 ``` The first thing to note is that the leading 7 is the equivalent of leading whitespace, and doesn't have any effect on the program. The only reason it's there is to obey PPCG's rules against literal-only quines (it's encoded by the second `1` in the program rather than itself). The rest of the program is a single stack element (it has balanced `7`s and `6`s), which does the following when run: ``` 717162234430…3 1716 Push a stack element "7" onto the stack 2 Copy it 23 Pop and output one of the copies (selecting format 7) 4430 Prepend it to the top of stack 3 Output it ``` In other words, this stack element is a program that prints the top of the stack, with `7` prepended, in output format 7 (which means "print literally, using the same encoding as the source code", and thus is clearly the best encoding for quines). It's fairly fortunate here that we can reuse the literal `7` for two purposes (the output format, and the leading whitespace.) Clearly, by inserting something just before the final `3`, we can output a function of `7` + the input, rather than just outputting `7` and the input directly. How does this stack element get at its own source code? Well, when the end of the program is reached, 7 `eval`s the top stack element by default. However, it's not actually popped from the stack in the process, so the stack element literal that was `eval`led is still there. (In other words, the program isn't reading its own source – as evidenced by the fact that it's unable to see the `7` at the start of the program, which is a stack element separator rather than part of a literal – but rather, it consists mostly of a literal that gets `eval`led by default.) ### The Jelly program This is perhaps one of the least Jelly-like Jelly programs I've written; it consists of three nilads (`“ṚƓ^ṾṂ’`, `³`, `3`), which are just output in sequence because no operations are performed on them. The `3` is obvious enough, just being an integer constant. The `³` is also simple if you know Jelly: it's Jelly's explicit notation for the first command-line argument (which is where Jelly typically takes its input). The rest of the Jelly program represents the bulk of my 7 universal quine constructor: by exploiting the fact that all the commands in 7 can be represented using ASCII digits, we can interpret `717162234430` not as a series of commands, or even as an octal number (like it conceptually is), but as a decimal number, meaning that we don't need any special formatting for the output. That decimal number becomes `“ṚƓ^ṾṂ’` in Jelly's compressed integer notation. ## Example If we give `24053` as program Q, we'll get the following output: ``` 717162234430240533 ``` [Try it online!](https://tio.run/##M///39zQ3NDMyMjYxMTYwMjEwNT4/38A "7 – Try It Online") `2405` concatenates the top stack element to itself: ``` 2405 Stack Explanation x 2 x|x Duplicate top of stack 4 x||x Swap two stack elements, with an empty element between 0 x|(X) Escape the top stack element, then concatenate the top two 5 xx Execute the top stack element ``` (The last step might look a little confusing; what's happening is that escaping a stack element converts each command in it from "run this command" to "append this command to the top of the stack", so each command appends itself to the original top stack element as it runs.) As such, running the resulting program R gives us two copies of R: ``` 7171622344302405371716223443024053 ``` [Answer] # Source = Target = JavaScript, 66 ``` console.log("function a(){console.log("+prompt()+"(a+'a()'))}a()") ``` ## Assumptions for Q: * `Q` should be a string-to-string JavaScript anonymous function. # Examples: * *Reverse*. Q = `function(s) { return s.split('').reverse().join(''); }` In this case, `P(Q)` (or `R`) will be: `function a(){console.log(function(s) { return s.split('').reverse().join(''); }(a+'a()'))}a()`, and by executing it, we will get: `)(a}))')(a'+a(} ;)''(nioj.)(esrever.)''(tilps.s nruter { )s(noitcnuf(gol.elosnoc{)(a noitcnuf` which is exactly the same as `Q(R)`. * *Identity*. Q = `function(s) { return s; }` in this case, `P(Q)` (or `R`) will be: `function a(){console.log(function(s) { return s; }(a+'a()'))}a()` which is a **JavaScript Quine**. Needless to say, `Q(R)` will be the same, since Q is the Identity function. --- # Some notes: STDIN in JavaScript is traditionally `prompt()`, however, I allowed myself to refrain from the tradition of `alert()` as STDOUT, in order to make the process of run output as a progrem using copy-paste easier. (I do realize I can **save up to 12 characters** when changing to `alert()`). I can also make things much shorter in ES6, but I want to stay with Native JavaScript for now. I'm considering submitting a S=Scala,T=ECMA6 answer in future, just for the experience. I also realize JavaScript can almost never beat **CJam** in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), but I had to take this challenge! It was surly a fun one. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) → [Underload](https://esolangs.org/wiki/Underload), 15 bytes ``` “(a(:^)*“S):^”j ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxyNRA2rOE0tICtY0yruUcPcrP///1sFxwEA "Jelly – Try It Online") Takes the input Underload function Q as a command-like argument. Q must take input from the stack and push output to the stack, without attempting to inspect deeper stack elements (as they won't exist). ## Explanation ### The Underload The Underload universal quine constructor used here is: ``` (a(:^)*…S):^ ``` Most of the program is a single literal. We follow that by `:^`, which copies it, then evaluates one copy (leaving the other copy on the stack). When the literal starts evaluating, we run `a` (escape, which brings it back into the same form as the original programA), and `(:^)*` (which appends `:^`), thus reconstructing the entire program's source code. We can then run the function Q to transform this in an arbitrary way, and print the result with `S`. ### The Jelly I can't use Charcoal this time because a validating Underload interpreter crashes at the end of the program if the program ends with a newline. (Some Underload interpreters, such as the one on TIO, don't enforce this rule, but I wanted to be properly portable.) Unfortunately, Charcoal naturally adds trailing newlines to its output. Instead, I used Jelly, which is almost as terse in simple cases like this; the program consists of a list literal with two elements (`““”`), and joins them on the input (`j`), thus interpolating the user input into the program. ## Example Using the input `:S^` (print a copy, then evaluate the original), we get the following Underload program: ``` (a(:^)*:S^S):^ ``` [Try it online!](https://tio.run/##K81LSS3KyU9M@f9fI1HDKk5Tyyo4LljTKu7/fwA "Underload – Try It Online") This prints itself infinitely many times, in a fairly interesting way: after doing the normal quine behaviour, it then runs `eval` on a copy of what it output. That causes the entire reconstructed program to run again, indefinitely (Underload is tail-recursive). Quining yourself and doing an `eval` is actually the only way to do an infinite loop in Underload. [Answer] # [CJam](https://sourceforge.net/p/cjam) → CJam, 13 bytes ``` {`"_~"+7}_~qt ``` [Try it online!](https://tio.run/##S85KzP3/vzpBKb5OSdu8Nr6usOT//2CtcFUA "CJam – Try It Online") The input `Q` should be a code snippet that modifies the only string in the stack. `Q` is read from stdin. ### Example Input: ``` S*W% ``` It adds a space between every two characters, and reverses the string. Output: ``` {`"_~"+S*W%}_~ ``` Output of the generalized quine: ``` ~ _ } % W * S + " ~ _ " ` { ``` ### Explanation ``` {`"_~"+7}_~ e# Evaluate a generalized quine in CJam that only appends a 7. q e# Read the input. t e# Replace the 7th character (0-based) with the input. ``` It firstly evaluates the quine, so we can get its string representation without unnecessary double quotes. Then replace the payload with the input. It could be `{`"_~"+ }_~7qt` where the space is the placeholder of the payload. But changing the payload to `7` saves a byte. [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 11 bytes ``` '{`{.%s}{'F ``` ## Program Explanation ``` '{`{.%s}{'F '{`{.%s}{' # Push the string "{`{.%s}{" to the stack. F # Format the input with the top of the stack as a template. Which produces {`{.<INPUT>}{ ``` ## Quine Explanation The quine that's produced is simple, yet uses the functionality of unmatched function handlers in RProgN2 to create a short and sweet quine, called a "Looping" quine. It's a surprisingly similar concept to a ><> quine. ``` {`{.}{ {`{.} # Push the function {`{.} to the stack. { # Try to define a new function, fail, loop back to index 1. (Which in turn, skips the function definition.) `{ # Push the string "{" to the stack. . # Concatenate the top two values of the stack, which stringifies the function, then appends { to it. } # Try to terminate a function, fail quietly, and terminate the program. ``` Of course, because of the structure of this quine, anything but true no-ops (Which don't get stringified) can be placed after the concatenate function, and ## Some quines * [`{`{.i}{`](https://tio.run/##Kyooyk/P0zX6/786oVovs7b6/38A "RProgN 2 – Try It Online"): Outputs `{}i.{`{`. `i` is just the "inverse" function, so this program outputs itself reversed. * [`{`{.S§.}{`](https://tio.run/##Kyooyk/P0zX6/786oVov@NByvdrq//8B "RProgN 2 – Try It Online"): Outputs `..S`{{{}§`. `S` converts the string to a stack of characters, `§` sorts the stack lexographically, then `.` joins it back together, outputting itself sorted. [Try it online!](https://tio.run/##Kyooyk/P0zX6/1@9OqFaT7W4tlrd7f///z75@QWZeemBpZl5qQA "RProgN 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal) → [Perl](https://www.perl.org/) (5), ~~29~~ 33 bytes ``` A$_=q(αA);evalβαS"\α$_β\n";printβ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noUq8baFGuc2Alma1qlliTnnNoE4m5Vizm1UiT@3KSZPybqgKDOv5Nym//@BaotSy1KLilMB "Charcoal – Try It Online") The Perl program Q should return a snippet that takes input as a string to its right hand side and provides output in the variable `$_`. (Arbitrary Perl functions can be converted to this form via wrapping them as `sub x {…}; $_=x` . In most cases, though, Perl's syntax means that no wrapping is required.) ## Explanation ### The Perl Here's what the universal Perl quine constructor looks like: ``` $_=q(…"\$_=q($_);eval";print);eval ``` (In most cases you'd want to golf this down to `$_=q(say…"\$_=q($_);eval");eval`, but I'm not sure you can fit arbitrary Perl code into the `…` there.) In other words, we have an outside wrapper `$_=q(…);eval` which assigns a string to `$_` and then evaluates it. Inside the wrapper is `"\$_=q($_);eval"`, i.e. a reconstruction of the wrapper together with its contents via using the value we stored in `$_`, plus the code Q specified by the user, plus `print` to print the output. (Unfortunately we can't use `say`; it adds a newline, and that's relevant in quines.) ### The Charcoal The "point" of this answer was to produce generalized quines in Perl, so once I had a golfed strategy for doing that (one I've used in many other answers), it was time to write the program P, which basically just substitutes a string into a template. What I wanted here was a language which was good at printing constant strings (ideally compressing them a bit), and interpolating user input into them. After trying a few, I settled on Charcoal, which I've never used before (and which could really do with some documentation); it's designed for ASCII art but capable of writing strings in one dimension too. ASCII characters are printed literally in Charcoal, meaning that printing constant strings takes no boilerplate, and we can use the `S` command to interpolate a string taken from user input into the program. It's possible to go (slightly) shorter, though. The Perl universal quine constructor contains two fairly long repeated sections. We can thus use the `A` command to assign them to variables (e.g. `A…α` assigns to the variable `α`), and simply interpolate the variables into the string we're printing via using their names. That saves a few bytes over just writing the string literally. Unfortunately, Charcoal also appends a newline to the program, but that's not a huge deal; it simply costs two bytes for an `\n` to add that newline to the input of Q too. ## Example If we give the input `$_=reverse` (which reverses a string), we get the following output: ``` $_=q($_=reverse"\$_=q($_);eval\n";print);eval ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rZQA0gUpZalFhWnKsVABTStU8sSc2LylKwLijLzSiBcrv//AQ "Perl 5 – Try It Online") which is a quine-alike that prints its source backwards, as expected. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `D` -> Vyxal `D`, 4 bytes ``` \IpI ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJEIiwiIiwiXFxJcEkiLCIiLCJcImBoZWxsb2Ar4bmYXCIiXQ==) The D flag is necessary due to vyxal decompressing non-ASCII strings by default. ``` p # Prepend \I # "I" I # Quote and prepend to itself ``` For example, with the input `"`hello`+Ṙ"` (append "hello" and reverse) this outputs ``I\`hello\`+Ṙ`I`hello`+Ṙ`, which: ``` `I\`hello\`+Ṙ` # "I`hello`+Ṙ" I # Quote and prepend to self, obtaining source code `hello`+ # Append "hello" Ṙ # Reverse ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 1 year ago. [Improve this question](/posts/15932/edit) When I was a kid, I played the Intellivision game [Advanced Dungeons and Dragons: Treasure of Tarmin](http://en.wikipedia.org/wiki/Advanced_Dungeons_&_Dragons:_Treasure_of_Tarmin). The 3-D graphics put you in a first-person-perspective point of view with shocking realism: ![Shockingly Realistic 3-D Graphics](https://i.stack.imgur.com/X4aGT.png) But then I got a C-64. And I was able to draw on the 40x25 character grid by cursoring around the screen, setting the color with the Ctrl key and a digit, and putting symbols anywhere I wanted *(why doesn't `bash` let me do that?)*. The character set had triangular components and solid block components. So I was able to reason through how one might generate a rendering of one's perspective in a grid through that medium. I found the nearly-three-decades-old spec, in spiral-bound notebook paper, about "Dungeon Construction Set" this week: ![enter image description here](https://i.stack.imgur.com/WHYpo.jpg) *(**UPDATE**: Careful readers will notice that this doesn't quite hold together on the slanted parts. Corrected numbers are provided below.)* Though Treasure of Tarmin was played on a grid, the walls existed only on the *edges* of grid squares. Having learned what bytes were, I realized that if I made the map out of bytes...then each square on the map could have four possible states for each of its edges: 1. Unobstructed 2. Wall 3. Door 4. Something Else? I never did get around to writing it (until last night). I thought it might be fun for others to try. So your task is to implement a character-mode-based maze renderer that implements my *(corrected!!)* spec...but using the technologies of 2013. ## Input Because the spec doesn't define rendering for doors, we'll just assume the only options are wall-and-not-wall. For simplicity, your input is a map composed of lines of strings that look like this: ``` WN.. .N.. .N.. .N.. .N.E W... .... .... ..S. ...E W... .N.E W... .N.. ...E W... .... .... .... ...E W.S. ..S. ..S. ..S. ..SE ``` That would be a 5x5 map. The upper left corner (1,1) has its `W`est and `N`orth wall set. The lower right corner (5,5) has its `S`outh and `E`ast wall set. This is considerably less fun with no map navigation. So at minimum, put your player at (1,1) facing north and offer them: ``` [F]orward, [B]ackward, turn [L]eft, turn [R]ight or [Q]uit? ``` At each step, output a 16x15 display of the first-person perspective, as defined by the notebook paper spec. To keep you from having to count, the size of flat walls at the three distances are: ``` 14x13 (directly in front of you; e.g. wall is in same cell) 8x7 (one step away) 6x5 (two steps away) ``` The bounding sizes of the slanted walls are: ``` 1x15 (your direct left or right; e.g. wall is in same cell) 3x13 (one step away) 1x7 (two steps away) ``` ## Clarifications * Adjacent cells may disagree about shared walls. So the south edge on a square might be a wall, while the north edge on the square to the south of it would be unobstructed. In the original design I considered this a feature: it permits interesting ideas like one-way doors...or invisible walls that only appear after you passed through them. For this simplification, follow the same rule: for navigation and rendering, pay attention only to the edge status on the cell *closest to you in the direction you are facing*. * The view is a lot better with "shading". So for your full blocks, alternate either Unicode 2593 ▓ and 2591 ░, or use `X` and `+` if your implementation is ASCII. * Unicode triangle characters (25E2 ◢, 25E3 ◣, 25E4 ◤, 25E5 ◥) are a bit lame for drawing this. Besides not having any shaded variants, they often stretch only the width of the character and not the full height...even in fixed width fonts. You can draw full blocks or slash characters or something of your choosing in the places I wanted diagonals. Interesting creative solutions that incorporate color and use these characters instead of shading appreciated. * You may assume the outermost walls are set to bound the playing area, so you don't have to worry about rendering anything outside of the maze. Any walls farther away from you than the spec are ignored and just leave empty space. * The shading of the wall you see directly in front of you if facing North at (1,1) should be DARK. Alternate shading on adjacent walls in the map, such that if all walls were present then a light wall would never abut a dark wall. * A C-64 implementation that actually does what I originally intended...with the diagonal characters and all...will trump any other entry criterion. :-) ## Examples For the sample map given above... At (1,3) facing south: ``` / /+ /X+ /XX+ /XXX+ +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ \XXX+ \XX+ \X+ \+ \ ``` At (3,2) facing south: ``` /* blank line */ X / X /+ X /++ X +++ X +++ X +++ X +++ X +++ X +++ X +++ X \++ X \+ X \ /* blank line */ ``` At (3,2) facing east: ``` /* blank line */ / /X /XX XXX +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ XXX \XX \X \ /* blank line */ ``` At (2,3) facing north: ``` / ++++++++++++++X ++++++++++++++X ++++++++++++++X ++++++++++++++X X++++++++++++++X X++++++++++++++X X++++++++++++++X X++++++++++++++X X++++++++++++++X ++++++++++++++X ++++++++++++++X ++++++++++++++X ++++++++++++++X \ ``` [Answer] ## Commodore 64 Basic Man, that was fun. And hard. C64 Basic is almost undebuggable, you can't even use `print` debugging because the screen is already taken for rendering the dungeon. You know you're having fun when you're writing code like `55250 goto 55110`. Dijkstra will kill me. The program uses two colors, and diagonal characters. Needless to say I didn't golf it. It says *code challenge* now, after all. It's **7183** bytes if you're interested. It's slow - at default speed it takes several seconds for it to render the scene. The maximum map size is 10 by 10 but it can be changed by editing line 120. I have developed and tested this using the **VICE** emulator. The code below is displayed in ASCII, so that means *shifted* PETSCII. *However, when inputting the map, you should use **unshifted** PETSCII*. Screenshot: ![Screenshot](https://i.stack.imgur.com/f2YWU.png) Code: ``` 10 rem c64 dungeon construction set. 20 rem enter using lowercase mode 99 rem DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD 100 rem initialisation 110 poke 53272,21 115 poke 53280,0 120 dim m%(10,10) 121 dim di$(3),wa$(1),ma%(2,2) 122 di$(0)="north" 123 di$(1)="east " 124 di$(2)="south" 125 di$(3)="west " 126 wa$(1)="-wall" 127 wa$(0)=" " 130 x=0:y=0:di=0:xs=0:ys=0:wa=0 134 rem read map 135 print "input map" 140 l$="":input l$ 150 if len(l$)=0 goto 250 160 cz=0 170 for i=1 to len(l$) 180 c$=mid$(l$,i,1) 190 if c$="n" then cz=cz or 8 200 if c$="e" then cz=cz or 4 205 if c$="s" then cz=cz or 2 210 if c$="w" then cz=cz or 1 215 if c$=" " then m%(x,y)=cz:cz=0:x=x+1 220 if x>=xs then xs=x 225 next 230 m%(x,y)=cz:x=0:y=y+1 240 goto 140 250 rem come from 150 260 print chr$(147) 265 ys=y:xs=xs+1 270 x=0:y=0 500 rem loop 510 gosub 1000: rem status 515 gosub 2000: rem render 520 gosub 55000: rem input 530 goto 500 1000 rem display current (x,y) value 1010 sx=5 1020 sy=17 1030 sl$=" " 1035 sw=14 1040 gosub 63900 1050 cz=m%(x,y) 1060 sx=5:sl$=".":if cz and 8 then sl$="n" 1065 gosub 63900 1070 sx=6:sl$=".":if cz and 4 then sl$="e" 1075 gosub 63900 1080 sx=7:sl$=".":if cz and 2 then sl$="s" 1085 gosub 63900 1090 sx=8:sl$=".":if cz and 1 then sl$="w" 1095 gosub 63900 1100 return 2000 rem render dungeon 2010 rem DDDDDDDDDDDDDD 2020 rem clear area 2030 sw=14:sz=32 2040 for sy=0 to 15 2050 for sx=0 to 16 2060 gosub 63950 2070 next 2080 next 2090 rem find cells / reorient sw 2100 rem store in ma% - we're at (0,1) 2110 sx=x:sy=y 2113 co=di+x+y and 1 2115 for ty=0 to 2 2120 gosub 59800:rem left/right sx/sy 2125 ma%(1,ty)=0 2126 if sx>=0 and sy>=0 and sx<xs and sy<ys then ma%(1,ty)=m%(sx,sy) 2130 ma%(0,ty)=rl 2140 ma%(2,ty)=rr 2150 gosub 59900:rem advance 2160 next 2170 rem draw back walls 2180 sa=ma%(1,2):gosub 59700 2190 if rf=0 goto 2245 2195 sw=14-11*co:sz=160 2200 for sy=5 to 9 2210 for sx=5 to 10 2220 gosub 63950 2230 next 2240 next 2245 sw=3:if co=1 then sw=14 2250 for de=0 to 2 step 2 2260 sa=ma%(de,2):gosub 59700 2270 if rf=0 goto 2350 2280 for sx=de*5.5 to 4+de*5.5 2290 for sy=5 to 9 2300 gosub 63950 2310 next 2340 next 2350 next 2360 rem 1,2 left wall 2370 sa=ma%(1,2):gosub 59700 2380 if rl=0 goto 2430 2390 sx=4:sz=160 2400 for sy=5 to 9:gosub 63950:next 2410 sy=4:sz=223:gosub 63950 2420 sy=10:sz=105:gosub 63950 2430 rem 1,2 right wall 2440 if rr=0 goto 2490 2450 sx=11:sz=160 2460 for sy=5 to 9:gosub 63950:next 2470 sy=4:sz=233:gosub 63950 2480 sy=10:sz=95:gosub 63950 2490 rem 1,1 back wall 2500 sa=ma%(1,1):gosub 59700 2510 sz=160 2520 sw=14:if co=1 then sw=3 2520 if rf=0 goto 2580 2530 for sy=4 to 10 2540 for sx=4 to 11 2550 gosub 63950 2560 next 2570 next 2580 rem (0-2),1 back walls 2590 sw=14:if co=1 then sw=3 2600 for de=0 to 2 step 2 2610 sa=ma%(de,1):gosub 59700 2620 if rf=0 goto 2680 2630 for sx=de*6 to 3+de*6 2640 for sy=4 to 10 2650 gosub 63950 2660 next 2670 next 2680 next 2690 rem 1,1 left side wall 2700 sw=14:if co=1 then sw=3 2710 sa=ma%(1,1):gosub 59700 2720 if rl=0 goto 2760 2730 for sx=1 to 3 2735 sy=sx:sz=223:gosub 63950 2736 sy=14-sx:sz=105:gosub 63950 2737 sz=160 2740 for sy=1+sx to 13-sx:gosub 63950:next 2750 next 2760 rem 1,1 right side wall 2770 if rr=0 goto 2850 2780 for qx=1 to 3 2790 sx=15-qx 2800 sy=qx:sz=233:gosub 63950 2810 sy=14-qx:sz=95:gosub 63950 2820 sz=160 2830 for sy=1+qx to 13-qx:gosub 63950:next 2840 next 2850 rem 0,1 back wall 2860 sa=ma%(1,0):gosub 59700 2870 if rf=0 goto 2930 2880 for sy=1 to 13 2890 for sx=1 to 14 2900 gosub 63950 2910 next 2920 next 2930 rem (0,2)-0 back walls 2940 sw=3:if co=1 then sw=14 2950 for de=0 to 2 step 2 2960 sa=ma%(de,0):gosub 59700 2970 if rf=0 goto 3000 2980 sx=de*7.5 2990 for sy=1 to 13:gosub 63950:next 3000 next 3010 rem (1,0) left side wall 3020 sa=ma%(1,0):gosub 59700 3030 if rl=0 goto 3080 3040 sx=0:sy=0:sz=223:gosub 63950 3050 sy=14:sz=105:gosub 63950 3060 sz=160 3070 for sy=1 to 13:gosub 63950:next 3080 rem (1,0) right side wall 3085 if rr=0 goto 3130 3090 sx=15:sy=0:sz=233:gosub 63950 3100 sy=14:sz=95:gosub 63950 3110 sz=160 3120 for sy=1 to 13:gosub 63950:next 3130 rem done 3140 return 55000 rem ask for prompt & handle input 55010 sx=0:sy=20:gosub 63850 55013 print "at";x+1;y+1;"going ";di$(di);" size";xs;ys;wa$(wa) 55020 print "{f}rwd {b}kwd {l}eft {r}ight {q}uit" 55030 input c$ 55040 if c$="q" goto 63999 55050 if c$="f" then dm=1:goto 55100 55060 if c$="b" then dm=-1:goto 55100 55070 if c$="l" then di=(di-1)and 3 55080 if c$="r" then di=(di+1)and 3 55090 return 55100 goto 55200:rem check walls 55110 if di=0 then y=y-dm 55120 if di=1 then x=x+dm 55130 if di=2 then y=y+dm 55140 if di=3 then x=x-dm 55145 wa=0 55146 if y>=ys then y=0 55147 if y<0 then y=ys-1 55148 if x>=xs then x=0 55149 if x<0 then x=xs-1 55150 return 55200 rem check walls 55205 cz=m%(x,y) 55207 if dm=-1 goto 55280 55210 if (di=0) and (cz and 8) goto 55260 55220 if (di=1) and (cz and 4) goto 55260 55230 if (di=2) and (cz and 2) goto 55260 55240 if (di=3) and (cz and 1) goto 55260 55250 goto 55110 55260 wa=1 55270 return : rem wall in the way 55280 rem backward 55290 if (di=2) and (cz and 8) goto 55260 55300 if (di=3) and (cz and 4) goto 55260 55310 if (di=0) and (cz and 2) goto 55260 55320 if (di=1) and (cz and 1) goto 55260 55330 goto 55110 59700 rem return front/back/left/right 59710 rem given sa and d 59720 sn=0:if sa and 8 then sn=1 59725 se=0:if sa and 4 then se=1 59730 ss=0:if sa and 2 then ss=1 59735 zw=0:if sa and 1 then zw=1 59740 if di=0 then rf=sn:rr=se:rb=ss:rl=zw 59745 if di=1 then rf=se:rr=ss:rb=zw:rl=sn 59750 if di=2 then rf=ss:rr=zw:rb=sn:rl=se 59755 if di=3 then rf=zw:rr=sn:rb=se:rl=ss 59760 return 59800 rem return left/right from sx/sy/d 59810 if di=0 then ly=sy:ry=sy:lx=sx-1:rx=sx+1 59820 if di=1 then lx=sx:rx=sx:ly=sy-1:ry=sy+1 59830 if di=2 then ly=sy:ry=sy:lx=sx+1:rx=sx-1 59840 if di=3 then lx=sx:rx=sx:ly=sy+1:ry=sy-1 59850 rl=0:rr=0 59860 if lx<0 or lx>=xs or ly<0 or ly>=ys goto 59880 59870 rl=m%(lx,ly) 59880 if rx<0 or rx>=xs or ry<0 or ry>=ys goto 59895 59890 rr=m%(rx,ry) 59895 return 59900 rem step forward 59910 if di=0 then sy=sy-1:rem N 59920 if di=1 then sx=sx+1:rem E 59930 if di=2 then sy=sy+1:rem S 59940 if di=3 then sx=sx-1:rem W 59950 return 63850 rem set cursor position 63851 rem sx=x sy=y 63860 poke 781,sy 63870 poke 782,sx 63880 poke 783,0 63890 sys 65520 63895 return 63900 rem write str to screen 63901 rem sl$ = string 63910 gosub 63850 63920 print sl$; 63930 return 63950 rem write chr to screen 63951 rem sx = x coordinate 63952 rem sy = y coordinate 63953 rem sz = character code 63954 rem sw = color 63950 sv=sx+sy*40 63960 poke 1024+sv,sz 63970 poke 55296+sv,sw 63980 return 63998 rem quit program 63999 print chr$(147):end ``` Tape image: [download here](http://frankenstein.d-n-s.org.uk/~marinus/dungeon.tap "download here"). The examples: ![examples](https://i.stack.imgur.com/9y2HO.png) [Answer] > > *(why doesn't `bash` let me do that?)* > > > I just had to now. ## Bash, 12743 chars ``` #!/bin/bash IFS= declare -a term typeset -i term[0] term[1] IFS=' ' read -a term <<< `stty size` front[0]='\e[2;2H██████████████ \e[3;2H██████████████ \e[4;2H██████████████ \e[5;2H██████████████ \e[6;2H██████████████ \e[7;2H██████████████ \e[8;2H██████████████ \e[9;2H██████████████ \e[10;2H██████████████ \e[11;2H██████████████ \e[12;2H██████████████ \e[13;2H██████████████ \e[14;2H██████████████' front[1]='\e[5;5H████████ \e[6;5H████████ \e[7;5H████████ \e[8;5H████████ \e[9;5H████████ \e[10;5H████████ \e[11;5H████████' front[2]='\e[6;6H██████ \e[7;6H██████ \e[8;6H██████ \e[9;6H██████ \e[10;6H██████' lfront[0]='\e[2;1H█ \e[3;1H█ \e[4;1H█ \e[5;1H█ \e[6;1H█ \e[7;1H█ \e[8;1H█ \e[9;1H█ \e[10;1H█ \e[11;1H█ \e[12;1H█ \e[13;1H█ \e[14;1H█' lfront[1]='\e[5;1H████ \e[6;1H████ \e[7;1H████ \e[8;1H████ \e[9;1H████ \e[10;1H████ \e[11;1H████' lfront[2]='\e[6;1H█████ \e[7;1H█████ \e[8;1H█████ \e[9;1H█████ \e[10;1H█████' rfront[0]='\e[2;16H█ \e[3;16H█ \e[4;16H█ \e[5;16H█ \e[6;16H█ \e[7;16H█ \e[8;16H█ \e[9;16H█ \e[10;16H█ \e[11;16H█ \e[12;16H█ \e[13;16H█ \e[14;16H█' rfront[1]='\e[5;13H████ \e[6;13H████ \e[7;13H████ \e[8;13H████ \e[9;13H████ \e[10;13H████ \e[11;13H████' rfront[2]='\e[6;12H█████ \e[7;12H█████ \e[8;12H█████ \e[9;12H█████ \e[10;12H█████' left[0]='\e[1;1H▙ \e[2;1H█ \e[3;1H█ \e[4;1H█ \e[5;1H█ \e[6;1H█ \e[7;1H█ \e[8;1H█ \e[9;1H█ \e[10;1H█ \e[11;1H█ \e[12;1H█ \e[13;1H█ \e[14;1H█ \e[15;1H▛' left[1]='\e[2;2H▙ \e[3;2H█▙ \e[4;2H██▙ \e[5;2H███ \e[6;2H███ \e[7;2H███ \e[8;2H███ \e[9;2H███ \e[10;2H███ \e[11;2H███ \e[12;2H██▛ \e[13;2H█▛ \e[14;2H▛' left[2]='\e[5;5H▙ \e[6;5H█ \e[7;5H█ \e[8;5H█ \e[9;5H█ \e[10;5H█ \e[11;5H▛' right[0]='\e[1;16H▟ \e[2;16H█ \e[3;16H█ \e[4;16H█ \e[5;16H█ \e[6;16H█ \e[7;16H█ \e[8;16H█ \e[9;16H█ \e[10;16H█ \e[11;16H█ \e[12;16H█ \e[13;16H█ \e[14;16H█ \e[15;16H▜' right[1]='\e[2;13H ▟ \e[3;13H ▟█ \e[4;13H▟██ \e[5;13H███ \e[6;13H███ \e[7;13H███ \e[8;13H███ \e[9;13H███ \e[10;13H███ \e[11;13H███ \e[12;13H▜██ \e[13;13H ▜█ \e[14;13H ▜' right[2]='\e[5;12H▟ \e[6;12H█ \e[7;12H█ \e[8;12H█ \e[9;12H█ \e[10;12H█ \e[11;12H▜' echo -e "\e[2J" # Read map typeset -i cout cout=0 echo "Please input your map!" echo "Please input the next row (or leave it blank if you're finished!)" read input declare -A map typeset -i xlen ylen ylen=0 until [ -z $input ] do IFS=' ' read -a inputmap <<< "$input" xlen=${#inputmap[*]} let ylen++ for index in "${!inputmap[@]}" do typeset -i map[$index,$cout] map[$index,$cout]=0 el=${inputmap[index]} if [[ $el == W??? ]] then let "map[$index,$cout]|=1" fi if [[ $el == ?N?? ]] then let "map[$index,$cout]|=2" fi if [[ $el == ??S? ]] then let "map[$index,$cout]|=4" fi if [[ $el == ???E ]] then let "map[$index,$cout]|=8" fi done echo "Please input the next row (or leave it blank if you're finished!)" read input cout+=1 done echo -ne "\e[2J" typeset -i dir x y dir=0 x=0 y=0 move() { if ((dir == 0)) && ( ((${map[$x,$y]} & 2)) || ((y == 0)) ) then return 1 elif ((dir == 1)) && ( ((${map[$x,$y]} & 8)) || (($x == $xlen)) ) then return 1 elif ((dir == 2)) && ( ((${map[$x,$y]} & 4)) || ((y == $ylen)) ) then return 1 elif ((dir == 3)) && ( ((${map[$x,$y]} & 1)) || ((x == 0)) ) then return 1 fi x=$1 y=$2 } input= until [[ $input == [qQ] ]] do if [[ $input == [DlL] ]] then let dir-=1 if (( dir == -1 )) then dir=3 fi elif [[ $input == [CrR] ]] then let dir+=1 if (( dir == 4 )) then dir=0 fi elif [[ $input == [AfF] ]] then if (( dir == 0 )) then move $x $(( y-1 )) elif (( dir == 1 )) then move $(( x+1 )) $y elif (( dir == 2 )) then move $x $(( y+1 )) elif (( dir == 3 )) then move $(( x-1 )) $y fi elif [[ $input == [bB] ]] then if (( dir == 0 )) then dir=2 move $x $(( y+1 )) dir=0 elif (( dir == 1 )) then dir=3 move $(( x-1 )) $y dir=1 elif (( dir == 2 )) then dir=0 move $x $(( y-1 )) dir=2 elif (( dir == 3 )) then dir=1 move $(( x+1 )) $y dir=3 fi fi echo -ne "\e[2J" echo -ne "\e[16;1Hd=$dir; x=$x; y=$y\e[48;5;29m" for (( y2=1; y2 <= 15; y2++ )) do echo -ne "\e[$y2;16H\e[1K" done if (( dir == 0 )) then for (( y2=(y-2); y2 <= y; y2++ )) do if (( y2 < 0 )); then continue; fi let i=y-y2 if (( x > 0 )) && (( ${map[$((x-1)),$y2]} & 2 )) then if (( ((x-1) + y2) & 1 )) then echo -ne "\e[38;5;40m" else echo -ne "\e[38;5;28m" fi echo -ne ${lfront[$i]} fi if (( (x+1) < xlen )) && (( ${map[$((x+1)),$y2]} & 2 )) then if (( ((x-1) + y2) & 1 )) then echo -ne "\e[38;5;40m" else echo -ne "\e[38;5;28m" fi echo -ne ${rfront[$i]} fi if (( ${map[$x,$y2]} & 1 )) then if (( (x + y2) & 1 )) then echo -ne "\e[38;5;28m" else echo -ne "\e[38;5;40m" fi echo -ne ${left[$i]} fi if (( ${map[$x,$y2]} & 8 )) then if (( (x + y2) & 1 )) then echo -ne "\e[38;5;28m" else echo -ne "\e[38;5;40m" fi echo -ne ${right[$i]} fi if (( ${map[$x,$y2]} & 2 )) then if (( (x + y2) & 1 )) then echo -ne "\e[38;5;40m" else echo -ne "\e[38;5;28m" fi echo -ne ${front[$i]} fi done elif (( dir == 1 )) then for (( x2=x+2; x2 >= x; x2-- )) do if (( x2 > 16 )) || (( x2 >= xlen )); then continue; fi let i=x2-x if (( y > 0 )) && (( ${map[$x2,$((y-1))]} & 8 )) then if (( (x2 + (y-1)) & 1 )) then echo -ne "\e[38;5;28m" else echo -ne "\e[38;5;40m" fi echo -ne ${lfront[$i]} fi if (( (y+1) < ylen )) && (( ${map[$x2,$((y+1))]} & 8 )) then if (( (x2 + (y-1)) & 1 )) then echo -ne "\e[38;5;28m" else echo -ne "\e[38;5;40m" fi echo -ne ${rfront[$i]} fi if (( ${map[$x2,$y]} & 2 )) then if (( (x2 + y) & 1 )) then echo -ne "\e[38;5;40m" else echo -ne "\e[38;5;28m" fi echo -ne ${left[$i]} fi if (( ${map[$x2,$y]} & 4 )) then if (( (x2 + y) & 1 )) then echo -ne "\e[38;5;40m" else echo -ne "\e[38;5;28m" fi echo -ne ${right[$i]} fi if (( ${map[$x2,$y]} & 8 )) then if (( (x2 + y) & 1 )) then echo -ne "\e[38;5;28m" else echo -ne "\e[38;5;40m" fi echo -ne ${front[$i]} fi done elif (( dir == 2 )) then for (( y2=(y+2); y2 >= y; y2-- )) do if (( y2 > 15 )) || (( y2 >= ylen )); then continue; fi let i=y2-y if (( x > 0 )) && (( ${map[$((x-1)),$y2]} & 4 )) then if (( ((x-1) + y2) & 1 )) then echo -ne "\e[38;5;40m" else echo -ne "\e[38;5;28m" fi echo -ne ${rfront[$i]} fi if (( (x+1) < xlen )) && (( ${map[$((x+1)),$y2]} & 4 )) then if (( ((x+1) + y2) & 1 )) then echo -ne "\e[38;5;40m" else echo -ne "\e[38;5;28m" fi echo -ne ${lfront[$i]} fi if (( ${map[$x,$y2]} & 8 )) then if (( (x + y2) & 1 )) then echo -ne "\e[38;5;28m" else echo -ne "\e[38;5;40m" fi echo -ne ${left[$i]} fi if (( ${map[$x,$y2]} & 1 )) then if (( (x + y2) & 1 )) then echo -ne "\e[38;5;28m" else echo -ne "\e[38;5;40m" fi echo -ne ${right[$i]} fi if (( ${map[$x,$y2]} & 4 )) then if (( (x + y2) & 1 )) then echo -ne "\e[38;5;40m" else echo -ne "\e[38;5;28m" fi echo -ne ${front[$i]} fi done elif (( dir == 3 )) then for (( x2=(x-2); x2 <= x; x2++ )) do if (( x2 < 0 )); then continue; fi let i=x-x2 if (( y > 0 )) && (( ${map[$x2,$((y-1))]} & 1 )) then if (( (x2 + (y-1)) & 1 )) then echo -ne "\e[38;5;28m" else echo -ne "\e[38;5;40m" fi echo -ne ${rfront[$i]} fi if (( (y+1) < ylen )) && (( ${map[$x2,$((y+1))]} & 1 )) then if (( (x2 + (y+1)) & 1 )) then echo -ne "\e[38;5;28m" else echo -ne "\e[38;5;40m" fi echo -ne ${lfront[$i]} fi if (( ${map[$x2,$y]} & 4 )) then if (( (x2 + y) & 1 )) then echo -ne "\e[38;5;40m" else echo -ne "\e[38;5;28m" fi echo -ne ${left[$i]} fi if (( ${map[$x2,$y]} & 2 )) then if (( (x2 + y) & 1 )) then echo -ne "\e[38;5;40m" else echo -ne "\e[38;5;28m" fi echo -ne ${right[$i]} fi if (( ${map[$x2,$y]} & 1 )) then if (( (x2 + y) & 1 )) then echo -ne "\e[38;5;28m" else echo -ne "\e[38;5;40m" fi echo -ne ${front[$i]} fi done fi echo -ne "\e[0m" echo -ne "\e[${term[0]};0H[F]orward, [B]ackward, turn [L]eft, turn [R]ight or [Q]uit?" read -n 1 input done echo ``` Please keep in mind that this is pretty much the first thing I did with `bash` that was more than just piping a few commands together. It would probably be reducable by quite a lot if I didn't hardcode all the walls, but it seemed easier. It's got no consistency whatsoever. The byte format for each square is picked in a horrible way. But it works. I even added support for movement through the arrow keys :) These are some screenshots for the sample input ( Note that my map starts at (0|0) ): ![0|0, facing north](https://i.stack.imgur.com/xTnf2.png) ![0|2, facing south](https://i.stack.imgur.com/eMaYx.png) ![2|1, facing east](https://i.stack.imgur.com/NcugR.png) ![2|1, facing south](https://i.stack.imgur.com/n8TmE.png) ![1|2, facing north](https://i.stack.imgur.com/YEuMe.png) Apart from the fourth one they all look like the sample ones as well (see my comment on the OP). These screenshots were taken on urxvt v9.15 with 256 color support, it probably would look quite crap on a 88 color terminal, and terminals without unicode support don't work at all. The font I used was [Source Code Pro](http://sourceforge.net/projects/sourcecodepro.adobe/) by Adobe. [Answer] Here's my version, in Python 3. It's something like 3k characters and could get a bit smaller with a little effort (there's lots of white space that could be removed, to start with). It currently uses `+X/\` as its drawing characters, but it is set up to draw with Unicode characters if you have a fixed width font that will render them properly. It supports using separate tiles for the angled parts of the differently collored walls, though I'm not using that feature. It also lets you provide ceiling, floor and "distant" tiles, and you can use different ones for when the player is facing east or west vs north or south. Alas this never looked very good, so probably all of these should be blank (or something solid, like `█`). Alas, on my Windows 7 system I had a horrible time trying to find a monospaced font with the full set of block characters (e.g. `▜` and `▟`). Most of the ones I found could not be made available in the `cmd` console for some reason (perhaps because they're not perfectly monospaced?). If you think your console is more functional, try using the alternate character set that I've commented out near the top of the file, which doesn't look too bad even with just two colors. It has filled in ceilings and floors and mostly transparent walls. The code: ``` from itertools import product as p r=range cs=r"+X//\\//\\ " #" ░▛▛▜▜▟▟▙▙██████" shapes=[(1,[(x,y,0)for x,y in p(r(5),r(5,10))]), (0,[(x,y,0)for x,y in p(r(5,11),r(5,10))]), (1,[(x,y,0)for x,y in p(r(11,16),r(5,10))]), (1,[(4,4,4),(4,10,6)]+[(4,y,0)for y in r(5,10)]), (1,[(11,4,2),(11,10,8)]+[(11,y,0)for y in r(5,10)]), (0,[(x,y,0)for x,y in p(r(4),r(4,11))]), (1,[(x,y,0)for x,y in p(r(4,12),r(4,11))]), (0,[(x,y,0)for x,y in p(r(12,16),r(4,11))]), (0,[(1,1,4),(2,2,4),(3,3,4),(1,13,6),(2,12,6),(3,11,6)]+ [(x,y,0)for x,y in p(r(1,4),r(2,14)) if x<y<14-x]), (0,[(14,1,2),(13,2,2),(12,3,2),(14,13,8),(13,12,8),(12,11,8)]+ [(x,y,0)for x,y in p(r(12,15),r(2,14)) if 15-x<y<x-1]), (1,[(0,y,0) for y in r(1,14)]), (0,[(x,y,0) for x,y in p(r(1,15),r(1,14))]), (1,[(15,y,0) for y in r(1,14)]), (1,[(0,0,4),(0,14,6)]+[(0,y,0)for y in r(1,14)]), (1,[(15,0,2),(15,14,8)]+[(15,y,0) for y in r(1,14)])] def rr(s): for r in s:print("".join(r)) def dw(s,a,p,d): for i,r in enumerate(s):r[:]=cs[10+i//5*2+d%2]*16 for w,(pl,sh) in zip(a,shapes): if w: for x,y,c in sh: s[y][x]=cs[c+(p+d+pl)%2] dx=[1,0,-1,0] def ga(x,y,d,m): fx=dx[d];fy=lx=dx[d-1];ly=dx[d-2] return [m[y+2*fy+ly][x+2*fx+lx][d],m[y+2*fy][x+2*fx][d], m[y+2*fy-ly][x+2*fx-lx][d],m[y+2*fy][x+2*fx][d-1], m[y+2*fy][x+2*fx][d-3],m[y+fy+ly][x+fx+lx][d], m[y+fy][x+fx][d],m[y+fy-ly][x+fx-lx][d], m[y+fy][x+fx][d-1],m[y+fy][x+fx][d-3], m[y+ly][x+lx][d],m[y][x][d], m[y-ly][x-lx][d],m[y][x][d-1],m[y][x][d-3]] def rd(): l=input(); while l!="": if "\n" in l:yield from l.split("\n") else:yield l l=input() def rm(): m=[[[d in s for d in"ESWN"]for s in r.strip().split()]+[[1]*4]*2 for r in rd()] return m+[[[1]*4 for _ in m[0]]]*2 def cl():print("\n"*30) def gl(): print("Enter map, followed by a blank line.") x=y=0;d=3;m=rm();mv="";s=[[""]*16 for _ in r(15)] while True: cl();dw(s,ga(x,y,d,m),x+y,d);rr(s) print("X:",x+1,"Y:",y+1,"Facing:","ESWN"[d]) if mv:print("Last move:",mv) mv=input("[FBLRQ]? ").upper() if mv=="F": if not m[y][x][d]:x+=dx[d];y+=dx[d-1] else:mv+=" (Blocked)" elif mv=="B": if not m[y][x][d-2]:x+=dx[d-2];y+=dx[d-3] else:mv+=" (Blocked)" elif mv=="L":d=(d-1)%4 elif mv=="R":d=(d+1)%4 elif mv=="Q":break else:mv="I didn't understand %r."%mv gl() ``` The character set is specified near the top of the file. The order of the characters are: 1. even parity wall 2. odd parity wall 3. even parity top right wall angle (e.g. `/` with a wall below it) 4. odd parity top right wall angle 5. even parity top left wall angle 6. odd parity top left wall angle 7. even parity bottom right wall angle 8. odd parity bottom right wall angle 9. even parity bottom left wall angle 10. odd parity bottom left wall angle 11. ceiling facing E/W 12. ceiling facing N/S 13. horizon facing E/W (the middle of the screen if there are no walls) 14. horizon facing N/S 15. floor facing E/W 16. floor facing N/S There are 15 walls that might need to be rendered by the game, in a pattern like this (with `V` indicating the player's position and arc of view): ``` _ _ _ _|_|_ _|_|_ |V| ``` The tiles used by the 15 walls are defined in the `shapes` list. It's a list of 2-tuples. The first value of the tuple indicates the "parity" of the wall, with `0` indicating that it should be drawn with the same characters as a wall directly in front of the character and a `1` indicating that it should be the alternate pattern (e.g. `+` vs `X`). The second value is a list of `x,y,t` tuples indicating the screen coordinates and tile index of one pixel (walls being rendered with odd parity will have `1` added to each of these indexes). The shapes are ordered by distance, so the first three represent the perpendicular walls two tiles ahead of the character, followed by the two parallel walls two tiles ahead, and so on. The functions are: * `rr`: "render" the screen (by printing the tiles in the screen buffer). * `dw`: "draw walls" to a provided screen buffer. This uses the painters algorithm, so the most distant walls are drawn first and may get covered up by closer ones. * `ga`: "get area" returns a list of boolean values indicating which walls are opaque for a given map position and facing. * `rd`: "read", a generator that reads the map, yielding the lines. This is only needed because IDLE's console does weird stuff when you paste multi-line inputs rather than entering one line at a time. * `rm`: "read map", parses the map into a nested list of booleans, indexed by `m[y][x][d]` (with `d=0` being East and `d=1` being South). It also adds two rows and two columns of padding squares, to avoid index errors in the other code. * `cl`: "clear" the output (by writing enough newlines to scroll the old view off the top of the most consoles). * `gl`: "game loop", where the input is gathered and the above stuff gets called. A few "screenshots": The starting position: ``` \ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ +XXXXXXXXXXXXXX+ / X: 1 Y: 1 Facing: N [FBLRQ]? ``` Looking along the north wall: ``` \ X\ X+\ X++\ X+++\ X+++X X+++X X+++X X+++X X+++X X+++/ X++/ X+/ X/ / X: 1 Y: 1 Facing: E Last move: R [FBLRQ]? ``` A couple of shots matching your examples (note, the blank first lines are being chopped off by Stack Overflow, they're in the program output): ``` X / X /+ X /++ X +++ X +++ X +++ X +++ X +++ X +++ X +++ X \++ X \+ X \ X: 3 Y: 2 Facing: S Last move: F [FBLRQ]? ``` And: ``` / /X /XX XXX +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ +++++XXXXXX+XXX+ XXX \XX \X \ X: 3 Y: 2 Facing: E Last move: L [FBLRQ]? ``` Here's one of the stranger views in the supplied map, as the wall parallel to our view is the same color as the perpendicular wall sticking out behind it: ``` \ +\ ++\ ++++ ++++ ++++ ++++ ++++ ++++ ++++ ++++ ++++ ++++ ++++ ++++ ++++ ++++ ++/ +/ / X: 3 Y: 4 Facing: N Last move: R [FBLRQ]? ``` Here's what the area of last shot would look like from above: ``` _ _ | V ``` ]
[Question] [ \$ 1089 \$ is a very special number. To prove why, select any 3-digit number whose first and last digits differ by at least 2. Then, reverse the digits, and take the *difference* of these two numbers. Reverse the digits once more, and *add* these two numbers together. You will get \$ 1089 \$. The magic is left as an exercise to the reader. Taking this a step further, let's define an algorithm for all possible integers: * Choose any positive integer \$ n \$ * Reverse the digits of \$ n \$, and call it \$ x \$ * Set \$ n \$ equal to \$ n - x \$ if \$ x < n \$, and \$ n + x \$ otherwise * Repeat the above step until \$ n \$ reaches a number it has already visited In turns out that this algorithm gets stuck in an infinite loop, for certain numbers. Let's call a number *1089-able™*, if it does in fact terminate (in other words, a duplicate is reached at some point). For example, everyone's favorite number, `2022`, is *1089-able™*: ``` 2022 + 2202 -> 4224 + 4224 -> 8448 + 8448 -> 16896 + 69861 -> 86757 - 75768 -> 10989 + 98901 -> 109890 - 98901 -> 10989 (*) ``` In this challenge, you are given a positive integer, and are required to determine whether it is *1089-able™*. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins. The first 50 *non-1089-able™* numbers are as follows: ``` [10057, 10118, 10168, 10254, 10458, 10598, 10698, 10798, 10898, 11047, 11108, 11158, 11244, 11448, 11499, 11588, 11688, 11788, 11888, 11998, 11999, 12037, 12148, 12234, 12438, 12489, 12578, 12678, 12778, 12878, 12988, 12989, 13027, 13138, 13224, 13428, 13479, 13568, 13668, 13768, 13868, 13978, 13979, 14017, 14128, 14198, 14214, 14418, 14469, 14558] ``` [Answer] # [Python](https://www.python.org), 117 bytes ``` def f(n): v={n} while 1: x=int(str(n)[::-1]);n-=[-x,x][x<n] if n in v:return 1 if n/100in v:return 0 v|={n} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZJNTsMwEEbFsjmF2TmiERl7HDuBnCTKohIJjQQuStMSBJyETVnAneA0eMZBajZP3-jN-C8f308v03bnT6evw9Rn7udw1_Wilz6tktWxfvXvyep5Ozx0AkJhNdeDn-R-GoPQVFUGbXrjs7rJ5vXcNvOtb4M09MKLwYtjNXbTYfQCluI15Pl5PQ_14xstEhf_vfj0O183QTN2LSAHcIyCoQwS0HAyJaOIsBGOERxqD-QE3AAKqR0QOWFZEozjVETYCBdRlgvIVLmmmQq4XSlNwxRqTuhYMZZTEWEjXETpFpCpc0XDNHC7VoqGaVSc0LJi-NC6iLARLqK0C8jEHGgYArcj8K4xbJSAfIOIBZvGuDZJ-t0oZnqgcePvOwnrx80sw8WnVxBeXYRvs9934yRkL-dUXNZCsk5KGl_q_3f5Aw) It works for all positive integers less or equal to the 50th *non-1089-able™* number. Haven't proven that it works for numbers greater than `14558`. [Answer] # [Python](https://www.python.org), ~~162~~ ~~136~~ 128 bytes ``` def h(n,e=0):e=(e or[])+[n];n+=(x:=int(str(n)[::-1]),-x)[x<n];return f"1089{(len(z:=str(n))-7)*'9'}099"!=z and(n in e or h(n,e)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZLRSsMwFIbx1qeIu1niWkjSkyap5klKkYGtK0g2ug62ieB7eLMbxVfSp7HnpIJXHz_8_5-TnLx_7k7jZhsvl4_D2OXu--2x7diGx6wNUlRt4C3bDnUjVnVs7uIq8GMV-jjy_TjwKOqqylUjsvwo6uP95Bja8TBE1i2UdP6FP7eRn6uQzCK34nbpl6_S-8VNOLN1fOSR9ZHhGelQIdIcP1dfXT_sx4eu78YTC6xWUhqbMSWVcoSSoA0gwJAynlAm2ARHmDwYn0hKUUBpwLgCIAXeI4wjVSbYBJfg_Qx0allgp1YU17rAMg0FKXBkMZZUmWATXIJ3M9BZSI1lhaJ4oTWWFaBJgSWLoUsXZYJNcAnezkAnSIVloCgOiqaGaVAE0AsClOQ0xjXXuwGX-u_JQ6h71k1r6XFBwzo-tVxl6PaC9R2L23HaWC-aeWF_H-gX) Haven't proven that it works for *non-1089-able™* numbers past the first 50. -26 bytes thanks to benrg and ovs (and for pointing out the rules with reusable functions) -8 bytes thanks to Jo King [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 70 bytes ``` ^ $($^$%')*_;$%'*_¶ ^(_+);\1\B|; _+ $.& D^` /^./}s`^1099+8900+¶.+ ^¶ ``` [Try it online!](https://tio.run/##K0otycxLNPyvqqHhnvA/jktFQyVORVVdUyveGkhpxR/axhWnEa@taR1jGONUY83FFa/NpaKnxuUSl8ClH6enX1ucEGdoYGmpbWFpYKB9aJueNhdX3KFt//8bGRgZcRkaGJiaAwA "Retina – Try It Online") Link only includes two test cases as it's too slow otherwise. Explanation: ``` ^ $($^$%')*_;$%'*_¶ ``` Take the first number and its reverse and convert them both to unary with the reversed number first. ``` ^(_+);\1\B|; ``` Subtract the two numbers of the second is larger otherwise add them. ``` _+ $.& ``` Convert back to decimal. ``` D^` ``` Delete the total if it's been seen before. ``` s`^1099+8900+¶.+ ``` But delete the entire buffer if the value will increase infinitely. ``` /^./}` ``` Repeat until at least the current total was deleted. ``` ^¶ ``` Check to see whether an infinite loop was detected. [Answer] ## [Javascript](https://www.javascript.com/), 149 145 137 128 bytes ``` c=n=>{a=[n];while(n){x=+[...''+n].reverse().join``;n=x<n?n-x:n+x;if(a[i='includes'](n))return 1;if(a[i](n/100))break;a.push(n)}} ``` * Thanks to [@Radvylf Programs](https://codegolf.stackexchange.com/users/79857/radvylf-programs) for saving 4 bytes! * Saved 8 bytes replacing `return false` with `break` now that the loop is wrapped * Thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan) for saving 9 bytes! [Try me online.](https://ato.pxeger.com/run?1=NZLBToQwFEXjUr6CzAYaHKTlFYoMuvMnCMkg05lBSTEwoySTSfwPNy507-_o19i-4urklntvHn19_1T9Rn58fB0P26X4eWsKVdye6qJUVf66bzvpK3KaiqAMw9DzAlWFg3yRwyh9Ej72rVqvc1VMK3WnltONCqa83fp12RZeq5ruuJGjV-kGMsjDcVAunT_rs2saRYQ8DLJ-yuvw-Tjute98tnP8XnyrXhWl9vD0yqURpQKRIBgHA-CoeIZILFILgdAeE9dERTFAGZg4BUAFWWbABarEIrUQFlk2wzhZFJtORjHOWGzKGMSoQKCFp6gSi9RCWGRihnHGETNlMcV4zJgpi4GhghQtHH86TixSC2GRpTOMEyJqyoBiHChODXpQA8AbBEjQybmoHGfbD34nD27rFm6Ua6xcfe1hJ9XusNc6CMjJudQra3x9rtdGiNv0auw7GXb9zl_c1_qFbBYkd-bF_T-kPw) ## [Javascript](https://www.javascript.com/), 171 bytes (readable) ``` c=n=>{ a = [n] while(n){ x=+n.toString().split('').reverse().join('') n=x<n?n-x:n+x if(a.includes(n)) return true if(a.includes(n/100)) break a.push(n) } } ``` [Try me online.](https://ato.pxeger.com/run?1=ZZI9TsNAEIVFGZ_CShNbAeNdz9prwNBxAcoohUk2icEaR_6BSFFOQpMCKhquA6dhdjZUuPn0Zt8bjXfn7R2bpTkeP4Z-daG_PxcFFrd7z6ev9At_hnNv9LqpahNguPdGo10xxahvHvq2wnUQRt22rvpgMgmj1ryYtjNUe2oqtCWyY7G7wTu82F3hdEe6WgVlVOGiHpamo5ah35p-aNHv28H8P78UcUyex9aUz3RaRtuh21DMGx28gxv55-wLGyxm5FTZuS9iITQjZUgFFqBYqZyROmQOmkEeGyeyEhwQEmxcALCCPLdQmlXqkDlohzw_wTplnNieUnBcysQ2k5CwAs0WlbFKHTIH7ZDrE6wziaVtlgiOJ1LaZglIVpCxRfFPJ6lD5qAd8uwE64RY2GYgOA6CpwYa1AL4BgFSdiql5563atqgNr1f0VLE14Qbn649qg2u-w3p6dSuBz3fIqD6rJrTsy0a7JraRHWzDsb3JS3Rchxe_z3c3879Ag) A good chunk of the bytes in this are coming from included functions `.reverse()`, `.includes()`, etc. Have not tested past the 50 provided. [Answer] # [Ruby](https://www.ruby-lang.org/), 84 bytes ``` ->n,*r{q=0;1while(r!=r|=[n+=(w=n.digits.join.to_i)*(w<n ?-1:1)])&&q=[]!=[n/100]-r;q} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PR6uoutDWwNqwPCMzJ1WjSNG2qMY2Ok/bVqPcNk8vJTM9s6RYLys/M0@vJD8@U1NLo9wmT8Fe19DKUDNWU02t0DY6VhGoXt/QwCBWt8i6sPZ/gUJatJGBkVEsF4gFFDc1j/0PAA "Ruby – Try It Online") [Answer] # [Javascript](https://www.javascript.com/), ~~94~~ 87 bytes ``` f=(n,s={},x=+[...``+n].reverse().join``,m=x<n?n-x:n+x)=>s[m]?!!(m-11e12+11):f(s[m]=m,s) ``` ## How it works! If the function does get stuck in a forever loop it will max out at the magic number `11e12+11` and this function returns the result minus that number casted to a boolean. * 7 Bytes thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)! [Try it online!](https://tio.run/##dZHNbsIwEITvPEXggi2c4J91bKMGxIWXQEikNFQg4iBSoUhVnz2N13BAVU@fZj0zayfn8l62h9vp@pX65qPq@2NBPGuL7x/WFbNtlmX7/czvslt1r25tRWh2bk6eTCaU1UX35lc@7RZ@1tFi2W7r3Wo8JnXKuzUXUgmz3mw0XRxJOCpq1tJ@Pk8Et658v1SjQ@Pb5lJll@aTTJ/TKX2ZbwXniiWSS8kSZY1hieNas8TkMEyGU7fL6vJKuqRYJkfSUUpHo2GLb3waOl@3PKf/bNImVAphETlCaggAjUo7RB5hIixi8IT4QFQCA0JCiAsAVOBcgLao8ggTYSOceyA4JVehUwqMS6lCmQSFCixatEGVR5gIG@HsA8GpuAxlSmBcSRnKFEhUYNCi8dEqjzARNsKZB4ITuAhlIDAOAm8Nw0UDAL8gQI5Ore2ff9T/Ag) ]
[Question] [ # Introduction [Forte](http://esolangs.org/wiki/Forte) is a very peculiar esoteric language based on the concept of modifying the values of numbers. In Forte numbers are not constants but variables, you can use the `LET` instruction to assign new values to them. For example, after executing `LET 2=4-1` from now on `2` assumes the value of `3`, which means that whenever the value `2` comes up in an expression it is instead "replaced" by `3`. The expression `(1+1)*2` would now evaluate to `9`. This instruction in Forte is used both for storing information and for flow control (lines are numbered and by changing the value of their numbers you can determine the order of their execution). In this challenge we will not deal with this second aspect. # The challenge You are required to write an interpreter for a simplified subset of Forte's `LET` expressions. You will receive as input a series of lines following this grammar: ``` <line>::= <number>=<expression> <expression>::= <number>|<expression>+<number> ``` Note: this grammar is not valid Forte because it lacks line numbers, LET, and parentheses (which are always mandatory) That is, you will only need to deal with computing summations and assigning values to numbers. Parentheses won't be present in the input, and each expression will need to be evaluated from left to right: beware that partial results are affected by redefinitions! Numbers will always be non-negative integers, up to the limit of your language's native integer type (or 2^32, whichever is higher). For each line you should output the result of the expression and assign this result to the (possibly reassigned) value of the first number, which will affect how the following lines will be interpreted. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code (in bytes) wins! # Other rules * The input format is flexible, you can for example take a single string with newlines, a list of strings, a list of lists of numbers... The same goes for the output, as long as it's clear what's the result of each expression in the input. * You may submit either a function, a full program, or a solution to be run in a REPL environment calling it once for each line. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden, in particular you can't call an external Forte interpreter in your code. # Examples These are all part of the same input. After each line the expected output relative to that line is shown, sometimes with a comment indicating relevant reassignments (not part of the required output). ``` 5=4 4 6=5 4 # 5 -> 4 7=1+2+5 7 7=5+2+1 4 # Order of operations matters! 5+2 -> 4+2 -> 6 -> 4 18=5+6+7 12 5=3 3 # Remember: 5 -> 4 10=6+4 3 # 6 -> 4 -> 3, 3+3 = 6 -> 3 ``` [Answer] # [Perl 5](https://www.perl.org/), 92 bytes 90 bytes of code + `-pl` flags. ``` sub f{($b=$h{$a=pop}//$a)!=$a?f($b):$a}s%(\d+)\+(\d+)%f($1)+f$2%e&&redo;/=/;$_=$h{f$`}=f$' ``` [Try it online!](https://tio.run/nexus/perl5#HcxBCoMwFATQfU6h9McaPiWNNbFUPr2I0EZM6EIwKF1Jzp7Grt4wA3Mqg1vn4hLmtH3Hwu81jASfHSyFJUQpwYqSwD59HsQDbNx4PUwoBvzDc68Eemi4q6rVTUsvSfbwOk48vCN5OKekqWWGNOtIYYOHOquYuudgsGOabkxdyWD7Aw "Perl 5 – TIO Nexus") I use the hashtable `%h` to store the mapping between numbers. The function (`sub`) `f` returns the number to which its input map (or its input if it's mapped to no number): `$h{$a=pop}` retrieves the number toward which the input maps. If it's none, thanks to `//$a`, the value of `($b=$h{$a=pop}//$a)` is the input (`$a`). We make sure that this values isn't the input itself to not loop infinitely (`!=$a`). Then, we either recursively call `f` or return the input. The main program consists of two steps: - `s%(\d+)\+(\d+)%f($1)+f$2%e&&redo` evaluates the first addition on the right side, while there is still an addition: it replaces `x+y` by the result of the evaluation of `f(x)+f(y)`. - `/=/;$_=$h{f$`}=f$'` does the assignment: `/=/` allows to access the left side with `$`` and the right side with `$'`, then `$h{f$`}=f$'` does the assignment. And we also assign it to `$_` that is implicitly printed after each line. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 81 bytes ``` v=x=>(v[x]=v[x]||x,v[x]-x?v(v[x]):x) f=x=>l=>v[v(x)]=l.reduce((p,x)=>v(v(x)+p),0) ``` [Try it online!](https://tio.run/nexus/javascript-node#TYwxDsIwDEX3nILRFm7VAk0RKOUgVQYUUhiipgIReei1mUtSBYnFfv/Z@ktQrDoIPWuVxjwzpV3wJawWT4xiSE9OdaEPwKiVK5/29jYWYCLG6CH57YRU4WL8@PLOls7fQWwGaBD6g0ZKLCM3mdvINe3oPzcx1znXx1VIarNIRfvfsYpBUuwVeF4@oy/M1TzsFw "JavaScript (Node.js) – TIO Nexus") Receives input by calling f with the value to assign to, then calling the result of that with an array of values to add together. (i.e. `f(5)([4])`) Repeat for multiple lines. `v` is used as a function to compute the actual current value of a number, and also as an object to store the actual values. First `v[x]=v[x]||x` ensures that `v[x]` is defined. `v[x]-x` performs a comparison to determine whether this is the actual number or not. If the number does not map to itself, `v(v[x])` recursively tries again, otherwise return `x`. `f` performs the calculation and assignment, curried to save one byte, where the second call returns the computed value. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes ``` ®y$ÐL ṪÇ+Ç¥/Ṅ;®⁸Ǥ;© ⁸©ḷƓÇ€¤ ``` [Try it online!](https://tio.run/nexus/jelly#@39oXaXK4Qk@XA93rjrcrn24/dBS/Yc7W6wPrXvUuAPIW2J9aCUXkHlo5cMd249NPtz@qGnNoSX//0dHm@pEm8TG6kSb6USbgmhznWhDHSMdGNsUyDYEsQ0tQBwzHXMQB6jJGCxoANII1B8LAA "Jelly – TIO Nexus") This is one of the few Jelly programs where it seems to be terser to take input from standard input. It's a full program (writing a function would have been shorter but is banned by PPCG rules, because it wouldn't run correctly the second time). The input format looks like this: ``` [[5,[4]],[6,[5]],[7,[1,2,5]],[7,[5,2,1]],[18,[5,6,7]],[5,[3]],[10,[6,4]]] ``` ## Explanation **Helper function** `1Ŀ` (translate an integer to its value) ``` ®y$ÐL ÐL Repeatedly, until there are no further changes, $ apply the following unary function to {the input}: y replace values using the mapping table ® stored in the register. {Then return the eventual result.} ``` Rather conveniently, this helper function will work correctly either on a single value, or a list of values, due to the way `y` is defined. If more than one mapping is given for a single value, we take the first mapping from the table. The mapping table is stored in the register (which is basically just a variable; Jelly only has one variable). **Helper function** `2Ŀ` (evaluate one LET instruction) ``` ṪÇ+Ç¥/Ṅ;®⁸Ǥ;© Ṫ On the last element of {the input}, Ç Run 1Ŀ, / left fold it via ¥ the following binary function: + add {the two arguments} Ç and run 1Ŀ on {the result}, Ṅ write {the result} (and a newline) to standard output, ;® append the value of the register, ; prepend ¤ the following value: ⁸ {the input, without its last element} Ç with 1Ŀ run on it © and store that value in the register {and return it}. ``` We don't really want a return value here; we're just running this for its side effects (updating the register and outputting the assigned value). Jelly functions always return a value, though, so we just let the mapping table get returned, as that's tersest. **Main program** ``` ⁸©ḷƓÇ€¤ © Initialize the mapping table ⁸ with the empty string (which is also the empty list) ḷ then evaluate and discard ¤ the following value: Ɠ a line from standard input, parsed into a data structure Ç€ with each element transformed via 2Ŀ {and leave the empty string to be printed implicitly} ``` Normally, `⁸` would give us the first command-line argument when run in this context, but there isn't one (we're taking input from standard input), so it runs in an alternative mode that gives us the null string. The need to initialise the register (from its default value of `0`, which crashes `y`) means that we can't mention the user's input implicitly, meaning that it's as cheap to take it from standard input (`Ɠ`) as it would be to take it from a command line argument (`³` or `⁸`), and being able to access the alternative use of `⁸` means that the unusual (for Jelly) form of input is actually a byte shorter. It's possible this is improvable. I still haven't figured out why the second line needs to say `⁸Ǥ;` rather than just `;@Ç` – the two should be equivalent, as far as I understand Jelly, given the lack of use of `µ`/`ð`/`ø` – but the latter crashes for some reason. Likewise, there are various other ways to rearrange the program without losing bytes, so it's possible that I've missed a way to make things a bit shorter. Incidentally, changing the `ḷ` in the last line to `;` gives you an interesting look into the internal workings of the program, as it'll then output the "history of the register" that's implicitly output by the return values of `2Ḷ`. [Answer] # [Haskell](https://www.haskell.org/), ~~116 113 108~~ 106 bytes ``` (#)=until=<<((==)=<<) e?((n,s):r)|m<-foldl1(\a b->e#(e#a+e#b))s=m:(\x->last$m:[e#x|x/=e#n])?r e?r=[] (id?) ``` [Try it online!](https://tio.run/nexus/haskell#NYzBCoMwEETvfkUgHnbpSmtbtYirHxI9KKYS0LRECx78dxsLPc17AzM7SOSPXczIRQHAjD4x0BWApRlzh9tURM/X2I8x1K3oolJL0LI9adkhzjzlUK9RObbzEk650nLd1jNraRusnP9xrJpgYDB9hfvUGitYvJ2xiwjFIBQkpO4NEqSkkiMzUjFd6c@J5/jg@HFIStkhfnT7lRdSKfl9s38B "Haskell – TIO Nexus") Each equation `4=3+1+5` is notated as tuple `(4,[3,1,5])`. The anonymous function `(id?)` takes a list of such tuples and returns a list of all intermediate results. `#` is a function to find a fixpoint of a given function `e` and a start value `x`. The function `?` takes an evaluation function `e` and recursively solves each equation.`foldl1(\a b->e#(e#a+e#b))s` evaluates the right hand side of an equation and saves the result to `m`, e.g. for `4=3+1+5` it computes `eval(eval(eval 3 + eval 1) + eval 5)`, where each `eval` is a fix point application of `e`. Then the eval function is modified to take the new assignment of `n` into account: `(\x->last$m:[e#x|x/=e#n])` which is the same as `\x -> if x == eval n then m else eval x`. The initial evaluation function is `id` which maps each integer to itself. --- Thanks to Ørjan Johansen for a shorter fixpoint function, saving 2 bytes! [Answer] # oK, 48 bytes ``` a:[];s:{*(a@x;x)^0N}/;f:{a[s@x]:y:{s@x+y}/s'y;y} ``` Usage: `f[5;1 2 3] / 5=1+2+3` [Try it online!](https://tio.run/nexus/k-ok#Hco7DoAgFETRrdD5e1FQQfOmYQVuwGhC4wZoIIS1I9rMPcUUx@cFz6lvnQ0I3S2PPOHh5E5vw8WRU@0Q8@SbiJjLMzatJqIVpq7GRqTELH7oCgW1fzJiw/dboCSREWtXXg) --- If you don't mind having an upper limit to the numbers you can use, such as only using numbers `0` through `998`, then the following suffices (**41 bytes** ± a few depending on the maximum): ``` a:!999;s:(a@)/;f:{a[s@x]:y:{s@x+y}/s'y;y} ``` --- Explanation: `;` separates three definitions. `a` is a dictionary/map of numbers. In the first case, it's an actual, empty dictionary `[]`, in the second case it's a list of the numbers `0` to `998`. `s` is a function that finds the "resulting" number when given a number. The `/` on the end of the function means that it will apply itself to its own output until the output stops changing. The last bit, `f`, means that: ``` f:{ } /function called f, input number x, list y s'y /apply s to every number in the list / /fold through the list {s@x+y} / sum the two numbers, apply s a[s@x]: /set the s(x) to map to the final sum y: ;y /redefine y to be the final sum, then return it ``` [Answer] # Python 3, ~~146~~ ~~132~~ 130 bytes *14 bytes saved thanks to @Dada* *2 bytes saved thanks to @mbomb007* ``` d={} g=lambda x:d.get(x)and x!=d[x]and g(d[x])or x def f(t): for n,(s,*r)in t: for b in r:s=g(g(s)+g(b)) d[g(n)]=s;yield g(n) ``` [Try it online!](https://tio.run/nexus/python3#TY9BCsIwEEX3OcW4m9EgVq2VSk4SsmhJGwoape0iIp69ztQK7t68Tz4/kzevtwrmWt1qX0Eq/TY0Iyaqooe0Mt4mJxhQiO49JOWbFlocqVTQsogaB73uqYswsppdDXz15WACBhxoE7Am4szbgJGcGS7PrrlKbaRJ1WDAcoq5Bnt0pIVPzPnCBXOmYa/h3@SzyRaTnb@K3xWLkrrDL97xwRnXK6eUjEwysuVlsvrRd1H@PX0A) Receives input as tuples of equations [`x = y + z + w` as `(x, (y, z, w))`], outputs via generator. ]
[Question] [ You are a foreign trader, hoping to make a profit. There are 5 goods people wish to trade: `A`pricots, `B`oars, `C`anaries, `D`affodils, and `E`arwigs. Starting in the winter, you need to decide what to produce. Then, in the fall, you travel and spend your days trading for a profit. ## Gameplay You start the game with 10 of each product in storage. Each year, you will consume 2 of each product. At the beginning of the game, you receive a list of 5 products, along with the amount you will be able to produce each year (ex:`5-A,6-B,3-C,12-D,4-E`). You then will return a letter A through E deciding what to produce. Then, in the fall time you will bring your products (including those in storage) to the market. You have 50 turns to trade. You must decide if you want to `P`urchase, `S`ell, or `L`eave the market. The buyers will then be paired up randomly with the sellers. If a group has extra, the random extras will miss out this turn. If a trader is skipped, they will receive `S`, otherwise, `T`. The seller must decide what he wants to sell, and amount (ex:`3-A`), and then what he would accept (ex:`5-B,2-D,1-E`) (The values are *any of* not *all of*). The buyer will then be told what product the seller is selling, then the products the seller will take for it, and he can choose a product to trade for it (ex: `D` or `X` for nothing). After all trades are over, or after you have left the market, you will consume 2 of each product, and the year starts over. If you have less than 2 of any 1 product, you will die (and passed `Q`). Your score will be the number of years you last, and after 50 games, your scores will be averaged for your total score. ## Optional moves At any time you can return `G` to query your goods At any time you can return `N` to query the number of new products in your inventory (produced by any player in the past year, and new products will be traded before old products) At any time you can return `T` for the current Turn phrase: `P`roduce, `M`arket, or `T`rading During a trade, you can query `I` for an identifier unique to the player you are trading with. During a trade, you can return `M` to query the number of people trading ## How to code it: You may use any standard language, and must include a `command.txt` which is the command to run your program. The general flow of your program should be: ``` Get productivity While alive: Output product you want to produce While in trading: Output whether you want to purchase or sell Get whether or not you were skipped. If not skipped: If purchasing: print product you offer, and products you will accept Else: Get product offered, products being accepted, and choose the product you will give ``` I have a tester program [here](https://github.com/thenameipicked/Traders). To use it, create a folder in the bots folder with your bot's name. Add a `command.txt`, your program, and anything else your program needs. I will be adding submissions as they come in. If you don't want to install the languages required to run some or all of them, you just need to delete the command.txt in the bot's folder. ## Inner Workings There will be 5 bots for each program submitted. The ID will be different for bots of the same type. I will call the amount a person can produce a given product the productivity. Each product will be given a base productivity, where all of the base productivity will add up to 30. One of the scores will be ensured to be at most 3, and all will be at least 2. Then, each player's productivity will vary from the base productivity (One value will vary by +2, another +1, then +0, -1, and the remaining value will vary by -2). The base productivity will change from game to game. ## Scores: ``` seer: 10.128 years level_headed_trader: 8.196 years introvert: 6.856 years random_ando: 5.408 years hoarder_trader: 4.12 years ratio_trader: 3.532 years scared_trader: 3.056 years ``` [Answer] # Level-headed Trader This bot tries to make his quantities as equal as possible ## command.txt ``` python leveller.py ``` ## leveller.py ``` import sys def current_goods(): print "G" return parse_goods(readline()) def parse_goods(good_string): return dict([(a, int(b)) for a, b in [product.split("-") for product in good_string.split(",")]]) def get_minimum(goods): cur_min = 200 min_good = "X" for good, amount in goods.items(): if amount < cur_min: min_good = good cur_min = amount return min_good def get_maximum(goods): cur_max = -1 max_good = "X" for good, amount in goods.items(): if amount > cur_max: max_good = good cur_max = amount return max_good def add_goods(x, y): return {k: int(x.get(k, 0)) + int(y.get(k, 0)) for k in set(x) | set(y)} def readline(): line = sys.stdin.readline().strip() if line == 'Q' or not line: exit() return line def output_goods(goods): print ",".join([good+"-"+str(amount) for good, amount in goods.items()]) def output_good(good, amount): print good+"-"+str(amount) def current_turn_is(turn): print "T" return readline() == turn turns = MARKET, PRODUCE, TRADING, SKIPPED = "M", "P", "T", "S" market_options = PURCHASE, SELL = "P", "S" items = APRICOTS, BOARS, CANARIES, DAFFODILS, EARWIGS, NOTHING = "A", "B", "C", "D", "E", "X" productivity = parse_goods(readline()) while True: product_to_produce = get_minimum(current_goods()) print product_to_produce while current_turn_is(MARKET): print SELL if readline() != SKIPPED: maximum = get_maximum(current_goods()) goods = {"A": 1, "B": 1, "C": 1, "D": 1, "E": 1} del goods[maximum] output_good(maximum, 1) output_goods(goods) ``` [Answer] # Scared Trader This trader avoids getting low numbers ## command.txt ``` python scared.py ``` ## scared.py ``` import sys def current_goods(): print "G" return parse_goods(readline()) def parse_goods(good_string): return dict([(a, int(b)) for a, b in [product.split("-") for product in good_string.split(",")]]) def get_minimum(goods): cur_min = 200 min_good = "X" for good, amount in goods.items(): if amount < cur_min: min_good = good cur_min = amount return min_good def get_maximum(goods): cur_max = -1 max_good = "X" for good, amount in goods.items(): if amount > cur_max: max_good = good cur_max = amount return max_good def add_goods(x, y): return {k: int(x.get(k, 0)) + int(y.get(k, 0)) for k in set(x) | set(y)} def readline(): line = sys.stdin.readline().strip() if line == 'Q' or not line: exit() return line def output_goods(goods): print ",".join([good+"-"+str(amount) for good, amount in goods.items()]) def output_good(good, amount): print good+"-"+str(amount) def current_turn_is(turn): print "T" return readline() == turn turns = MARKET, PRODUCE, TRADING, SKIPPED = "M", "P", "T", "S" market_options = PURCHASE, SELL = "P", "S" items = APRICOTS, BOARS, CANARIES, DAFFODILS, EARWIGS, NOTHING = "A", "B", "C", "D", "E", "X" productivity = parse_goods(readline()) while True: current = current_goods() min_product = get_minimum(current) min_amount = current[min_product] product_to_produce = min_product if min_amount < 4 else get_minimum(productivity) print product_to_produce while current_turn_is(MARKET): print SELL if readline() != SKIPPED: current = current_goods() maximum = get_maximum(current) minimum = get_minimum(current) to_offer = {maximum: max(productivity[maximum]/productivity[minimum], 1)} output_good(minimum, 1) output_goods(goods=to_offer) ``` [Answer] # Seer This program predicts the future, and he chooses the trades which will increase his expected lifespan. This isn't completely finished, because he only knows how to buy things but not sell things, so expect an update in the future. Regardless, I believe that he will be competitive as-is. ``` $| = 1; @names = ('A','B','C','D','E'); @counts = (12,12,12,12,12); %names = ('A',0,'B',1,'C',2,'D',3,'E',4); sub predict{ local @a = @_; local $minval = 1000; local $minloc = 0; for(0..~~@a-1){ if($a[$_]<$minval){ $minloc = $_; $minval = $a[$_] } $a[$_]-=2; } if($minval <= 1){return (0,@a)} if($minval == 100){return (10000,@a)} $a[$minloc] += $productivity[$minloc]; local @b = predict(@a); @b[0]++; return @b; } sub choice{ local @a = @_; local $minloc = 0; local $minval = 1000; for(0..~~@a-1){ if($a[$_]<$minval){ $minloc = $_; $minval = $a[$_] } } return $minloc; } $productivity = <>; @productivity = split(',',$productivity); #@c = predict(@counts); #print "@c\n"; $alive = 1; while($alive){ for(0..4){ $counts[$_] -= 2; } $choice = choice(@counts); print "$names[$choice]\n"; $counts[$choice] += $productivity[$choice]; for(1..50){ print "P\n"; chomp($in = <>); if($in eq "T"){ chomp($forsale = <>); ($quantity,$type) = split("-",$forsale); $type = $names{$type}; #print "$quantity, $type\n"; chomp($in = <>); @options = split(",",$in); @baseline = predict(@counts); $lifespan = shift @baseline; $basescore = $lifespan * 1000; @bestcounts = @counts; for(0..4){ $basescore -= 10**(-1 * $baseline[$_]); } #print "Base: $basescore\n"; @hypo = (); $bestscore = $basescore; $choice = "X"; for(0..$#options){$curchoice = $_; ($cost,$ctype) = split("-",$options[$curchoice]); $ctype = $names{$ctype}; @tempcounts = @counts; $tempcounts[$type] += $quantity; $tempcounts[$ctype] -= $cost; @curhypo = predict(@tempcounts); @hypo[$curchoice] = [@curhypo]; #print "@curhypo\n"; $lifespan = shift @curhypo; $score = $lifespan * 1000; for(0..4){ $score -= 10**(-1 * $curhypo[$_]); } #print"$score\n"; if($score > $bestscore){ $bestscore = $score; $choice = $names[$ctype]; @bestcounts = @tempcounts; } } print "$choice\n"; @counts = @bestcounts; } #print"@counts\n"; #@c = predict(@counts); #print "@c\n"; } } ``` I run this program like so: ``` perl seer.plx ``` [Answer] # Hoarder Trader This trader tries to get as many products as possible. ## command.txt ``` python hoarder.py ``` ## hoarder.py ``` import sys def current_goods(): print "G" return parse_goods(readline()) def parse_goods(good_string): try: return dict([(a, int(b)) for a, b in [product.split("-") for product in good_string.split(",")]]) except: raise IOError(good_string) def get_minimum(goods): cur_min = 200 min_good = "X" for good, amount in goods.items(): if amount < cur_min: min_good = good cur_min = amount return min_good def get_maximum(goods): cur_max = -1 max_good = "X" for good, amount in goods.items(): if amount > cur_max: max_good = good cur_max = amount return max_good def add_goods(x, y): return {k: int(x.get(k, 0)) + int(y.get(k, 0)) for k in set(x) | set(y)} def readline(): line = sys.stdin.readline().strip() if line == 'Q' or not line: exit() return line def output_goods(goods): print ",".join([good+"-"+str(amount) for good, amount in goods.items()]) def output_good(good, amount): print good+"-"+str(amount) def current_turn_is(turn): print "T" return readline() == turn turns = MARKET, PRODUCE, TRADING, SKIPPED = "M", "P", "T","S" market_options = PURCHASE, SELL = "P", "S" items = APRICOTS, BOARS, CANARIES, DAFFODILS, EARWIGS, NOTHING = "A", "B", "C", "D", "E", "X" productivity = parse_goods(readline()) while True: product_to_produce = get_minimum(add_goods(current_goods(), productivity)) print product_to_produce while current_turn_is(MARKET): print PURCHASE if readline() != SKIPPED: offered_good = parse_goods(readline()) accepted_goods = parse_goods(readline()) minimum = get_minimum(accepted_goods) current = current_goods() if minimum not in current or current[minimum] < accepted_goods[minimum]: print NOTHING elif accepted_goods[minimum] < offered_good.values()[0]: print minimum elif accepted_goods[minimum] == offered_good.values()[0] \ and productivity[minimum] > productivity[offered_good.keys()[0]]: print minimum else: print NOTHING ``` [Answer] # Ratio Trader This bot offers products matching the ratio of his productivity ## command.txt ``` python ratio.py ``` ## ratio.py ``` import sys def current_goods(): print "G" return parse_goods(readline()) def parse_goods(good_string): return dict([(a, int(b)) for a, b in [product.split("-") for product in good_string.split(",")]]) def get_minimum(goods): cur_min = 200 min_good = "X" for good, amount in goods.items(): if amount < cur_min: min_good = good cur_min = amount return min_good def get_maximum(goods): cur_max = -1 max_good = "X" for good, amount in goods.items(): if amount > cur_max: max_good = good cur_max = amount return max_good def add_goods(x, y): return {k: int(x.get(k, 0)) + int(y.get(k, 0)) for k in set(x) | set(y)} def readline(): line = sys.stdin.readline().strip() if line == 'Q' or not line: exit() return line def output_goods(goods): print ",".join([good+"-"+str(amount) for good, amount in goods.items()]) def output_good(good, amount): print good+"-"+str(amount) def current_turn_is(turn): print "T" return readline() == turn turns = MARKET, PRODUCE, TRADING, SKIPPED = "M", "P", "T", "S" market_options = PURCHASE, SELL = "P", "S" items = APRICOTS, BOARS, CANARIES, DAFFODILS, EARWIGS, NOTHING = "A", "B", "C", "D", "E", "X" productivity = parse_goods(readline()) while True: current = current_goods() min_product = get_minimum(current) min_amount = current[min_product] product_to_produce = min_product if min_amount < 4 else get_minimum(productivity) print product_to_produce while current_turn_is(MARKET): print SELL if readline() != SKIPPED: current = current_goods() maximum = get_maximum(current) minimum = get_minimum(current) to_offer = {maximum: max(productivity[maximum]/productivity[minimum], 1)} output_good(minimum, 1) output_goods(goods=to_offer) ``` [Answer] # Family Farmers - Java The five family farmers do their best to cover all production options with whoever can make the most in any category working on that category. However, after the initial assignments the family members all strike out on their own; they don't collude after the initial assignments. I may get around to having them help each other while trading. **FamilyFarmers.java** ``` import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Scanner; public class FamilyFarmers { final int MIN_PRODUCTION_CUTOFF = 4; // If my decision making has ended up // with a family member producing // less than this number, he will // just produce his most productive // item final int NUMBER_PRODUCTS = 5; final int MAX_TRADES = 50; // The number of trades per phase final byte EOF = 04; final byte NEW_LINE = 10; final int BILLBOARD_SIZE = 1000; boolean alive = true; int[] myInventory; int myNumber; // Primarily, the line this instance of the program will be printing on in // the billboard number 0 will be the "boss", and will do a bunch of the // calculations (To avoid them being done multiple times) MappedByteBuffer familyBillboard; String myProduct; // What product (single string character) we will be // making Scanner stdin = new Scanner(System.in); /** * @param args * A string in the form A-#,B-#,C-#,D-#,E-# representing the * productivity of each good. * @throws IOException * @throws InterruptedException * @throws UnexpectedPhaseTokenException */ public static void main(String[] args) throws IOException, InterruptedException { new FamilyFarmers(); } public FamilyFarmers() throws IOException, InterruptedException { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { familyBillboard.clear(); familyBillboard.put(new byte[familyBillboard.limit()]); Runtime.getRuntime().halt(0); } }); initialSetup(); mainLoop(); } protected void mainLoop() throws InterruptedException { int tradeCounter = 0; // 50 trades per phase String currentStage; int toTrade = -1; int toGet = -1; boolean purchase = false; while (alive) { System.out.println("T"); currentStage = stdin.nextLine(); if (currentStage.equals("P")) { // Production period System.out.println(myProduct); /* System.out.println("G"); String currentInv = stdin.nextLine(); myInventory = parseProducts(currentInv); toTrade = getMostProduct(); toGet = getLeastProduct(); */ tradeCounter = 0; } else if (currentStage.equals("M")) { // Market System.out.println("G"); String currentInv = stdin.nextLine(); myInventory = parseProducts(currentInv); tradeCounter++; purchase = (Math.random() >= 0.5); toTrade = getMostProduct(); toGet = getLeastProduct(); // If my goods are fairly even, it's time to head home! if (myInventory[toTrade] - myInventory[toGet] <= 2) { System.out.println("L"); continue; } // If I don't have much to trade... if (toTrade <= 6) { // But my goods levels are fairly even... if (toGet >= 4) { // I'll just leave the market System.out.println("L"); } } if (purchase) { System.out.println("P"); } else { System.out.println("S"); } } else if (currentStage.equals("T")) { String toSend = ""; if (purchase) { // Buying boolean finished = false; String offer = stdin.nextLine(); offer += "," + stdin.nextLine(); String[] offers = parseOffer(offer); int quantityOffered = Integer.parseInt(offers[0].split("-")[0]); int productOffered = offers[0].split("-")[1].charAt(0) - 65; // This loop will probably never get off the first // iteration... // Go through the offers, blindly pick the first one that // looks good. for (int index = 1; index < offers.length && !finished; index++) { int quantityDesired = Integer.parseInt(offers[index].split("-")[0]); int productDesired = offers[index].split("-")[1].charAt(0) - 65; // If the request would leave me with less than two, I'm // not interested if (quantityDesired - (myInventory[productDesired]) > 2) { // Too rich for my blood! continue; } if (productDesired == toGet) { // I'm not interested in trading what I'm trying to // get! } if (productOffered == toGet) { // Since this is what I want to trade for, I'll be // willing to consider different offers than // otherwise if (quantityDesired <= quantityOffered * 1.25 && myInventory[productDesired] - quantityDesired > 4) { System.out.println((char) (productDesired + 65)); finished = true; } // If I would otherwise die without the product, // I'll accept a really bad trade // (Remember that the incoming offers are already // sorted least to highest) if (myInventory[toGet] < 2 && tradeCounter > MAX_TRADES / 2) { System.out.println((char) (productDesired + 65)); finished = true; } } // If the product is what I'm trying to trade, and the // offer isn't too bad if (productDesired == toTrade && quantityOffered * 1.25 <= quantityDesired) { System.out.println((char) (productDesired + 65)); finished = true; } // If I am offered either as much as or more of // something, I'll do it. if (quantityOffered >= quantityDesired) { System.out.println((char) (productDesired + 65)); finished = true; } } if (!finished) { // If we get this far, nothing struck my fancy System.out.println("X"); } } else { // Selling int[] toBuy = getSameProducts(toGet); // Make some self-beneficial offers in the first few rounds. if (tradeCounter <= 5) { toSend = "" + ("2-" + ((char) (toTrade + 65))); for (int index = 0; index < toBuy.length; index++) { toSend += (",3-" + ((char) (toBuy[index] + 65))); } } else { // Basic offer. Just offer 1:1 for what I want. toSend = "" + ("2-" + ((char) (toTrade + 65))); for (int index = 0; index < toBuy.length; index++) { toSend += (",2-" + ((char) (toBuy[index] + 65))); } } // If trading has been going for awhile and I would die the // next turn, I frantically offer everything I have for what // I need to survive one more turn. This is probably a // terrible strategy! if (myInventory[toGet] < 2 && tradeCounter > MAX_TRADES / 2) { toSend += ("4-" + ((char) (toTrade + 65))) + ",2-" + ((char) (toGet + 65)); } if (toSend.length() < 6) { // I couldn't find enough to sell... System.out.println(toSend + "," + toSend); // That's safe, right? break; } // Put the products I would accept on a line after the // product I want to sell String[] splitSend = toSend.split(","); toSend = splitSend[0] + "\n"; boolean first = true; // Don't prepend a comma on the first string for (int index = 1; index < splitSend.length; index++) { if (!first){ toSend += ","; } toSend += splitSend[index]; first = false; } System.out.println(toSend); } } else if (currentStage.equals("S")) { // I was skipped! Darn it! } else { // AAK! I received a token I don't know what to do with! I must // be dead... alive = false; } } } /** * Returns the offers, sorted from least product desired to most, with the * product being offered at the first index * * @param offer * @return String[] index 0 contains the product being offered, the * following indicies are the desired products ordered from least to * most */ protected String[] parseOffer(String offer) { String[] splitOffers = offer.split(","); // Sort. Just using selection sort. The first index contains the string // with the product being asked for, // so should not be sorted. for (int index = 1; index < splitOffers.length; index++) { int indexOfMin = index; int minimum = Integer.parseInt(splitOffers[index].split("-")[0]); for (int jdex = index + 1; jdex < splitOffers.length; jdex++) { int thisValue = Integer.parseInt(splitOffers[jdex].split("-")[0]); if (thisValue < minimum) { indexOfMin = jdex; minimum = thisValue; } } String temp = splitOffers[index]; splitOffers[index] = splitOffers[indexOfMin]; splitOffers[indexOfMin] = temp; } return splitOffers; } /** * Returns an array of the indices of the product which I have the same * quantity of in myInventory * * @param startingIndex * - The index of a value to match * @return */ protected int[] getSameProducts(int startingIndex) { int[] toReturn = new int[0]; for (int index = startingIndex + 1; index < myInventory.length; index++) { if (myInventory[index] == myInventory[startingIndex]) { int[] temp = new int[toReturn.length + 1]; for (int jdex = 0; jdex < toReturn.length; jdex++) { temp[jdex] = toReturn[jdex]; } temp[temp.length - 1] = index; toReturn = temp; } } return toReturn; } /** * Returns the index of the product which I have the least of in myInventory * I can't help but feel that this lacks object-oriented design... * * @return */ protected int getLeastProduct() { int toReturn = 0; for (int index = 1; index < myInventory.length; index++) { toReturn = myInventory[index] < myInventory[toReturn] ? index : toReturn; } return toReturn; } /** * Returns the index of the product which I have the most of in myInventory * I can't help but feel that this lacks object-oriented design... * * @return */ protected int getMostProduct() { int toReturn = 0; for (int index = 1; index < myInventory.length; index++) { toReturn = myInventory[index] > myInventory[toReturn] ? index : toReturn; } return toReturn; } /** * Returns an int[] containing the productivity of each product in * alphabetical order * * @param products * @return */ protected int[] parseProducts(String products) { int[] toReturn; // Split the string so that each line of the array has #-P String[] lineProductivities = products.split(","); // Split each string in the array so that it is just the number for (int index = 0; index < lineProductivities.length; index++) { lineProductivities[index] = lineProductivities[index].split("-")[0]; } toReturn = new int[lineProductivities.length]; for (int index = 0; index < lineProductivities.length; index++) { toReturn[index] = Integer.parseInt(lineProductivities[index]); } return toReturn; } /** * Append my productivity string to the family billboard. If the file was * empty when I got here (contained no newlines), I am the boss! The boss * gives orders. * * @throws IOException * @throws InterruptedException */ protected void initialSetup() throws IOException, InterruptedException { String input; myNumber = 0; FileChannel familyBillboardFC; Path billboardPath = FileSystems.getDefault().getPath("family_billboard.txt"); FileLock billboardLock; byte[] argsByteArray; byte currentByte = 0; input = stdin.nextLine(); // Open the file and lock it familyBillboardFC = FileChannel.open(billboardPath, StandardOpenOption.WRITE, StandardOpenOption.READ); billboardLock = familyBillboardFC.lock(); // Map the contents of the file to a space in memory familyBillboard = familyBillboardFC.map(FileChannel.MapMode.READ_WRITE, 0, BILLBOARD_SIZE); // Convert the incoming string into an array of bytes argsByteArray = input.getBytes(); for (int index = 0; index < BILLBOARD_SIZE; index++) { currentByte = familyBillboard.get(); if (currentByte == NEW_LINE) { myNumber++; familyBillboard.mark(); } } if (myNumber == 0) { familyBillboard.position(0); familyBillboard.mark(); } familyBillboard.reset(); for (byte b : argsByteArray) { familyBillboard.put(b); } familyBillboard.put(NEW_LINE); familyBillboard.put(EOF); billboardLock.release(); Thread.sleep(100); // Give other programs a chance to launch // Boss needs to wait for awhile to make sure the others have finished // writing... // I don't have any idea how to do this in an intelligent fashion. It is // *probably* safe to sleep for a few hundred milliseconds, but I'm not // certain. Instead, I'll try to take out a new lock. If I succeed // twice, the file must be finished! int counter = 0; while (myNumber == 0) { billboardLock = familyBillboardFC.tryLock(); if (billboardLock != null) { billboardLock.release(); counter++; } else { counter = 0; Thread.sleep(10); } if (counter >= 2) { giveOrders(); break; } } byte foo = familyBillboard.get(); // Until the boss has written out the instructions, sleep while (foo < 65) { Thread.sleep(10); familyBillboard.reset(); foo = familyBillboard.get(); } familyBillboard.reset(); myProduct = String.valueOf((char) familyBillboard.get()); } // initialSetup() /** * Run by the boss. Tries to sort the family so that every product is * covered and so that whoever can produce the most of a product is * producing it. Writes the character code representing the product to * produce to the first character of the relevant line in the family * billboard. */ protected void giveOrders() { final int MAX_LINE_LENGTH = 24; int numberMembers = 0; byte currentByte = 0; Integer[][] productivities; // Table of member's productivities char[] selections; // Who will make what. selections[#] = the production // letter for member # familyBillboard.position(0); // I have seen the rules to these games change. It's easy for me to // accommodate more (or less than) 5 instances now. It may not be easy // later while (currentByte != EOF) { currentByte = familyBillboard.get(); if (currentByte == NEW_LINE) { numberMembers++; } } currentByte = 0; familyBillboard.reset(); selections = new char[numberMembers]; productivities = new Integer[numberMembers][NUMBER_PRODUCTS]; for (int index = 0; index < numberMembers; index++) { byte[] currentLineBytes = new byte[MAX_LINE_LENGTH]; String currentLine; // Read the next line for (int jdex = 0; jdex < currentLineBytes.length; jdex++) { currentByte = familyBillboard.get(); if (currentByte == NEW_LINE) { break; } currentLineBytes[jdex] = currentByte; } currentLine = new String(currentLineBytes); currentByte = 0; int[] lineProductivities = parseProducts(currentLine); // Need to iterate to get the int[] to Integer[] for (int jdex = 0; jdex < NUMBER_PRODUCTS; jdex++) { productivities[index][jdex] = lineProductivities[jdex]; } } // If there are at least as many producers as products, select the most // productive for each producer. If there are overlaps, move the smaller // one to the second most productive and re-check for overlaps. If there // are overlaps and the productivity is tied, compare the second highest // and so on. // TODO What if members > 5? if (numberMembers <= NUMBER_PRODUCTS) { int[] overlapResult; for (int index = 0; index < selections.length; index++) { selections[index] = (char) (maxInArray(productivities[index]) + 65); // Can convert from a max value in productivities to a // human-readable character by adding 65, since 0 -> A, 1 -> B, // etc. } int counter = 0; // I imagine there is a possibility of this loop // not terminating. I will use this counter to // forcefully break it. // While there is an overlap while ((overlapResult = arrayHasOverlaps(selections)) != null && overlapResult[0] != -1) { byte productIndex = (byte) (selections[overlapResult[0]] - 65); // 0 through the number of production options, where A = 0, B = // 1, etc. if (productivities[overlapResult[0]][productIndex] > productivities[overlapResult[1]][productIndex]) { int index = findNextHighestFromIndex(productivities[overlapResult[1]], productIndex); selections[overlapResult[1]] = (char) (index + 65); } if (productivities[overlapResult[1]][productIndex] > productivities[overlapResult[0]][productIndex]) { int index = findNextHighestFromIndex(productivities[overlapResult[0]], productIndex); selections[overlapResult[0]] = (char) (index + 65); } // Things are beginning to get mega hairy if (productivities[overlapResult[0]][productIndex] == productivities[overlapResult[1]][productIndex]) { int index0 = findNextHighestFromIndex(productivities[overlapResult[0]], productIndex); int index1 = findNextHighestFromIndex(productivities[overlapResult[1]], productIndex); if (productivities[overlapResult[0]][index0] > productivities[overlapResult[1]][index1]) { selections[overlapResult[0]] = (char) (index0 + 65); } else { // I can't be bothered to go any further with this... If // they're tied here, then to heck with it! selections[overlapResult[1]] = (char) (index1 + 65); } } counter++; if (counter > BILLBOARD_SIZE) { break; } } } // Check for less than my minimum cutoff. If one is, set it to its max. for (int index = 0; index < selections.length; index++) { byte b = (byte) (selections[index] - 65); if (productivities[index][b] < MIN_PRODUCTION_CUTOFF) { selections[index] = (char) (maxInArray(productivities[index]) + 65); } } // Write the product to produce to the correct line familyBillboard.position(0); familyBillboard.put((byte) selections[0]); // If we find a newline, write the selected character to the next // spot. Otherwise, read the next character for (int index = 1; index < selections.length;) { byte thisByte = familyBillboard.get(); if (thisByte == NEW_LINE) { familyBillboard.put((byte) selections[index]); index++; } } } /** * Look through the array. Find an element that is either later in the array * and <= the value at the incoming index and > the value at the toReturn * index, or earlier in the array and < the value at the current index and > * the value at toReturn. If we weren't able to set the new index (Maybe we * are already at the max value) return the index of the largest value * * @param array * the array to search in * @param incomingIndex * the index of the value to begin searching with * @return an index as described */ protected int findNextHighestFromIndex(Integer[] array, int incomingIndex) { int toReturn = incomingIndex; int comparisonValue = -1; // The value at toReturn int index = (incomingIndex + 1) % array.length; for (int counter = 0; counter < array.length; counter++) { if (index > incomingIndex && array[index] == array[incomingIndex]) { // If we have found an equal value later in the array, return // immediately. In the unlikely event everything is equal, // don't just take the value at the bottom index! return index; } if (index > incomingIndex && array[index] < array[incomingIndex] && array[index] > comparisonValue) { toReturn = index; comparisonValue = array[toReturn]; } if (index < incomingIndex && array[index] < array[incomingIndex] && array[index] > comparisonValue) { toReturn = index; comparisonValue = array[toReturn]; } index++; index %= array.length; // How often do you get to use %= ? } if (comparisonValue == -1) { // In the unlikely event we weren't able to set comparisonValue // (maybe we are already at the minimum?) toReturn = maxInArray(array); // This will probably contribute to those endless loops I mentioned // above! } return toReturn; } /** * Checks the array for any two elements being the same. If two are, return * the indices. If not, return {-1, -1} * * @param selections * The array to examine * @return Indices of the overlapping elements or {-1, -1} */ protected int[] arrayHasOverlaps(char[] selections) { int[] toReturn = new int[] { -1, -1 }; for (int index = 0; index < selections.length - 1; index++) { for (int jdex = index + 1; jdex < selections.length; jdex++) { if (selections[index] == selections[jdex]) { toReturn[0] = index; toReturn[1] = jdex; return toReturn; } } } return toReturn; } /** * Returns the index of the max value of an array. In the case of a tie, * returns the earliest index. * * @param array * the array to read * @return the index of the largest element in the array */ protected <T extends Comparable<T>> byte maxInArray(T[] array) { byte currentMax = 0; for (byte index = 0; index < array.length; index++) { currentMax = array[index].compareTo(array[currentMax]) > 0 ? index : currentMax; } return currentMax; } } ``` **command.txt** ``` cd bots/family_farmer && java FamilyFarmers ``` It can be compiled with ``` javac FamilyFarmer.java ``` There should also be another blank file, family\_billboard.txt, in the bots/family\_farmer folder. [Answer] # Introvert - Java This bot is so introverted, it would rather die than talk to anyone in trading, so it immediately leaves market if it is there. However, it doesn't want to die so it tries to keep its supplies up as long as possible. **Introvert.java** ``` import java.util.Scanner; public class Introvert{ static int[] current = {10,10,10,10,10}; static int[] potentialProduction = new int[5]; static boolean alive = true; public static void main(String[] args){ Scanner s = new Scanner(System.in); String input = s.nextLine(); String[] inputArray = input.split(","); for(int i = 0; i < 5; i++){ potentialProduction[i] = Integer.parseInt(inputArray[i].replaceAll("\\D+","")); } while(alive){ int pos = decideProduction(); produce(pos); System.out.println("L"); for(int i = 0; i < 5; i++){ current[i] -= 2; if(current[i] < 0) alive = false; } } s.nextLine(); //read final `q` message } public static int decideProduction(){ int lowestPotential = 9999; int lowestPotentialPosition = 9999; for(int i = 0; i < 5; i++){ if(current[i] == 2 || current[i] == 3){ lowestPotentialPosition = i; break; } int potential = current[i] + potentialProduction[i]; if(potential < lowestPotential){ lowestPotential = potential; lowestPotentialPosition = i; } } switch(lowestPotentialPosition){ case 0: System.out.println("A"); return 0; case 1: System.out.println("B"); return 1; case 2: System.out.println("C"); return 2; case 3: System.out.println("D"); return 3; case 4: System.out.println("E"); return 4; default: System.out.println("A"); return 0; } } public static void produce(int pos){ current[pos] += potentialProduction[pos]; } } ``` **command.txt** ``` java Introvert ``` Compile with ``` javac Introvert.java ``` Note: I did this on my lunch break and my work computer doesn't have the jdk or python so I have not been able to test it at all. If it does not work let me know and I will try to fix it. [Answer] # Random Ando Every KOTH should have a random bot. Coded, hopefully, so that it won't make invalid deals (like trying to sell more than what it has in stock). ``` --RandomAndo math.randomseed(os.time()) math.random()math.random()math.random() ITEMS = {"A", "B", "C","D", "E"} MARKETOPTION = {"P", "S"} MyGoods = {0,0,0,0,0} local function readline() -- checks for the dying "Q" or just reads line local line = io.read("*l") if line == "Q" then os.exit() end return line end local function getCurrentTurn() -- asks for M,T,P print("T") return readline() end local function getRandom(array) -- returns for a random element in array local r=math.random(#array) return array[r] end local function getRandomMyItems() -- make a list of items I have and return a random one (no more than one of) local rgood=math.random(5) local amount=1 while MyGoods[rgood] <= 0 do rgood=math.random(5) end return amount.."-"..ITEMS[rgood] end local function parseGoods(goodString) -- specialized to getMyGoods atm local goods={0,0,0,0,0} local c = 1 example = "5-A,6-B,3-C,12-D,4-E" for good in goodString:gmatch("%d+%p[ABCDE]") do goods[c]=goods[c]+good:match("%d+") c=c+1 end return goods end local function getMyGoods() -- asks for my goods print("G") local temp = parseGoods(readline()) for i=1,5 do MyGoods[i]=temp[i] end end productivity = readline() -- doesn't matter while true==true do print(getRandom(ITEMS)) -- produce random item while getCurrentTurn()=="M" do getMyGoods() local action=getRandom(MARKETOPTION) -- make a random market decision if action == "S" then -- offer to sell 1 of a random item I have in stock, will take any 2 offered print("S") if readline()=="T" then print(getRandomMyItems()) print("2-A,2-B,2-C,2-D,2-E") end elseif action == "P" then -- if I can do the deal, I will print("P") if readline()=="T" then local offered=readline() local accepted =readline() local taccepted={} for i in accepted:gmatch("%d+%p[ABCDE]") do oitem =i:match("[ABCDE]") oamount = i:match("%d+") for k=1,5 do if ITEMS[k]==oitem and MyGoods[k]>=tonumber(oamount) then table.insert(taccepted, oitem) end end if #taccepted>=1 then print(getRandom(taccepted)) else print("X") end end end elseif action == "L" then print("L") end end end ``` command.txt should be: ``` lua RandomAndo.lua ``` ]
[Question] [ As we learned from the IBM PC AT, [YouTube (see video)](https://www.youtube.com/watch?v=gffS40Djmxc), [Wikipedia (see article)](http://en.wikipedia.org/wiki/Beast_(video_game)), and Sesame Street: # **The letter `H` is the *most merciless letter of the alphabet*!** *(Even when actually composed from two elements in [Code Page 437](http://en.wikipedia.org/wiki/Code_page_437). In fact, it's even MORE merciless that way.)* Like the Aliens in, uhm...er... *Aliens*, Beasts relentlessly pursue all who would dare come near their eggs. There is no reasoning with them. You must squash them if not to perish. ![A frightening encounter with the 4H Club](https://i.stack.imgur.com/MszXh.png) For this scenario we will assume you're down to your last life, and you've met plain Beasts in a terrain with no eggs (as in the Wikipedia screenshot). You don't have a numeric keypad and can only move directly up/down/left/right...but the beasts apparently have one, and can move diagonally on their turn. A Beast's choice of move among its options will be the one that minimizes distance from the player. If the distances are equal then tie breaking is done favoring left+up over right+down, but here's the disambiguation matrix to be explicit about it...lowest number to tie-break: ``` 1 3 4 2 H 5 6 8 7 ``` A beast never sleeps, but they are fortunately a bit slower than the player. They move *every other turn* (giving the player a head start by beginning their alternations on the second turn). They must move if a move is possible, regardless of if that takes them further from the player. You crush a beast if you move a train of movable walls where it was sitting in a closed gap. These plain beasts are worth 2 points a head. # Input 1. A pair of integers indicating a map's size in columns then rows. 2. Row count of lines of input, each of the column size...containing either a solid wall (`#`), a movable wall (`~`), a beast (`H`), the player (`O`) or just a space. 3. Input that will be either U, D, L, R indicating an *attempted* move by the player... or W to just wait. Note that attempting to push a movable wall which is blocked is legal input, it just will result in no action. # Output 1. `aHHHH!` if the beasts killed the player...or nothing if the player won with no beasts remaining 2. The score *(Note: For debugging purposes and/or amusement, you'll probably want to be able to output the state at each step; but that's too long to post here.)* # Clarifications * Maps are guaranteed to be bounded by solid walls. * The order of who moves in a turn matters for the outcome. Thus: The player always goes first, then the beasts are given an ordering based on their *initial map position* if you were sweeping across the screen top to bottom left to right. *(A row 1 beast moves before a row 2 beast, and two beasts on the same row it would be the one with the lowest column number that would move before the other)* * Diagonal moving beasts can move into any open adjacent diagonal space, regardless of if it requires squeezing between walls. * A player can push any number of movable walls in a line provided that there's a space or a beast on the other end. But trying to push a train of walls into a Beast that is not pinned between walls treats the Beast as a wall, and won't allow the move. * A Beast's move decision during a turn is based on the player's location at the *beginning* of the turn. Its desired optimization of "distance to player" is through an "as the crow flies" calculation. Any approximation which would give the same result as measured from the center of its square to the center of the player's square is fine. * If a Beast can't make what would have been its first preferred move in a turn because a higher priority Beast took its spot, it will take its next best choice as opposed to staying in place (if a move is still possible). # Sample Cases ### Simple Crush *Input* ``` 5 3 ##### #O~H# ##### R ``` *Output* ``` 2 ``` ### Preference Matrix -> Death *Input* ``` 5 5 ##### #O # # ~ # # H# ##### WWDW ``` *Output* ``` aHHHH! 0 ``` ### Preference Matrix -> Win *Input* ``` 5 5 ##### #O # # ~ # # H# ##### WRD ``` *Output* ``` 2 ``` ### Waiting For the Reaper *Input* ``` 5 5 ##### #O # # ~ # # H# ##### WWW ``` *Output* ``` aHHHH! 0 ``` ### Successful Defeat in the Wikipedia Scenario *Input* ``` 40 23 ######################################## #~ ~ ~~ ~ ~ ~~ ~ ~~ ~ ~ ~~ # #~~ ~ ~~ ~ ~ ~~ ~ # #~# ~~ ~~~~ ~ ~~~~ ~ ~~~ ~# # ~ ~ ~ ~~ #~~ ~ # #~~ ~~~ ~ ~ ~ ~ ~~ ~ ~ ~ ~ # # ~~ ~ ~ ~ ~~~ H ~ #~ # # O~ ~ # ~~~ ~ ~ ~~ ~ ~ ~~ # # ~ ~H~~ ~~ ~ # ~~ ~ # # ~~ ~ ~~~ ~~ ~~~~ ~ ~# #~ ~ ~~~ ~ ~ ~ ~ ~~ ~~# # ~ # ~ ~~ ~~~ ~ ~ ~ # ~# #~ ~ ~~ ~ ~ H ~~ ~~ ~ ~ ~~~ # # ~ ~ ~ ~ ~ ~~~ ~ # # ~~ ~ ~ ~~ ~ ~ ~ ~ ~ # # ~~ ~ ~ ~ ~ ~~ # #~ ~ # ~~~~ ~ ~~~H # ~ # # ~ ~ ~ ~ ~ ~~ ~ # # ~ ~ #~ ~ ~~ ~ ~ ~# # ~~ ~ ~ ~~ ~ ~ # # ~~~ ~ ~~ ~ ~ ~ ~ # # ~ ~ ~ ~~ ~ ~ ~ # ######################################## RRRUWWWRRRURWWWWRDRRWWRDWWWWD ``` *Output* ``` 8 ``` Map provided by me, moves and output by @bobbel, corroborated by myself and @Allbeert. # Winning Criteria I think this is golfable, so I'll go with code golf rules unless people complain. # Extra Credit Playable Unicode implementation with the double-wide characters to resemble the image! [Answer] # Java, 1,843 My first try of solving this puzzle with Java. I know, that there are a lot of improvements to make it shorter. But in the end it works for now. To try it, you have to create a class `C` and paste the code. `args[0]` (strictly speaking `a[0]`) is for input. The print method of the map is not included since it's not necessary for the puzzle output. ``` class C{static char [][]C;static int A= 0,B=0,D=0,E=0,F=0,G = 0 ; public static void main(String[]a ){String []b= a[0]. split("\n");int c = Byte. decode(b [0]. split(" ")[1]); G=a [ 0 ] . replaceAll( "[^H]","").length() ; String d = b [ b. length - 1 ] ;C=new char[c][];for(int e =1;e<b.length-1;e++ ) C [ e - 1 ]=b[e]. toCharArray ( ) ; f ();boolean X= 0> 1; for ( char g : d . toCharArray ( ) ) { switch(g){case 'U': h(0,-1);break; case 'D':h(0, 1); break; case 'L':h( -1, 0); break;case'R':h(1,0 );}if(X)i();X=!X;f( );}System.out.print (D);}static void f( ){for(int a= 0;a<C. length;a++)for( int b=0;b<C[a].length;b ++)if(C[a][b]=='O') {A=b;B= a;}}static void h(int x,int y){E =x;F =y;switch(C[ B +y][A +x]){case 'H':g();break;case ' ':j(A,B);break;case '~':k();}}static void i(){if(G<1){return;}int[][]l=new int [G][];int m=0;for(int r=0;r<C.length;r++){for(int c=0;c<C[ r].length; c++){if(C[r][c]=='H'){l[m++]=new int[]{c,r};}}} for(int[]n:l){o(n[0],n[1]);}} static void o(int a, int b){ int[]c=d (a,b);E=c[0];F =c[1];if(E !=0||F !=0){ j(a,b);} } static int[]d(int a,int b){int[][]d={{1,3,4},{2,0,5},{6,8, 7},};int[]e=new int[]{0,0};double f=999;for(int r=-1;r<2;r ++){for(int c=-1;c<2;c++){if(C[b+r][a+c]==' '||C[b+r][a+c] =='O'){int g=a+c-A; int h=b+r-B; double i=Math.sqrt(g*g+h*h );if(i<f){e=new int []{ c,r};f =i;}else if(i==f){if(d[r+1][ c+1]<d[e[1]+1][e[0] +1]){e=new int[]{c, r};}}} }}return e;} static void k(){if( p(E,F,false)){q(E,F );} }static void q( int x,int y){switch (C[B+y][A+x]){ case '~':q(x+E,y+F);case 'H':case ' ':j(A+x- E,B+y- F);}} static boolean p(int x,int y,boolean h){switch (C[B+y][ A+x]){case ' ':return !h; case '~':return h?h:p(x+ E,y +F, false);case 'H':return h?!h:p(x +E , y+ F, true) ;} return h&&C[B+y][A+ x] == '#' ; }static void j(int a,int b) {char c=C[b][a];if( C[b+F][a+E]=='O'){g ();}else if(C[b+F][ a+E]=='H'){D+=2;G-- ;c=C[b][a];C[b][a]= ' ';}else{C[b][a]=C [b+F][a+E];}C[b+F][ a+E]=c;}static void g () { System .out. print("aHHHH!\n"+D) ; System . exit ( 0 ) ; } } ``` --- To run it, try for example: ``` root@host:/cygdrive/c/workspace/project/bin> java C "5 5 > ##### > #O # > # ~ # > # H# > ##### > WWDW" aHHHH! 0 root@host:/cygdrive/c/workspace/project/bin> ``` --- Output of the last big scenario one turn before a beast eats the player: ``` ████████████████████████████████████████████████████████████████████████████████ ██▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓▓▓ ██ ██▓▓▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓▓▓ ▓▓ ██ ██▓▓██ ▓▓▓▓ ▓▓▓▓▓▓▓▓ ▓▓ ▓▓▓▓▓▓▓▓ ▓▓ ▓▓▓▓▓▓ ▓▓██ ██ ▓▓ ▓▓ ▓▓ ▓▓▓▓ ██▓▓▓▓ ▓▓ ██ ██▓▓▓▓ ▓▓▓▓▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ██ ██ ▓▓▓▓ ▓▓ ▓▓ ▓▓ ▓▓▓▓▓▓ ▓▓ ██▓▓ ██ ██ ▓▓▓▓ ██ ▓▓▓▓▓▓ ▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓▓▓ ██ ██ ▓▓ ▓▓ ▓▓▓▓ ▓▓▓▓ ▓▓ ██ ▓▓▓▓ ▓▓ ██ ██ ▓▓▓▓ ▓▓ ▓▓▓▓▓▓ ▓▓▓▓ ├┤ ▓▓▓▓▓▓▓▓ ▓▓ ▓▓██ ██▓▓ ▓▓ ├┤◄►▓▓▓▓▓▓├┤ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓▓▓ ▓▓▓▓██ ██ ▓▓ ██ ▓▓ ▓▓▓▓ ▓▓▓▓▓▓ ▓▓ ▓▓ ▓▓ ██ ▓▓██ ██▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓▓▓▓▓ ██ ██ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓├┤ ▓▓▓▓▓▓ ▓▓ ██ ██ ▓▓▓▓ ▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ██ ██ ▓▓▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓▓▓ ██ ██▓▓ ▓▓ ██ ▓▓▓▓▓▓▓▓ ▓▓ ▓▓▓▓▓▓ ██ ▓▓ ██ ██ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓▓▓ ▓▓ ██ ██ ▓▓ ▓▓ ██▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓██ ██ ▓▓▓▓ ▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ██ ██ ▓▓▓▓▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ██ ██ ▓▓ ▓▓ ▓▓ ▓▓▓▓ ▓▓ ▓▓ ▓▓ ██ ████████████████████████████████████████████████████████████████████████████████ ``` Without silly line spaces: <http://pastebin.com/raw.php?i=QhpxKcCT> So the players way is ending after the moves `RRDDDRRRWW`, because on the last `W`ait, the beast to the left will go to the right to eat the player. --- Another example of the original big map but different moves: <http://pastebin.com/raw.php?i=nBWjC3PZ> See this animation: <http://youtu.be/0DIhEhjWd6s> --- And the last example with original map and different moves (according to the new beast movement rules): <http://pastebin.com/raw.php?i=NNmgzx7U> See on youtube: <http://youtu.be/jXPzL88TU2A> [Answer] # C - ~~1004~~ ~~984~~ 917 Ahh, the beauty of C. Following the spirit of the other answer, I tried to format mine as well :) I imagine there are still some improvements here and there, but this was really fun to write and golf. The character count includes all necessary spaces and new lines. ``` #define M(y,x,c) {t[y][x]=32;t[p][q]=c;y=p;x=q;} #define E {printf("aHHHH!\n%d",Z);exit(0);} #define A sqrt(pow(X-Q,2)+pow(Y-P,2))*30 #define L (char)(m[s]>>8) #define G (char)(m[s]) #define B(b) if(T==b) #define J M(Y,X,79) #define T t[P][Q] r,c,X,Y,H,i,j,k,Z,p,q,P,Q,u,v,s,w,m[99],b[8]={ -1,255,65280,65281,1,511,257,256},t[999][999], x[99],y[99];main(){char N[99];m[85]=b[2];m[68] =256;m[76]=255; m[82]=1; scanf("%d %d",&c,&r); for(;P<r;P++) for(Q=0;Q<c&& scanf("%c",&T );T-10&&T-13? Q++:Q){B(79){ Y=P;X=Q;}B(72 ){y[H]=P ;x[H ++]=Q;}}scanf ("%s",N);for( ;i<strlen(N); i++){s=N[i];P =p=Y+L;Q=q=X+ G;B(32)J B('~') {while(P+=L,Q +=G,T=='~');B (72){u=P+L;v= Q+G;if(t[u][v] ==35||t[u][v] =='~'){Z+=2;T= '~';J}}B(32){ T='~';J}}else B(72)E if(r=!r) for(j=0;j<H;j ++){P=y[j];Q= x[j];if(T-72)continue;v=A;s=0;for(k=0;k<8;k++) {P=y[j]+(char)(b[k]>>8);Q=x[j]+(char)(b[k]);u= A;B(32)if((c=v-u+99)>s){s=c;q=Q;p=P;}B(79)E}if (s)M(y[j],x[j],72)}}printf("%d",Z);}////////// ``` I tested this with all the sample cases and a few more of mine, and it seems to be working properly. If anyone finds any situation in which it doesn't answer properly, please let me know. Input is from stdin, and output to stdout. There are no checks for incorrect input. And, it returns the score if the player gets eaten, or if the player is alive after all movements are executed (even if there are still `H`'s around. Ungolfed version: ``` #define M(y,x,c) {t[y][x]=32;t[p][q]=c;y=p;x=q;} #define E {printf("aHHHH!\n%d",Z);exit(0);} #define A sqrt(pow(X-Q,2)+pow(Y-P,2))*30 #define L (char)(m[s]>>8) #define G (char)(m[s]) #define B(b) if(T==b) #define J M(Y,X,79) #define T t[P][Q] r, c, X, Y, H, i, j, k, Z, p, q, P, Q, u, v, s, w, m[99], b[8] = { -1, 255, 65280, 65281, 1, 511, 257, 256 }, t[999][999], x[99], y[99]; main() { char N[99]; m[85] = b[2]; m[68] = 256; m[76] = 255; m[82] = 1; scanf("%d %d", &c, &r); for (; P < r; P++) for (Q = 0; Q < c && scanf("%c", &T);T-10&&T-13?Q++:Q) { B(79) { Y=P; X=Q; } B(72) { y[H]=P; x[H++]=Q; } } scanf("%s", N); for (; i < strlen(N); i++) { s = N[i]; P = p = Y + L; Q = q = X + G; B(32) J B('~') { while (P += L, Q += G, T=='~'); B(72) { u=P+L; v=Q+G; if(t[u][v]==35||t[u][v]=='~') { Z+=2; T='~'; J } } B(32) { T='~'; J } } else B(72)E if (r = !r) for (j = 0; j < H; j++) { P = y[j]; Q = x[j]; if (T-72) continue; v = A; s = 0; for (k = 0; k < 8; k++) { P = y[j] + (char) (b[k] >> 8); Q = x[j] + (char) (b[k]); u = A; B(32) if ((c = v - u + 99) > s) { s = c; q = Q; p = P; } B(79) E } if (s) M(y[j], x[j], 72) } } printf("%d", Z); } ``` [Answer] # Perl 6: 741 characters, 758 bytes The golfed version is at the bottom, since it's basically linenoise. Above it is my pre-golfed version. Both are interactive (they'll read as many commands from the input file as they can and then move on to using STDIN to get commands). They try to use the original characters and colors. Usage is like `perl6 beast.p6 beast-input`: ``` use Term::ANSIColor; class BeastGame { enum BeastParts <None Player Beast M-Wall S-Wall>; has @.board; has Int $.turn = 0; has Int $.score = 0; method indices (\matcher) { @.board.pairs.map: { .key*i X+ .value[].pairs.map: { .key if .value ~~ matcher } } } multi postcircumfix:<[ ]> (BeastGame \SELF, Complex \c) is rw { SELF.board[c.im][c.re] } has Complex $!player; method player { $!player = $.indices(Player)[0] } method Bool { so $.indices(Player) & $.indices(Beast) } method new (@lines) { my @board = @lines.map: {[ %(' ',<O H ~ #> Z=> None, Player, Beast, M-Wall, S-Wall){ .comb } ]} self.bless: :@board } method gist { state @symbol-map = map {colored .key, .value~' on_black'}, (' ',<◄► ├┤ ▒▒ ██> Z=> <default cyan red green yellow>); @.board.map({ @symbol-map[@$_].join }).join("\n") } method step ($d) { my $direction = %(:W(0), :L(-1+0i), :R(1+0i), :U(-1i), :D(1i)){$d}; $direction // return self; self.move($.player,$direction); if ++$!turn %% 2 { for $.indices(Beast).eager -> $c { for (-1-1i,-1+0i,-1i,1-1i,1+0i,-1+1i,1+1i,1i,0i)\ .sort({abs $c + $^d - $!player}) { last if self.move($c, $_).defined; } } } self; } method move ($cur, $by) { return $cur if $by == 0; my $to = $cur + $by; my &cur-is = { self[$cur] ~~ $^o } my &next-is = { self[$to] ~~ $^o } return if cur-is S-Wall; (self[$to], self[$cur]) = (self[$cur], None) if next-is None # Move wall or cur-is Player | M-Wall and next-is M-Wall and self.move($to, $by) # Kill Player or cur-is Beast and next-is Player # Squish Beast or cur-is M-Wall and next-is Beast and self[$to+$by] ~~ M-Wall|S-Wall and $!score += 2 } } my $width = get.words[1]; my $game = BeastGame.new(lines[^$width]); my @commands = '',lines.comb,{$*IN.get.comb}...*; while $game { $game.step: @commands.shift; print "\e[2J"; print "\e[H"; say $game; } say "aHHHH!" unless $game.player; say $game.score; ``` The golfed version: ``` my ($u,$s,$m)=0,0;my@b=lines[^get.words[1]].map:{[%(' ',<O H ~ #>Z=>^5){.comb}]} my@a='',lines.comb,{$*IN.get.comb}...*;sub g(\c)is rw {@b[c.im][c.re]} my&n=->\o{@b.kv.map:{$^k*i X+$^v[].kv.map:{$^l if $^w==o}}} my&p={$m=n(1)[0]} my&M=->$c,$b{my$t=$c+$b;my&c={$^o==g $c} my&x={$^o==g $t} c(4)??0!!$b??(($c,$t)».&g=(0,g $c) if x(0)||c(1|3)&&x(3)&&M($t,$b)||c(2)&&x(1)||c(3)&&x(2)&&2 <g($t+$b)&&($s+=2))!!1} while n(1)&n(2) {for 1 {M p,%(:W(0),:L(-1),:R(1),:U(-1i),:D(1i)){@a.shift}//last;if $u++%2 {for n(2).eager ->$c{last if M $c,$_ for(-1-1i,-1+0i,-1i,1-1i,1+0i,-1+1i,1+1i,1i,0i).sort({abs $c+$_-$m})}}} say "\e[2J\e[H",join "\n",map {[~] (map {"\e[$^v;40m$^k\e[0m"},' ',<39 ◄► 36 ├┤ 31 ▒▒ 32 ██ 33>)[@$_]},@b} say "aHHHH!" if !p;say $s; ``` Happy Easter! ]
[Question] [ Given a string, like `potatocarrot`, break it into the smallest number of substrings possible. These substrings can consist either be a single character, or one of a list of words passed as input. For example, if `[carrot, potato]` was the input, the optimal way to break the string up would be `[potato][carrot]`. If the list was `[potat, tatocarr, rot]`, the optimal way would be `[p][o][tatocarr][o][t]`. You can take the string in any reasonable format, and the list of substrings in any reasonable format. As for output, any of the following would be examples of allowed output formats: * Inserting characters into the string to delimit substrings (e.g., `"potato,carrot"` or `"[potato][carrot]"`) * Delimiting words, but not individual characters (e.g., `"po[tatocarr]ot"`, but not `"po,tatocarr,ot"`) * Returning an array of substrings (e.g., `["potato", "carrot"]`) You can assume the input strings consist of lowercase letters, and that there won't be duplicates or strings with a length of 0 or 1 in the list of substrings. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) per language wins. **Test cases:** ``` STRING WORDS OPTIMAL SOLUTION potatocarrot potato, carrot [potato][carrot] potatocarrot pot, tatocarr, rot [p][o][tatocarr][o][t] potatocarrot atocarr, ot [p][ot][atocarr][ot] potatocarrot tatocarr, potato, carr [potato][carr][o][t] purpur [p][u][r][p][u][r] purpur carrot [p][u][r][p][u][r] purpur pur [pur][pur] purpur pu, rp [pu][r][pu][r] OR [pu][rp][u][r] purpur pu, rp, urp [pu][r][pu][r] OR [pu][rp][u][r] OR [p][urp][u][r] todoornottodo to, do, or, not [to][do][or][not][to][do] todoornottodo tod, nott, door [t][o][door][nott][o][d][o] ``` [Answer] # [Python](https://www.python.org), 82 bytes ``` f=lambda s,d:s and min([[w,*f(s[len(w):],d)]for w in[*d,*s]if w+"~">s>=w],key=len) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lZLBagMhEIbpNU8hnnRj7iWweYhexYOtkSxNnEVnkVz6Ir3k0r5T8gR5jLq6gXRZyEZEZsbvH-ZHv3_bI-7AnU4_HdrV6_nN1nt9eDeaBGHWgWhnyKFxTMooKsuC3G8di3ythOHKgieRNE5WRlRBNZbEJf2im7CpoxKf22OdaF46X16urW8cMstoC6gRPrT3gFSQtORQSxkd6orzxSNFj98u-niW7o6fg9_3_z_kSNv5tIuqLDltZYLrCzOgbLF9gkxnNxYgGADvAPsg65LH7CmnFLJTNx57WmYGFoseso3y4Lcv9Qc) Depth-first search over solution space. -6 bytes thanks to loopy walt [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 42 bytes [SBCS](https://github.com/abrudz/SBCS) Assumes index origin 0. Takes the string as right argument ⍵ and the word list as left argument ⍺. ``` {e⊃⍨⊃⍋≢¨e←d/⍨(1∧.=≢¨∨∊∘⍺)¨d←⊂∘⍵¨~,⍳1+×⍳≢⍵} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q0591NX8qHcFmOx@1Lno0IrUR20TUvSBYhqGjzqW69mCBR91AFHXo44Zj3p3aR5akQJU86irCczfemhFnc6j3s2G2oenAymgcqBYLQA&f=e9Q31dP/UdsEAy71gvySxJL85MSiovwSdQWFtEe9KxQedbVBxdUV1KFSeFUClcHkgEz8yhHq8CpDMg/FKSAtpUVABFQMAXAtCnjkEL7AoQAkiE8W5K8CIlQoqJeC1ZXkp@TnF@Xll4AY6kj@AnkEJKKeD/JbHthRuBWnQNSUgDUBdQAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) `⍳≢⍵` Indices of the string: `0 1 ... (length-1)` `1+×` Sign of that incremented: `1 2 2 ... 2 2` `,⍳` Indices of an array of that shape, flattened. All these indices have a 0 in the first position and some combination of 1's and 0's after that. `~` Boolean inverse. `d←⊂∘⍵¨` Partition the string according to each of these sequences. This yields a list of all partitions. (Call this `d`) `≢¨∨∊∘⍺ ¨` For each substring in each partition, take the gcd of its length and the boolean indicating whether it is in the word list. This is only 1 if at least one of the values is 1. `1∧.=` For each partition, are all values 1? `e←d/⍨` Only keep partitions where this is the case and call these `e`. `e⊃⍨⊃⍋≢¨` Pick the partition with minimal length. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~60~~ 53 bytes ``` ->s,l,r=""{s=~/^#{r+="(.|"+l*?|+?)}$/?$~[1..-1]:redo} ``` [Try it online!](https://tio.run/##lZNBb4IwFMfvfIqGmUVnxeHBg5ERDx48OJNtyQ5NZ5xoQsJoU8phEf3q7LUFIcBm1kBp/6@//2v6ikg/v/Ojl4@eEhxh4dn2KfEu44@7kxh6dt/J7GH04GdDf3Dujf3ehbiOM3LpTBwCds6jMD4k3nz@vtmuXt@26@XqebldL9YLizO5k2y/E4JJBM3MMaoU04gJUGICtAvEqJQwusKEUwJYGTGTNn4F60lLXFJS4R1wlba@/camr5lTAQ@62VTmlBLgykELbR7SP9DftkAgQHXXgcCx8k7E5NIftHkplD9yKyOM0obbLSOjwKSylixgTMRMqoGqBJx9AC@DWsS1oyGqCgG8DPxjVdBC6HAINCqVERM1B11ApWmHYqp6q32t9YV3TP@146dsn1kIJd6ePGJ3Sp1EipCDEoHiTvFkAhKPQtn38UAB/fuZXjKANRwdCfx01DrnPw "Ruby – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~81~~ 65 bytes ``` /,;/^+%L$w`\b(\w(\w+)?)(\w*;(?(2).*\b\1\b)) $`$1,$3$' 0G`,; ,;.* ``` [Try it online!](https://tio.run/##ZY09DoMwDIV3nyOoCVhQ2tEDI0uPEFWB0qEDuIpccfw0COgPSLb8vvdk29/lMTRlSHTtQoFUXLPkokZnW23HWJmpTBwp6UqfTJ7a1pa2NQaUUyWqszrAsXZIgJSnEMKTpRG@Nd6z0Aw4E2wjXBF36Rps/c/Gz2XoXz4WrXP5tlDsr0Tf/wFGDcIdsx9YJkHxaMfIHqOxi7rJFZzMNw "Retina – Try It Online") Link includes test cases. Explanation: ``` /,;/^+ ``` Repeat until a complete substring list has been found... ``` %L$w`\b(\w(\w+)?)(\w*;(?(2).*\b\1\b)) ``` ... find all of the leading substrings of the rest of the input that are either a single character or are present in the list of words, ... ``` $`$1,$3$' ``` ... and create new substring lists containing each of those substrings. ``` 0G`,; ,;.* ``` Output just the first complete list of substrings. [Answer] # [Python](https://www.python.org), ~~353~~ ~~348~~ ~~342~~ 309 bytes ``` import re,itertools as I def f(s,a): u=[] for e in I.permutations(a): *r,=s for x in e: if x in s: p=0 for _ in"_"*s.count(x): b=s.index(x,p);p=b+len(x);j=''.join(r[b:p]) if j.isalpha():r[b]='<'+r[b];r[p-1]+='>' u+=''.join(r), return min(u,key=lambda x:len(re.sub('<.+?>','',x))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVPNbpwwEFZz5ClGXIyDg9pDpWoX03OeAaHIG4zClrUt_0jkDfIOveTSPlSfpmPDZldKiIQ9ns_fzOcx499_zbN_0ur19U_ww92Pf1--jyejrQcr2eil9VpPDoSD-6yXAwyFY4LuMgi87TIYtAUJo4L7ykh7Cl74UStXJArcWsYd2siaI0tGFMZh8VzywPCvyUbWA-L5Q37rqkcdlC9munDgwF01ql7OxcwM3Rt-KCepcH9_5IRURz2qwraHnenoEoAix2p0YjJPoqA73Os4qUkZF3vbmrtvXclJQ5AdyksKyjKs3Aer4IR-YL_kM5_E6dALmHdR0srKhUNB6qr82RBGCJsppevt3bx46bwDDi0mbnOj8Ub0o7BW-5zB6jO4IPUCNfUCNXnHtiIZnCEGb2h9xhpENmLfotagGnXqc1j9iehF7_rg7459LR0sfpGRlBbv3d5VWRuM1dRomzR9RMFrMCursWnaYjEIW1Sve62t0j4uUtFYZo9DY9lq_Umx0h6HxtOoeHsr8EmSPkX7mEvbBarjMiXwTeR1WZdlse0dA8GWh5T6Jza9xSaKrw0ECNWDqJyZRl8QBoTi2aBNnW7siM8EuRwkFooynKOYXBvy_Kz_Aw) *-5 bytes thanks to ophact* *-33 bytes thanks to pxeger* [Answer] # JavaScript (ES6), ~~104 102 97~~ 96 bytes Expects `(word_list)(string)`. Returns a list of substrings. ``` a=>g=(s,O=o='',...b)=>[s[O.length],...a].every(e=>e&&g(s,O+e,...b,e))|O!=s||b[o&&o.length]?o:o=b ``` [Try it online!](https://tio.run/##rZLNToQwEMfvPgX2wNKI7N2k@AgkXpse@OiihjCklE1MeHfs5y4EWFdjA0M7w/z@03Y@83Pel@Kjk88tVHw6kSknaU2iPs4IkMMhTpKkwCSlPc2Shre1fGfal7OEn7n4ijhJeRjWOuGJm79jjvGYPZJ@HAsKYQg@7xVegBRTCW0PDU8aqKNTRFEHMpeA4gCVuRAgUXAZDEcu7EMYB8djQK2TUetmDxtMDfSZeu7J@0xGFdEH7GJNnhEXpf5EloxeyRvceanLE0F3ncJOvcGNYbiDUI/fx7XegVGF9JNVtaub@hfqLOd@6qCJwybNXHuHfkWzFZpPkL05z42KnYayw1LqrxrWoxb7qrY3KmPBdEzrL0OrSqgAhHLpCXKquk8q9YKSbnU3OscGvHJEaVXgsoF9uOk@HTBwt9R2@gY "JavaScript (Node.js) – Try It Online") [Answer] # Python3, 145 bytes: ``` lambda s,w:min(f(s,w),key=len) f=lambda s,w,c=[]:[c]if''==s else[x for y in w for x in f(s[len(y):],w,c+[y])if s[:len(y)]==y]+f(s[1:],w,c+[s[0]]) ``` [Try it online!](https://tio.run/##dYzBDsIgDEDv@4reoBkxGi9mCVd/AnuYc0TiBgRINr5@Dt3iydvr62t9Tk9nzxcflqu8LUM73h8tRDE1o7Fc85VQvPosh95ipeUvEJ1U1KiOjGZMygj9EHs1g3YBMhgL0wfngusftT7gGRsql7XKhEZDVM1Xk5SZ6pKd9iKqIxEuPhib@JUz71KbXNeG4BIToDaxItskIVb/8jIL2JWAYg/RDybxskXE5Q0) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~73~~ 67 bytes ``` ≔⟦⟦S⟧⟧θ≔⟦⟧ηWS⊞ηιFθ«≔⊟ιζ¿ζF⁺η⟦§ζ⁰⟧F⁼κ✂ζ⁰Lκ⊞θ⁺ι⟦κ✂ζLκ⟧⊞υι»⊟Φυ⁼Lι⌊EυLλ ``` [Try it online!](https://tio.run/##VU87a8MwEJ6jX3HjHajQPVOGFgINGDIaD8ZRrCOKZOvRFpf@dleyHdpqEHf6nup06zvXmnk@hMC9xbo@2iHFc/Rse6SmkTDSXjzQvOq8fmg2CvAflaBKQaOWwJlxdR5wJPgSu01buQGZJEwZ3fEVcCJYWJVJocjqQzzai/rEScIzNbTBL2NqTcCbhLPhTi2ohDdl@6jxRvQIHiUsTpyd/pJ/mdkyRysT1KpIa9VvUeUfxKXgK5uofEG22E1dip/Y8j3d8dQOhbAhhtazn@foLs5562IZRL5EmUV5FPPTu/kB "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list of words and outputs each substring on its own line (default output for an array of substrings). Explanation: ``` ≔⟦⟦S⟧⟧θ ``` Start a breadth-first search with an empty substring list that still has the initial input to processes. ``` ≔⟦⟧ηWS⊞ηι ``` Input the list of words. ``` Fθ« ``` Loop over the list of substring lists. ``` ≔⊟ιζ ``` Remove the remainder of the input from this substring list. ``` ¿ζ ``` If there is still any input left: ``` F⁺η⟦§ζ⁰⟧ ``` For each of the input words, plus the first letter of the remainder of the input, ... ``` F⁼κ✂ζ⁰Lκ ``` ... if the remainder of the input begins with this string, ... ``` ⊞θ⁺ι⟦κ✂ζLκ⟧ ``` ... then push a new substring list obtained by splitting the input after that string. ``` ⊞υι ``` Otherwise, save this substring list. ``` »⊟Φυ⁼Lι⌊EυLλ ``` Output any one shortest substring list. ]
[Question] [ ## Challenge: Given an ASCII art of a (possibly leaky) bowl consisting of a random distinct non-whitespace and non-`~` character, fill it completely with `~` characters. If the bowl is leaky, fill the bottom row below the bowl and a stream of liquid emerging from that, with the intended amount of `~` if the bowl would not have been leaky. For example: *Regular bowl:* | Input | Output | | --- | --- | | ``` # # # # #### ``` | ``` #~~~~~~# #~~~~# #### ``` | *Leaky bowl:* | Input | Output | | --- | --- | | ``` 00 00 00 00 000 0 ``` | ``` 00 00 00 00 ~~000~0~~ ~ ~ ~ ``` | If there wouldn't have been a leak, it could have contained eight `~`. Instead, the bottom row including leak position is now filled with five `~`, and the remaining three `~` are below the leak. (Imagine the bowl standing on a table, so the five `~` at the bottom row of the bowl are on the table, and the `~` vertically below the leak are dripping off the table.) ## Challenge rules: * The potential leak is guaranteed to be at the bottom row, and there will never be any gaps at the sides of a bowl. * The potential leak is guaranteed to be a single character gap. * The character used for the bowl can be any printable ASCII character, except for the `~` and whitespaces. * The bowl can be in an irregular shape (see some of the test cases). * The top ridges of the bowl are guaranteed to be on the same top row, and there will only be two top ridges. * If the bottom row contains more space characters than inside the leaky bowl (see the third leaky bowl test case below), we still fill the entire bottom row of the output regardless, but there won't be any additional `~` below it. * For the sake of this challenge, there won't be any smaller inner bowls (e.g. no doughnut-shaped bowls if we'd imagine it as 3D). So every space in the bowl will always flow towards the leak. (See the fourth leaky bowl test case below, which doesn't have `#~# #` as its second line.) * There also won't be any enclosed blobs at the sides (or inside) of a bowl, not any 'stalagmites' nor 'stalactites'. * The bottom of the bowl won't have a path traveling up and back down. * I/O is flexible. Could be a multi-line string; a list of lines; a character matrix; etc. + You're allowed to pad the input with trailing spaces to make the input a rectangle. + You're allowed to have leading/trailing whitespaces and/or newlines in the output, as long as the expected result is somewhere on the screen. [**Here some examples of invalid bowls based on the rules.**](https://pastebin.com/20NzwGyp) Your program can have unspecified behavior for any of the invalid bowls. If you have a question about a certain bowl-shape, feel free to ask in the comments. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases *Regular bowls:* | Inputs | Outputs | | --- | --- | | ``` # # # # #### ``` | ``` #~~~~~~# #~~~~# #### ``` | | ``` !!! !! !! ! !!! ! !!!! ``` | ``` !!!~~~~~~~~!! !!~~~~~~! !!!~~~! !!!! ``` | | ``` 4 44 4 444444 ``` | ``` 4~~~44~4~444444 ``` | | ``` B B B B B BB B B B BBB ``` | ``` B~B B~~~B B~~~~~BB~~~~~B B~~~B BBB ``` | | ``` sss sss s s s s ssssssssss ``` | ``` sss~~sss s~~s s~s ssssssssss ``` | *Leaky bowls:* | Inputs | Outputs | | --- | --- | | ``` 00 00 00 00 000 0 ``` | ``` 00 00 00 00 ~~000~0~~ ~ ~ ~ ``` | | ``` ^^^ ^ ^^ ^ ^^^ ^ ^ ^ ``` | ``` ^^^ ^ ^^ ^ ^^^ ^~~~~~~~~^~^~ ~ ~ ~ ~ ~ ~ ~ ``` | | ``` @@@ @@@ @ @ ``` | ``` @@@ @@@~~@~@~~ ``` | | ``` # ## # #### # ``` | ``` # ## # ####~# ~ ~ ~ ~ ``` | | ``` xx xxx xx x xx ``` | ``` xx xxx xx x~xx~~ ~ ~ ~ ~ ``` | | ``` 2 22 2 ``` | ``` 2 22~2 ``` | [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 145 bytes [SBCS](https://github.com/abrudz/SBCS) A dfn taking a character matrix. ``` {h w←⍴m←' '=⍵ i←{∪⍵,(⌷∘(0@h⊢m)¨n)/n←⍵~⍨,(⌽q)(-q)q∘.+⍵}⍣≡⊂q+⊃⍸m⍷⍨q←0 1 b←h⌷m ×x←⊃⍸b∧i∊⍨(h-1),¨⍳w:'~'@((h,¨⍸b),x,⍨¨h+⍳d)⊢⍵↑⍨h+d←0⌈(≢i)-+/b '~'@i⊢⍵} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=JY49DoJAEIV7TkHHbgDB1sSEs2xMXApItsLESKGJWQibaKWtWkhskWhjgzd5J3EWqzc/35s3S@wPa@kWJDDPjMRzvTlM76R2A/2gOmBoXtBnFicS9TXjQ5vzKB89fQnTWuCjOAsVV8RNfJpvYG6oLqi3yke9g3lnMC@CFflid@oIUkmHM@d7WtlbIySg7yl0TSCT4ZQHQwvTFTOv9BLG5Ni@BQ9WARFDKymqW3D6iiKxP9JQ@gubgEYzVNeUh34kHGtP/9TmBw&f=XVE7DsIwDN17ild1yMJQ2vCdqs5MiLkSQ8UAEwWprAwMlSpxBiRuwIlyEvxJWoQb5zn2s904u7q5wD2ecN1r4vq36@6HKDLb@nA97c9rE@2YkGPp@o9JIJIgUSAlATzLYpozLY5jeBErHAOoEyOHHEOjGVew5LaWCloRH5xjwUGgpA9eS6lRehgD7Bn/K@XEpmkA2QhkQU31DGIis6n3x9t4@xWnp6nQCcTyG51@G2XMrKoqXI6NcFLQ4A@hCumZ3q8oCrCCAH@D0ZnzC/Dgk6GvBNsWLSmgm8BQWl4mQ0bLfAE&i=AwA&r=tryapl&l=apl-dyalog&m=tradfn&n=f) **Ungolfed:** ``` Fill ← { Height Width ← ⍴ Mask ← ' '=⍵ Fixed ← 0@Height⊢Mask ⍝ The initial interior piece is identified by the first occurence of <wall><no wall> Opening ← ⊂0 1+⊃⍸0 1⍷Mask ⍝ Iteratively expand the interior to the right, left and bottom Deltas ← (1 0)(0 ¯1)(0 1) Volume ← ≢ Interior ← {∪⍵,(⌷∘Fixed¨n)/n←⍵~⍨,Deltas∘.+⍵}⍣≡ Opening Bottom ← Height⌷Mask ⍝ There is an hole when air on the bottom is below an interior point Hole ← ⊃⍸Bottom∧Interior∊⍨(Height-1),¨⍳Width ⍝ If there is no hole, fill the interior 0=Hole: '~'@Interior⊢⍵ ⍝ Otherwise expand the matrix downwards and fill the column below the hole ⍝ and the spaces on the last row Drip ← 0⌈Volume-+/Bottom '~'@((Height,¨⍸Bottom),Hole,⍨¨Height + ⍳Drip)⊢⍵↑⍨Height+Drip } ``` [Read it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=VVOxbtswEN3zFbfZgpRGWoukCIIiaIYiS9HOtETHRGnSoJjKQZEMLRAoggW0W5YOdYcYWTqkhTv7U/glvSMl151E3Z3eu/cedSqkBHf7BT7uAbzi4mJi4Z0o7MQXXfsLXrPyvX8ZwODItb9x7lTMeQHgq@lx@Mo1S5rErmu/wZsJB6GEFUzi03IjtIGZ4DmWSxAFV1aMBYKMrsDi7FiY0oLO80vDFQ7pMRxWTMoXh0qDPyDw@YwroS7CZs2nFLLYNZ9d@wdPrl3v0J8hI7PiA5dXwOczpgrPst3Eav9uaPEEJB9boJmRtlZPEeMll5aVQeAwgzQaprD5mdEji7D/VsvLKQ99d7eEsx7YO@nqR/QpGbrF2tX33qzNSkUHCrvYuHHtKgkM2H4WY@natT/c3fdeITKc@FUCQ2fwYv2/wcZ7yRRMtORQTbgCJgxo5bUFLTQx4lJXNPcvCI1Hyps@7HIMTgZaVz/0ilzd4LrDsMJ@FiWblWuf/A3pvR4TX1gGw6JlEswTr9Wu5TicHhHfcxjcDI638M0yXClCOiecSpR8N7Mps0bModCVqpgpSh/UFj6nIFQnkQpE38H1COWM5bzsfZEML5rRFaVsxKyXn7pFHVLdjw9O@ntAqw478V55Z1CUkJQEndmsup8mRs4nQoyCJnf7FduhGVN97/ov&f=XVE7DsIwDN17ild1yMJQSvhOVQcmJsRciaFCiE4UpLIyMCAhcQYkbsCJchL8SVqEG@c59rPdOJuqOcHdnnD318A93u5@Xe7rOorMutqd6@1xYaINc0aYucfHJBBJkCiQkgCeZTEcMS2OY3gRKxwDqBM9hxxdozFXsOS2lgpaER@cYMpBoKAPXgupUXjoA@zp/yvlxKZpANkIZEFN9XRiIrOqtodLf/s5p6ep0AnE8hudfhtlzCzLMlyOjXBS0OAPoQzpmd4vz3OwggB/g9GZ8wvw4JOurwTbFi0poJtAV1peJkNGy3wB&i=AwA&r=tryapl&l=apl-dyalog&m=tradfn&n=f) Apparently this doesn't run with the comments on there, so if you want to have to run this version, you'll have to remove the comments. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 76 bytes ``` WS⊞υι≔Eυ⭆ι⎇∧∧⁻…ιμ ⁻✂ιμLι¹ ⁼ λ~λη¿⁼§η±¹⊟υη«υ≔⊟ηζ⟦⭆ζ⎇⁼ ι~ι⟧E⁻№⪫ηω~№KA~⭆ζ§ ~⁼~λ ``` [Try it online!](https://tio.run/##TVDBasMwDD03XyFyksGD9LxTKDt0rCPQ3cYOIfViU8/pYntdO7Zfz6Q4IQ1Elp6e0HtqdN03XW2H4ayNVYBbd4phH3rjWhQCqug1RglG3Gel96Z1uKtPjCQOF0bCi@pd3V@wdIfx3xkXPW4ujVUb3Y2UDyEhh5xiau6tadTYkPCkXBs0GmquJxo9D5@xth6pkmAZyP9SRqkmPeYdcOKUYesO6hu1hGfV1kHhmlkVrY6CbZDWgDykrFfwk60SEglZTb6YrGnoylhqvy4mr4vJW11mlmWEeFsGeWK6QRepfuyMY3HnRKeY8EqpY2ktTrC4PSttnG3lwCvmvfMVBO37HYaiAP6KIoMxpZBxLICqbLj7sv8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a rectangular list of newline-terminated strings. Explanation: ``` WS⊞υι≔ ``` Input the bowl. ``` Eυ⭆ι⎇∧∧⁻…ιμ ⁻✂ιμLι¹ ⁼ λ~λη ``` Try to fill the bowl with water. ``` ¿⁼§η±¹⊟υη« ``` If the bowl isn't leaky, then output the filled bowl. Otherwise: ``` υ ``` Output all but the last row of the bowl. ``` ≔⊟ηζ ``` Get the last row of the leaky bowl. ``` ⟦⭆ζ⎇⁼ ι~ι⟧ ``` Flood it and output the result. ``` E⁻№⪫ηω~№KA~⭆ζ§ ~⁼~λ ``` Count how much extra water there is and output just the hole of the last row of the leaky bowl for each extra line needed. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~256 251~~ 223 bytes ``` lambda s:[[*map(F,s)],s+[(b:=s.pop()).replace(E,W)]+[E*(h:=F(''.join(map(max,zip(b,s[-1])))).find(W))+W]*(sum(F(x).count(W)for x in s)-b.count(E))][h>-1] E,W=' ~' F=lambda s:E*(len(s)-len(s.lstrip()))+s.strip().replace(E,W) ``` [Try it online!](https://tio.run/##rVLbbuIwEH33VwziAbvQiLY8rJCyQkjlF/qQJigQs6SbixUHNd0H/zo741wINLvqSusk47mdmeOJ1Ud5zLOnb6o4H9zXcxKmuygEvfS8uzRUfDPTwp/pqcd3S1c7KldcCKeQKgn3kj/PXoQ/9Z7v@HHpbvhk4rzlccYJmIbV7Fes@G6mvfsHX@ByDnEW8Rchpi/@HdenlG94JZx9fspKdB/yAiqIM9Diftd4n4XwveN3LMCwlzsBM2EbtyOJjROZcQTYzUl0WcTEUEy10@hXZM@RPIAKo@0uf084CbFkAEh2ixXAJc3SR2sGNi4wXsjyVGTgJXEmneTtpEveQAQQbfITcwL4jFGTQrZdqAMpWN3zGbwf40TCA7WtcS4i1akkpg1lCsUHyPLSZthUgB2W/EkqFXNCpSROk@KY3xC8PhljvV4yVeXHtuHRI0ehSsl9KaPtIU4SGQ0lXRXYpnFR5IWM6EREwFsu8Q9dTeKS7f@hw5eqDOB8InPN9MAv7ehAYyjiH8eSxmHLyVB/wD5PVVjEOs6zTwW6ufXc9tCqiPEWTl6z5mb346KLX7Srsu4gf3HDvz@H/kE6/7@fqF9y6GhXpT8R76Hdv/850Z@Qe7NwZhg/j@3dhTEDq42BToMLgLGxsYtidu/HRqMRNGs0YlY2FrDGO@pZtWNUA02zWmBjXYA96wJcoLpAuSBJC12YiIZZmM4FsMYHwSjwY2tbYt3trR/FmvJIMTUAixHAkll3e@vvAFprABTo0fYlotoquls2zZgmDZUmzdymzeeW2HzOwKooGMk5zKnZUNgYDJu5MfWEDAAMaiwIgnaGAflbM6iT6nDQzTnA58ug9h8G@HQVqO9/NthqtQL80It732HMCh@D19Te3zHeXZRjkrcuusJUbkCyqoKqYhVarUQbBgOmquqhD1d6hEf71YpB5Tc "Python 3.8 (pre-release) – Try It Online") A function taking in a list of strings representing an empty bowl, and output a list of strings representing the filled bowl. The input must be padded with whitespaces so that each line is the same length. # Explanation `F` is a helper functions for filling a line with water between the walls. This is done by stripping all leading and trailing whitespaces, replace the remaining whitespaces with water, then add the leading whitespaces back. `f` is the main function, and has the structure: `[answer_if_not_leak, answer_if_leak][has_leak]` * `h:=F(''.join(map(max,zip(b,s[-1])))).find(W)` is the the index of the hole. This is done by first merging the walls of the bottom 2 lines (`b` and `s[-1]`), then fill the merged line with water. The only position that has water must be the hole: ``` L1 | xxx xx | L2 | xxxx xxxx | Merged | xxxxxx xxxxxx | Filled | xxxxxx~xxxxxxx | ``` * If the bowl doesn't leak, there's no hole. So `h>-1` indicates that there's a leak. * If no leak, simply applies `F` to each line * If there is a leak, we returns a list consists of: + Every line except the bottom: `s` (note that we used `b:=s.pop()` so the bottom is already removed) + The bottom, with all whitespaces replaced with water: `[(b:=s.pop()).replace(E,W)]` + The rows representing leaking water stream: `[E*h+W]*number_of_water_in_the_stream` [Answer] # Python3, 522 bytes: ``` from re import* r=range g=lambda x:[i for i in r(len(x))if i and i<len(x)-1 and findall('^(?:[^\s]|\s)\s+$',''.join(x[i]))and any(d!=' ' for d in x[i-1][1:])and any(d!=' ' for d in x[i+1][1:])] f=lambda x:'\n'.join(sub('(?<=[^\s])\s+(?=[^\s])',lambda x:'~'*len(x.group()),l)for l in k)if not(j:=g([*zip(*(k:=x.split('\n')))]))else'\n'.join(k[:-1]+[sub(' ','~',k[-1])]+[' '*j[0]+'~'+' '*(len(k[-1])-j[0]+1) for _ in r(sum(len(findall('(?<=[^\s])\s+(?=[^\s])',n)[0])for n in k[:-1])-k[-1].count(' ')+(k[-1].count(' ')==1))]) ``` [Try it online!](https://tio.run/##fVBtj6IwEP7eXzHIJW1FDez54UKWaPwbCBf2FK@KhVBM2Mtl/7o3M6JuNnotfZiXp/PMtHnvftf2@4@mPZ/Ltj5CuwVzbOq2G4s2aQu724pdUhXHt00BfZwaKOsWDBgLraq2VvVamxIDhd2Aeb1EphG7pbGboqqUzNUiTvO1y/6unV674JucSDnb1wbJqcm0JnZh39XGSyRIltiQBGanUZZGcfY/SjBQMlHeO5VrO0i405uSavGacAukrxaDLSd3/occc/ezXVufGqX1pNKkUpHKgYa0daf2cbJT6fiPadRYHeKkn7mmMp0iOa01zrKt3PYufkhjnCBIuQnAuT/k5JBiSGMQA@N9GmYBRgNy@EUv6SknIs2T/ry8tzsdmXF72GdTWY2XuXvL3XMTesqVZ7/qk@2oGR2or5EkiWiIs0tGo1EYAq0wFMAmgiAMAT3Mi6Y1eK9UTmvBN/I8h2HlgiD/5JCb3x2ycD@ss1wuAQ8S8f9Ey8cCvvDBJ/QRH7L6Hvpe9Mi9IvpPKr7Ai8DzVI0FgS2fXsIn2celPM@7Dul5gnHwQAxR75N3CXiPa80xOxdzmBPSesgCWOHGegh4xIqrrm7/axxhtXrStXMOAAFJjj/qzrHhbuvLzfM/) [Answer] # [J](https://www.jsoftware.com/),(Version 903) 270 bytes ``` fb=:{{((y~:' ')+.(*./\"1 &.|."1 y=' ')+.(*./\"1 y=' '))}'~',:y}} l=:{{'~' e. {."1 (]#~"1' '&~:) |."1|: fb y}} flb=:{{ lr=.{:I.+./"1 '~'= fy=.fb y lb=.(lr{(' '=y)} y,:'~') lr} y r=.('~'=lr{fy){' ~' c=.-/+/"1^:2 '~'=fy ,: lb lb, ((c,#r)$r) }} cgb=:{{>(l y){(fb y);flb y}} ``` With comments: ``` NB. FillBowl fb=:{{((y~:' ')+.(*./\"1 &.|."1 y=' ')+.(*./\"1 y=' '))}'~',:y}} NB. LeakyBowl? l=:{{'~' e. {."1 (]#~"1' '&~:) |."1|: fb y}} NB. Fill Leaky Bowl flb=:{{ lr=.{:I.+./"1 '~'= fy=.fb y NB. leak row lb=.(lr{(' '=y)} y,:'~') lr} y r=.('~'=lr{fy){' ~' NB. dripping row c=.-/+/"1^:2 '~'=fy ,: lb NB. add c dripping rows lb, ((c,#r)$r) }} cgb=:{{>(l y){(fb y);flb y}} NB. Code Golf Bowl solution ``` # [J](http://jsoftware.com/),(Version 806) 320 bytes tio.run currently only has an older version of j without the direct definition syntax: ``` fb=:3 : 0 ((y~:' ')+.(*./\"1 &.|."1 y=' ')+.(*./\"1 y=' '))}'~',:y ) l=:3 : 0 '~' e. {."1 (]#~"1' '&~:) |."1|: fb y ) flb=:3 : 0 lr=.{:I.+./"1 '~'= fy=.fb y lb=.(lr{(' '=y)} y,:'~') lr} y r=.('~'=lr{fy){' ~' c=.-/+/"1^:2 '~'=fy ,: lb lb, ((c,#r)$r) ) cgb=:3 : 0 >(l y){(fb y);flb y ) echo b1 ; cgb b1 echo lb1 ; cgb lb1 ``` [Try it online!](https://tio.run/##fU5BTsMwELz7FZMGNTYNjlNurtwjEhJPACMlakqRBSjtxUqbr4e1k0Zw6Vqyd8czs/M5VKXR7@VFbl@ecPxxh9Px1B6@9lDQUCxFrJQhnV6kVEwwVq1vCZMkwVRJwuI9TWATmvyZRoAmMna3IykV6UoxxDY0dCn6iuKbsay11302bL6Odowxfts5k6VDrkNTGf0YDTj3vc6QiZXk97J4XZRYyrOkx5v/8DiLS9Znufbk4q4ehGAn0QUVf0v7RUnMZa8FgtFZo6kQBI2b17rWyE4/y5UsSEQGBo03MhKJJblrO04uxosLfK6JIeBa6hkpeRAQo/Giy9BnrDbyoViRldXr6NZ45BquIrMcnNd52oq7VlCIej@H2HIHcuBhq9hQupiS7eqPb1QlNiAuNSPgZoS6YfgF "J – Try It Online") ## Explanation I'm still relatively new to J and this solution could probably be made shorter again by someone with more experience golfing in J. We define three helper verbs (J terminology for functions) `fb` "FillBowl", `l` "IsBowlLeaky?" and `flb` "FillLeakyBowl" and then finally a main verb `cgb` "CodeGolfBowl" to tie them all together. All three verbs take a rectangular 2 dimensional array of characters as argument y. ### `fb` "FillBowl" ``` fb=:{{((y~:' ')+.(*./\"1 &.|."1 y=' ')+.(*./\"1 y=' '))}'~',:y}} ``` `fb` creates a boolean mask of not-spaces and spaces from the sides and then uses the mask to index into either water ('~' array) or the original argument. Eg: ``` y # # # # #### ((y~:' ')+.(*./\"1 &.|."1 y=' ')+.(*./\"1 y=' ')) 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 ``` ### `l` "IsBowlLeaky?" ``` l=:{{'~' e. {."1 (]#~"1' '&~:) |."1|: fb y}} ``` `l` fills the bowl ignoring whether it leaks or not and then checks if the bottom non-whitespace row contains any water ('~' chars). If it does then the bowl is leaky. To check for the leak we transpose the array to the right, delete leading spaces and then check if any water '~' is in the first column. Eg: ``` y 00 00 00 00 000 0 fb y 00~~~~~00 00~~~00 000~0 (]#~"1 ' '&~:) |."1 |: fb y 0 00 00~ 0~~ 0~~ ~~~ 00~ 00 0 ``` ### `flb` "FillLeakyBowl" ``` flb=:{{ lr=.{:I.+./"1 '~'= fy=.fb y lb=.(lr{(' '=y)} y,:'~') lr} y r=.('~'=lr{fy){' ~' c=.-/+/"1^:2 '~'=fy ,: lb lb, ((c,#r)$r) }} ``` `flb` proceeds with the following logic: * Find the leaky row index `lr` * Create the leakybowl array `lb` with the leaky row flooded * Create the dripping row `r` with the drip in the correct location * Count `c` how many water drops are missing * Append `c` dripping rows `r` to the leakybowl array `lb` ### `cgb` "CodeGolfBowl" ``` cgb=:{{>(l y){(fb y);flb y}} ``` Finally our `cgb` verb combines everything together with the following logic: * Create a boxed array of both the filledbowl and filledleakybowl solutions `(fb y);flb y` * Check if the bowl is leaky `(l y)` and use the boolean 0 or 1 as the index into the previous boxed array Eg: ``` y 00 00 00 00 000 0 (fb y);flb y ┌─────────┬─────────┐ │00~~~~~00│00 00│ │ 00~~~00 │ 00 00 │ │ 000~0 │~~000~0~~│ │ │ ~ │ │ │ ~ │ │ │ ~ │ │ │ ~ │ └─────────┴─────────┘ ``` For more information on this fascinating and fun language the J wiki has a huge amount of information and also links to quite a few free books: * [GettingStarted](https://code.jsoftware.com/wiki/Guides/GettingStarted) * [Books](https://code.jsoftware.com/wiki/Books) [Answer] # Python 3, 387 365 bytes ``` from re import* def l(b): s=b[-1];r=search;l=len;m=r("^( *[^ ]+)(.*?)([^ ]+ *$)",b[-2]) if r("^.{"+str(l(m.group(1)))+"}[^ ]{"+str(l(m.group(2)))+"}",s):b=[r("^ *(?=[^ ])",x).group(0)+x.strip().replace(" ","~")for x in b] else:b[-1]=s.replace(" ","~");b+=[" "*l(r("^( *[^ ]+)",s).group(0))+"~"]*(sum([x.strip().count(" ")for x in b[:-1]])-s.count(" ")) return b ``` [Try it online!](https://tio.run/##zVfbjtowEH3PVxhTqTZQlKU8VKBoKVLbD@i@ZZOKi9lNFZLIDlWqqv51OnYuC8QpRm2lOpCEMzNnLg7RTPY9f06Tt@8yfjzueLpHnKFon6U8HzhbtkMxWdOZg2AJb@2/uQvm3BNsxTfP89iLWTLfe5zgkKCBH6JgSMl4cE@JvkeDVxSPwGgS0Ept/AMPRc5JTPbjJ54eMnJHKR3in8qgJZuUMjwSVEcQ7dB@tvZ8xYQG5N5TVuCioJWBS4fFGDiijNAxZ1m82jCCER5hieku5ahAUYLWgWZjsWAznZInWsrz9dDz4ccgJmfpqVgaZxCcxMGAiMOe@C@ON@khyRXTiUt/Bn4C@kacSMukOMsPPMGPCR5/TaMEyn3Mmci/bFaCCeQhX2sRfVbLb@7Uwv3y2sejcxxpQR@1cNSHBTcNHIxQJ7nUy0CuYRtyOvp9/L1er77v9dp8qBb3DM60uNctLOU9u1xBUVarI5BK2BlIt9AQyLW6TOE0vSSboqkBVMsqxSlE2DaXU3mV81q0CC3haCcPGHwv4aW@LC3hDhLAlkvL5xh0pTE8KIghPL3PS0u4g6Qd3rUaCiHgJStEm0noj@HJEiZcNMuqNqAnpdkt4Ga30tbttZxdV19dt@VFS@DUdu8C6lpu/O38UgK/dKU0/pFvQ@3rEIZhfR8ayGppaHRUGoddb54QDqti/Ysg6ldqCEdXgOj/ltjv4mKxQPBtcwFs@cB2UEi5gOOWWPqmpqAPDUEb7CvQqh24hdPQNZjrbI/ZZ18UqCguOQo42YFgbLlff@hIFoWUf71OI/tCTdDkkkJBNqmbTOWpKXUCx8lWouxjH/iBOaohjkZINbiqLWbJYc/4KmfkpeWtpo2MR6pNfkwekwelrWQzyG@I1IwQVc0zKzK2ydkW@F86aMXl3wV1e71h0TetEZcSt5LUHvIPFckMGCr@mpfSi2DyT2l@olezt8OBeYBXAwFqxoBaPhZZHGlCTIPLMI2WtbxtqUuqVVbJEyMwkp1EP2t2A2anJM2bCPwoQJ7X0MLP2dlWNtv2cQVjkuOAeQmd7c77OC73shxWtMYWU0ePVqeKn9M9O9XcRtvkda4NMD3@Ag "Python 3.8 (pre-release) – Try It Online") Takes input as a list of strings and returns a string representation of the bowl. The first line sets up variables and then checks for bowl leaky-ness. The second line deals with non-leaky bowls, replacing spaces from the whitespace trimmed version of each line with `~`. The third line deals with leaky bowls, first filling the bottom row with water, then adding extra lines on the bottom as many times as is necessary. Just out of interest, this answer, and I would guess most, are able to use bowls made of `~` characters, it is just confusing to look at. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 315 308 303 bytes ``` e=enumerate def f(b): for y,l in e(b): s=0 for x,c in e(l): if c==" ": if s and(L:=b[y])[x:].strip(): if y<len(b)-1:b[y]=L[:x]+"~"+L[x+1:] else:return[n.replace("~"," ")for n in b[:y]]+[l.replace(" ","~")]+[" "*x+"~"]*max(0,"".join(b).count("~")-l.count(" ")) else:s=1 return b ``` [Try it online!](https://tio.run/##RU9BjoQgELz7ig4XYXTMmL1syPIDf8Biog5m3TBIQBO8zNddEM12J6Srq7q6MdvyM@uPT2P3XTKp15e03SKzpxxhxD2hGYyzha1UMGmQqQOOPcIbCV8OiVAHAdMIA2MI0IEidNDpJ24o6/kmCPdUVG6xk8Fp4NBsX0rq4H2vaVSxhlMvCvRGRcN9UVORlFI5Sa1cVqu5rqw0qhskDrIyLCTxHB2P6TndhCi4@pdAkLwRCc1Q3ny0FrdX5/GjRKj6nae4vRrmVS/Rj9zVBYIxya7djtUZpAOg342douJbnw4jzvO8bVs4o41zF2zTFxJ9gliFDFOVM2pKXiTE/gc "Python 3.8 (pre-release) – Try It Online") Takes a list of strings (each representing a line) and outputs a modified version of that list. Input must be padded to a rectangle. Not the smallest Python solution here, but I wanted to try a more standard iterative approach. If anyone has ideas on how to make it smaller it'd be much appreciated! [Answer] # [JavaScript (Node.js)](https://nodejs.org), 314 bytes ``` (r,l=r.pop(),w=t=>t.replace(/ /g,'~'),m=r.reduce((a,c)=>a+(s=t=>t.split` `.length-1)(c.trim()),0))=>((q=l.trim()).search` `>0|q.length<s([...r].pop().trim())?[r,w(l),[...Array((m-=s(l))<0?0:m)].map(_=>'~'.padStart(l.search`\\S `+2))]:[r.map(v=>v.trimEnd().replace(/( *\S)( +)/g,(_,x,y)=>x+w(y))),l]).flat().join` ` ``` [Try it online!](https://tio.run/##PVBBbsIwELznFb5ltzEm9Ag4qIe@gCOJiJUYCHISY7sQpKpfTxdoerHk2Zmd2Tmrq/KVa2yYdX2tx6rvfGAHOYLjRjphewvIbzLILAinrVGVhjmbH3n8EyNvieJ0/UUgKF6hzFQC/sX21jShZKUwujuG02yBUIngmhYQeYrEBbhIM0HCa@WqEwmy9PvyJ1p72AkhXPEKMnE3O8dvYJA/hh/OqTtAO5OeIFynm3TZYiFaZWEvM8oprKq3QbkAZnLJ8y0rk3fEYrlzT@pVZtfn/s@uJqf/W4G95VsEliAdDXs@8DtFH5Ib3JEOMQWKg1GBJOe@6cqoHFdR9KixN1qY/ggHKKNhYMMQDYyx6aU/Y1EpvGnIZcGpnldjEOddTJtX4y8 "JavaScript (Node.js) – Try It Online") Expects input as an array of strings, each representing a line. Outputs a string with the bowl. ]
[Question] [ Consider a linear system of equations, in \$n\$ unknowns, expressed as $$A \textbf x = \textbf b$$ where \$A \in M\_{n,n}(\mathbb Z)\$ is an \$n \times n\$ matrix of integers, \$\textbf x\$ is a column vector of unknowns \$(x\_1, x\_2, \dots, x\_n)\$ and \$\textbf b = (b\_1, b\_2, \dots, b\_n)\$ is a column vector of integers. We can consider the "augmented" matrix of this system as $$A' = \begin{pmatrix} a\_{11} & \cdots & a\_{1n} & b\_1 \\ a\_{21} & \cdots & a\_{2n} & b\_2 \\ \vdots & \ddots & \vdots & \vdots \\ a\_{n1} & \cdots & a\_{nn} & b\_n \end{pmatrix} $$ That is, the matrix \$A\$ but with an additional column vector \$\textbf b\$ as its final column. Let the \$i\$th row of \$A'\$ be represented as \$R\_i\$ There are three elementary row operations we can do to the rows of \$A'\$ that leave the solution set \$\textbf x\$ unchanged: * Swapping the order of two rows (\$R\_i \leftrightarrow R\_j\$) * Multiplying a row by a constant \$\lambda\$ (\$R\_i \to \lambda R\_i\$) * Adding a multiple of row to a given row (\$R\_i \to R\_i + \lambda R\_j\$) For example, we can say that the two following matrices are equivalent under these row operations: $$ \begin{pmatrix} 7 & 0 & 0 \\ -3 & -1 & 7 \\ 8 & 0 & -9 \\ \end{pmatrix} \equiv \begin{pmatrix} 8 & 0 & -9 \\ 5 & -1 & -2 \\ 1 & 0 & 0 \\ \end{pmatrix} $$ (The specific row operations here are \$R\_1 \to \frac 1 7 R\_1\$, \$R\_1 \leftrightarrow R\_3\$, \$R\_2 \to R\_2 + R\_1\$) --- Consider the \$n\times n\$ identity matrices: $$ I\_1 = \begin{pmatrix} 1 \end{pmatrix} \\ I\_2 = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \\ I\_3 = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{pmatrix} \\ \vdots $$ i.e. a given cell \$(I\_n)\_{ij}\$ is \$1\$ if \$i = j\$ and \$0\$ otherwise. We'll say that an integer matrix is an "elementary matrix" if it is **exactly one** elementary row operation away from the identity matrix. For example, the following are all elementary matrices (with the row operation shown) $$\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \tag{$R\_1 \leftrightarrow R\_2$}$$ $$\begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 3 \\ 0 & 0 & 1 \end{pmatrix} \tag{$R\_2 \to R\_2 + 3R\_3$}$$ $$\begin{pmatrix} -5 \end{pmatrix} \tag{$R\_1 \to -5R\_1$}$$ $$\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & -1 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} \tag{$R\_2 \to R\_2 - R\_4$}$$ $$\begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \tag{$R\_1 \to R\_1$}$$ However, none of these matrices are elementary matrices, as they all require 2 or more row operations from an identity matrix (some row operations shown): $$\begin{pmatrix} 0 & 2 \\ 1 & 0 \end{pmatrix} \tag{$R\_1 \leftrightarrow R\_2$, $R\_1 \to 2R\_1$}$$ $$\begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{pmatrix}$$ $$\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 1 & 0 & 0 \end{pmatrix} \tag{$R\_2 \leftrightarrow R\_4$, $R\_3 \leftrightarrow R\_4$}$$ --- You are to take a square \$n \times n\$ integer matrix and indicate whether it is an elementary matrix or not. This indication can either be: * Two consistent distinct values to indicate whether the input is or isn't an elementary matrix (e.g. `True`/`False`, `1`/`0`, `"a"`/`7`, etc.) * Two classes of values, which are naturally interpreted as truthy and falsey values in your language (e.g. `0` and non-zero integers, and empty vs non-empty list etc.) You may take input in any [standard manner or format](https://codegolf.meta.stackexchange.com/q/2447/66833), including taking \$n\$ as an optional input. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Test cases | Input | Output | | --- | --- | | ``` 0 11 0 ``` | `True` | | ``` 1 0 00 1 30 0 1 ``` | `True` | | ``` -5 ``` | `True` | | ``` 1 0 0 00 1 0 -10 0 1 00 0 0 1 ``` | `True` | | ``` 1 00 1 ``` | `True` | | ``` 0 0 00 1 00 0 1 ``` | `True` | | ``` 0 21 0 ``` | `False` | | ``` 1 2 34 5 67 8 9 ``` | `False` | | ``` 1 0 0 00 0 1 00 0 0 10 1 0 0 ``` | `False` | | ``` 2 0 00 0 10 1 0 ``` | `False` | | ``` 1 1 10 1 00 0 1 ``` | `False` | [Answer] # [Python 3](https://docs.python.org/3/) + numpy, 84 bytes ``` lambda m:sum(m!=eye(len(m)))-3*all((m*m==m)*(m@m==eye(len(m))))<2 from numpy import* ``` [Try it online!](https://tio.run/##XU/JbsMgED2Xr5hyAje27KTpEhWpvfQLfMyFtFhBYgBhfPDXu3hrnV5g5m08fB@vzh6GRpwHI/HyLQFPbYcM74XqFTPKMuSc54dMGsMYZigE8ozhexq2Cv62J01wCLZD34NG70LMhvleQNmC9aQWlFJSQkUqKAm5q0OnyDinLaFwSOfIrkx@vBUtshLyalZOwK1nxv72je1fegn7pcenNO1k3acKj3CEJ/IML/C6pdac21fnOr8Z6XtF642OjKqzpZw0LkAEbaE@EQC9cyAgFm0M2jO@Ss920gI44VZOCJpa0tEkrC9QRqZXjhcfRVDtVXrF8mqniy/X2SmH8odqDPJBJ0DvGqZTkuOEDD8 "Python 3 – Try It Online") I'll get things started. No idea how good this is. Criterion: If the matrix differs from the identity in one or zero places return True. Otherwise allow up to four if the matrix has only ones and zeroes and is its own inverse. Not 100% sure this is tight. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~41~~ 31 bytes ``` ⊙θ⊙謋⁼κμΣEθΣEν¬⁼π⁼ξ⎇⁼ρκμ⎇⁼ρμκρ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxr1KjUEcBSvnll2j4pBYXa7gWlibmFGtk6yjkauooBJfmavgmFoBUwJh5EMVQdQU6ClBWhY5CSGpRXmJRJUyuSEchG2hGLjYJkOFAO4o0UYD1///R0dGGOgoGQBSrw6WgEA1kAfnGcA6IHxsb@1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if elementary, nothing if not. Explanation: There must be a pair of rows such that the number of differences between the input and the identity matrix with the pair of rows swapped must not exceed zero if the rows are different or one if the rows are the same (i.e. there can be one difference between the input and the identity matrix). ``` ⊙θ⊙θ Any two rows satisfy ⁼κμ Same rows ¬‹ Is not less than Eθ Eι Map over input matrix π Current element ¬⁼ Does not equal ⁼ξ Identity matrix ⎇⁼ρκμ⎇⁼ρμκρ With rows swapped Σ Σ Take the sum Implicitly print ``` [Answer] # JavaScript (ES6), 92 bytes Returns a Boolean value. ``` m=>m.some((P,p)=>m.some((Q,q)=>m.map((r,y)=>(y-p?y-q?r:P:Q).map(v=>e+=v!=!y--),e=p!=q)|e<2)) ``` [Try it online!](https://tio.run/##VY1Lb4MwEITv/IqFS7wKJkCaPtKanNpjlSjXXCgxKRXGYBMk1Pa3U4eHkl7Wnm9mZ7/iJtaJysqaFvLIu5R1gkXC01JwQrZuiVe1c6teibgkRLmtEaSl5aal1Uatt@sd9lbDIj5njc3sllJ0OSttVuEPfwkRO8Wrc6Y4maV6hp7i8fEty/m@LRLio1fLfa2y4kTQ02We1cQ5FIfCQS@V6jVOPokGFsG3BZDzGgQw0NegM5zvIxNeHPR8MfD3s/jgCvHZbCey0DLnXi5PJCUC0frFzofACsC3LsM8RsLSzAu26GrEo@EDDQavB2NqEOZzE5wafAin9tD03sEK7q0HeISn2@b/hcMl/w8 "JavaScript (Node.js) – Try It Online") ### Commented ``` m => // m[] = input matrix m.some((P, p) => // for each row P[] at position p in m[]: m.some((Q, q) => // for each row Q[] at position q in m[]: m.map((r, y) => // for each row r[] at position y in m[]: ( // select the relevant row: y - p ? // if y is not equal to p: y - q ? // if y is not equal to q: r // use r[] : // else: P // use P[] (swapped with Q[]) : // else: Q // use Q[] (swapped with P[]) ).map(v => // for each value v in this row: e += // increment e if ... v != !y-- // ... v is not equal to the expected // value in the identity matrix ), // end of inner map() e = p != q // start with e = 1 if two rows were // actually swapped, or 0 otherwise ) // end of outer map() | e < 2 // yield true if e is less than 2 ) // end of inner some() ) // end of outer some() ``` [Answer] # [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), ~~315~~ ~~302~~ ~~286~~ ~~277~~ ~~276~~ ~~273~~ 268 bytes ``` mod E is pr LIST{Int}. ops e i : Int ~> Int . var A B N X Y Z :[Int]. ceq e(N X A Y B Z)= 1 if(size(X)rem N + size(Y)rem N)size(A)size(B)i(N 0)X B Y A Z = 0 N N i(N(N ^ 2)). ceq e(N X A Y)= 1 if i(N 0)X I:Int Y := i(N(N ^ 2)). eq i(N s A)= i(N A)(0 ^(A rem s N)). endm ``` The result is obtained by reducing the `e` function with the width \$n\$ prepended to the matrix as a flattened list. The output is either the constant `1` for true, or an error term of sort `[List{Int}]` for false. ### Example Session ``` Maude> --- True > red e( > 2 > 0 1 > 1 0 > ) . result NzNat: 1 Maude> > --- True > red e( > 3 > 1 0 0 > 0 1 3 > 0 0 1 > ) . result NzNat: 1 Maude> > --- True > red e( > 1 > -5 > ) . result NzNat: 1 Maude> > --- True > red e( > 4 > 1 0 0 0 > 0 1 0 -1 > 0 0 1 0 > 0 0 0 1 > ) . result NzNat: 1 Maude> > --- True > red e( > 2 > 1 0 > 0 1 > ) . result NzNat: 1 Maude> > --- True > red e( > 3 > 0 0 0 > 0 1 0 > 0 0 1 > ) . result NzNat: 1 Maude> > --- False > red e( > 2 > 0 2 > 1 0 > ) . result [List{Int}]: e(2 0 2 1 0) Maude> > --- False > red e( > 3 > 1 2 3 > 4 5 6 > 7 8 9 > ) . result [List{Int}]: e(3 1 2 3 4 5 6 7 8 9) Maude> > --- False > red e( > 4 > 1 0 0 0 > 0 0 1 0 > 0 0 0 1 > 0 1 0 0 > ) . result [List{Int}]: e(4 1 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0) ``` ### Ungolfed ``` mod E is pr LIST{Int} . ops e i : Int ~> Int . var A B N X Y Z : [Int] . ceq e(N X A Y B Z) = 1 if (size(X) rem N + size(Y) rem N) size(A) size(B) i(N 0) X B Y A Z = 0 N N i(N (N ^ 2)) . ceq e(N X A Y) = 1 if i(N 0) X I:Int Y := i(N (N ^ 2)) . eq i(N s A) = i(N A) (0 ^ (A rem s N)) . endm ``` We guess a partition of the input list into three or five (possibly empty) sublists, and then attempt to perform the inverse of one of the three row operations. * Swapping is undone by picking two rows and swapping them. * Multiplying and adding rows is undone by picking a single element and ignoring it — it either corresponds to the single \$1\$ in the row that was multiplied by \$\lambda\$, or the single \$1\$ in a *different* row that was added. --- Saved 13 bytes by simplifying the identity matrix function, by recognizing that the \$1\$ occurs every \$(n + 1)\$ entries. Saved 16 more bytes by collapsing multiplying and adding into a single case and changing the signature to only one list argument with length prepended. Saved ~~9~~ 10 more bytes by combining conditions into one list equality. Saved 3 more bytes using `0 ^ X` to do the equivalent of `!x` in C — i.e., convert non-zero to zero and zero to one. Maude's convention is that \$x ^ 0 = 1\$ even for \$x = 0\$. Saved 5 more bytes by removing the base case for `i` and handling it in the pattern matches. [Answer] # [Desmos](https://desmos.com/calculator), 117 bytes ``` K=[0...W^2] J=K[(L-0^{mod(K,W+1)})^2>0] n(L)=L.length f(L,W)=\{n(J)<2,32=n(\mod(J,W).\unique)^23^{L[J+1]^2}.\total\} ``` This turned out pretty well, considering Desmos's limitations. The blank line indicates that the subsequent line (`f(L,W)=...`) should be pasted including a leading newline. Takes input as a flattened list and the width of the matrix. Returns 1 if the matrix is elementary, otherwise NaN (shown as "undefined") [Try it on Desmos!](https://www.desmos.com/calculator/pdinuqpqr5) ### How it works It's not clear that this golfy approach works, so I'll start with a line-by-line explanation of what the code does, then give a proof of its correctness in the next section. ``` # K: indices of the list L, 0-indexed # this has one element more than L, but it gets ignored because # operations applied element-wise use the smallest length K=[0...W^2] # J: 0-indexed positions in L whose entries differ from the W×W identity matrix J = K[ # filter K for elements where: ( # the corresponding entries differ from the identity matrix: L - # value of L minus 0^{mod(K,W+1)} # 1 if on main diagonal (mod(K,W+1)=0) else 0 )^2>0 # this difference must be nonzero; (a-b)^2 > 0 ⟺ a ≠ b ] # n: helper function to give the length n(L)=L.length # f: return 1 if the matrix is elementary, otherwise NaN f(L,W) = \{ # If 0 or 1 positions differ from the identity matrix, return 1 n(J)<2, # If the following is true, return 1: 32 = # 32 is equal to n(\mod(J,W).\unique)^2 * # the number of columns containing at least one entry # differing from the identity matrix, squared 3^{L[J+1]^2}.\total # the total of 3^{e_j} for each entry e_j differing from identity \} ``` ### Proof of correctness As observed in the other answers, "multiplying a row by a constant" and "adding a multiple of a row to another row" give either the same identity matrix (multiplying by 1 or adding 0 times a row to another row) or the identity matrix with exactly one entry changed. This is handled by `n(J)<2`. The only condition left to check is swapping two rows. **Claim:** `32 = n(\mod(J,W).\unique)^2 * 3^{L[J+1]^2}.\total` if and only if L differs from an identity matrix by swapping two rows **Proof (backward direction):** Assume L differs from an identity matrix by swapping two rows. Then exactly two columns contain entries different from the identity, so `n(\mod(J,W).\unique) = 2`. Additionally, the entries in `L` that are different than the identity must be exactly `0,0,1,1`, so `3^{L[J+1]^2}.\total = 3^0 + 3^0 + 3^1 + 3^1 = 8`. Hence `n(\mod(J,W).\unique)^2 * 3^{L[J+1]^2}.\total = 2^2 * 8 = 32` as desired. **Proof (forwards direction):** Assume `32 = n(\mod(J,W).\unique)^2 * 3^{L[J+1]^2}.\total`, and assume for sake of contradiction that L does *not* differ from an identity matrix by swapping two rows. Since each factor is a non-negative integer, we must have that `n(\mod(J,W).\unique)^2` is a factor of 32, so `n(\mod(J,W).\unique)` is a factor of 4. *Case 1:* Assume `n(\mod(J,W).\unique)=1`, so all incorrect entries are in a single column. Then we must have `3^{L[J+1]^2}.\total = 32/1^2 = 32`. Since all incorrect entries are in a single column, there could be at most 1 incorrect value of `0`. Hence we must have `32` written as a sum of powers of `3` with at most 1 copy of `3^0`; this is impossible since 32 is 2 mod 3, contradiction. *Case 2:* Assume `n(\mod(J,W).\unique)=2`, so all incorrect entries are in two columns. Then we must have `3^{L[J+1]^2}.\total = 32/2^2 = 8`. Since all incorrect entries are in a single column, there could be at most 2 incorrect values of `0`. Hence we must have `8` written as a sum of powers of `3` with at most 2 copies of `3^0`: the only way to have this is `3^0 + 3^0 + 3^1 + 3^1`, which can only occur when L differs from an identity matrix by swapping two rows, contradiction. *Case 3:* Assume `n(\mod(J,W).\unique)=4`, so there are at least 4 incorrect entries. We must have `3^{L[J+1]^2}.\total = 32/4^2 = 2`, but this can't happen because `3^{L[J+1]^2}.\total` is the sum of at least 4 terms which are each at least 1, contradiction. In all cases, there is a contradiction, so L must differ from an identity matrix by swapping two rows, as desired. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` δQαDΘO0K22SQsĀ˜O!Θ~ ``` Can probably be a golfed a bit more.. Not too happy about the `ΘO0K22SQ`. [Try it online](https://tio.run/##yy9OTMpM/f//3JbAcxtdzs3wN/A2MgoOLD7ScHqOv@K5GXX//0dHG@kY6BjE6kQDSR1DMG0I5McCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCf/PbQk8t9Hl3Ax/A28jo@DA4iMNp@f4K56bUfdf5390dLSBjmGsTrShjkFsrI5CNIgBZOqAhHWMwTRIAVhK1xRJCVyRgY6uIUwdVBBJD0wIykXRiGo61FRkIxBKUOxDVoNkshGqN4zAzjfRMdUxA9LmOhY6lpjOR3cz3AqIUiNkhXBnx8YCAA). **Explanation:** ``` δQ # Push an identity matrix of the same size as the input-matrix: δ # Apply on the rows of the (implicit) input-matrix double-vectorized: Q # Equality check α # Take the absolute difference of the values of this identity matrix # with the values of the input-matrix at the same positions D # Duplicate this ΘO0K22SQ # Check that there are exactly two rows containing exactly two 1s: Θ # Check for each value if it's equal to 1 (1 if 1; 0 otherwise) O # Sum each row to get the amount of 1s per row 0K # Remove all 0s from the sums 22SQ # And check if this is equal to [2,2] s # Swap so the duplicated list is at the top again Ā˜O!Θ # Check that there are either 0 or 1 cell values changed: Ā # Check for each whether it's NOT 0 (0 if 0; 1 otherwise) ˜ # Flatten the matrix O # Get the sum of this list ! # Get the factorial of it (0 to 1; 1 remains 1; >=2 just becomes larger) Θ # Check if this is equal to 1 ~ # Bitwise-OR to check if either of the two checks is 1 # (after which this is output implicitly as result) ``` ]
[Question] [ I've been working on this iOS app recently and I encountered a (rather easily solved) problem: How do I determine if my string is comprised only of emojis? Well, that's your job today! ### Input A string. If the presence of unicode characters is problematic for you then you may use a different reasonable format. Please state what you do if you do something different from a regular string for taking input. ### Output Print or return a truthy value if the input string contains only emojis, and a falsey value if it contains any characters other than emojis. ### Wait a sec... what's an emoji? 😅 An emoji is a character that falls in these ranges: ``` 0x1F600...0x1F64F // Emoticons 0x1F300...0x1F5FF // Misc Symbols and Pictographs 0x1F680...0x1F6FF // Transport and Map 0x2600...0x26FF // Misc symbols 0x2700...0x27BF // Dingbats 0xFE00...0xFE0F // Variation Selectors ``` (I think) ### This is 🔹[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")🔹, so shortest code in bytes wins❕ ### Test cases ``` "Is it an emoji? 🤔" -> False "🔹code-golf🔹" -> False "😮 😥 😨 😩 😪" -> False "I have no fancy emojis :(" -> False "😎" -> True "😊😘" -> True ``` For you poor souls who cannot see emojis, [here is an image of the test cases](https://i.stack.imgur.com/e1Ji5.png). [Answer] # [Emojicode](http://www.emojicode.org/), 179 bytes ``` 🍇a🍨🐚🚂➡🚂🔂n🍡a🍇🍊🎉🎉◀n 9728🎊▶n 10175◀n 65024🎉🎉🎊▶n 65039◀n 127744🎊▶n 128591◀n 128640▶n 128767🍇🍎0🍉🍉🍎1🍉 ``` A callable that takes a list of integers representing the codepoints and returns 1 or 0. [Try it online!](https://tio.run/##bZFdToQwEMff9xQ9AkWgcAAPQlgSMRHMwgFWXjYQF9fY6AYTG5LNxhdf1cTbcILeAGfasrDGhw7z2fn/aHyTXSdRtowHKR7upNhuFgTskST5JZYGTIVg3qXYtVK0Zf/W4UcKXqaQ77C4gVNL0VR4@pd1SgJm@xDU/fNnSqhFmavSnmvZzth4qkP2IlB1ajPmONOg7bsBNRXfc6wxyzxm1jYWmMqchqIzaAKkus2StMgh5l9kDgHB7tuQFnFeLMMixK6DvpV3ivLxHikR0iw7avKJFZX@8etRGMw3c20Qb7XPD7ialyS6CldhVMQrVNLNleA7oMifc4x2NqPkV8rWYPavhKL/MT7d@aS5cL82mKhF61Dqnv7paKaOhfqvvw "Emojicode – Try It Online") # [Emojicode](http://www.emojicode.org/), 187 bytes ``` 🍇a🔡➡👌🔂i🍡a🍇🍦n🚂i🍊🎉🎉◀n 9728🎊▶n 10175◀n 65024🎉🎉🎊▶n 65039◀n 127744🎊▶n 128591◀n 128640▶n 128767🍇🍎👎🍉🍉🍎👍🍉 ``` A callable that takes a string and returns a boolean. [Try it online!](https://tio.run/##S83Nz8pMzk9J/f9hfn/jh/m97VwKQHKZQmaxK0jqP0go8cP8KQsfzVv4Yf7EHiCzKRMouDARJANSmvdh/iywUNeH@X2dIPxoekOegqW5kQWQ0/Vo2rY8BUMDQ3NTsLCZqYGRCUwhXB4oamwJljc0Mjc3MUFoNLIwtTSEyliYmRjARM3NzKEO6AM6C4h7O6EYxO8Fsf8rQBzVuxbqGaDbl0A0oXgH5BuYZ0B@QfYKyCFo7C5C9sKs4VIAOmBGA4QLkpqyBBy4IMWTMRX0IRRwgZ0PAA "Emojicode – Try It Online") ## Ungolfed and explained ``` 👴 A callable that takes a 🔡 called input and returns a 👌 🍇 input 🔡 ➡ 👌 👴 For each character in input 🔂 character 🍡 input 🍇 👴 Create a frozen called n containing the unicode codepoint of character 🍦 n 🚂 character 👴 If the value is in one of specific ranges, return 👎 (if the current character is not an emoji) 🍊🎉🎉◀n 9728🎊▶n 10175◀n 65024🎉🎉🎊▶n 65039◀n 127744🎊▶n 128591◀n 128640▶n 128767🍇 🍎 👎 🍉 🍉 👴 Since we're here, all characters are an emoji, so return 👍 🍎👍 🍉 ``` [Try it online!](https://tio.run/##ZVLNTgIxEL7zFHNTEw6AwMLRGE08@wS1DFDFlnS7mnhCLkYia4xEjQcJCeHmzfhAPAFvgDPt8hM8tNud7@s3880Ur82lkqaBy8X4@X4xHj7kgPYZqPiEIQq//MARSNHpiIsOgmsLB05cYQyCmKOJh7ABSncTB0I3wKJLrA74y1OORTPU8@dfkwCA1z41FlDINsi2sEI6tEQOfGaM@lsASU3WUlxqkDi2KBxSvqY1d6hXFdHBaCeUVrpFdSMk2lsF3rpGaQemuVH3auRc0@ezvxOnLGdNL3IjOglSe7hKo5El4i5K1VQSrNAtjPNZB/haCvsq3JOJtUgpt2zGoA23DJBbfRAKGCzG6SOv@XtPQz0q1ehnMH/71VAsFKOKD1crhVJ5RVzjFD2se7xYiqJyeXOxVKvUixlSq5YLq2hUjbJGcurUVxzKeMytd/J@rrREuMU9i9BGi3mgFm@s0KwJWBnJQ2y2WjD0Sqk/seQyczn8zt4YDXnKVfDroMfBb4PnzsMO4eGMJ7LdG3a2cx5kXE6Ucp5s@cThHNJ4fx@98MvQaBq80nr9T0g3hFD@Hw "Emojicode – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~61~~ 56+1 = ~~62~~ ~~57~~ 47 bytes Uses the `-n` flag and takes input from STDIN. Prints `0` for truthy and `nil` for falsy. -5 bytes because for some reason I initially thought the regex solution would not work??? -10 bytes from [NieDzejkob](https://codegolf.stackexchange.com/users/55934/niedzejkob) for noticing a code point overlap that I missed :o ``` p$_=~/^[🌀-🙏🚀-🛿☀-➿︀-︀️]*$/ ``` [Try it online!](https://tio.run/##KypNqvz/v0Al3rZOPy76w/yeBt0P82f2f5g/C8SYvf/RjAbdR/P2v9/RoAvE73f0x2qp6P///2H@jC4gnvEvv6AkMz@v@L9uHgA "Ruby – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), 39 bytes Since [the proposal for Unicode property escapes](https://github.com/tc39/proposal-regexp-unicode-property-escapes) is now part of V8, this can also be addressed without manually specifying ranges. Granted, this comes years after the original question was asked, but I think it is an interesting addition none the less. ``` a=>/^\p{Emoji_Presentation}*$/u.test(a) ``` [Try it online!](https://tio.run/##PU4xbsJAEOz9ipEVCRvZ0EaxgCoFHT0h6OTckUPm1vItlhDKByhSUbijIVJCQZ9f8QPHhwnFjnZmdlazFKWwaaFzjsvHOiVjGQoD1GIw7L@@5NvnFS31fFJIKw0L1mQ@ug/9dY@l5UCEdeK1IW3yNdsmOfUAf2yhGcJAuvgIl8Nx70fOuRz2vym9yXhBmXLkX67OzVX15eDbwY@DU@uO8S5KCUNQwqSb9qvFU3APf963XTOV780ST1GB4NaO5Qqkbi1DOJUy2ctoETgvQicediKoKwvDpP4D "JavaScript (V8) – Try It Online") [Answer] # Python, 87 bytes ``` lambda x:re.match('^[😀-🙏🌀-🗿🚀-🛿☀-➿︀-︀️]*$',x)and 1 import re ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCqihVLzexJDlDQz0u@sP8GQ26H@bP7P8wvwfEmL7/w/xZIMbs/Y@AMo/m7X@/o0EXiN/v6I/VUlHXqdBMzEtRMOTKzC3ILypRKEr9n6hgqxDNpaCg5FmskFmikJinkJqbn5Vpr/Bh/pIpSjogmQ/zp@xMzk9J1U3Pz0kDcWDCM9YBVc1YCiJWgIiVIGIVRNZTISOxLFUhL18hLTEvuRJiarGClQZccx@c1QXEM5S4Yrm4uNLyixSyFTLzFBKtuDgLijLzSjTUq61sTAxqFapr1fWA0kDPa2TrKKRpZGtqav4HAA "Python 3 – Try It Online") Returns `1` as truthy value and `None` as falsy value. [Answer] # [Proton](https://github.com/alexander-liao/proton), 54 bytes ``` map(/[🌀-🙏🚀-🛿☀-➿︀-︀️]/.match)+all ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z83sUBDP/rD/J4G3Q/zZ/Z/mD8LxJi9/9GMBt1H8/a/39GgC8Tvd/TH6uvlJpYkZ2hqJ@bk/C8oyswr0UjTUP8wf8Y6IF4KxCuAeCUQr1LX1PwPAA "Proton – Try It Online") -9 bytes (3 chars) thanks to NieDzejkob "Borrowing" Uriel's regex :P This is shorter thanks to Proton's obscure features and regex literals [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 47 bytes ``` ''≡⍵ [🌀-🙏🚀-🛿☀-➿︀-︀️] ``` [Try it online!](https://tio.run/##KyxNTCn6/19d/VHnwke9W7miP8zvadD9MH9m/4f5s0CM2fsfzWjQfTRv//sdDbpA/H5HfyzX//8f5s/oAuIZAA "QuadR – Try It Online") Is…  `''≡⍵` an empty string identical to the result when…  `[🌀-🙏🚀-🛿☀-➿︀-︀️]` all emojis are…   replaced with nothing ? [Answer] # JavaScript, ~~83~~ 61 bytes -22 bytes thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) `s=>(s.match(/\ud83d[\ude00-\ude4f]/g)||"").length==s.length/2` **Demo** ``` f=s=>(s.match(/\ud83d[\ude00-\ude4f]/g)||"").length==s.length/2 document.writeln(f("🔹code-golf🔹")) //false document.writeln(f("😮 😥 😨 😩 😪")) //false document.writeln(f("I have no fancy emojis :(")) //false document.writeln(f("😎")) //true document.writeln(f("😊😘")) //true ``` ]
[Question] [ The inspiration for this code golf puzzle is the [Bridge and Torch problem](https://en.wikipedia.org/wiki/Bridge_and_torch_problem), in which ***d*** people at the start of a bridge must all cross it in the least amount of time. The catch is that at most two people can cross at once, otherwise the bridge will crush under their weight, and the group only has access to one torch, which must be carried to cross the bridge. Each person in the whole puzzle has a specified time that they take to walk across the bridge. If two people cross together, the pair goes as slow as the slowest person. There is no set number of people that must cross the bridge; your solution MUST work for any value of ***d***. You needn't use standard input for this problem, but for the sake of explaining the problem, I will be using the following input and output format for the explanation. The first number, ***d***, is the number of people at the start of the bridge. Then, the code will scan for ***d*** numbers, each representing the speed of a person. The code output will be the LEAST amount of time required to cross everyone from the start of the bridge to the end of the bridge, while meeting the criteria explained earlier. Here are some input cases and output cases and the explanation for the first input case. It is up to you to derive an algorithm from this information to solve the problem in the fewest bytes of code possible. **input** ``` 4 1 2 5 8 ``` **output** ``` 15 ``` To reach this output, the people must cross in the following way. ``` A and B cross forward (2 minutes) A returns (1 minute) C and D cross forward (8 minutes) B returns (2 minutes) A and B cross forward (2 minutes) ``` Here's another test case to guide you along your way. **input** ``` 5 3 1 6 8 12 ``` **output** ``` 29 ``` Rules: 1. Assume that the input will not be sorted, and you must do so on your own (if you need to) 2. The number of people in the puzzle is not fixed at 4 (N >= 1) 3. Every group and individual crossing must have a torch. There is only one torch. 4. Each group must consist of a maximum of only 2 people! 5. No, you may not jump off the bridge and swim to the other side. No other tricks like this ;). [Answer] ## Python 3, ~~100~~ 99 bytes a recursive solution ``` f=lambda s:s[0]+s[-1]+min(2*s[1],s[0]+s[-2])+f(s[:-2])if s.sort()or 3<len(s)else sum(s[len(s)==2:]) ``` *Thanks to @xnor for [this paper](https://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf)* *Thanks to @lirtosiast save 2 bytes, @movatica save 1 bytes and to @gladed pointing at that my previous solution doesn't work* use the following trick to evaluate something in lambda function `s.sort() or s` here we compute sort and return the result of the test `s.sort()or len(s)>3` ## Ungolfed ``` def f(s): s.sort() # sort input in place if len(s)>3: # loop until len(s) < 3 a = s[0]+s[-1]+min(2*s[1],s[0]+s[-2]) # minimum time according to xnor paper return a + f(s[:-2]) # recursion on remaining people else: return sum(s[len(s)==2:]) # add last times when len(s) < 3 ``` ## Results ``` >>> f([3, 1, 6, 8, 12]) 29 >>> f([1, 2, 5, 8]) 15 >>> f([5]) 5 >>> f([1]) 1 >>> f([1, 3, 4, 5]) 14 ``` [Answer] # Python 2, ~~119~~ ~~114~~ ~~112~~ ~~119~~ ~~110~~ ~~100~~ 95 bytes I have been advised to separate my answers out. A solution using `Theorem 1, A2:09` [of this paper xnor linked](https://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf). To quote the paper (changing it to zero-indexing): `The difference between C_{k-1} and C_k is 2*t_1 - t_0 - t_{N-2k}.` ``` lambda n,t:t.sort()or(n-3)*t[0]*(n>1)+sum(t)+sum(min(0,2*t[1]-t[0]-t[~k*2])for k in range(n/2)) ``` **Ungolfing:** ``` def b(n, t): # using length as an argument t.sort() z = sum(t) + (n-3) * t[0] * (n>1) # just sum(t) == t[0] if len(t) == 1 for k in range(n/2): z += min(0, 2*t[1] - t[0] - t[-(k+1)*2]) # ~k == -(k+1) return z ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 39 bytes ``` {2≥≢⍵:⊃⍵⋄(⊃∘⌽+⊃+(∇1↓⊢)⌊(∇2↓⊢)+2×2⊃⌽)⍵}∨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v9roUefSR52LHvVutXrU1QykHnW3aIBYHTMe9ezVBrK0NR51tBs@apv8qGuR5qOeLhDXCMrVNjo83QikumevJlBv7aOOFf/THrVNeNTb96hvqqc/UOrQeuNHbROBvOAgZyAZ4uEZ/D9NwVjBUMFMwULB0IgrDcg0UjBVsACydExBhCGQMFEwBcsYg1gA "APL (Dyalog Extended) – Try It Online") A tacit function which includes a recursive dfn. ### How it works: the idea My solution is based on subproblem analysis. Given the crossing times \$ t\_1, t\_2, \cdots, t\_n \$ sorted in ascending order, there are two possibly optimal ways to help the worst person cross the bridge: 1. \$ (t\_1, t\_n) \rightarrow t\_1 \$: net effect is \$ t\_n \$ crossing, and the cost is \$ t\_n + t\_1 \$. 2. \$ (t\_1, t\_2) \rightarrow t\_2 \rightarrow (t\_{n-1}, t\_n) \rightarrow t\_1 \$: net effect is \$ t\_{n-1} \$ and \$ t\_n \$ crossing, and the cost is \$ t\_1 + 2t\_2 + t\_n \$. Let's say \$ T\_k \$ be the optimal time to cross the first \$k\$ people. Then, for the first \$k\$ people crossing, we can choose between "use (1) and let \$ k-1 \$ remaining people cross" and "use (2) and let \$ k-2 \$ remaining people cross", which becomes $$ \begin{aligned} T\_k &= \min(T\_{k-1} + t\_n + t\_1, T\_{k-2} + t\_1 + 2t\_2 + t\_n) \\ &= t\_1 + t\_n + \min(T\_{k-1}, T\_{k-2} + 2t\_2) \end{aligned} $$ ### How it works: the code ``` {2≥≢⍵:⊃⍵⋄(⊃∘⌽+⊃+(∇1↓⊢)⌊(∇2↓⊢)+2×2⊃⌽)⍵}∨ ∨ ⍝ Descending sort to get [t_n .. t_1] { } ⍝ Pass on to recursive function 2≥≢⍵:⊃⍵ ⍝ Base case: If input length ≤ 2, return the first element ⍝ [t_1] → t_1, [t_2 t_1] → t_2 (⊃∘⌽+⊃+(∇1↓⊢)⌊(∇2↓⊢)+2×2⊃⌽)⍵ ⍝ Recursive case ( 1↓⊢) ⍝ Choice 1: Drop 1 to get [t_{n-1} .. t_1] ∇ ⍝ Recursive call to get T_{n-1} (∇2↓⊢) ⍝ Choice 2: Drop 2 and recurse to get T_{n-2} +2×2⊃⌽ ⍝ and add 2×t_2 ⌊ ⍝ Minimum of two choices ⊃∘⌽+⊃+ ⍝ Add common terms t_1 and t_n ``` --- Using DP to solve the recursive problem costs a few more bytes: # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 44 bytes ``` ⊃⊃(+∘(⊃∘⌽+⊃⌊2∘⊃+2×2⊃⌽),⊢)/(¯2∘↓,∘⊂0~⍨¯2∘↑)∨⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@jrmYg0tB@1DFDA8TumPGoZ682iNXTZQTidTVrGx2ebgQW2aup86hrkaa@xqH1YLm2yTpgJU0GdY96V8AEJ2o@6ljxqG8qyAIuIE7nsnLLL1LIVLDyzFN41LvZlEtBIY3LyjUvBSgMUvA/nctYwVDBTMFCwdCIy1DBSMFUwYJLx5RLxxDIM1YwUTAFAA "APL (Dyalog Extended) – Try It Online") A full program. ### How it works: the code ``` ∨⎕ ⍝ Descending sort the given array (¯2∘↓,∘⊂0~⍨¯2∘↑) ⍝ Set up the initial element for reduce ⍝ e.g. [12 8 6 3 1] → [12 8 6 (3 1)] ¯2∘↑ ⍝ Take the last two elements ⍝ If input length is 1, ↑ becomes "overtake" and yields [0 n] 0~⍨ ⍝ Remove zeros to undo "overtake" ⊂ ⍝ Enclose to make it the initial item ¯2∘↓,∘ ⍝ Append to the original array with last two elements dropped (+∘(⊃∘⌽+⊃⌊2∘⊃+2×2⊃⌽),⊢)/ ⍝ Reduce by the logic, right to left 2∘⊃+2×2⊃⌽ ⍝ Choice (2): 2∘⊃+ ⍝ T_{k-2} + 2×2⊃⌽ ⍝ 2*t_2 ⊃ ⍝ Choice (1): T_{k-1} (⊃∘⌽+ ) ⍝ Common term: + t_1 +∘ ⍝ + t_n ,⊢ ⍝ Prepend the resuting value T_k to the DP array ( )/ ⍝ Reduce by the function above ⊃⊃ ⍝ Remove the layering and take the first element (which is T_n) ``` [Answer] # Ruby, ~~94~~ ~~133~~ ~~97~~ ~~96~~ ~~101~~ ~~96~~ 99 bytes I have been advised to separate my answers out. This is a solution based on the algorithm described in `A6:06-10` of [this paper on the Bridge and Torch Problem](https://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf). **Edit:** Fixing a bug where `a=s[0]` is not yet defined when `a` is called at the end if `s.size <= 3`. ``` ->s{r=0;(a,b,*c,d,e=s;r+=a+e+[b*2,a+d].min;*s,y,z=s)while s.sort![3];r+s.reduce(:+)-~s.size%2*s[0]} ``` **Ungolfing:** ``` def g(s) r = 0 while s.sort![3] # while s.size > 3 a, b, *c, d, e = s # lots of array unpacking here r += a + e + [b*2, a+d].min *s, y, z = s # same as s=s[:-2] in Python, but using array unpacking end # returns the correct result if s.size is in [1,2,3] return r + s.reduce(:+) - (s.size+1)%2 * s[0] end ``` [Answer] # [Python 2](https://docs.python.org/2/), 89 bytes ``` lambda t:t.sort()or reduce(lambda x,c:x+[min(x[-2]+x[1]*2,x[-1])+c+x[0]],t[2:],t[:2])[-1] ``` [Try it online!](https://tio.run/##LYzNDoIwEITvPMUcW1mNVDDahCepPSA/sYm0BGuCT49b5TKZ@b7NTp/4CF6tQ31bn8147xpEHQ@vMEchw4y5795tLza1UKuX3IzOi8Xslc0XU9idIh6FlXnL@2gtRaN0Sq2sTGYd@JMjBDgPkwHCnAgF4Uy4cFGWoK6SfoaxIlRsmBbVRise3JNP@N8I/KZkkVApM6sxzc5HiEE4PkmJukaQ6xc "Python 2 – Try It Online") Uses the same formulation as [my APL answer](https://codegolf.stackexchange.com/a/199440/78410), except that direct reduction turns out shorter in this case. Incidentally, this wins against all the previous entries (except APL). [Answer] # Scala, ~~113~~ 135 (darnit) ``` def f(a:Seq[Int]):Int={val(s,b)=a.size->a.sorted;if(s<4)a.sum-(s+1)%2*b(0)else b(0)+Math.min(2*b(1),b(0)+b(s-2))+b(s-1)+f(b.take(s-2))} ``` Ungolfed somewhat: ``` def f(a:Seq[Int]):Int = { val(s,b)=a.size->a.sorted // Sort and size if (s<4) a.sum-(s+1)%2*b(0) // Send the rest for cases 1-3 else Math.min(b(0)+2*b(1)+b(s-1),2*b(0)+b(s-2)+b(s-1)) + // Yeah. f(b.take(s-2)) // Repeat w/o 2 worst } ``` Tester: ``` val tests = Seq(Seq(9)->9, Seq(1,2,5,8)->15, Seq(1,3,4,5)->14, Seq(3,1,6,8,12)->29, Seq(1,5,1,1)->9, Seq(1,2,3,4,5,6)->22, Seq(1,2,3)->6, Seq(1,2,3,4,5,6,7)->28) println("Failures: " + tests.filterNot(t=>f(t._1)==t._2).map(t=>t._1.toString + " returns " + f(t._1) + " not " + t._2).mkString(", ")) ``` Not great in general, but maybe not bad for a strongly-typed language. And begrudging thanks to xnor for spotting a case I didn't catch. [Answer] # Ruby, ~~104~~ ~~95~~ 93 bytes I have been advised to separate my answers out. This is a solution based on [my Python 2 solution](https://codegolf.stackexchange.com/a/75782/47581) and `Theorem 1, A2:09` of [this paper on the Bridge and Torch Problem](https://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf). ``` ->n,t{z=t.sort!.reduce(:+)+t[0]*(n>1?n-3:0);(n/2).times{|k|z+=[0,2*t[1]-t[0]-t[~k*2]].min};z} ``` **Ungolfing:** ``` def b(n, t) # using length as an argument z = t.sort!.reduce(:+) + t[0] * (n>1 ? n-3 : 0) (n/2).times do each |k| a = t[1]*2 - t[0] - t[-(k+1)*2] # ~k == -(k+1) z += [0, a].min end return z end ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 34 bytes ``` W>l=SQ3=+Zs[hQ.)QhS[y@Q1+hQ.)Q;+Zs ``` There's probably some way to write it as a reduce or some other functional magic, but I've spent enough time doing high school programming coursework today that actually writing anything resembling good code is a nice change of pace. [Try it online!](https://tio.run/##K6gsyfj/P9wuxzY40NhWO6o4OiNQTzMwIzi60iHQUBvMsQYK//8fbaxjqGOmY6FjaBT7L7@gJDM/r/i/bgoA "Pyth – Try It Online") ]
[Question] [ ## Introduction RNA is the less famous cousin of DNA. Its main purpose is to control the production of proteins in cells through a process called [translation](https://en.wikipedia.org/wiki/Translation_%28biology%29). In this challenge, your task is to implement a part of this process where the RNA is split into *codons*. [This challenge](https://codegolf.stackexchange.com/questions/42038/rna-to-protein-translation) is thematically related, but concentrates on another part of the translation process. ## Codons We will think of RNA as a long string over the alphabet of base pairs, `AUCG`. In translation, RNA is split into non-overlapping chunks of three base pairs, called codons. The process begins at a *start codon*, `AUG`, and ends at a *stop codon*, one of `UAA`, `UAG` or `UGA`. Each codon (except the stop codons) corresponds to an amino acid, and the resulting string of amino acids forms the protein. ## Input Your input is a non-empty string of RNA. ## Output Your output is the list of codons in which the RNA is split, in any reasonable format. In this simplified model, the process begins at the **leftmost** start codon `AUG`, which is included in the output. It ends when a stop codon is encountered, or when we run out of RNA. If the input contains no start codon, the output shall be an empty list. ## Examples Consider the input sequence ``` ACAUGGAUGGACUGUAACCCCAUGC ``` The parsing begins at the leftmost occurrence of `AUG`, at index 2. It continues as follows: ``` AC AUG GAU GGA CUG UAA CCCCAUGC * ^ ^ ^ + ``` The codon marked with `*` is the start codon, and those marked with `^` are also part of the output. The stop codon is marked with `+`. The correct output is ``` AUG,GAU,GGA,CUG ``` For the shorter input ``` ACAUGGAUGGACUGU ``` the process goes ``` AC AUG GAU GGA CUG U * ^ ^ ^ ``` This time, a stop codon is not encountered, so the process stops when we run out of base pairs. The output is the same as above. ## Rules and scoring You can write a full program of a function. The lowest byte count wins, and standard loopholes are disallowed. ## Test cases ``` GGUACGGAUU -> GGCGAAAUCGAUGCC -> AUG ACAUGGAUGGACUGU -> AUG,GAU,GGA,CUG AUGACGUGAUGCUUGA -> AUG,ACG UGGUUAGAAUAAUGAGCUAG -> AUG,AGC ACAUGGAUGGACUGUAACCCCAUGC -> AUG,GAU,GGA,CUG CUAAGAUGGCAUGAGUAAUGAAUGGAG -> AUG,GCA AAUGGUUUAAUAAAUGUGAUAUGAUGAUA -> AUG,GUU UGUCACCAUGUAAGGCAUGCCCAAAAUCAG -> AUG UAUAGAUGGUGAUGAUGCCAUGAGAUGCAUGUUAAU -> AUG,GUG,AUG,AUG,CCA AUGCUUAUGAAUGGCAUGUACUAAUAGACUCACUUAAGCGGUGAUGAA -> AUG,CUU,AUG,AAU,GGC,AUG,UAC UGAUAGAUGUAUGGAUGGGAUGCUCAUAGCUAUAAAUGUUAAAGUUAGUCUAAUGAUGAGUAGCCGAUGGCCUAUGAUGCUGAC -> AUG,UAU,GGA,UGG,GAU,GCU,CAU,AGC,UAU,AAA,UGU ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~39~~ ~~38~~ ~~32~~ 30 bytes ``` M!`AUG|\B\G... U(AA|AG|GA)\D* ``` The trailing linefeed is significant. Output as a linefeed-separated list. [Try it online.](http://retina.tryitonline.net/#code=TSFgQVVHfFxCXEcuLi4KVShBQXxBR3xHQSlcRCoK&input=VUdBVUFHQVVHVUFVR0dBVUdHR0FVR0NVQ0FVQUdDVUFVQUFBVUdVVUFBQUdVVUFHVUNVQUFVR0FVR0FHVUFHQ0NHQVVHR0NDVUFVR0FVR0NVR0FD) ### Explanation ``` M!`AUG|\B\G... ``` This is match stage which turns the input into a linefeed-separated list of all matches (due to the `!`). The regex itself matches every codon starting from the first `AUG`. We achieve this with two separate options. `AUG` matches unconditionally, so that it can start the list of matches. The second match can be any codon (`...` matches any three characters), but the `\G` is a special anchor which ensures that this can only match right after another match. The only problem is that `\G` also matches at the beginning of the string, which we don't want. Since the input consists only of word characters, we use `\B` (any position that is not a word boundary) to ensure that this match is not used at the beginning of the input. ``` U(AA|AG|GA)\D* ``` This finds the first stop codon, matched as `U(AA|AG|GA)` as well as everything after it and removes it from the string. Since the first stage split the codons into separate lines, we know that this match is properly aligned with the start codon. We use `\D` (non-digits) to match any character, since `.` wouldn't go past the linefeeds, and the input won't contain digits. [Answer] ## Haskell, ~~115~~ 112 bytes ``` import Data.Lists fst.break(\e->elem e["UAA","UAG","UGA"]||length e<3).chunksOf 3.snd.spanList((/="AUG").take 3) ``` Usage example: ``` *Main> ( fst.break(\e->elem e["UAA","UAG","UGA"]||length e<3).chunksOf 3.snd.spanList((/="AUG").take 3) ) "AUGCUUAUGAAUGGCAUGUACUAAUAGACUCACUUAAGCGGUGAUGAA" ["AUG","CUU","AUG","AAU","GGC","AUG","UAC"] ``` How it works: ``` spanList((/="AUG").take 3) -- split input at the first "AUG" snd -- take 2nd part ("AUG" + rest) chunksOf 3 -- split into 3 element lists fst.break(\e-> -- take elements from this list elem e["UAA","UAG","UGA"]|| -- as long as we don't see end codons length e<3) -- or run out of full codons ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 27 bytes ``` "ᶠx„ẋİ⁻/3Ŀ:ƛ"ᴴλ†ᶤ¤@„⁻=a]Ṙƒh ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCJcIuG2oHjigJ7huovEsOKBuy8zxL86xptcIuG0tM674oCg4bakwqRA4oCe4oG7PWFd4bmYxpJoIiwiIiwiYWF1Z2d1dXVhYXVhYWF1Z3VnYXVhdWdhdWdhdWEiLCIzLjQuMiJd) lowercase input [Answer] ### JavaScript ~~88~~ ~~82~~ ~~70~~ 69 chars ``` s=>/AUG(...)+?(?=(U(AA|AG|GA)|$))/.exec(s)[0].match(/.../g).join(",") ``` Usage Example: ``` (s=>/AUG(...)+?(?=(U(AA|AG|GA)|$))/.exec(s)[0].match(/.../g).join(","))("ACAUGGAUGGACUGUAACCCCAUGC") ``` [Answer] # Python 2, 185 bytes ``` i=input() o=[] if i.find('AUG')>=0:i=map(''.join,zip(*[iter(i[i.find('AUG'):])]*3)) else:print "";exit() for j in i: if j not in['UGA','UAA','UAG']:o+=[j] else:break print ','.join(o) ``` **Explanation** Set `i` to input. Split it from 'AUG' to the end. Split into strings of three. Check if stop codon, and cut. [Try it here](http://ideone.com/mm548N) [Answer] # [MATL](https://esolangs.org/wiki/MATL), 57 bytes ``` j'AUG(...)*?(?=(UAA|UAG|UGA|.?.?$))'XXtn?1X)tnt3\-:)3[]e! ``` This uses [current version (9.3.1)](https://github.com/lmendo/MATL/releases/tag/9.3.1) of the language/compiler. Input and output are through stdin and stdout. The output is separated by linebreaks. ### Example ``` >> matl > j'AUG(...)*?(?=(UAA|UAG|UGA|.?.?$))'XXtn?1X)tnt3\-:)3[]e! > > ACAUGGAUGGACUGUAACCCCAUGC AUG GAU GGA CUG ``` *EDIT (June 12, 2016): to adapt to changes in the language, `[]` should be removed. The link below includes that modification* [**Try it online!**](http://matl.tryitonline.net/#code=aidBVUcoLi4uKSo_KD89KFVBQXxVQUd8VUdBfC4_Lj8kKSknWFh0bj8xWCl0bnQzXC06KTNlIQ&input=VUFVQUdBVUdHVUdBVUdBVUdDQ0FVR0FHQVVHQ0FVR1VVQUFV) ### Explanation The code is based on the regular expression ``` AUG(...)*?(?=(UAA|UAG|UGA|.?.?$)) ``` This matches substrings starting with `AUG`, containing groups of three characters (`...`) and ending in either `UAA`, `UAG`, or `UGA`; or ending at the end of the string, and in this case there may be one last incomplete group (`.?.?$`). *Lookahead* (`(?=...)`) is used so that the stop codons are not part of the match. The matching is *lazy* (`*?`) in order to finish at the first stop codon found, if any. ``` j % input string 'AUG(...)*?(?=(UAA|UAG|UGA|.?.?$))' % regex XX % apply it. Push cell array of matched substrings tn? % if non-empty 1X) % get first substring tnt3\-:) % make length the largest possible multiple of 3 3[]e! % reshape into rows of 3 columns % implicit endif % implicit display ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, 40 bytes ``` map/UAA|UAG|UGA/?last:say,/AUG|\B\G.../g ``` [Try it online!](https://tio.run/##JYuxDoMwDER/qCR0YOmCDg@eGL2xZKhQJQoRYamUb8fYdPCd9e4uv/elU/2mHAWoAq7CiP2SyvEq6feIEK7TMHEIIc6qllrJoNi530JCjskg4KGbK4sx@IjttwbdG/Lmf8igc8vHZ1uLNmMX2merzXoB "Perl 5 – Try It Online") [Answer] # Ruby, ~~97~~ ~~95~~ ~~78~~ ~~75~~ 62 bytes ``` ->(r){r.scan(/AUG|\B\G.../).join(?,).sub(/,U(AA|AG|GA).*/,'')} ``` I don't golf much, so I'm sure it can be improved. Edit: ~~Stole~~ Borrowed Martin Büttner's excellent `\B\G` trick [Answer] # [Scala 2](https://www.scala-lang.org/), ~~170~~ 156 bytes A port of [@nimi's Haskell answer](https://codegolf.stackexchange.com/a/69516/110802) in Scala. Saved 14 bytes thanks to @pacman256 --- Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=TZC_TsMwEMbF2olHMB4qW6ERogtq5UhWhmyAWkUMVQfjOCE0tRPb5V_VJ4GhDLDwRPA0XBqoasl3su_nz9_d66eTohLnXzM80OZRWI3nP0fH5vZeSY8ml3yqmpXSUl1bI5VzxqJ1r4dQpnK0FKUmwhZuhLi14nk29bbUxZyOUKpLjxigCNaDqJDV4l8J7jFPkzhNIXLYSQwh5XEKB55Ajnlb5EmcJEC0EN4LSZPBHxNVlEaDUk4OlOmOqsGErzTBMxwEh3i4XHQOCT7FNAjwHLcvNrB7nXg-Ih3BItDc94PYx8rng4vvN8eidQs2zIWlztTTVU7aZjAdlzlpInZGd3UJ9cyamjQ0LKxZ1SojQxp6A7JjGXqxUDd3ZaWIZJEMXfmiGBv2--gE6gRD7-AQZtHGhGMaSqM9TNsRSelGVU4hAEO1rP1-6pvO4_tf3m67_As) ``` s=>{val q=s.indexOf("AUG");if(q>=0){val c=s.drop(q).grouped(3).toSeq;c.takeWhile(c=>c.size==3&& !Seq("UAA","UAG","UGA").contains(c))}else Seq.empty[String]} ``` Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=ZVPNbpwwED70lqeY-BAZbUJU7aVaiUoItdyaareohygHF4Zdd702tU2bqton6SWX9I166dN0wEDYBAksPPN9883f7z-uFEosHx4eW19fvfn36q_58hVLD-sP6Qa_tahL_GhNic4ZC7_OzgAqrOEgpObCbt0KUmvFz9uNt1Jv76IVFFp6SMgV6PkuFFgtRia6Z2mRZ0VB35TePKNPkWYF_aQ5nVnaGdM8y3Py6JzYRFSaimKscSuNJqZa6iqbXfFZoKgHNaTJK83ZLVss5uj4sA-CObtk0WLB7liHOI7pvaB2A-8KAo7ypFBj1lO619fwnqDgdwjOC-vB1P1PCA42aOe1tI5sZdla29eF3LrCsGhKtoff1EEFBRgVxMSP9zc1n_nLGvip_3kCV6-jQVWv6929t4L62ksb21FbcwiBwegfwlaD_1O1Z52bFFTWNKfxogH3FG7TKPksGPXCdKxGO-DlrtV71-W9BN2WCo2XFbroVEDnmjxTEm-taRus-DKKvaHbF7E_iT2O6FZ7qUBQOU0T7kA6IB5DFrRYAY310CGyKdRbv-tcFE08GYSG5cAcGGNP7J93UiEPkORtsMQDNkkopYsLOCdpnNEss0ugI--PPGVRXBrtaX9cIIhCzkdA5XDqGIFjPDR-2qwusTX61mogTb1pVtphfDrh2nioKbvQy2M_1sew3cOSj8v-Hw) ``` object RNASequenceProcessor { def main(args: Array[String]): Unit = { val rnaSequence = "AUGCUUAUGAAUGGCAUGUACUAAUAGACUCACUUAAGCGGUGAUGAA" val codingRegion = findCodingRegion(rnaSequence) println("["++codingRegion.mkString(",")++"]") } def findCodingRegion(sequence: String): Seq[String] = { // Find the start of the coding region (first occurrence of "AUG") val startOfCoding = sequence.indexOf("AUG") if (startOfCoding != -1) { // Extract the sequence from "AUG" onward val codingSequence = sequence.drop(startOfCoding) // Split the sequence into codons (chunks of 3 nucleotides) val codons = codingSequence.grouped(3).toSeq // Take codons until a stop codon is encountered or the codon length is less than 3 codons.takeWhile(codon => codon.length == 3 && !Seq("UAA", "UAG", "UGA").contains(codon)) } else { Seq.empty[String] // Return an empty sequence if "AUG" is not found } } } ``` ]
[Question] [ I think the ASCII art questions on PPCG are fun to do, but personally I think it can be pretty hard, especially when the question is tagged as [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). I wonder if anyone here might have some tips that will be useful for producing ASCII art. Simply arranging characters is easy, but with (short) algorithms, things will become more complicated. I'm talking about ASCII art like: * Text to ASCII art (characters) * Images (logos or icons) I'm just looking for general tips, but language-specific is allowed since most of them can be translated anyhow. [Answer] ## Compression algorithms You can apply LZMA compression to the string. Many languages support it. ## Run-length encoding You can use processing instructions such as `[char][number]` (e.g. `b12`). This compression algorithm is used here: <https://codegolf.stackexchange.com/a/20589/10920> Further reading: <http://en.wikipedia.org/wiki/Run-length_encoding> ## Integer packing You can use arrays of integers to store small shapes such as: ``` // This is an invader! // (SE line height makes it looks awful) // ~158 characters ## ## ## ## ############## #### ###### #### ###################### ## ############## ## ## ## ## ## #### #### ``` Each space will be translated into a `0`. Each sharp will be translated into a `1`. ``` // ~58 characters // Saved ~100 bytes! [ 196656, 49344, 262128, 999228, 4194303, 3407859, 3342387, 62400 ] ``` Each bit is then read using bitwise operator `&`. The above algorithm could be improved by using a bigger integer base: ``` // ~44 characters // Integers are in base 36. // Use `_` as a separator (or a line break). "47qo_122o_5m9c_lf0c_2hwcf_211ir_1zn03_1c5c" ``` [Answer] ## Look for symmetry Sometimes the required ASCII art is symmetric at some point. For example, [Argyle ASCII Art](https://codegolf.stackexchange.com/questions/56032/argyle-ascii-art) requires an output similar to this: ``` /\ /\ / \ /\ / \ /\/ \/ \/ \/\ \/\ /\ /\ /\/ \ / \/ \ / \/ \/ ``` One could just print this normally, but depending on the language, the code required can be shortened by only generating the top half of the result, reversing it and swapping `/` and `\`. ## Try transposing In [ASCII Art Archery Arrows](https://codegolf.stackexchange.com/questions/54682/ascii-art-archery-arrows) the result to print is this, scaled to a given `n`: ``` /\ / \ / \ / \ \ / \____/ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | /| |\ / | | \ / | | \ / | | \ / | | \ / |__| \ / / \ \ / / \ \ // \\ / \ ``` If we take a look at the arrow, we can see there's 8 kinds of lines: ``` / \ \ / \_/ | | / | | \ / |_| \ / / \ \ / \ ``` Let's try the same for its transpose. ``` /////// / / /\ / / / \ / / / _|||||||||||||||||||||| / _ _ \ _ _ \ _|||||||||||||||||||||| \ / \ \ \/ \ \ \ \ \\\\\\\ ``` Here, there are 10 kinds of lines. ``` / / / / \ / / / _| / _ _ \ _ _ \ _| \ / \ \ \ \ \ ``` But here's the catch: the bottom 5 are identical to the top 5, except for swapping `/` and `\`. As per the previous rule, you can first generate the first 5, copy, do the swap, and finally transpose to get the arrow. This can save a lot of code. [Answer] # Control characters, escape sequences and console codes Unless the question forbids them, [the current consensus on Meta](http://meta.codegolf.stackexchange.com/a/5515) is that ASCII art challenges do not require a specific byte stream, but output that looks correct. This means that we can use [ASCII control characters](https://en.wikipedia.org/wiki/Control_character#In_ASCII), [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code) and [Linux console codes](http://man7.org/linux/man-pages/man4/console_codes.4.html) in our answers, assuming a supporting terminal. Unless specified otherwise, the rest of this answer will explain the behavior of Linux terminals, which is what I have available for testing right now. ### ASCII control characters Support/interpretation varies from terminal to terminal and character to character. The most portable one ought to be the linefeed (`\n`, `\x0a`), which moves the character to the beginning of the next line. Other useful characters include: * The vertical tab (`\v`, `\x0b`) moves the cursor one position to the right, then one position down. ``` $ echo -e 'a\vb' a b ``` * The carriage return (`\r`, `\x0d`) moves the cursor to the beginning of the *current* line. Any subsequent printable character will overwrite the first character of the current line. ``` $ echo -e 'ab\rc' cb ``` * The backspace (`\b`, `\x08`) moves the cursor one position to the left. Any subsequent printable character will overwrite the character before the backspace. ``` $ echo -e 'ab\bc' ac ``` * The escape (`\e`, `\x1b`) does nothing on its own, but forms part of ANSI escape sequences (optionally) and Linux console codes. Many languages permit actual control characters in the source code. ### ANSI escape sequences (yet to come) ### Linux console codes While there are many more, the most useful console codes for ASCII art are probably these: * The sequence `\ec` will *reset* the terminal. This clears the screen, moes the cursor the upper left corner and sets fore- and background color, cursor blinking rate, etc. to their default values. * The sequence `\eM` causes a *reverse linefeed*, i.e., the cursor will move one position up. ``` $ echo -e '\na\eMb\n' b a ``` * The sequence `\eH` sets the *tab stop* at the current column. ``` $ echo -e ' \eHa\n\tb' a b ``` [Answer] ## Look for patterns This one might be a bit obvious, but... look for patterns, similarities and repetitions in the output. For instance, when I saw the [Transform number into 7-segment display pattern](https://codegolf.stackexchange.com/questions/19196/transform-number-into-7-segment-display-pattern) task I started thinking about how one could golf it, and started looking for similarities. Due to the way the horizontal segments go between the vertical ones in the character matrix it'd probably be easiest to deal with three segments at a time, grouped together as such (adding two "always empty" segments for the first, topmost one): ![segments groping](https://i.stack.imgur.com/06X47.png) Thus, you could do something like `lc + " "*N + rc + "\n"` N-1 times and then `lc + bc*N + rc` once, for every three segments (`lc`, `bc`, `rc` being the left-, bottom-, and right-segment characters, i.e. one of `|`, `_` or ). [Answer] # Use base conversion [This answer](https://codegolf.stackexchange.com/a/53432/20080) was to a question which wanted ASCII art which consisted of the characters `+ |-` and newlines. Since there are only 5 possible characters, these can be treated as a base 5 number and converted to bytes, packing 3.45 characters per byte. # Exploit regularities Often, the data will have some regularities, even if those regularities aren't strong enough to employ specific tools such as mirroring. For instance, in the above question, the desired output had newlines roughly evenly spaced throughout the test, since the text was roughly rectangular. I exploited this to shorten my code, by using Pyth's split into n pieces function, then joining on newlines. # Know your tools, and choose the right one for the job. The most powerful and efficient text processing tools I know are: Regex engines: `///`, Retina, Perl, in order of power/conciseness tradeoff. Use if the thing you want to do can be conscisely described in regex substitutions, such as [this answer](https://codegolf.stackexchange.com/a/57195/20080) Obscure text-processing tools: gema, etc. (I'm sure there are others, but they're too obscure) Use if they have a feature that is exactly what you need, that nothing else has. Such as in [this question](https://codegolf.stackexchange.com/a/52977/20080), with gema's recursive matching. General code golfing languages: CJam, Pyth, etc. Use if you're exploiting some subtlety complex enough that no other tool will do the job or it just does the job shorter. # Try many approaches This applies in every code-golf question, but especially here. You're not going to know whether a regularity is exploitable until you try it out. Possibly in multiple languages. ]
[Question] [ **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. Write a program that generates and prints a [random maze](http://en.wikipedia.org/wiki/Maze_generation_algorithm) using the algorithm of your choice. The maze should be different for multiple runs of the program. Height and width are given as command line arguments. Use `|` for vertical wall, `-` for horizontal wall and `+` for corner. The maze is bounded by walls and the entrances are marked by missing wall. The maze contains a treasure `#` which must be reachable from at least one entrance. ``` $ python2 random-maze.py 4 5 +-+-+ |#| | | +---+ ``` [Answer] ## Python, 375 characters ``` import random,sys H,V=map(int,sys.argv[1:]) H-=1 V-=1 b,h,v,p=' -|+' M=H/2*h n=random.randint(1,(H/2)*(V/2-1)) for i in range(V/2): e=s=t='';N=v for j in range(H/2): if i and(random.randint(0,1)or j==0):s+=N+b;t+=v;N=v;M=M[1:]+p else:s+=M[0]+h;t+=b;N=p;M=M[1:]+h n-=1;t+=' #'[n==0] if H&1:s+=s[-1];t+=b;e=h print s+N+'\n'+t+v if V&1:print t+v print h.join(M)+e+h+p ``` This generates a maze with one entrance and a randomly placed treasure. The maze is a simple [binary tree maze](http://en.wikipedia.org/wiki/Maze_generation_algorithm#Simple_algorithms). ``` $ ./maze.py 15 15 --------------+ | | | ----------+ | | | | +-----+ | --+ | | | | | --+ --+ +---+ | | | | | --+-+ +---+ | | | | | | --+ +-+ --+ | | | | |#| | | | --+ --+-+ | | | | | +-+-+---+-----+ ``` [Answer] ## Ruby 1.9.2p136 : 90 ``` eval ARGV[0] z=[l="+"+"-"*@w+"+"] @h.times{z<<"|"+" "*@w+"|"} z[rand(@h)+1]="|#" puts z<<l ``` Output ``` $> ruby maze.rb "@h=8;@w=8;" +------+ | | | | | | | | |# | | +------+ ``` Hey, no one said it had to be a **good** maze. OK, OK, I'll make a real one now. [Answer] I think this technically isn't a maze generator, but it creates a maze like result: <https://gist.github.com/803450>. Some horrible code in there I know, and it only works less than half the time, and the result doesn't look quite right to do with walls sticking out from other walls. But its close enough that I can't be bothered fixing the rest. Some example output: ``` → ruby random-maze.rb 30 30 +----+-+-----------++-+----+ | + | ++ | | ++ + | ++ ++ + + ++ ++ | ++ ++ | | +---+ + | | + | +| + +++ + + | | + +| +| +-+ | + + | | + + + + ++ |+ | | + ++ + ++ + | + ++| | | | | ++ + +----+ + +-+ | | | + | +-+ |+ | | | | +-+ +| ++ ++ + + | | | | ++ + + | ++| + | ++ | | + + + + +---++-+ +++ | | + | +| + | ++ | | | | +++ +| + ++ +--+ + |---+ |#+ | | | +++ + + | ++ | ++ +-+ ++ +--+ + + | | ++ | + ++| + ++ | | ++ +--------+ +| + + | | | | +++ | + +-+ | | | +--+ |++ |+ | ++ | | | +--+ | | || | | | | +-+ +-+ |+ |+ | | | +---+ ++ + | | | +-| + + ++ ++ | + ++ +---+ | | ++ + +-+ | + ++ +-+ +-------------+---+ ``` [Answer] ## C 844 ``` #include <stdlib.h> #include <time.h> h,w,*m,y,x,z;d(t,b,l,r){int i=b-t,j=r-l;if(i>1&&j>1){i=(rand()%--i)|1;j=(rand()%--j)|1;z=rand()%4;x=rand()%i+t;x|=1;for(y=t;y<i+t;y++)if(y!=x||!z)m[y*w+j+l]=124;x=rand()%(b-i-t)+i+t;x|=1;for(y=t+i;y<b+1;y++)if(y!=x||!(z-1))m[y*w+j+l]=124;y=rand()%j+l;y|=1;for(x=l;x<j+l;x++)if(y!=x||!(z-2))m[(i+t)*w+x]=45;y=rand()%(r-j-l)+j+l;y|=1;for(x=l+j;x<r+1;x++)if(y!=x||!(z-3))m[(i+t)*w+x]=45;m[(i+t)*w+j+l]=43;m[(t-1)*w+l+j]=43;m[(b+1)*w+j+l]=43;m[(i+t)*w+l-1]=43;m[(i+t)*w+r+1]=43;d(t,t+i-1,l,l+j-1);d(t+i+1,b,l,l+j-1);d(t,t+i-1,l+j+1,r);d(t+i+1,b,l+j+1,r);}}main(int c,char**v){h=atoi(v[1]),w=atoi(v[2]),m=calloc(h*w,4);srand(time(0));while(y<h){while(x<w){m[y*h+x]=(!y||y==h-1)?(!x||x==w-1)?43:45:(!x||x==w-1)?124:32;x++;}y++;x=0;}d(1,h-2,1,w-2);z=rand()%(w-2);z|=1;m[z]=32;z=rand()%(w-2);z|=1;m[h*(w-2)+z]=35;} ``` **To Test:** ``` #include <stdio.h>//beginning for(y=0;y<h;y++){for(x=0;x<w;x++){putchar(m[y*h+x]);}putchar('\n');}getchar();//end ``` **3x3** ``` + + |#| +-+ ``` **7x8** ``` +-+-- -+ | | + +-+--+ | | | +-+ -+ | | # | +-+-+--+ ``` **18x20** ``` +-+-+ +---+---+-+--+ | | | | | | + + +-- +---+ +--+ | | | | + + +-+---+-- +-+ -+ | | | | +-+ +-+-+-+---+-+--+ | | | | | | | + + + +-+-- --+ | | | | | | | | | +-+-+ ----+ | | | | | | + + +-+-+-+-- --+ -+ | | | | | | + +-+-- +-- --+ | | | | | | | | | | #| | | +-+-+-+---+-----+--+ ``` [Answer] Here's a simple java solution: ``` import java.util.*; public class MazeGen { public static void main(String[]a){ int w,l; Random rand=new Random(System.currentTimeMillis()%1000+System.nanoTime()); if(a.length==2){ w=Integer.parseInt(a[0]); l=Integer.parseInt(a[1]); }else{ System.out.println("No command line arguments, taking from STDIN."); Scanner input=new Scanner(System.in); w=input.nextInt(); l=input.nextInt(); input.close(); } char[][]maze=new char[w][l]; for(int x=0;x<w;x++){ for(int y=0;y<l;y++){ maze[x][y]=' '; } } for(int x=0;x<w;x++){ maze[x][0]=maze[x][l-1]='|'; } for(int y=0;y<l;y++){ maze[0][y]=maze[w-1][y]='-'; } maze[0][0]=maze[w-1][0]=maze[w-1][l-1]=maze[0][l-1]='+'; int dor=1+rand.nextInt(l-2); maze[0][dor]=' '; int tx=2+rand.nextInt(w-3),ty=1+rand.nextInt(l-2); maze[tx][ty]='#'; if(ty<dor-1){ maze[tx][ty+1]='|'; if(tx==w-2){ maze[tx+1][ty+1]='+'; } if(tx==1){ maze[0][ty+1]='+'; } } if(ty>dor+1){ maze[tx][ty-1]='|'; if(tx==w-2){ maze[tx+1][ty-1]='+'; } if(tx==1){ maze[0][ty-1]='+'; } } if(ty==dor&&tx>3&&(maze[tx][ty+1]==' '||maze[tx][ty-1]==' ')){ maze[tx-1][ty]='-'; } if(dor>5){ int z=2+rand.nextInt(dor-3); int q=1+rand.nextInt(w-3); for(int i=0;i<w;i++){ if(i==0||i==w-1){ maze[i][z]='+'; }else if(i!=q&&maze[i][z]==' '){ maze[i][z]='|'; } } } if(l-dor>5){ int z=dor+2+rand.nextInt(l-dor-3); int q=1+rand.nextInt(w-3); for(int i=0;i<w;i++){ if(i==0||i==w-1){ maze[i][z]='+'; }else if(i!=q&&maze[i][z]==' '){ maze[i][z]='|'; } } } for(char[]row:maze){ System.out.println(row); } } } ``` # Some sample results: 3x3: ``` + + |#| +-+ ``` 4x4: ``` + -+ | #| | | +--+ ``` 4x5: ``` +-+ + |#| | | | +---+ ``` 5x5: ``` + --+ | | | | | |#| +-+-+ ``` 5x8: ``` + --+--+ | | | | | | # | | +---+--+ ``` 8x15: ``` +---- ----+---+ | | | | | | | | | | | | #| | | | | | +---------+---+ ``` ]
[Question] [ Consider a binary operator \$\*\$ that operates on a set \$S\$. For simplicity's sake, we'll assume that \$\*\$ is closed, meaning that its inputs and outputs are always members of \$S\$. This means that \$(\*, S)\$ is a [magma](https://en.wikipedia.org/wiki/Magma_(algebra)) Let's define some basic terms describing the properties of \$\*\$. We can say that \$\*\$ can have any of these properties, if they hold for all \$a,b,c \in S\$: * **Commutative**: \$a\*b \equiv b\*a\$ * **Associative**: \$(a\*b)\*c \equiv a\*(b\*c)\$ * **Distributive**: \$a\*(b+c) \equiv (a\*b)+(a\*c)\$, for some binary operator \$+\$ on \$S\$ We can also define 3 related properties, for a unary operation \$-\$ on \$S\$: * **Anti-commutative**: \$a\*b \equiv -(b\*a)\$ * **Anti-associative**: \$(a\*b)\*c \equiv -(a\*(b\*c))\$ * **Anti-distributive**: \$a\*(b+c) \equiv -((a\*b)+(a\*c))\$ Finally, we define 3 more, that only describe \$\*\$ if the complete statement is true for \$a,b,c \in S\$: * **Non-commutative**: There exists \$a, b\$ such that \$a\*b \not\equiv b\*a\$ and \$a\*b \not\equiv -(b\*a)\$ * **Non-associative**: There exists \$a, b, c\$ such that \$(a\*b)\*c \not\equiv a\*(b\*c)\$ and \$(a\*b)\*c \not\equiv -(a\*(b\*c))\$ * **Non-distributive**: These exists \$a,b,c\$ such that \$a\*(b+c) \not\equiv (a\*b)+(a\*c)\$ and \$a\*(b+c) \not\equiv -((a\*b)+(a\*c))\$ We now have 9 distinct properties a binary operator can have: commutativity, non-commutativity, anti-commutativity, associativity, non-associativity, anti-associativity, distributivity, non-distributivity and anti-distributivity. This does require two operators (\$-\$ and \$+\$) to be defined on \$S\$ as well. For this challenge we'll use standard integer negation and addition for these two, and will be using \$S = \mathbb Z\$. Obviously, any given binary operator can only meet a maximum of 3 of these 9 properties, as it cannot be e.g. both non-associative and anti-associative. However, it is possible to create a function that is, for example, neither commutative, anti-commutative or non-commutative, by creating an operator \$\*\$ such that \$a\*b = b\*a\$ for some inputs and \$a\*b = -b\*a\$ for others. Therefore, it is possible to create an operator that meets fewer than 3 of these properties. --- Your task is to write 9 programs (either full programs or functions. You may "mix and match" if you wish). Each of these 9 programs will: * take two integers, in any reasonable format and method * output one integer, in the same format as the input and in any reasonable method * be a [surjection](https://en.wikipedia.org/wiki/Surjective_function) \$\mathbb Z^2 \to \mathbb Z\$ (takes two integers as input and outputs one integer). This means that for any distinct output, there is at least one input that yields that output * uniquely exhibit one of the 9 properties described above. This means that, of your nine programs, one should be commutative, one associative, one distributive over addition, one anti-commutative, one anti-associative, one anti-distributive, one non-commutative, one non-associative and one non-distributive. Your programs must each exhibit **exactly** 1 of these 9 behaviours, and violate the other 8. For example, multiplication would be banned, as it is commutative, associative and distributive. However, this also means that 6 of your programs must not be e.g. any of commutative, anti-commutative or non-commutative. How you reconcile this is up to you. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the combined lengths of all 9 of your programs is your score, and you should aim to minimise this. Additionally, you should include some form of proof that your programs do indeed have the required properties and do not satisfy the other properties. Answers without these are not considered valid. Alternatively, your answer may be in the form of a proof of impossibility. If this is the case, you must prove that there are no such operators that are valid answers to this. You do not have to show that all 9 properties are impossible to exhibit - only one - in this proof. In this case, there can only be one answer, which, by default, will be the winner. [Answer] # Proof of impossibility The only anti-distributive operator when \$S=\mathbb Z\$ is such that \$\forall a, \forall b, a\*b=0\$. Indeed, suppose that \$\*\$ is anti-distributive. Then \$\*\$ has the following property, for all \$ a,b,c\in\mathbb Z\$: * (D) \$a\*(b+c) = - (a\*b+a\*c)\$ (In my notation, \$\*\$ has precedence over \$+\$.) Take \$a,b \in \mathbb Z\$. By (D), \$a\*(2b) = a\*(b+b) = - (a\*b + a\*b) = -2(a\*b)\\ a\*(3b) = a\*(2b+b) = -(a\*2b + a\*b) = -(-2(a\*b) + a\*b) = a\*b\\ a\*(4b) = a\*(2b+2b) = -(a\*2b + a\*2b) = -(-2(a\*b) -2(a\*b)) = 4(a\*b)\\ a\*(4b) = a\*(3b+b) = -(a\*3b + a\*b) = -(a\*b + a\*b) = -2(a\*b) \$ Hence \$4(a\*b) = -2(a\*b)\$ and \$a\*b=0\$. We thus have that \$\forall a,\forall b, a\*b=0\$. The only anti-distributive operator is therefore always equal to \$0\$. In particular, it is commutative, anti-commutative, associative, anti-associative, distributive, anti-distributive, and not a surjection. It is therefore impossible to exhibit an operator which is only anti-distributive. ]
[Question] [ # Introduction I don't see many regex challenges on here, so I would like to offer up this deceptively simple one which can be done in a number of ways using a number of regex flavours. I hope it provides regex enthusiasts with a bit of fun golfing time. # Challenge The challenge is to match what I've very loosely dubbed an "egalitarian" series: a series of equal numbers of different characters. This is best described with examples. Match: ``` aaabbbccc xyz iillppddff ggggggoooooollllllffffff abc banana ``` Don't match: ``` aabc xxxyyzzz iilllpppddff ggggggoooooollllllfff aaaaaabbbccc aaabbbc abbaa aabbbc ``` To generalize, we want to match a subject of the form `(c1)n(c2)n(c3)n...(ck)n` for any list of characters `c1` to `ck`, where `ci != ci+1` for all `i, k > 1, and n > 0.` **Clarifications:** * Input will not be empty. * A character may repeat itself later in the string (eg. "banana") * `k > 1`, so there will always be at least 2 different characters in the string. * You can assume only ASCII characters will be passed as input and no character will be a line terminator. # Rules (Thank you to Martin Ender for this excellently-stated block of rules) Your answer should consist of a single regex, without any additional code (except, optionally, a list of regex modifiers required to make your solution work). You must not use features of your language's regex flavour that allow you to invoke code in the hosting language (e.g. Perl's `e` modifier). You can use any regex flavour which existed before this challenge, but please specify the flavour. Do not assume that the regex is anchored implicitly, e.g. if you're using Python, assume that your regex is used with re.search and not with re.match. Your regex must match the entire string for valid egalitarian strings and yield no matches for invalid strings. You may use as many capturing groups as you wish. You may assume that the input will always be a string of two or more ASCII characters not containing any line-terminators. This is regex golf, so the shortest regex in bytes wins. If your language requires delimiters (usually `/.../`) to denote regular expressions, don't count the delimiters themselves. If your solution requires modifiers, add one byte per modifier. # Criteria This is good ol' fashioned golf, so forget efficiency and just try to get your regex as small as possible. Please mention which regex flavour you have used and, if possible, include a link showing an online demo of your expression in action. [Answer] ## .NET flavour, 48 bytes ``` ^(.)\1*((?<=(\5())*(.))(.)(?<-4>\6)*(?!\4|\6))+$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP05DTzPGUEtDw97GViPGVENTUwsoognEQBFdE7sYM6CAvWKMSQ2Qpamt8v9/YmJiUlJScnIyV0VlFVdmZk5OQUFKSloaVzoY5INBDhikgQEXSENiIogC6qmoqKysqoJoBOrEoxUA "Retina – Try It Online") (using [Retina](https://github.com/m-ender/retina)) Well, turns out that *not* negating the logic is simpler after all. I'm making this a separate answer, because the two approaches are completely different. ### Explanation ``` ^ # Anchor the match to the beginning of the string. (.)\1* # Match the first run of identical characters. In principle, # it's possible that this matches only half, a quarter, an # eighth etc of of the first run, but that won't affect the # result of the match (in other words, if the match fails with # matching this as the entire first run, then backtracking into # only matching half of it won't cause the rest of the regex to # match either). ( # Match this part one or more times. Each instance matches one # run of identical letters. (?<= # We start with a lookbehind to record the length # of the preceding run. Remember that the lookbehind # should be read from the bottom up (and so should # my comments). (\5())* # And then we match all of its adjacent copies, pushing an # empty capture onto stack 4 each time. That means at the # end of the lookbehind, we will have n-1 captures stack 4, # where n is the length of the preceding run. Due to the # atomic nature of lookbehinds, we don't have to worry # about backtracking matching less than n-1 copies here. (.) # We capture the character that makes up the preceding # run in group 5. ) (.) # Capture the character that makes up the next run in group 6. (?<-4>\6)* # Match copies of that character while depleting stack 4. # If the runs are the same length that means we need to be # able to get to the end of the run at the same time we # empty stack 4 completely. (?!\4|\6) # This lookahead ensures that. If stack 4 is not empty yet, # \4 will match, because the captures are all empty, so the # the backreference can't fail. If the stack is empty though, # then the backreference will always fail. Similarly, if we # are not at the end of the run yet, then \6 will match # another copy of the run. So we ensure that neither \4 nor # \6 are possible at this position to assert that this run # has the same length das the previous one. )+ $ # Finally, we make sure that we can cover the entire string # by going through runs of identical lengths like this. ``` [Answer] ## .NET flavour, 54 bytes ``` ^(?!.*(?<=(\2)*(.))(?!\2)(?>(.)(?<-1>\3)*)(?(1)|\3)).+ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP07DXlFPS8PexlYjxkhTS0NPUxMoAmRq2NsBOUAJXUO7GGNNLSBTw1CzBsjU1NP@/z8xMTEpKSk5OZmrorKKKzMzJ6egICUlLY0rHQzywSAHDNLAgAukITERRAH1VFRUVlZVQTQCdeLRCgA "Retina – Try It Online") (using [Retina](https://github.com/m-ender/retina)) I'm pretty sure this is suboptimal, but it's the best I'm coming up with for balancing groups right now. I've got one alternative at the same byte count, which is mostly the same: ``` ^(?!.*(?<=(\3())*(.))(?!\3)(?>(.)(?<-2>\4)*)(\2|\4)).+ ``` ### Explanation The main idea is to invert the problem, match non-egalitarian strings and put the whole thing in a negative lookahead to negate the result. The benefit is that we don't have to keep track of **n** throughout the entire string (because due to the nature of balancing groups, you usually consume **n** when checking it), to check that all runs are of equal length. Instead, we just look for a single pair of adjacent runs that *don't* have the same length. That way, I only need to use **n** once. Here is a breakdown of the regex. ``` ^(?!.* # This negative lookahead means that we will match # all strings where the pattern inside the lookahead # would fail if it were used as a regex on its own. # Due to the .* that inner regex can match from any # position inside the string. The particular position # we're looking for is between two runs (and this # will be ensured later). (?<= # We start with a lookbehind to record the length # of the preceding run. Remember that the lookbehind # should be read from the bottom up (and so should # my comments). (\2)* # And then we match all of its adjacent copies, capturing # them separately in group 1. That means at the # end of the lookbehind, we will have n-1 captures # on stack 1, where n is the length of the preceding # run. Due to the atomic nature of lookbehinds, we # don't have to worry about backtracking matching # less than n-1 copies here. (.) # We capture the character that makes up the preceding # run in group 2. ) (?!\2) # Make sure the next character isn't the same as the one # we used for the preceding run. This ensures we're at a # boundary between runs. (?> # Match the next stuff with an atomic group to avoid # backtracking. (.) # Capture the character that makes up the next run # in group 3. (?<-1>\3)* # Match as many of these characters as possible while # depleting the captures on stack 1. ) # Due to the atomic group, there are three two possible # situations that cause the previous quantifier to stopp # matching. # Either the run has ended, or stack 1 has been depleted. # If both of those are true, the runs are the same length, # and we don't actually want a match here. But if the runs # are of different lengths than either the run ended but # the stack isn't empty yet, or the stack was depleted but # the run hasn't ended yet. (?(1)|\3) # This conditional matches these last two cases. If there's # still a capture on stack 1, we don't match anything, # because we know this run was shorter than the previous # one. But if stack 1, we want to match another copy of # the character in this run to ensure that this run is # longer than the previous one. ) .+ # Finally we just match the entire string to comply with the # challenge spec. ``` ]
[Question] [ Take two lists of non-negative integers, and output an ASCII-box as it's defined below. * Corners and intersections are pluses: `+` (ASCII-code 43) * Vertical lines are bars `|` (ASCII-code 124) * Horizontal lines are minuses `-` (ASCII-code 45) The first input list specifies the number of minuses between each plus sign, in the horizontal direction. The second input list specifies the number of bars between each plus sign, in the vertical direction. It's easier to explain with a few examples: ``` 0 // No minuses between each + sign 0 // No bars between + signs ++ ++ ------------------ 1 2 // First a single minus, then two minuses 1 2 // First one bar, then two bars +-+--+ | | | +-+--+ | | | | | | +-+--+ ------------------ 1 0 3 0 2 0 2 1 0 0 +-++---++--++ | || || || | || || || +-++---++--++ | || || || +-++---++--++ +-++---++--++ +-++---++--++ ``` Clarifications: * Input order and format are optional * Only the boxes should be printed/displayed, but a trailing space or newlines are accepted. * You may optionally add 1 to all input values if that's more convenient. The second example would then be: `2 3; 2 3`. This is code golf, so the shortest code in bytes win. [Answer] # Python 2, 117 Bytes ``` def f(h,v):r="+"+"+".join("-"*i for i in h)+"+\n";print r+r.join(("|"+"|".join(" "*i for i in h)+"|\n")*i for i in v)+r ``` [Try it on ideone.](https://ideone.com/yFGxrK) Not expecting too much from this. Really simple, just uses python joins and string multiplication to pull everything together. [Answer] ## JavaScript (ES6), 83 bytes ``` (a,b,g=(a,[s,t])=>t+a.map(n=>s.repeat(n)+t).join``+` `)=>g(b,[g(a,` |`),g(a,`-+`)]) ``` Output includes two trailing newlines. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~25~~ ~~22~~ 21 bytes ``` '|-+ '2:"1tiYsQ(]E!+) ``` Uses inputs with `1` added (allowed by the challenge). [Try it online!](http://matl.tryitonline.net/#code=J3wtKyAnMjoiMXRpWXNRKF1FISsp&input=WzIgMSA0IDEgMyAxXQpbMyAyIDEgMV0) ### Explanation The code initially builds an array containing `1` for the column indices of non-space characters in the final result, and `0` otherwise. So if the first input is `[2 1 4 1 3 1]` (would be `[1 0 3 0 2 0]` in the 0-based format) this array will be ``` 1 0 1 1 0 0 0 1 1 0 0 1 1 ``` Note how the length of runs of zeros is related to the input. Specifically, this array is built as follows: 1. Initiallize the array to a single `1`. 2. Compute the cumulative sum of the input and add `1`. In the example this gives `[3 4 8 9 12 13]`. 3. Extend the array from step 1 by assigning `1` to the entries with (1-based) indices given by step 2. Intermediate entries are automatically set to `0`. A similar array is built for the rows. Second input `[3 2 1 1]` (or `[2 1 0 0 ]`) gives ``` 1 0 0 1 0 1 1 1 ``` Now the second array is multiplied by `2`, transposed and added with broadcast to the first. This gives the 2D array ``` 3 2 3 3 2 2 2 3 3 2 2 3 3 1 0 1 1 0 0 0 1 1 0 0 1 1 1 0 1 1 0 0 0 1 1 0 0 1 1 3 2 3 3 2 2 2 3 3 2 2 3 3 1 0 1 1 0 0 0 1 1 0 0 1 1 3 2 3 3 2 2 2 3 3 2 2 3 3 3 2 3 3 2 2 2 3 3 2 2 3 3 3 2 3 3 2 2 2 3 3 2 2 3 3 ``` Indexing into the string `'|-+ '` gives the final result as a 2D char array. Since indexing is modular and 1-based, index `0` corresponds to the last element (space). ``` '|-+ ' % Push this string 2:" ] % Do this twice 1 % Push 1 (initial array) t % Push another 1 (contents to be filled in) i % Take input Ys % Cumulative sum Q % Add 1 ( % Fill 1 into those entries of the array E % Multiply by 2 ! % Transpose + % Add, with broadcast ) % Index (modular, 1-based) into the string ``` [Answer] # CJam, 50 Bytes ``` 0lS/:i0++:H;lS/:i0+{H{'-*}%'+*N+o{H{S*}%'|*N+o}*}% ``` [Try it online!](http://usandfriends.github.io/CJam101/#code=0lS%2F%3Ai0%2B%2B%3AH%3BlS%2F%3Ai0%2B%7BH%7B%27-*%7D%25%27%2B*N%2Bo%7BH%7BS*%7D%25%27%7C*N%2Bo%7D*%7D%25&input=1%202%0A1%202) [Answer] # Pyth, 45 bytes ``` AQj.i*hlH]Js.i*hlG\+m*d\-G-mjb*d]XJ"+-""| "Hk ``` A program that takes input of two comma-separated lists on STDIN and prints the result. There is probably still some golfing to be done here. [Try it online](https://pyth.herokuapp.com/?code=AQj.i%2ahlH%5DJs.i%2ahlG%5C%2Bm%2ad%5C-G-mjb%2ad%5DXJ%22%2B-%22%22%7C+%22Hk&test_suite=1&test_suite_input=%5B0%5D%2C%5B0%5D%0A%5B1%2C2%5D%2C%5B1%2C2%5D%0A%5B1%2C0%2C3%2C0%2C2%2C0%5D%2C%5B2%2C1%2C0%2C0%5D&debug=0) *Explanation coming later* [Answer] # Haskell, 55 bytes ``` f[a,b]x=a:do n<-x;(b<$[1..n])++[a] g x=f[f"+-"x,f"| "x] ``` Defines a function `g` which takes the two input lists and returns a list containing the lines of the output [Answer] ## PowerShell v2+, 89 bytes ``` param($a,$b)($x="+$(($a|%{'-'*$_})-join'+')+") $b|%{,"|$(($a|%{' '*$_})-join'|')|"*$_;$x} ``` Dang, don't think I can quite catch JavaScript. Takes input `$a` and `$b` as explicit arrays. Sets variable `$x` to be the top row of the boxes based on looping through `$a` and some string concatenation. That's encapsulated in parens so it's placed on the pipeline. Then, we loop through `$b`, each iteration putting two strings on the pipeline -- the same style string but with spaces and `|` instead of hyphens and `+`, and `$x`. Those strings are all gathered from the pipeline with an implicit `Write-Output` at program completion, with default newline between them. ### Examples ``` PS C:\Tools\Scripts\golfing> .\make-some-ascii-boxes.ps1 @(0) @(0) ++ ++ PS C:\Tools\Scripts\golfing> .\make-some-ascii-boxes.ps1 @(1,0,3,0,2,0) @(2,1,0,0) +-++---++--++ | || || || | || || || +-++---++--++ | || || || +-++---++--++ +-++---++--++ +-++---++--++ PS C:\Tools\Scripts\golfing> .\make-some-ascii-boxes.ps1 @(1,4,1) @(1,2,1) +-+----+-+ | | | | +-+----+-+ | | | | | | | | +-+----+-+ | | | | +-+----+-+ ``` [Answer] # Ruby, 66 bytes ``` ->x,y{d=->c,m,z=x{c+z.map{|w|m*w}*c+c+$/} d[d[?+,?-],d[?|,' '],y]} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḣị“+-“| ”ị@ 1;+\Ṭ Ç€,€/Ñ€Y ``` Test it at **[TryItOnline](http://jelly.tryitonline.net/#code=4bii4buL4oCcKy3igJx8IOKAneG7i0AKMTsrXOG5rArDh8K14oG5w4cswrUs4oKsL8OR4oKsWQ&input=&args=WzIsMSw0LDEsMywxXQ+WzMsMiwxLDFd)** How? The input taken is a list of the two lists, `[vertical, horizontal]`, and uses the incremented option - so example 3 takes `[[3,2,1,1], [2,1,4,1,3,1]]` Each of these is then converted to a boolean array indicating the rowType or rowCharacterType respectively, e.g. `[[1,0,0,1,0,1,1,1], [1,0,1,1,0,0,0,1,1,0,0,1,1]]` The boxes are then constructed by making the rows from the characters identified by the rowType and rowCharacterType combinations - i.e. a rowType identifies either `"+-"` or `"| "` and a rowCharacterType identifies one of those two characters. ``` Ḣị“+-“| ”ị@ - Link 1, create a row: [rowType, [rowCharaterTypes]] Ḣ - head - get the rowType “+-“| ” - list of strings ["+-", "| "] ị - index into (if rowType is 1 "+-"; if rowType is 0 "| ") ị@ - index into with reversed operands (index into that from rowCharaterTypes) (replace each 1 in rowCharaters with "+" or "|" and each 0 with "-" or " ") 1;+\Ṭ - Link 2, create the Type lists from the inputs: int[] nCharacters 1; - 1 concatenated with the input +\ - reduce with addition (accumulation provides the indices) Ṭ - boolean array with 1s at those indices As an example take the vertical of example 3: [3,2,1,1] -> [1,3,2,1,1] -> [1,4,6,7,8] -> [1,0,0,1,0,1,1,1] each of which will be passed as a rowType for Link 1 Ç€,€/Ñ€Y - Main link, takes one argument: [Vertical, Horizontal] (incremented option) Ç€ - call the last link (2) for each of the two lists in the input ,€/ - pair each and reduce (making a list of [rowtype [rowCharacterTypes]]) Ñ€ - call the next link (1) for each Y - join on line feeds ``` ]
[Question] [ Everyone knows the old minesweeper game that shipped with Windows XP. It's a simple grid with a 9x9 matrix of cells containing either a number (indicating how many mines are adjacent to it) or a mine. [![enter image description here](https://i.stack.imgur.com/kpVkm.png)](https://i.stack.imgur.com/kpVkm.png) The challenge is to generate a random 9x9 grid with 10 bombs given any integer seed (up to whatever your machine/language's largest int is) with brownie points if you implement the PRNG yourself example output: cells contain either numerals 0-8 or \* for mines ``` *101*1000 110111000 123210000 1***10000 123210011 00000002* 00000114* 000112*3* 0001*2121 ``` Shortest code in bytes wins.. standard rules etc, etc.. [Answer] # MATLAB, ~~94~~ 93 bytes ``` rng(input(''));x(9,9)=~1;x(randperm(81,10))=1;y=[conv2(+x,ones(3),'s')+48 ''];y(x)=42;disp(y) ``` Example run (the first line after the code is the input typed by the user): ``` >> rng(input(''));x(9,9)=~1;x(randperm(81,10))=1;y=[conv2(+x,ones(3),'s')+48 ''];y(x)=42;disp(y) 99 *10001*2* 220001232 *201111*1 *312*1111 12*211000 011211000 0001*1000 000112110 000001*10 ``` ### Explanation ``` rng(input('')); ``` takes an integer and uses it as seed. (This works in modern MATLAB versions. Old versions may need a different syntax.) ``` x(9,9)=~1; ``` assigns logical `0`, or `false` (obtained by logically negating `1`) to the entry `(9,9)` of a matrix `x`. The rest of the entries are automatically initiallized to logical `0` too. ``` x(randperm(81,10))=1; ``` assigns `1` (autoomatically cast to logical `1`, or `true`) to `10` of the `81` entries of `x`, chosen randomly without replacement. These entries are the ones that contain bombs. ``` conv2(+x,ones(3),'s') ``` is an abbreviation of `conv2(+x,ones(3),'same')`. It convolves the matrix `x` (which needs to be cast to `double`, using `+`) with a 3×3 neighbourhood containing `1`. This counts how many bombs are adjacent to each entry. For entries that contain a bomb it includes that bomb, but the value there will be overwritten later. ``` y=[...+48 '']; ``` adds 48 to the value, to convert from number to ASCII code. Concatenating with the empty matrix casts these ASCII codes to chars. ``` y(x)=42; ``` assigns 42 (ASCII code for `'*'`) to the positions of the bombs. These positions are given by `x`, which is here used as a logical index. ``` disp(y) ``` displays the result. [Answer] ## Javascript (ES6), 204 or 198 bytes ### Custom PRNG (204 bytes) ``` s=>(p=-1,S=n=>(x=p%9-(n+=p)%9)*x-64&&b[n]=='*',T=n=>S(n)+S(-n),b=[...'*00000000'.repeat(9)]).sort(_=>(s=(22695477*s+1)>>>0)&1||-1).map(c=>(p++,c=='0'?T(1)+T(8)+T(9)+T(10):c)).join``.match(/.{9}/g).join` ` ``` This code is using a linear congruential generator with multiplier `22695477` and increment `1` (this is the Borland C/C++ implementation). Due to the poor efficiency of the PRNG during its warmup phase, I had to place one bomb per row (instead of 10 at the beginning or 10 at the end of the unshuffled array). So, there are only 9 bombs. I may try to fix that later. Also, there must be a simpler/shorter way of processing the 'out of board' check `(x=p%9-(n+=p)%9)*x-64` but I just can't figure it out right now. ### Using Math.random() (198 bytes) ``` s=>(p=-1,S=n=>(x=p%9-(n+=p)%9)*x-64&&b[n]=='*',T=n=>S(n)+S(-n),b=[...'**********'+'0'.repeat(71)]).sort(_=>Math.random()-.5).map(c=>(p++,c=='0'?T(1)+T(8)+T(9)+T(10):c)).join``.match(/.{9}/g).join` ` ``` This one includes 10 mines as requested. ### Demo ``` let f = _=>(p=-1,S=n=>(x=p%9-(n+=p)%9)*x-64&&b[n]=='*',T=n=>S(n)+S(-n),b=[...'**********'+'0'.repeat(71)]).sort(_=>Math.random()-.5).map(c=>(p++,c=='0'?T(1)+T(8)+T(9)+T(10):c)).join``.match(/.{9}/g).join` ` console.log(f()) ``` [Answer] # Dyalog APL, 40 bytes [`⎕rl←1⋄(1,¨a)⍕¨{⍉3+/0,⍵,0}⍣2⊢a←9 9⍴9≥?⍨81`](http://tryapl.org/?a=%u2395io%u21900%u22C4%20%u2395rl%u21901%u22C4%281%2C%A8a%29%u2355%A8%7B%u23493+/0%2C%u2375%2C0%7D%u23632%u22A2a%u21909%209%u23749%u2265%3F%u236881&run) (assumes `⎕io←0`) the `1` in `⎕rl←1` is the seed from right to left: `?⍨81` is the same as `81?81` - a random permutation `9≥` results in a bitmask containing ten 1s at random positions, the rest are 0s `a←9 9⍴` reshape to a 9-by-9 square and call it "a" `{ }⍣2` do the following twice: `⍉3+/0,⍵,0` sliding window sum of 3 columns (assume 0s outside), then transpose `(1,¨a)⍕¨` is format (convert to string) each. The left argument to `⍕` specifies the total number of characters and fractional characters in the result. If `⍕` can't format according to that spec it outputs a `*` - a lucky coincidence for this problem. `a` will be 1 where the mines are - trying to fit a whole and fractional part into a single char is impossible, so those will appear as `*`s. [Answer] # Python 2, ~~269~~ ~~266~~ 264 bytes ``` from random import* seed(input()) z=1,0,-1 n=range(9) m=[[0]*9 for _ in n] for x,y in sample([[x,y]for x in n for y in n],10): m[x][y]=-9 for a in z: for b in z: if 0<=x+a<9>0<=y+b<9:m[x+a][y+b]+=1 # it gets displayed as 4 spaces, but the beginning of this line is a single tab print("\n".join("".join([`c`,'*'][c<0]for c in l)for l in m)) ``` [Try it on ideone.com](https://ideone.com/d71T7h) Saved 2 bytes thanks to Aaron. Most likely still golfable. ### Explanation `random` is imported for using `seed` to seed the PRNG and `sample` to select ten bomb locations randomly. `m` is a 9 x 9 matrix saving the board. For each of the bomb locations, the corresponding entry in `m` gets set to `-9` and all neighbouring entries get incremented. This way `m` ends up containing the count of adjacent bombs for non-bomb cells and a negative number for bomb cells. The final `print` prints the whole board by iterating through all lines `l` in `m` and all cells `c` in `l`. [Answer] # R, 187 Bytes ``` set.seed();x=1:121;y=x[!(x%%11 %in% 0:1|(x-1)%/%11 %in% c(0,10))];z=sample(y,10);x=x*0;for(t in z){p=t+c(-10:-12,-1,1,10:12);x[p]=x[p]+1};x[z]=9;m=data.frame(matrix(x[y],9));m[m==9]='*';m ``` [Try it on Ideone](https://ideone.com/zymTCe) Explanation: `set.seed()` take a cst seed. `x` is the index for a 11\*11 matrix `y` is the index of the 9\*9 matrix in the 11\*11 matrix `z` is the index of the bomb `x=x*0` initialise the matrix value The loop add 1 to x in case of adjacent bomb. [Answer] ## JavaScript ES6, 244 bytes ``` f=(a=[...Array(11)].map(_=>Array(11).fill(0)),n=10,r=_=>Math.random()*9|0,x=r(),y=r())=>a[x+1][y+1]>8||[0,1,2].map(i=>[0,1,2].map(j=>a[x+i][y+j]++),a[x+1][y+1]=9)&&--n?f(a,n):a.slice(1,-1).map(a=>a.slice(1,-1).map(n=>n<9?n:`*`).join``).join` ` ;o.textContent=f() ``` ``` <pre id=o> ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~181~~ ~~194~~ 183+1 = 184 bytes Forgot to actually set the seed, whoops. Uses the `-n` flag. [Try it online!](https://tio.run/nexus/ruby#LcrdCoIwGADQ@z2FUUEpfm6Z4arlg4jEWoGL/GEr2nB7dqPs@pz5TL0uNojbUSveXhdneHZniTgrcRXmBJUhBshxBZo3/eO2IngNDe8HJ92bySU91Ewm9MBLWbGYUrRSLCYA5L@MMxF7I3PEzplTXuC9msA6G7Ea2S/YH/CShjYyVcSI9x71r6cO@JSFE0dcFOFeeLh3sgUteBskMFCfjGNKtiSjm12WZh8 "Ruby – TIO Nexus") ``` srand$_.to_i a=[0]*81 [*0..80].sample(10).map{|i|w=i%9;h=i/9;a[i]=-99 (r=-1..1).map{|x|x+=w x<0||x>8?0:r.map{|y|y+=h y<0||y>8?0:a[9*y+x]+=1}}} puts a.map{|c|c<0??*:c}.join.scan /.{9}/ ``` [Answer] # [Python 2](https://docs.python.org/2/), 172 bytes ``` from random import* seed(input()) r=range b=set(sample(r(81),10)) for j in r(9):print''.join([[`len({x-10,x-9,x-8,x-1,x+1,x+8,x+9,x+10}&b)`,'*'][x in b]for x in r(j,81,9)]) ``` [Try it online!](https://tio.run/##JYzRCoMgGEbvewqv5m/ZyNhFDnqSCCqyzSiVPweOsWd3xi4O3wcHjnv7pzV1jAvaneBo5jR6dxZ9nh1KzaCNe3lgLMM26YfKpvZQHo5xd5sChEYwLqrkF4tkJdoQBMnuDrXxlF5Xqw103bApA59QioqHUiaahOChOEm/kOevvpeJDZzmtO/CmZr6sxr@1ZU3gkvWsxhv9Q8 "Python 2 – Try It Online") ]
[Question] [ Write a program that takes in a standard [truecolor](https://en.wikipedia.org/wiki/Color_depth#True_color_.2824-bit.29) image and a single 24-bit [RGB](https://en.wikipedia.org/wiki/RGB_color_model#Color_depth) color (three numbers from 0 to 255). Modify the input image (or output a new image with the same dimensions) such that its *average color* is exactly the single color that was input. You may modify the pixels in the input image in any way you like to achieve this, **but the goal is to make the color changes as visually unnoticeable as possible**. The *average color* of an RGB image is really a set of three [arithmetic means](https://en.wikipedia.org/wiki/Arithmetic_mean), one for each color channel. The average red value is the sum of the red values across all the pixels in the image divided by the total number of pixels (the image area), rounded down to the nearest integer. The green and blue averages are calculated in the same way. This [Python 2](https://www.python.org/download/releases/2.7.8/) (with [PIL](http://www.pythonware.com/products/pil/)) script can compute the average color of most image file formats: ``` from PIL import Image print 'Enter image file' im = Image.open(raw_input()).convert('RGB') pixels = im.load() avg = [0, 0, 0] for x in range(im.size[0]): for y in range(im.size[1]): for i in range(3): avg[i] += pixels[x, y][i] print 'The average color is', tuple(c // (im.size[0] * im.size[1]) for c in avg) ``` (There are similar average color programs [here](https://codegolf.stackexchange.com/q/53525/26997), but they don't necessarily do the exact same calculation.) The main requirement for your program is that for *any* input image, its corresponding output's average color must *exactly* match the color that was input - as judged by the Python snippet or some equivalent code. The output image must also have the exact same dimensions as the input image. So you could technically submit a program that simply colors the entire input the specified average color (because the average would always be that color), but **this is a [popularity contest](https://codegolf.stackexchange.com/tags/popularity-contest/info) - the submission with the highest number of votes will win**, and such a trivial submission will not get you many upvotes. Novel ideas like taking advantage of quirks in human vision, or shrinking the image down and drawing a colored border around it will (hopefully) get you votes. Note that certain combinations of average colors and images necessitate extremely noticeable color changes. For example, if the average color to match were black (0, 0, 0), *any* input image would need to be made completely black because if any pixels had non-zero values, they would make the average non-zero as well (barring round-off errors). Keep such limitations in mind when voting. ## Test Images Some images and their default average colors to play around with. Click for full sizes. **A.** average (127, 127, 127) [![](https://i.stack.imgur.com/vwro9s.png)](https://i.stack.imgur.com/vwro9.png) From [fejesjoco](https://codegolf.stackexchange.com/users/14701/fejesjoco)'s *Images with all colors* [answer](https://codegolf.stackexchange.com/a/22326/26997). Found [original](http://joco.name/wp-content/uploads/2014/03/rgb_512_3.png) on [his blog](http://joco.name/2014/03/02/all-rgb-colors-in-one-image/). **B.** average (62, 71, 73) [![](https://i.stack.imgur.com/tDM2Is.jpg)](https://i.stack.imgur.com/tDM2I.jpg) [Yokohama](https://chat.stackexchange.com/transcript/message/22952445#22952445). Provided by [Geobits](https://codegolf.stackexchange.com/users/14215/geobits). **C.** average (115, 112, 111) [![](https://i.stack.imgur.com/F6LS6s.jpg)](https://i.stack.imgur.com/F6LS6.jpg) [Tokyo](https://chat.stackexchange.com/transcript/message/22952440#22952440). Provided by [Geobits](https://codegolf.stackexchange.com/users/14215/geobits). **D.** average (154, 151, 154) [![](https://i.stack.imgur.com/9BNEjs.jpg)](https://i.stack.imgur.com/9BNEj.jpg) [Escher's *Waterfall*](https://en.wikipedia.org/wiki/Waterfall_(M._C._Escher)). [Original](http://totallyhistory.com/wp-content/uploads/2013/01/mc-escher-waterfall.jpg). **E.** average (105, 103, 102) [![](https://i.stack.imgur.com/s04vas.jpg)](https://i.stack.imgur.com/s04va.jpg) [Mount Shasta](https://en.wikipedia.org/wiki/Mount_Shasta). Provided by me. **F.** average (75, 91, 110) [![](https://i.stack.imgur.com/c5jq1s.png)](https://i.stack.imgur.com/c5jq1.png) [*The Starry Night*](https://en.wikipedia.org/wiki/The_Starry_Night) ## Notes * The exact input and output formats and image file types your program uses does not matter much. Just make sure it is clear how to use your program. * It is probably a good idea (but not technically a requirement) that if an image already has the goal average color, it should be output as is. * Please post test images with the average color input as either (150, 100, 100) or (75, 91, 110), so voters can see the same inputs across different solutions. (Posting more examples than this is fine, even encouraged.) [Answer] # Python 2 + PIL, simple colour scaling ``` from PIL import Image import math INFILE = "street.jpg" OUTFILE = "output.png" AVERAGE = (150, 100, 100) im = Image.open(INFILE) im = im.convert("RGB") width, height = prev_size = im.size pixels = {(x, y): list(im.getpixel((x, y))) for x in range(width) for y in range(height)} def get_avg(): total_rgb = [0, 0, 0] for x in range(width): for y in range(height): for i in range(3): total_rgb[i] += int(pixels[x, y][i]) return [float(x)/(width*height) for x in total_rgb] curr_avg = get_avg() while tuple(int(x) for x in curr_avg) != AVERAGE: print curr_avg non_capped = [0, 0, 0] total_rgb = [0, 0, 0] for x in range(width): for y in range(height): for i in range(3): if curr_avg[i] < AVERAGE[i] and pixels[x, y][i] < 255: non_capped[i] += 1 total_rgb[i] += int(pixels[x, y][i]) elif curr_avg[i] > AVERAGE[i] and pixels[x, y][i] > 0: non_capped[i] += 1 total_rgb[i] += int(pixels[x, y][i]) ratios = [1 if z == 0 else x/(y/float(z)) for x,y,z in zip(AVERAGE, total_rgb, non_capped)] for x in range(width): for y in range(height): col = [] for i in range(3): new_col = (pixels[x, y][i] + 0.01) * ratios[i] col.append(min(255, max(0, new_col))) pixels[x, y] = tuple(col) curr_avg = get_avg() print curr_avg for pixel in pixels: im.putpixel(pixel, tuple(int(x) for x in pixels[pixel])) im.save(OUTFILE) ``` Here's a naïve approach which should serve as a good baseline. At each iteration, we compare our current average with the desired average, and scale the RGB of each pixel by the according ratio. We have to be a bit careful though, for two reasons: * Scaling 0 still results in 0, so before we scale we add something small (here `0.01`) * RGB values are between 0 and 255, so we need to adjust the ratio accordingly to make up for the fact that scaling capped pixels doesn't do anything. The images save as PNG because saving as JPG seems to mess up the colour averages. # Sample output ## (40, 40, 40) [![enter image description here](https://i.stack.imgur.com/rR7Nns.png)](https://i.stack.imgur.com/rR7Nn.png) [![enter image description here](https://i.stack.imgur.com/UB9Bys.jpg)](https://i.stack.imgur.com/UB9By.jpg) [![enter image description here](https://i.stack.imgur.com/AUkoVs.png)](https://i.stack.imgur.com/AUkoV.png) [![enter image description here](https://i.stack.imgur.com/hTtoLs.png)](https://i.stack.imgur.com/hTtoL.png) [![enter image description here](https://i.stack.imgur.com/PPDGCs.jpg)](https://i.stack.imgur.com/PPDGC.jpg) [![enter image description here](https://i.stack.imgur.com/gUTYys.jpg)](https://i.stack.imgur.com/gUTYy.jpg) ## (150, 100, 100) [![enter image description here](https://i.stack.imgur.com/bIJPTs.png)](https://i.stack.imgur.com/bIJPT.png) [![enter image description here](https://i.stack.imgur.com/UalBNs.jpg)](https://i.stack.imgur.com/UalBN.jpg) [![enter image description here](https://i.stack.imgur.com/X0IxQs.png)](https://i.stack.imgur.com/X0IxQ.png) [![enter image description here](https://i.stack.imgur.com/Tht5js.jpg)](https://i.stack.imgur.com/Tht5j.jpg) [![enter image description here](https://i.stack.imgur.com/XWqavs.jpg)](https://i.stack.imgur.com/XWqav.jpg) [![enter image description here](https://i.stack.imgur.com/MeK8qs.jpg)](https://i.stack.imgur.com/MeK8q.jpg) ## (75, 91, 110), Starry Night palette [![enter image description here](https://i.stack.imgur.com/fQ6Mgs.png)](https://i.stack.imgur.com/fQ6Mg.png) [![enter image description here](https://i.stack.imgur.com/hCv7ws.jpg)](https://i.stack.imgur.com/hCv7w.jpg) [![enter image description here](https://i.stack.imgur.com/jHhOVs.png)](https://i.stack.imgur.com/jHhOV.png) [![enter image description here](https://i.stack.imgur.com/iohy6s.jpg)](https://i.stack.imgur.com/iohy6.jpg) [![enter image description here](https://i.stack.imgur.com/PaQm0s.jpg)](https://i.stack.imgur.com/PaQm0.jpg) [![enter image description here](https://i.stack.imgur.com/v3wqLs.jpg)](https://i.stack.imgur.com/v3wqL.jpg) [Answer] # C++, gamma correction This does a brightness adjustment of the image using a simple gamma correction, with the gamma value determined separately for each component to match the target average. The high level steps are: 1. Read image and extract histogram for each color component. 2. Perform a binary search of the gamma value for each component. A binary search is performed on the gamma values, until the resulting histogram has the desired average. 3. Read the image a second time, and apply the gamma correction. All image input/output uses PPM files in ASCII. Images were converted from/to PNG using GIMP. The code was run on a Mac, image conversions were done on Windows. ### Code: ``` #include <cmath> #include <string> #include <vector> #include <sstream> #include <fstream> #include <iostream> static inline int mapVal(int val, float gamma) { float relVal = (val + 1.0f) / 257.0f; float newRelVal = powf(relVal, gamma); int newVal = static_cast<int>(newRelVal * 257.0f - 0.5f); if (newVal < 0) { newVal = 0; } else if (newVal > 255) { newVal = 255; } return newVal; } struct Histogram { Histogram(); bool read(const std::string fileName); int getAvg(int colIdx) const; void adjust(const Histogram& origHist, int colIdx, float gamma); int pixCount; std::vector<int> freqA[3]; }; Histogram::Histogram() : pixCount(0) { for (int iCol = 0; iCol < 3; ++iCol) { freqA[iCol].resize(256, 0); } } bool Histogram::read(const std::string fileName) { for (int iCol = 0; iCol < 3; ++iCol) { freqA[iCol].assign(256, 0); } std::ifstream inStrm(fileName); std::string format; inStrm >> format; if (format != "P3") { std::cerr << "invalid PPM header" << std::endl; return false; } int w = 0, h = 0; inStrm >> w >> h; if (w <= 0 || h <= 0) { std::cerr << "invalid size" << std::endl; return false; } int maxVal = 0; inStrm >> maxVal; if (maxVal != 255) { std::cerr << "invalid max value (255 expected)" << std::endl; return false; } pixCount = w * h; int sumR = 0, sumG = 0, sumB = 0; for (int iPix = 0; iPix < pixCount; ++iPix) { int r = 0, g = 0, b = 0; inStrm >> r >> g >> b; ++freqA[0][r]; ++freqA[1][g]; ++freqA[2][b]; } return true; } int Histogram::getAvg(int colIdx) const { int avg = 0; for (int val = 0; val < 256; ++val) { avg += freqA[colIdx][val] * val; } return avg / pixCount; } void Histogram::adjust(const Histogram& origHist, int colIdx, float gamma) { freqA[colIdx].assign(256, 0); for (int val = 0; val < 256; ++val) { int newVal = mapVal(val, gamma); freqA[colIdx][newVal] += origHist.freqA[colIdx][val]; } } void mapImage(const std::string fileName, float gammaA[]) { std::ifstream inStrm(fileName); std::string format; inStrm >> format; int w = 0, h = 0; inStrm >> w >> h; int maxVal = 0; inStrm >> maxVal; std::cout << "P3" << std::endl; std::cout << w << " " << h << std::endl; std::cout << "255" << std::endl; int nPix = w * h; for (int iPix = 0; iPix < nPix; ++iPix) { int inRgb[3] = {0}; inStrm >> inRgb[0] >> inRgb[1] >> inRgb[2]; int outRgb[3] = {0}; for (int iCol = 0; iCol < 3; ++iCol) { outRgb[iCol] = mapVal(inRgb[iCol], gammaA[iCol]); } std::cout << outRgb[0] << " " << outRgb[1] << " " << outRgb[2] << std::endl; } } int main(int argc, char* argv[]) { if (argc < 5) { std::cerr << "usage: " << argv[0] << " ppmFileName targetR targetG targetB" << std::endl; return 1; } std::string inFileName = argv[1]; int targAvg[3] = {0}; std::istringstream strmR(argv[2]); strmR >> targAvg[0]; std::istringstream strmG(argv[3]); strmG >> targAvg[1]; std::istringstream strmB(argv[4]); strmB >> targAvg[2]; Histogram origHist; if (!origHist.read(inFileName)) { return 1; } Histogram newHist(origHist); float gammaA[3] = {0.0f}; for (int iCol = 0; iCol < 3; ++iCol) { float minGamma = 0.0f; float maxGamma = 1.0f; for (;;) { newHist.adjust(origHist, iCol, maxGamma); int avg = newHist.getAvg(iCol); if (avg <= targAvg[iCol]) { break; } maxGamma *= 2.0f; } for (;;) { float midGamma = 0.5f * (minGamma + maxGamma); newHist.adjust(origHist, iCol, midGamma); int avg = newHist.getAvg(iCol); if (avg < targAvg[iCol]) { maxGamma = midGamma; } else if (avg > targAvg[iCol]) { minGamma = midGamma; } else { gammaA[iCol] = midGamma; break; } } } mapImage(inFileName, gammaA); return 0; } ``` The code itself is fairly straightforward. One subtle but important detail is that, while the color values are in the range [0, 255], I map them to the gamma curve as if the range were [-1, 256]. This allows the average to be forced to 0 or 255. Otherwise, 0 would always remain 0, and 255 would always remain 255, which might never allow for an average of 0/255. To use: 1. Save the code in a file with extension `.cpp`, e.g. `force.cpp`. 2. Compile with `c++ -o force -O2 force.cpp`. 3. Run with `./force input.ppm targetR targetG target >output.ppm`. ### Sample output for 40, 40, 40 Note that the images for all the larger samples are included as JPEGs since they exceed the SE size limit as PNGs. Since JPEG is a lossy compression format, they may not exactly match the target average. I have the PNG version of all files, which matches exactly. [![Af1](https://i.stack.imgur.com/CytL2s.png)](https://i.stack.imgur.com/CytL2.png) [![Bf1](https://i.stack.imgur.com/RwXaos.jpg)](https://i.stack.imgur.com/RwXao.jpg) [![Cf1](https://i.stack.imgur.com/5YAjWs.jpg)](https://i.stack.imgur.com/5YAjW.jpg) [![Df1](https://i.stack.imgur.com/cBa06s.jpg)](https://i.stack.imgur.com/cBa06.jpg) [![Ef1](https://i.stack.imgur.com/dresys.jpg)](https://i.stack.imgur.com/dresy.jpg) [![Ff1](https://i.stack.imgur.com/mvC8Ns.png)](https://i.stack.imgur.com/mvC8N.png) ### Sample output for 150, 100, 100: [![Af2](https://i.stack.imgur.com/XQzMSs.png)](https://i.stack.imgur.com/XQzMS.png) [![Bf2](https://i.stack.imgur.com/9lmGWs.jpg)](https://i.stack.imgur.com/9lmGW.jpg) [![Cf2](https://i.stack.imgur.com/Lpnmss.jpg)](https://i.stack.imgur.com/Lpnms.jpg) [![Df2](https://i.stack.imgur.com/6RoXas.jpg)](https://i.stack.imgur.com/6RoXa.jpg) [![Ef2](https://i.stack.imgur.com/8AiH8s.jpg)](https://i.stack.imgur.com/8AiH8.jpg) [![Ff2](https://i.stack.imgur.com/vbX33s.png)](https://i.stack.imgur.com/vbX33.png) ### Sample output for 75, 91, 110: [![Af3](https://i.stack.imgur.com/3UrTvs.png)](https://i.stack.imgur.com/3UrTv.png) [![Bf3](https://i.stack.imgur.com/qe7qxs.jpg)](https://i.stack.imgur.com/qe7qx.jpg) [![Cf3](https://i.stack.imgur.com/p3ijos.jpg)](https://i.stack.imgur.com/p3ijo.jpg) [![Df3](https://i.stack.imgur.com/nRTPos.jpg)](https://i.stack.imgur.com/nRTPo.jpg) [![Ef3](https://i.stack.imgur.com/AGcqvs.jpg)](https://i.stack.imgur.com/AGcqv.jpg) [![Ff3](https://i.stack.imgur.com/2eXA4s.png)](https://i.stack.imgur.com/2eXA4.png) [Answer] # Python 2 + PIL ``` from PIL import Image import random import math SOURCE = 'input.png' OUTPUT = 'output.png' AVERAGE = [150, 100, 100] im = Image.open(SOURCE).convert('RGB') pixels = im.load() w = im.size[0] h = im.size[1] npixels = w * h maxdiff = 0.1 # for consistent results... random.seed(42) order = range(npixels) random.shuffle(order) def calc_sum(pixels, w, h): sums = [0, 0, 0] for x in range(w): for y in range(h): for i in range(3): sums[i] += pixels[x, y][i] return sums def get_coordinates(index, w): return tuple([index % w, index // w]) desired_sums = [AVERAGE[0] * npixels, AVERAGE[1] * npixels, AVERAGE[2] * npixels] sums = calc_sum(pixels, w, h) for i in range(3): while sums[i] != desired_sums[i]: for j in range(npixels): if sums[i] == desired_sums[i]: break elif sums[i] < desired_sums[i]: coord = get_coordinates(order[j], w) pixel = list(pixels[coord]) delta = int(maxdiff * (255 - pixel[i])) if delta == 0 and pixel[i] != 255: delta = 1 delta = min(delta, desired_sums[i] - sums[i]) sums[i] += delta pixel[i] += delta pixels[coord] = tuple(pixel) else: coord = get_coordinates(order[j], w) pixel = list(pixels[coord]) delta = int(maxdiff * pixel[i]) if delta == 0 and pixel[i] != 0: delta = 1 delta = min(delta, sums[i] - desired_sums[i]) sums[i] -= delta pixel[i] -= delta pixels[coord] = tuple(pixel) # output image for x in range(w): for y in range(h): im.putpixel(tuple([x, y]), pixels[tuple([x, y])]) im.save(OUTPUT) ``` This iterates through each pixel in a random order, and reduces the distance between each component of the color of the pixel and `255` or `0` (depending on whether the current average is less or greater than the desired average). The distance is reduced by a fixed multiplicative factor. This is repeated until the desired average is obtained. The reduction is always at least `1`, unless the color is `255` (or `0`), to ensure that the processing does not stall once the pixel is close to white or black. ## Sample output ### (40, 40, 40) [![enter image description here](https://i.stack.imgur.com/Mnw38s.png)](https://i.stack.imgur.com/Mnw38.png) [![enter image description here](https://i.stack.imgur.com/S0bFDs.jpg)](https://i.stack.imgur.com/S0bFD.jpg) [![enter image description here](https://i.stack.imgur.com/LKtg2s.jpg)](https://i.stack.imgur.com/LKtg2.jpg) [![enter image description here](https://i.stack.imgur.com/p5ibds.jpg)](https://i.stack.imgur.com/p5ibd.jpg) [![enter image description here](https://i.stack.imgur.com/Ehsu4s.png)](https://i.stack.imgur.com/Ehsu4.png) [![enter image description here](https://i.stack.imgur.com/DmUgzs.png)](https://i.stack.imgur.com/DmUgz.png) ### (150, 100, 100) [![enter image description here](https://i.stack.imgur.com/7hJALs.png)](https://i.stack.imgur.com/7hJAL.png) [![enter image description here](https://i.stack.imgur.com/ta3FDs.jpg)](https://i.stack.imgur.com/ta3FD.jpg) [![enter image description here](https://i.stack.imgur.com/zkDUWs.jpg)](https://i.stack.imgur.com/zkDUW.jpg) [![enter image description here](https://i.stack.imgur.com/5v9pvs.jpg)](https://i.stack.imgur.com/5v9pv.jpg) [![enter image description here](https://i.stack.imgur.com/LipBqs.jpg)](https://i.stack.imgur.com/LipBq.jpg) [![enter image description here](https://i.stack.imgur.com/y8s1ns.png)](https://i.stack.imgur.com/y8s1n.png) ### (75, 91, 110) [![enter image description here](https://i.stack.imgur.com/x0fays.png)](https://i.stack.imgur.com/x0fay.png) [![enter image description here](https://i.stack.imgur.com/YpUdus.jpg)](https://i.stack.imgur.com/YpUdu.jpg) [![enter image description here](https://i.stack.imgur.com/z1sGRs.jpg)](https://i.stack.imgur.com/z1sGR.jpg) [![enter image description here](https://i.stack.imgur.com/VuLRbs.jpg)](https://i.stack.imgur.com/VuLRb.jpg) [![enter image description here](https://i.stack.imgur.com/Qou2is.jpg)](https://i.stack.imgur.com/Qou2i.jpg) [![enter image description here](https://i.stack.imgur.com/gfwO6s.png)](https://i.stack.imgur.com/gfwO6.png) [Answer] # Java An RNG based approach. A bit slow for large input images. ``` import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.util.*; import javax.imageio.ImageIO; public class Averager { static Random r; static long sigmaR=0,sigmaG=0,sigmaB=0; static int w,h; static int rbar,gbar,bbar; static BufferedImage i; private static File file; static void upRed(){ int x=r.nextInt(w); int y=r.nextInt(h); Color c=new Color(i.getRGB(x, y)); if(c.getRed()==255)return; sigmaR++; c=new Color(c.getRed()+1,c.getGreen(),c.getBlue()); i.setRGB(x, y,c.getRGB()); } static void downRed(){ int x=r.nextInt(w); int y=r.nextInt(h); Color c=new Color(i.getRGB(x, y)); if(c.getRed()==0)return; sigmaR--; c=new Color(c.getRed()-1,c.getGreen(),c.getBlue()); i.setRGB(x, y,c.getRGB()); } static void upGreen(){ int x=r.nextInt(w); int y=r.nextInt(h); Color c=new Color(i.getRGB(x, y)); if(c.getGreen()==255)return; sigmaG++; c=new Color(c.getRed(),c.getGreen()+1,c.getBlue()); i.setRGB(x, y,c.getRGB()); } static void downGreen(){ int x=r.nextInt(w); int y=r.nextInt(h); Color c=new Color(i.getRGB(x, y)); if(c.getGreen()==0)return; sigmaG--; c=new Color(c.getRed(),c.getGreen()-1,c.getBlue()); i.setRGB(x,y,c.getRGB()); } static void upBlue(){ int x=r.nextInt(w); int y=r.nextInt(h); Color c=new Color(i.getRGB(x, y)); if(c.getBlue()==255)return; sigmaB++; c=new Color(c.getRed(),c.getGreen(),c.getBlue()+1); i.setRGB(x, y,c.getRGB()); } static void downBlue(){ int x=r.nextInt(w); int y=r.nextInt(h); Color c=new Color(i.getRGB(x, y)); if(c.getBlue()==0)return; sigmaB--; c=new Color(c.getRed(),c.getGreen(),c.getBlue()-1); i.setRGB(x,y,c.getRGB()); } public static void main(String[]a) throws Exception{ Scanner in=new Scanner(System.in); i=ImageIO.read(file=new File(in.nextLine())); rbar=in.nextInt(); gbar=in.nextInt(); bbar=in.nextInt(); w=i.getWidth(); h=i.getHeight(); final int npix=w*h; r=new Random(npix*(long)i.hashCode()); for(int x=0;x<w;x++){ for(int y=0;y<h;y++){ Color c=new Color(i.getRGB(x, y)); sigmaR+=c.getRed(); sigmaG+=c.getGreen(); sigmaB+=c.getBlue(); } } while(sigmaR/npix<rbar){ upRed(); } while(sigmaR/npix>rbar){ downRed(); } while(sigmaG/npix<gbar){ upGreen(); } while(sigmaG/npix>gbar){ downGreen(); } while(sigmaB/npix<bbar){ upBlue(); } while(sigmaB/npix>bbar){ downBlue(); } String k=file.getName().split("\\.")[0]; ImageIO.write(i,"png",new File(k="out_"+k+".png")); } } ``` Tests: (40,40,40) ![enter image description here](https://i.stack.imgur.com/0VlB1.png)![enter image description here](https://i.stack.imgur.com/L34Y9.png)![enter image description here](https://i.stack.imgur.com/6j3oF.png)![enter image description here](https://i.stack.imgur.com/FTE1H.png)![enter image description here](https://i.stack.imgur.com/Qg88A.png)![enter image description here](https://i.stack.imgur.com/ONJsk.png) (150,100,100) ![enter image description here](https://i.stack.imgur.com/a88xG.png)![enter image description here](https://i.stack.imgur.com/S4ON2.png)![enter image description here](https://i.stack.imgur.com/FxZwL.png)![enter image description here](https://i.stack.imgur.com/iRbEO.png)![enter image description here](https://i.stack.imgur.com/EAQoI.png)![enter image description here](https://i.stack.imgur.com/XNr2V.png) (75,91,110) ![enter image description here](https://i.stack.imgur.com/pgEOH.png)![enter image description here](https://i.stack.imgur.com/1OioA.png)![enter image description here](https://i.stack.imgur.com/UgZYe.png)![enter image description here](https://i.stack.imgur.com/bO88E.png)![enter image description here](https://i.stack.imgur.com/CIvZF.png)![enter image description here](https://i.stack.imgur.com/d4k0W.png) ]
[Question] [ **Leaderboard - JIT Compiled (Lower is better)** > > 1. es1024 - 81.2 points (including a working compiler!) > 2. Kieth Randall - 116 points > 3. Ell - 121 points > > > **Leaderboard - Interpreted (Lower is better)** > > 1. Martin Büttner - 706654 points (somewhere around 2 hours). > 2. criptych - 30379 points (97 seconds) > > > Your mission, should you choose to accept it, is to write the smallest possible bytecode interpreter/VM. The VM/interpreter uses a small CISC architecture (operations can vary in size), with the language specified below. Upon completion, you must print the value of the 3 CPU registers to prove that the correct output is printed (3,126,900,366). **Compiler** If you'd like to make your own tests, a compiler is posted below. Feel free to post your tests with your answer. ``` window.compile=function(){var e=$("#text").val().toLowerCase().match(/[^\r\n]+/g);var t=[];for(var n=0;n<e.length;n++)compileLine(e[n],t);var r="";for(var n=0;n<t.length;n++)if(typeof t[n]=="string")r+="\n";else r+="0x"+t[n].toString(16)+" ";$("#compiledArray").val(r)};window.compileLine=function(e,t){var n=e.split(" ");if(n[0]=="load"){t.push(0);t.push(getInt(n[1]));t.pushArr(getInt(n[2]))}if(n[0]=="rload"){t.push(1);t.push(getInt(n[1]));t.push(getInt(n[1]))}if(n[0]=="push"){t.push(2);t.push(getInt(n[1]))}if(n[0]=="pop"){t.push(3);t.push(getInt(n[1]))}if(n[0]=="add"){t.push(4);t.push(getInt(n[1]));t.push(getInt(n[2]))}if(n[0]=="sub"){t.push(5);t.push(getInt(n[1]));t.push(getInt(n[2]))}if(n[0]=="mul"){t.push(6);t.push(getInt(n[1]));t.push(getInt(n[2]))}if(n[0]=="div"){t.push(7);t.push(getInt(n[1]));t.push(getInt(n[2]))}if(n[0]=="jmp"){t.push(8);t.pushArr(getInt(n[1]))}if(n[0]=="cmp"){t.push(9);t.push(getInt(n[1]));t.push(getInt(n[2]))}if(n[0]=="branchlt"){t.push(10);t.pushArr(getInt(n[1]))}if(n[0]=="brancheq"){t.push(11);t.pushArr(getInt(n[1]))}if(n[0]=="branchgt"){t.push(12);t.pushArr(getInt(n[1]))}if(n[0]=="branchne"){t.push(13);t.pushArr(getInt(n[1]))}t.push("NEW LINE")};window.getInt=function(e){if(e.trim().startsWith("<--"))return"COMMENT";if(e=="r0")return 0;if(e=="r1")return 1;if(e=="r2")return 2;if(e.startsWith("0x"))return parseInt(e,16);if(isNaN(parseInt(e)))alert(e);return getIntBytes(parseInt(e))};if(typeof String.prototype.startsWith!="function"){String.prototype.startsWith=function(e){return this.slice(0,e.length)==e}}Array.prototype.pushArr=function(e){this.push.apply(this,e)};window.getIntBytes=function(e){var t=[];var n=4;do{t[--n]=e&255;e=e>>8}while(n);return t} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <textarea id="text" cols="40" rows="10"></textarea> <br/> <button onclick="compile()">Compile</button> <br/> <textarea id="compiledArray" cols="40" rows="10" readonly></textarea> ``` **"VM" Specifications** The VM has 3 32 bit unsigned integral registers: R0, R1, R2. They are represented in hex as 0x00, 0x01, and 0x02. The following operations must be supported: The format is [name] [...operands...], [hexadecimal op-code] [...operands repeated...] * LOAD [register] [4 byte value], 0x00 [register] [4 byte value] * PUSH [register], 0x02 [register] * POP [register], 0x03 [register] * ADD [register, 1 byte] [register, 1 byte], 0x04 [register] [register] * SUB [register, 1 byte] [register, 1 byte], 0x05 [register] [register] * MUL [register, 1 byte] [register, 1 byte], 0x06 [register] [register] * DIV [register, 1 byte] [register, 1 byte], 0x07 [register] [register] * JMP [code line, 4 bytes], 0x08 [4 byte code line number] * CMP [register, 1 byte] [register, 1 byte], 0x09 [register] [register] * BRANCHLT [code line, 4 bytes], 0x0a [4 byte code line number] Some notes: * The above math operations add the values of 2 registers together, placing the output in the first register. * CMP, the comparison operator, should compare the values of 2 registers and store the output in some internal flag (this can be implementation specific) for future use on branch instructions. * If BRANCH is called before CMP, unless BRANCHEQ is called, the "VM" should not branch. * PUSH/POP unsurprisingly push or pop numbers from the stack. * Jump and Branch operators jump to a specific operation (line of code), not a binary address. * Branch operations do not do the comparison. Rather, they take the output from the last comparison to execute. * Branch and Jump operators use a zero based line number indexing system. (E.g. JMP 0 jumps to the first line) * All operations are to be performed on unsigned numbers which overflow to zero and do not throw an exception on an integer overflow. * Division by zero is not allowed and as such, the behavior of the program is not defined. You can (for example)... + Crash the program. + End execution of the VM and return it's current state. + Show a "ERR: Division by 0" message. * Termination of the program is defined as when the instruction pointer reaches the end of the program (a non empty program can be assumed). **Output** The output must be exactly this (newlines included) ``` R0 3126900366 R1 0 R2 10000 ``` **Points** Points are calculated based on the following formula: `Number Of Characters * (Seconds Needed To Run / 2)` To avoid hardware differences causing different times, each test will be run on my computer (i5-4210u, 8GB ram) in either ubuntu server or Windows 8, so try not to use some insane-exotic-runtime that only compiles on a Dual G5 Mac Pro with exactly 762.66 mb of free RAM. If you are using a specialized runtime/language, please post a link to it. * For interested parties, I have posted the testing code (written in C#) here: <http://pastebin.com/WYCG5Uqu> **Test Program** The idea came from [here](http://byteworm.com/2010/11/21/the-fastest-vm-bytecode-interpreter/), so we'll use a somewhat modified version of their program. The correct output for the program is: 3,126,900,366 In C: ``` int s, i, j; for (s = 0, i = 0; i < 10000; i++) { for (j = 0; j < 10000; j++) s += (i * j) / 3; } ``` In code: [R0 is representative of s, R1 of j, R2 of i] ``` LOAD R0 0 LOAD R2 0 <--outer loop value LOAD R1 0 <--inner loop value --Begin inner loop-- PUSH R1 <--push inner loop value to the stack MUL R1 R2 <--(i*j) PUSH R2 LOAD R2 3 DIV R1 R2 <-- / 3 POP R2 ADD R0 R1 <-- s+= POP R1 PUSH R2 LOAD R2 1 ADD R1 R2 <--j++ POP R2 PUSH R2 LOAD R2 10000 CMP R1 R2 <-- j < 10000 POP R2 BRANCHLT 3 <--Go back to beginning inner loop --Drop To outer loop-- LOAD R1 1 ADD R2 R1 <--i++ LOAD R1 10000 CMP R2 R1 <-- i < 10000 LOAD R1 0 <--Reset inner loop BRANCHLT 2 ``` In binary/hex: ``` 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x02 0x00 0x00 0x00 0x00 0x00 0x01 0x00 0x00 0x00 0x00 0x02 0x01 0x06 0x01 0x02 0x02 0x02 0x00 0x02 0x00 0x00 0x00 0x03 0x07 0x01 0x02 0x03 0x02 0x04 0x00 0x01 0x03 0x01 0x02 0x02 0x00 0x02 0x00 0x00 0x00 0x01 0x04 0x01 0x02 0x03 0x02 0x02 0x02 0x00 0x02 0x00 0x00 0x27 0x10 0x09 0x01 0x02 0x03 0x02 0x0a 0x00 0x00 0x00 0x03 0x00 0x01 0x00 0x00 0x00 0x01 0x04 0x02 0x01 0x00 0x01 0x00 0x00 0x27 0x10 0x09 0x02 0x01 0x00 0x01 0x00 0x00 0x00 0x00 0x0a 0x00 0x00 0x00 0x02 ``` **Bonus Points** (Effects are applied multiplicatively) E.g. if you qualify for all three, it would be ((characters \* 0.50) \* 0.75) \* 0.90 * 50% decrease if the interpreter is actually a JIT compiler * 25% decrease if it applies any sort of loop unrolling/meaningful optimization. * 10% decrease if you extend the VM with + BRANCHEQ [code line, 4 bytes] (Branch if equal - opcode 0x0b) + BRANCHGT [code line, 4 bytes] (Branch if greater than - opcode 0x0c) + BRANCHNE [code line, 4 bytes] (Branch if not equal - opcode 0x0d) + RLOAD [register 1] [register 2] (move the value of register 2 to register 1 - opcode 0x01). **Disallowed** * Precompiling the test case into the program is prohibited. You must either accept the bytecode from STDIN or from a file (Doesn't matter which). * Returning the output without running the program. * Any other way you can think of to cheat the VM requirement. [Answer] # C, 752 (589+163 for define flags) \* 0.5 (JIT) \* 0.9 (extensions) \* (0.75 optimization) \* (0.64 seconds/2) = 81.216 ``` C[S],J[S],i,j,k,y,c,X,Y,Z;char*R,a,b[9];main(x){R=mmap(0,S,6,34,-1,0);N=85;while(scanf("%c%s%*[ R]%d%*[ R]%d",&a,b,&x,&y)&&~getchar())a-=65,a-1?a-15?a-9?a?a-2?a-3?a-11?a-12?a-17?(N=41,v):(N=137,v):(N=137,u,N=247,g(H,4),N=139,u):(y?N=189+x,s(y):(N=51,g(G,G))):(N=137,u,N=247,g(H,6),N=139,u):(N=57,v,s(0xFC8A9F),--j):(N=1,v):(N=233,J[k++]=i,s(x)):b[1]-80?N=85+x:(N=93+x):(c=b[5],s(0x0F9EE78A),N=(c-69?c-71?c-76?1:8:11:0)+132,J[k++]=i,s(x)),C[++i]=j;U(E8,X)U(F0,Y)U(F8,Z)s(50013);i=j;while(k--)j=C[J[k]]+1,R[j-1]-233&&(j+=4),s(C[*(int*)(R+j)]-j-4);((int(*)())R)();printf("%u %u %u\n",X,Y,Z);} ``` Takes code (`LOAD R0`, etc), no trailing characters, single space, no blank lines in the middle, no comments, etc. Trailing newline required. This is then converted to 80386 bytecode and executed. Loading `0` into a register is replaced by `xor`ing the register with itself instead of `mov`ing `0` into the register, which is three bytes shorter in the generated bytecode, and may be very marginally faster. Compile with: ``` gcc -m32 -D"g(a,b)=(N=192|b<<3|a)"-D"s(b)=(*(int*)(R+j)=b,j+=4)"-DN=R[j++]-D"G=((x+1)|4)" -D"H=((y+1)|4)"-DS=9999-D"u=g(0,G)"-D"v=g(G,H)"-D"U(b,c)=s(0xA3##b##89),--j,s(&c);" bytecode.c -o bytecode ``` POSIX-compliant OS required. Input is read from STDIN (use `./bytecode < file` to pipe from a file). Resulting bytecode for the test program: ``` ; start 0: 55 push %ebp ; LOAD R0 0 1: 33 ed xor %ebp,%ebp ; LOAD R2 0 3: 33 ff xor %edi,%edi ; LOAD R1 0 5: 33 f6 xor %esi,%esi ; PUSH $1 7: 56 push %esi ; MUL R1 R2 8: 89 f0 mov %esi,%eax a: f7 e7 mul %edi c: 8b f0 mov %eax,%esi ; PUSH R2 e: 57 push %edi ; LOAD R2 3 f: bf 03 00 00 00 mov $0x3,%edi ; DIV R1 R2 14: 89 f0 mov %esi,%eax 16: f7 f7 div %edi 18: 8b f0 mov %eax,%esi ; POP R2 1a: 5f pop %edi ; ADD R0 R1 1b: 01 f5 add %esi,%ebp ; POP R1 1d: 5e pop %esi ; PUSH R2 1e: 57 push %edi ; LOAD R2 1 1f: bf 01 00 00 00 mov $0x1,%edi ; ADD R1 R2 24: 01 fe add %edi,%esi ; POP R2 26: 5f pop %edi ; PUSH R2 27: 57 push %edi ; LOAD R2 10000 28: bf 10 27 00 00 mov $0x2710,%ed ; CMP R1 R2 2d: 39 fe cmp %edi,%esi 2f: 9f lahf 30: 8a fc mov %ah,%bh ; POP R2 32: 5f pop %edi ; BRANCHLT 3 33: 8a e7 mov %bh,%ah 35: 9e sahf 36: 0f 8c cb ff ff ff jl 0x7 ; LOAD R1 1 3c: be 01 00 00 00 mov $0x1,%esi ; ADD R2 R1 41: 01 f7 add %esi,%edi ; LOAD R1 10000 43: be 10 27 00 00 mov $0x2710,%es ; CMP R2 R1 48: 39 f7 cmp %esi,%edi 4a: 9f lahf 4b: 8a fc mov %ah,%bh ; LOAD R1 0 4d: 33 f6 xor %esi,%esi ; BRANCHLT 2 4f: 8a e7 mov %bh,%ah 51: 9e sahf 52: 0f 8c ad ff ff ff jl 0x5 ; copy R0 to X 58: 89 e8 mov %ebp,%eax 5a: a3 28 5b 42 00 mov %eax,0x425b ; copy R1 to Y 5f: 89 f0 mov %esi,%eax 61: a3 38 55 44 00 mov %eax,0x4455 ; copy R2 to Z 66: 89 f8 mov %edi,%eax 68: a3 40 55 44 00 mov %eax,0x4455 ; exit 6d: 5d pop %ebp 6e: c3 ret ``` Ungolfed: ``` C[9999],J[9999],i,j,k,y,c,X,Y,Z; char *R,a,b[9]; main(x){ // 6 is PROC_WRITE|PROC_EXEC // 34 is MAP_ANON|MAP_PRIVATE R=mmap(0,'~~',6,34,-1,0); N=0x55; while(scanf("%c%s%*[ R]%d%*[ R]%d",&a,b,&x,&y)&&~getchar()) a-=65, a-1? // B[RANCH**] a-15? // P[USH/OP] a-9? // J[MP] a? // A[DD] a-2? // C[MP] a-3? // D[IV] a-11? // L[OAD] a-12? // M[UL] a-17? // R[LOAD] // SUB (N=0x29,g(G,H)) :(N=0x89,g(G,H)) :(N=0x89,g(0,G),N=0xF7,g(H,4),N=0x8B,g(0,G)) :(y?N=0xBD+x,s(y):(N=0x33,g(G,G))) :(N=0x89,g(0,G),N=0xF7,g(H,6),N=0x8B,g(0,G)) :(N=0x39,g(G,H),s(0xfc8a9f),--j) :(N=0x1,g(G,H)) :(N=0xE9,J[k++]=i,s(x)) :b[1]-80? N=0x55+x // PUSH :(N=0x5D+x) // POP :(c=b[5],s(0x0f9ee78a),N=( c-69? // EQ c-71? // GT c-76? // LT 1 // NE :8 :11 :0 )+0x84,J[k++]=i,s(x)), C[++i]=j ; // transfer registers to X,Y,Z s(0xA3E889),--j,s(&X); s(0xA3F089),--j,s(&Y); s(0xA3F889),--j,s(&Z); // pop and ret s(0xC35D); i=j; // fix distances for jmp/branch** while(k--) j=C[J[k]]+1,R[j-1]-0xE9&&(j+=4), s(C[*(int*)(R+j)]-j-4); // call ((int(*)())R)(); // output printf("%u %u %u\n",X,Y,Z); } ``` [Answer] ## C, Score = 854byte × (~0.8sec / 2) × 0.5 [JIT] × 0.9 [Extensions] = ~154byte sec ``` #define G getchar() #define L for(i=0;i<3;++i) #define N*(int*) #define M(x)"P\x8a\xe7\x9e\xf"#x" KL" *T[1<<20],**t=T,*F[1<<20],**f=F,R[3],r[]={1,6,7};char*I[]={"L\xb8 GGJH","I\x8b\xc0HHGH","H\x50GG","H\x58GG","I\3\xc0HHGH","I\53\xc0HHGH","M\x8b\xc0\xf7\xe0\x8b\xc0IHLGJ","O\63\xd2\x8b\xc0\xf7\xf0\x8b\xc0IJNGL","L\xe9 KH","L\73\xc0\x9f\x8a\xfcHHGH",M(\x82),M(\x84),M(\x87),M(\x85)},C[1<<24],*c=C;main(i,o,l,g){N c=0xb7ec8b60;c[4]=70;c+=5;while((o=G)>=0){char*s=I[o];l=*s-'G';memcpy(c,s+1,l);for(s+=l+1;o=*s++;){o-='G';if(o<3){g=r[G];c[*s++-'G']|=g<<3*(o&1);if(o>1)c[*s++-'G']|=g<<3;}else{if(o>3)*f++=c+*s-'G';for(i=4;i;--i)c[*s-'G'+i-1]=G;++s;}}*t++=c;c+=l;}*t=c;while(f>F)--f,**f=(int)T[**f]-(int)*f-4;L N&c[7*i]=0x5893e|r[i]<<19,N&c[3+7*i]=R+i;N&c[21]=0xc361e58b;mprotect((int)C>>12<<12,1<<24,7);((void(*)())C)();L printf("R%d %u\n",i,R[i]);} ``` Compile with `gcc vm.c -ovm -m32 -w` on a x86 POSIX compliant OS. Run with `./vm < program`, where `program` is a binary program file. --- Going for the speed. The program performs a pretty straight-forward translation of the input program to x86 machine code and lets the CPU do the rest. For instance, here's the translation of the test program. `ecx`, `esi` and `edi` correspond to `R0`, `R1` and `R2`, respectively; `bh` holds the status flags; `eax` and `edx` are scratch registers; the call-stack corresponds to the VM's stack: ``` # Prologue 0: 60 pusha 1: 8b ec mov ebp,esp 3: b7 46 mov bh,0x46 # LOAD R0 0 5: b9 00 00 00 00 mov ecx,0x0 # LOAD R2 0 <--outer loop value a: bf 00 00 00 00 mov edi,0x0 # LOAD R1 0 <--inner loop value f: be 00 00 00 00 mov esi,0x0 # --Begin inner loop-- # PUSH R1 <--push inner loop value to the stack 14: 56 push esi # MUL R1 R2 <--(i*j) 15: 8b c6 mov eax,esi 15: f7 e7 mul edi 19: 8b f0 mov esi,eax # PUSH R2 1b: 57 push edi # LOAD R2 3 1c: bf 03 00 00 00 mov edi,0x3 # DIV R1 R2 <-- / 3 21: 33 d2 xor edx,edx 23: 8b c6 mov eax,esi 25: f7 f7 div edi 27: 8b f0 mov esi,eax # POP R2 29: 5f pop edi # ADD R0 R1 <-- s+= 2a: 03 ce add ecx,esi # POP R1 2c: 5e pop esi # PUSH R2 2d: 57 push edi # LOAD R2 1 2e: bf 01 00 00 00 mov edi,0x1 # ADD R1 R2 <--j++ 33: 03 f7 add esi,edi # POP R2 35: 5f pop edi # PUSH R2 36: 57 push edi # LOAD R2 10000 37: bf 10 27 00 00 mov edi,0x2710 # CMP R1 R2 <-- j < 10000 3c: 3b f7 cmp esi,edi 3e: 9f lahf 3f: 8a fc mov bh,ah # POP R2 41: 5f pop edi # BRANCHLT 4 <--Go back to beginning inner loop 42: 8a e7 mov ah,bh 44: 9e sahf 45: 0f 82 c9 ff ff ff jb 0x14 # --Drop To outer loop-- # LOAD R1 1 4b: be 01 00 00 00 mov esi,0x1 # ADD R2 R1 <--i++ 50: 03 fe add edi,esi # LOAD R1 10000 52: be 10 27 00 00 mov esi,0x2710 # CMP R2 R1 <-- i < 10000 57: 3b fe cmp edi,esi 59: 9f lahf 5a: 8a fc mov bh,ah # LOAD R1 0 <--Reset inner loop 5c: be 00 00 00 00 mov esi,0x0 # BRANCHLT 3 61: 8a e7 mov ah,bh 63: 9e sahf 64: 0f 82 a5 ff ff ff jb 0xf # Epilogue 6a: 3e 89 0d 60 ac 04 09 mov DWORD PTR ds:0x904ac60,ecx 71: 3e 89 35 64 ac 04 09 mov DWORD PTR ds:0x904ac64,esi 78: 3e 89 3d 68 ac 04 09 mov DWORD PTR ds:0x904ac68,edi 7f: 8b e5 mov esp,ebp 81: 61 popa 82: c3 ret ``` --- **Ungolfed** ``` #include <stdio.h> #include <stdint.h> #include <string.h> #include <sys/mman.h> #define MAX_INST_COUNT (1 << 20) #define MAX_CODE_SIZE (8 * MAX_INST_COUNT) #define PAGE_SIZE (1 << 12) uintptr_t *targets[MAX_INST_COUNT], **targets_ptr = targets; int32_t *fixups[MAX_INST_COUNT], **fixups_ptr = fixups; char code[MAX_CODE_SIZE], *code_ptr = code; uint32_t R[3]; const char* inst_defs[] = { /* LOAD */ "\5\xb8 \1\0\4\1", /* RLOAD */ "\2\x8b\xc0\2\1\1\1", /* PUSH */ "\1\x50\1\0", /* POP */ "\1\x58\1\0", /* ADD */ "\2\x03\xc0\2\1\1\1", /* SUB */ "\2\x2b\xc0\2\1\1\1", /* MUL */ "\6\x8b\xc0\xf7\xe0\x8b\xc0\3\1\5\1\3", /* DIV */ "\x8\x33\xd2\x8b\xc0\xf7\xf0\x8b\xc0\3\3\7\1\5", /* JMP */ "\5\xe9 \5\1", /* CMP */ "\5\x3b\xc0\x9f\x8a\xfc\2\1\1\1", /* BRANCHLT */ "\x9\x8a\xe7\x9e\x0f\x82 \5\5", /* BRANCHEQ */ "\x9\x8a\xe7\x9e\x0f\x84 \5\5", /* BRANCHGT */ "\x9\x8a\xe7\x9e\x0f\x87 \5\5", /* BRANCHNE */ "\x9\x8a\xe7\x9e\x0f\x85 \5\5" }; int main() { int i; { const char prologue[] = /* PUSHAD */ "\x60" /* MOV EBP, ESP */ "\x8b\xec" /* MOV BH, 46h */ "\xb7\x46" ; memcpy(code_ptr, prologue, sizeof(prologue) - 1); code_ptr += sizeof(prologue) - 1; } { const char reg[] = {1, 6, 7}; char r; int op; while ((op = getchar()) != EOF) { const char* def = inst_defs[op]; int len = def[0]; memcpy(code_ptr, def + 1, len); for (def += len + 1; *def; ) { switch (*def++) { case 1: code_ptr[*def++] |= reg[getchar()]; break; case 2: code_ptr[*def++] |= reg[getchar()] << 3; break; case 3: r = reg[getchar()]; code_ptr[*def++] |= r; code_ptr[*def++] |= r << 3; break; case 5: *fixups_ptr = code_ptr + *def; ++fixups_ptr; case 4: for (i = 4; i; --i) code_ptr[*def + i - 1] = getchar(); ++def; break; } } *targets_ptr = code_ptr; ++targets_ptr; code_ptr += len; } *targets_ptr = code_ptr; ++targets_ptr; while (fixups_ptr != fixups) { --fixups_ptr; **fixups_ptr = (char*)targets[**fixups_ptr] - (char*)*fixups_ptr - 4; } } { const char epilogue[] = /* MOV R[0], ECX */ "\x3e\x89\x0d " /* MOV R[1], ESI */ "\x3e\x89\x35 " /* MOV R[2], EDI */ "\x3e\x89\x3d " /* MOV ESP, EBP */ "\x8b\xe5" /* POPAD */ "\x61" /* RET */ "\xc3" ; memcpy(code_ptr, epilogue, sizeof(epilogue) - 1); for (i = 0; i < 3; ++i) *(uintptr_t*)&code_ptr[3 + 7 * i] = &R[i]; code_ptr += sizeof(epilogue) - 1; } mprotect( (uintptr_t)code / PAGE_SIZE * PAGE_SIZE, MAX_CODE_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC ); { void (*program)(void) = code; program(); } for (i = 0; i < 3; ++i) printf("R%d %u\n", i, R[i]); return 0; } ``` [Answer] # CJam, ~~222~~ ~~187~~ 185 bytes \* (too slow / 2) I just wanted to see how short I can get a bytecode VM by writing it in CJam. Less than 200 bytes seems pretty decent. It's damn slow though, because CJam itself is interpreted. It takes ages to run the test program. ``` 304402480 6b:P;q:iD-);{(_P=@/(\L*@@+\}h;]:P;TTT]:R;{_Rf=~}:Q;{4G#%R@0=@t:R;}:O;{TP=("R\(\GG*bt:R; ~R= R\~@t:R; Q+O Q4G#+-O Q*O Q/O ~(:T; Rf=~-:U; GG*bU0<{(:T}*;"S/=~T):TP,<}g3,{'R\_S\R=N}/ ``` To run it, download the Java interpreter at [this sourceforge link](https://sourceforge.net/projects/cjam/), save the code in `vm.cjam` and run it with ``` java -jar cjam-0.6.2.jar vm.cjam ``` The program expects the bytecode on STDIN. I haven't found a way yet to pipe binary data into a program, without PowerShell adding a trailing line break and converting `0x0a` to `0x0d 0x0a`, which is really annoying. The code includes 4 bytes to fix that (`D-);`), which I haven't included in the total count, because it's not something the program should need to do if it actually received the bytecode itself on STDIN, instead of some weirdly encoded version of it. If someone knows a fix for that, please let me know. Slightly ungolfed: ``` 304402480 6b:P; "Create lookup table for instruction sizes. Store in P."; q:i "Read program and convert bytes to integers."; D-); "Remove spurious carriage returns. This shouldn't be necessary."; {(_P=@/(\L*@@+\}h;]:P; "Split into instructions. Store in P."; "We'll use T for the instruction pointer as it's initialised to 0."; "Likewise, we'll use U for the CMP flag."; TTT]:R; "Store [0 0 0] in R for the registers."; {_Rf=~}:Q; "Register lookup block."; {4G#%R@0=@t:R;}:O; "Save in register block."; {TP=("R\(\GG*bt:R; ~R= R\~@t:R; Q+O Q4G#+-O Q*O Q/O ~(:T; Rf=~-:U; GG*bU0<{(:T}*;"N/=~T):TP,<}g "Run program."; 3,{'R\_S\R=N}/ ``` I'll add a proper explanation tomorrow. In short, I'm storing all the registers, the instruction pointer and the comparison flag in variables, so that I can keep CJam's stack free to use as the VM's stack. [Answer] ## python/c++, score=56.66 1435 chars \* .234/2 seconds \* .5 [JIT] \* .75 [Optimization] \* .90 [Extra instructions] Compiles the input program to c++, runs gcc on it, then runs the result. Most of the time is spent inside gcc. The one optimization I do is reduce the stack operations to explicit variables if it is allowed semantically. It helps a lot, about 10x better runtime of the compiled code (about .056 sec to actually run the resulting binary). I'm not sure what gcc is doing that gets you that improvement, but it's good. ``` import sys,os x=map(ord,sys.stdin.read()) w=lambda x:(x[0]<<24)+(x[1]<<16)+(x[2]<<8)+x[3] I=[] while x: if x[0]==0:f='r%d=%d'%(x[1],w(x[2:]));n=6 if x[0]==1:f='r%d=r%d'%(x[1],x[2]);n=3 if x[0]==2:f='P%d'%x[1];n=2 if x[0]==3:f='O%d'%x[1];n=2 if x[0]==4:f='r%d=r%d+r%d'%(x[1],x[1],x[2]);n=3 if x[0]==5:f='r%d=r%d-r%d'%(x[1],x[1],x[2]);n=3 if x[0]==6:f='r%d=r%d*r%d'%(x[1],x[1],x[2]);n=3 if x[0]==7:f='r%d=r%d/r%d'%(x[1],x[1],x[2]);n=3 if x[0]==8:f='goto L%d'%w(x[1:]);n=5 if x[0]==9:f='a=r%d;b=r%d'%(x[1],x[2]);n=3 if x[0]==10:f='if(a<b)goto L%d'%w(x[1:]);n=5 if x[0]==11:f='if(a==b)goto L%d'%w(x[1:]);n=5 if x[0]==12:f='if(a>b)goto L%d'%w(x[1:]);n=5 if x[0]==13:f='if(a!=b)goto L%d'%w(x[1:]);n=5 I+=[f];x=x[n:] D=[] d=0 for f in I:D+=[d];d+='P'==f[0];d-='O'==f[0] J=[] if all(d==D[int(f[f.find('L')+1:])]for f,d in zip(I,D)if f[0]in'gi'): H='uint32_t '+','.join('s%d'%i for i in range(max(D)))+';' for f,d in zip(I,D): if f[0]=='P':f='s%d=r'%d+f[1:] if f[0]=='O':f='r'+f[1:]+'=s%d'%(d-1) J+=[f] else: H='std::vector<uint32_t>s;' for f,d in zip(I,D): if f[0]=='P':f='s.push_back(r'+f[1:]+')' if f[0]=='O':f='r'+f[1:]+'=s.back();s.pop_back()' J+=[f] P='#include<vector>\n#include<cstdint>\nuint32_t r0,r1,r2,a,b;'+H+'int main(){' for i,f in enumerate(J):P+='L%d:'%i+f+';' P+=r'printf("R0 %u\nR1 %u\nR2 %u\n",r0,r1,r2);}' c=open("t.cc", "w") c.write(P) c.close() os.system("g++ -O1 t.cc") os.system("./a.out") ``` Could certainly be golfed some more. [Answer] # Lua 5.2 (or LuaJIT), 740 bytes First try, only minimally golfed. This version works (at least on the test program), and implements the extra opcodes, but doesn't uphold the unsigned math requirement and isn't particularly fast. As a bonus, though, it's a VM running in a VM, and is written such that it can be either interpreted (run with PUC-Lua) or sort-of-JIT (run with LuaJIT; still interpreted, but the interpreter is now JITted). **EDIT:** Golfed better, still big. **EDIT:** Fixed a major error, and now restricts arithmetic to `unsigned long` range. Somehow managed to keep the size from getting out of hand, though, but it's still giving the wrong answer. **EDIT:** Turns out, the result was correct but the output wasn't. Switched to printing with `%u` instead of `%d` and all is well. Also switched out table-based registers for variables to improve the size *and* speed somewhat. **EDIT:** Using Lua 5.2's `goto` statement (also available in LuaJIT) I've replaced the interpreter with "JIT-to-Lua," generating code which is run directly by the Lua VM itself. Not sure if this really counts as JIT, but it does improve the speed. ``` U,S,P,F=table.unpack,table.insert,table.remove,math.floor X,r0,r1,r2,p,m,s=2^32,0,0,0,1,0,{}C={{'r%u=%u',1,4},{'r%u=r%u',1,1},{'S(s,r%u)',1},{'r%u=P(s)',1},{'r%u=(r%u+r%u)%%X',1,0,1},{'r%u=(r%u-r%u)%%X',1,0,1},{'r%u=(r%u*r%u)%%X',1,0,1},{'r%u=F(r%u/r%u)%%X',1,0,1},{'goto L%u',4},{'m=r%u-r%u',1,1},{'if m<0 then goto L%u end',4},{'if m==0 then goto L%u end',4},{'if m>0 then goto L%u end',4},{'if m~=0 then goto L%u end',4}}t={io.open(arg[1],'rb'):read('*a'):byte(1,-1)}i,n,r=1,0,{}while i<=#t do c,i,x,a=C[t[i]+1],i+1,0,{}for j=2,#c do y=c[j]if y>0 then x=0 for k=1,y do i,x=i+1,x*256+t[i]end end S(a,x)end S(r,('::L%d::'):format(n))n=n+1 S(r,c[1]:format(U(a)))end load(table.concat(r,' '))()print(('R0 %u\nR1 %u\nR2 %u'):format(r0,r1,r2)) ``` Here's the original, readable version. ``` U,S,P,F=table.unpack,table.insert,table.remove,math.floor X,r0,r1,r2,p,m,s=2^32,0,0,0,1,0,{} C={ {'r%u=%u',1,4}, {'r%u=r%u',1,1}, {'S(s,r%u)',1}, {'r%u=P(s)',1}, {'r%u=(r%u+r%u)%%X',1,0,1}, {'r%u=(r%u-r%u)%%X',1,0,1}, {'r%u=(r%u*r%u)%%X',1,0,1}, {'r%u=F(r%u/r%u)%%X',1,0,1}, {'goto L%u',4}, {'m=r%u-r%u',1,1}, {'if m<0 then goto L%u end',4}, {'if m==0 then goto L%u end',4}, {'if m>0 then goto L%u end',4}, {'if m~=0 then goto L%u end',4}, } t={io.open(arg[1],'rb'):read('*a'):byte(1,-1)} i,n,r=1,0,{} while i<=#t do c,i,x,a=C[t[i]+1],i+1,0,{} for j=2,#c do y=c[j] if y>0 then x=0 for k=1,y do i,x=i+1,x*256+t[i] end end S(a,x) end S(r,('::L%d::'):format(n)) n=n+1 S(r,c[1]:format(U(a))) end load(table.concat(r,' '))() print(('R0 %u\nR1 %u\nR2 %u'):format(r0,r1,r2)) ``` [Answer] ## C# 1505 1475 bytes This is my version of the interpreter, written in C# could be optimized / golfed more I think, but I don't really know where ;) golfed version: ``` using System;using System.Collections.Generic;using System.IO;using System.Linq;class M{static void Main(string[]a){if(a.Length==1&&File.Exists(a[0])){B.E(B.P(File.ReadAllLines(a[0])));Console.WriteLine(B.O);}}}class B{public enum I{L=0x00,P=0x02,Q=0x03,A=0x04,S=0x05,M=0x06,D=0x07,J=0x08,C=0x09,BL=0x0a,BE=0x0b,BG=0x0c,BN=0x0d}public enum R{A,B,C}enum C{N,L,E,G}public static Dictionary<R,uint>r=new Dictionary<R,uint>{{R.A,0},{R.B,0},{R.C,0}};public static Stack<uint>s=new Stack<uint>();static C c=C.N;public static string O{get{return string.Format("R0 {0}\nR1 {1}\nR2 {2}",r[R.A],r[R.B],r[R.C]);}}public static void E(byte[][]l){for(uint i=0;i<l.Length;i++){var q=l[i];switch((I)q[0]){case I.L:r[(R)q[1]]=U(q,2);break;case I.P:r[(R)q[1]]=s.Pop();break;case I.Q:s.Push(r[(R)q[1]]);r[(R)q[1]]=0;break;case I.A:s.Push(r[(R)q[1]]+r[(R)q[2]]);break;case I.S:s.Push(r[(R)q[1]]-r[(R)q[2]]);break;case I.M:s.Push(r[(R)q[1]]*r[(R)q[2]]);break;case I.D:s.Push(r[(R)q[1]]/r[(R)q[2]]);break;case I.J:i=U(q,1)-1;break;case I.C:{uint x=r[(R)q[1]],y=r[(R)q[2]];c=x<y?C.L:x>y?C.G:C.E;}break;case I.BL:if(c==C.L)i=U(q,1)-1;break;case I.BG:if(c==C.G)i=U(q,1)-1;break;case I.BE:if(c==C.E)i=U(q,1)-1;break;case I.BN:if(c!=C.E)i=U(q,1)-1;break;}}}public static byte[][]P(string[]c){return c.Where(l=>!l.StartsWith("#")).Select(r=>r.Split(' ').Where(b=>b.Length>0).Select(b=>Convert.ToByte(b,16)).ToArray()).Where(l=>l.Length>0).ToArray();}static uint U(byte[]b,int i){return(uint)(b[i]<<24|b[i+1]<<16|b[i+2]<<8|b[i+3]);}} ``` ### edit removed some unnecessary `public` and `private` modifiers: ``` using System;using System.Collections.Generic;using System.IO;using System.Linq;class M{static void Main(string[]a){if(a.Length==1&&File.Exists(a[0])){B.E(B.P(File.ReadAllLines(a[0])));Console.Write(B.O);}}}class B{enum I{L=0x00,P=0x02,Q=0x03,A=0x04,S=0x05,M=0x06,D=0x07,J=0x08,C=0x09,BL=0x0a,BE=0x0b,BG=0x0c,BN=0x0d}enum R{A,B,C}enum C{N,L,E,G}static Dictionary<R,uint>r=new Dictionary<R,uint>{{R.A,0},{R.B,0},{R.C,0}};static Stack<uint>s=new Stack<uint>();static C c=C.N;public static string O{get{return string.Format("R0 {0}\nR1 {1}\nR2 {2}\n",r[R.A],r[R.B],r[R.C]);}}public static void E(byte[][]l){for(uint i=0;i<l.Length;i++){var q=l[i];switch((I)q[0]){case I.L:r[(R)q[1]]=U(q,2);break;case I.P:r[(R)q[1]]=s.Pop();break;case I.Q:s.Push(r[(R)q[1]]);r[(R)q[1]]=0;break;case I.A:s.Push(r[(R)q[1]]+r[(R)q[2]]);break;case I.S:s.Push(r[(R)q[1]]-r[(R)q[2]]);break;case I.M:s.Push(r[(R)q[1]]*r[(R)q[2]]);break;case I.D:s.Push(r[(R)q[1]]/r[(R)q[2]]);break;case I.J:i=U(q,1)-1;break;case I.C:{uint x=r[(R)q[1]],y=r[(R)q[2]];c=x<y?C.L:x>y?C.G:C.E;}break;case I.BL:if(c==C.L)i=U(q,1)-1;break;case I.BG:if(c==C.G)i=U(q,1)-1;break;case I.BE:if(c==C.E)i=U(q,1)-1;break;case I.BN:if(c!=C.E)i=U(q,1)-1;break;}}}public static byte[][]P(string[]c){return c.Where(l=>!l.StartsWith("#")).Select(r=>r.Split(' ').Where(b=>b.Length>0).Select(b=>Convert.ToByte(b,16)).ToArray()).Where(l=>l.Length>0).ToArray();}static uint U(byte[]b,int i){return(uint)(b[i]<<24|b[i+1]<<16|b[i+2]<<8|b[i+3]);}} ``` call it with `executable.exe filename` where `filename` is the file containing the code to be interpreted My "test program": ``` # LOAD R0 5 # CMP R0 R1 # BRANCHEQ 13 # LOAD R1 1 # LOAD R2 1 # CMP R0 R2 # MUL R1 R2 # LOAD R1 1 # ADD R2 R1 # PUSH R2 # PUSH R1 # BRANCHEQ 13 # JMP 5 # POP R2 # POP R0 # POP R1 # PUSH R0 0x0 0x0 0x0 0x0 0x0 0x5 0x9 0x0 0x1 0xb 0x0 0x0 0x0 0xd 0x0 0x1 0x0 0x0 0x0 0x1 0x0 0x2 0x0 0x0 0x0 0x1 0x9 0x0 0x2 0x6 0x1 0x2 0x0 0x1 0x0 0x0 0x0 0x1 0x4 0x2 0x1 0x2 0x2 0x2 0x1 0xb 0x0 0x0 0x0 0xd 0x8 0x0 0x0 0x0 0x5 0x3 0x2 0x3 0x0 0x3 0x1 0x2 0x0 ``` Interpreter ungolfed with longer names variables, classes, ... ``` using System; using System.Collections.Generic; using System.IO; using System.Linq; class Program { static void Main(string[] args) { if (args.Length == 1 && File.Exists(args[0])) { var code = ByteCodeInterpreter.ParseCode(File.ReadAllLines(args[0])); ByteCodeInterpreter.Execute(code); Console.WriteLine(ByteCodeInterpreter.Output); } } } public static class ByteCodeInterpreter { public enum Instruction : byte { LOAD = 0x00, PUSH = 0x02, POP = 0x03, ADD = 0x04, SUB = 0x05, MUL = 0x06, DIV = 0x07, JMP = 0x08, CMP = 0x09, BRANCHLT = 0x0a, BRANCHEQ = 0x0b, BRANCHGT = 0x0c, BRANCHNE = 0x0d } public enum Register : byte { R0 = 0x00, R1 = 0x01, R2 = 0x02 } private enum CompareFlag : byte { NONE = 0x00, LT = 0x01, EQ = 0x02, GT = 0x03, } public static readonly Dictionary<Register, uint> register = new Dictionary<Register, uint> { {Register.R0, 0}, {Register.R1, 0}, {Register.R2, 0} }; public static readonly Stack<uint> stack = new Stack<uint>(); private static CompareFlag compareFlag = CompareFlag.NONE; public static string Output { get { return string.Format("R0 {0}\nR1 {1}\nR2 {2}", register[Register.R0], register[Register.R1], register[Register.R2]); } } public static void Execute(byte[][] lines) { for (uint i = 0; i < lines.Length; i++) { var line = lines[i]; switch ((Instruction)line[0]) { case Instruction.LOAD: register[(Register)line[1]] = GetUint(line, 2); break; case Instruction.PUSH: register[(Register)line[1]] = stack.Pop(); break; case Instruction.POP: stack.Push(register[(Register)line[1]]); register[(Register)line[1]] = 0; break; case Instruction.ADD: stack.Push(register[(Register)line[1]] + register[(Register)line[2]]); break; case Instruction.SUB: stack.Push(register[(Register)line[1]] - register[(Register)line[2]]); break; case Instruction.MUL: stack.Push(register[(Register)line[1]] * register[(Register)line[2]]); break; case Instruction.DIV: stack.Push(register[(Register)line[1]] / register[(Register)line[2]]); break; case Instruction.JMP: i = GetUint(line, 1) - 1; break; case Instruction.CMP: { uint v0 = register[(Register)line[1]], v1 = register[(Register)line[2]]; if (v0 < v1) compareFlag = CompareFlag.LT; else if (v0 > v1) compareFlag = CompareFlag.GT; else compareFlag = CompareFlag.EQ; } break; case Instruction.BRANCHLT: if (compareFlag == CompareFlag.LT) i = GetUint(line, 1) - 1; break; case Instruction.BRANCHGT: if (compareFlag == CompareFlag.GT) i = GetUint(line, 1) - 1; break; case Instruction.BRANCHEQ: if (compareFlag == CompareFlag.EQ) i = GetUint(line, 1) - 1; break; case Instruction.BRANCHNE: if (compareFlag != CompareFlag.EQ) i = GetUint(line, 1) - 1; break; } } } public static byte[][] ParseCode(string[] code) { return code.Where(line => !line.StartsWith("#")) .Select(line => line.Split(' ').Where(b => b.Length > 0).Select(b => Convert.ToByte(b, 16)).ToArray()) .Where(line => line.Length > 0) .ToArray(); } private static uint GetUint(byte[] bytes, int index) { return (uint)(bytes[index] << 24 | bytes[index + 1] << 16 | bytes[index + 2] << 8 | bytes[index + 3]); } } ``` ]
[Question] [ Researchers recently discovered an interesting bee colony that lives in an infinite field of honeycomb: [![Honeycomb](https://i.stack.imgur.com/1B983.png)](https://i.stack.imgur.com/1B983.png) Each cell can house a bee or not. In fact, the lives of those creatures appear to be a bit ... chaotic. It could be calculated that a colony always starts with the following pattern: [![Initial pattern](https://i.stack.imgur.com/Y0UE6.png)](https://i.stack.imgur.com/Y0UE6.png) (Bee drawn by [Emmanuel Boutet](http://commons.wikimedia.org/wiki/User:Emmanuel.boutet) on [Wikimedia Commons](http://commons.wikimedia.org). This honeycomb-and-bees image thus is released under [CC-By-SA](http://creativecommons.org/licenses/by-sa/2.5/deed.en). *grumbles*) After that the bee's life cycles are divided into so-called generations. Each generation old bees die and new ones hatch and it primarily depends on their cell's neighbors: * If a bee has less than two neighbors it dies due to loneliness. * If a bee has more than three neighbors it dies due to overcrowding. * If a cell has two, three or four living bees in neighboring cells a new bee hatches there in the next generation. Dying bees don't die until the end of a generation so they still affect surrounding cells that might hatch bees in the next generation. Now that we know how such a colony works, we can simulate it through any number of generations. **Input** Input is a single number **N**, given on standard input, terminated by a line break. 0 ≤ **N** ≤ 150. This is the number of generations to simulate. **Output** Output is a single number, on standard output and optionally followed by a single line break, which represents the number of living bees after **N** generations. Additional output on standard error is ignored. **Sample inputs** ``` 0 5 42 100 ``` **Sample outputs** ``` 6 44 1029 5296 ``` **Winning condition** Shortest code wins, as is customary in golf. In case of a tie, the earlier solution wins. **Test cases** There are two tests scripts, containing identical test cases: * [bash](http://hypftier.de/dump/CG2993/test) * [PowerShell](http://hypftier.de/dump/CG2993/test.ps1) Invocation is in both cases: `<test script> <my program> [arguments]`, e.g. `./test ruby beehive.rb` or `./test.ps1 ./beehive.exe`. I know there are only 22 tests instead of 151 (mainly because solutions are often quite slow). Please refrain from embedding the exact test cases instead of solving the task. These scripts are a convenience for you to test whether a change still causes the program to behave correctly; not that you can adapt your code to the specific test cases. **Another note** This task was part of a golf contest held at my university during 2011-W24. The scores and languages of our contestants were as follows: * 336 – C * 363 – C * 387 – C * 389 – Haskell * 455 – C Our own solution was * 230 – Ruby [Answer] ### Ruby, 181 163 153 146 characters ``` h=[0]*4e4 [0,-200,201,202,2,3].map{|i|h[i]=1} gets.to_i.times{h=h.map{[g=1,200,201].map{|x|g+=h[x]+h[-x]};g>5-h.rotate![-1]||g<3?0:1}} p h.count 1 ``` This implementation follows a standard approach using an array `h` (dimensions `200` x `200` flattened), where each element is either `0` (no bee) or `1` (bee included). The array `[0,-200,201,202,2,3]` describes the initial positions of bees (relative to any initial cell). Input and output as specified above, passes all test cases defined. *Edit 1:* changed back to a wrapping solution instead of the "additional space"-version (which was shorter in an intermediate version but now is several characters longer). *Edit 2:* removed variable `b` completely. *Edit 3:* warning: this edit made the program horribly slow. I thus reduced the dimensions to 200 each which still is sufficient for up to 150 iterations. Instead of indexing the array by a variable we constantly rotate the array forward. Not really good design, but now we are considerably below the 150. [Answer] ## Python, 152 characters ``` P=[0,2,3,1j,1+1j,1-1j] for i in' '*input():Q=[p+d for d in(1,-1,1j,-1j,1j-1,1-1j)for p in P];P=set(p for p in Q if 1<Q.count(p)<5-(p in P)) print len(P) ``` This solution keeps track of bee locations with a set of complex numbers. It is pretty slow because the inner loop is quadratic in the number of bees. I've tested up to 50 and it works. [Answer] ## Python, 171 169 158 chars ``` w=300 s=w*w x=[0]*297 h=[1,1,0]+x+[1,0,1,1]+x+[1]+x*s exec('h=[1<sum(h[(i+x)%s]for x in[-1,-w-1,-w,1,w+1,w])<5-h[i]for i in range(s)];'*input()) print sum(h) ``` I model the world as a 300\*300=900000 1D array (`h` is actually bigger, but the end is not used), where a bee is a 1 and empty is 0. Size of 300 is fine because at *most* the growth would be of 2 in each dimension for each generation, and there is no more than 150 generations. Here is a slightly ungolfed and commented version: ``` w=300 # width and height of the world s=w*w # create initial grid l=[1,1]+[0]*298+[1,0,1,1]+[0]*297+[1]+[0]*s for k in range(input()): h=l[:] for i in range(s): # for each point, compute the number of neighbors n=sum(map(lambda x:h[(i+x)%s],[-1,-w-1,-w,1,w+1,w])) # if that number verifies the conditions, put 1 here, if not put 0 l[i]=1<n<5-h[i] print sum(l) ``` ]
[Question] [ A binary matrix represents a shape in the plane. 1 means a unit square at that position. 0 means nothing. The background is 0. For example, the array `[[0,1,0],[0,0,1],[1,1,1]]` represents the following shape: ``` o----o |////| |////| o----o----o |////| |////| o----o----o----o |////|////|////| |////|////|////| o----o----o----o ``` # Challenge You take input as the array and output the matching ASCII art. ### As with all code-golfing challenges, the shortest code in terms of bytes wins. # Examples `[[1,1,1],[0,0,0]]` ``` o----o----o----o |////|////|////| |////|////|////| o----o----o----o ``` (You may or may not trim) `[[0,1,0],[1,0,1]]` ``` o----o |////| |////| o----o----o----o |////| |////| |////| |////| o----o o----o ``` `[[1,0,1,0],[0,0,0,0],[1,1,1,0]` ``` o----o o----o |////| |////| |////| |////| o----o o----o o----o----o----o |////|////|////| |////|////|////| o----o----o----o ``` `[[1]]` ``` o----o |////| |////| o----o ``` You can choose whether or not to trim surrounding whitespace, from either rows, columns, both or neither [Answer] # [Python](https://www.python.org), ~~232~~ ~~223~~ 209 bytes *-9 bytes thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)* *-11 bytes thanks to [@a stone arachnid](https://codegolf.stackexchange.com/users/80050/a-stone-arachnid)* *-3 bytes thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)* ``` def f(a):R=range;E=enumerate;s=[[*" "*6*len(_)]for _ in 4*a];[s[I+3*i].__setitem__(J+j*5,"/|-o"[2*(I%3<1)+(J%5<1)])for i,r in E(a)for j,x in E(r)if x for I in R(4)for J in R(6)];print(*map("".join,s),sep="\n") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVC7bsMgFJ3br0BIkQCT1DQPVXE9ZrDHrBQhS4UWq8YWJlIi9U-6ZGn_p2P_phAcKdO553EPj6-f4eTfe3s-fx-8nj_9_b4qDTRq8HZfusa-qWJXKnvolGu8KsaScwIBJBvyoSySWOjeAQmMBSvSiIKPvMqWxIiFlKPyxqtOSlRnLVlT-PA57yF_JKiaLZ8ZzlA9WwcUOHYY6mLLLpwcaUuPiTpsNDiCqFVR2aPVJVAnssGiGJyxHpGuGRCEi7Y3lo6Yjmoo4YuFeHrYKW51cYtznlNGc0EDhikgC5wJQYOXxmTlSbqm2SU9pW4r8slmFy0FhBDb-zuNuukC1x_-Bw) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` FA«Fι«FκP”{⊟∨¹↖﹪H✂sρSjυ%‖”M⁵→»⸿⸿⸿ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLREQ1NToZqLEyyQCWZC2NmaCr6lOSWZBUWZeSUaSvm6QJAfk1ejDwQ1CBoirqRpDdTnm1@WqmGqo2AVlJmeUQISquXiDIDojykCQZC62v//o6OjDXUMdIA4VifaQAcMgSxDHUOwWGzsf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FA« ``` Loop through the rows. ``` Fι« ``` Loop through the cells of this row. ``` FκP”{⊟∨¹↖﹪H✂sρSjυ%‖” ``` If this cell is `1` then output a compressed representation of the shape without moving the cursor. ``` M⁵→ ``` In any case move the cursor five characters to the right. This causes adjacent shapes to overlap by one character. ``` »⸿⸿⸿ ``` After each row move the cursor to the start of the bottom row of the current line, so that the next row will overlap by one character. Drawing the shape using Charcoal commands turns out to also take 33 bytes: ``` FA«Fι«Fκ«F²F²«o⁻⁴⊗ν↷»↘¤/↖»M⁵→»⸿⸿⸿ ``` [Try it online!](https://tio.run/##TY7BC8IgFMbP66@QnRSMtqjLuo4gaBBBJ9thra1JosO2dYj97abPLeKhfu/3vU8tm0KXqhDG1EojfJBt32FC0GcRAOAgvX567Zs1QfMJMDhpLjscqpDs/vqMy/6FNxSlqr@J6o4lIfMAH1R35o/GPghkdFumhgonqXpLsLyz50LgcDVd7Ucu7bGqve@CALcUJb@YpdOfrtqVS4/GMMZiGlG7csoiCmVVTGNgeW6Wg/gC "Charcoal – Try It Online") Link is to verbose version of code. Explanation: As above, except instead of `P”{⊟∨¹↖﹪H✂sρSjυ%‖”`: ``` F²F²«o⁻⁴⊗ν↷» ``` Draw a rectangle with `o`s at the corners. ``` ↘¤/↖ ``` Fill the rectangle with `/`s. If `+`s had been acceptable for corners then `F²F²«o⁻⁴⊗ν↷»` could have been replaced with `B⁶¦⁴` saving eight bytes. ``` FA«Fι«Fκ«B⁶¦⁴↘¤/↖»M⁵→»⸿⸿⸿ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLREQ1NToZqLEyyQCWZC2NkQNqdTfoWGmY6CiaY1iOebX5aqYeWSX54XlJmeUQIRdMvMydFQ0ldCVhJa4JOaBpGv5YIKmuooWMG1AUUDijLzSjSUYopAEKS79v//6OhoQx0DHSCO1Yk20AFDIMtQxxAsFhv7X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [J](http://jsoftware.com/), 58 bytes ``` ' -o/|'{~(1 3 3 1+/#:33)>./@((]$_3 _5&*@#:I.@,)|.*&$~{.[)] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RV08/Vr1KvrNAwVjIHQUFtf2crYWNNOT99BQyNWJd5YId5UTctB2cpTz0FHs0ZPS02lrlovWjP2vyZXanJGvkIaWJ8K0ExDIAYiEAOIgBCiQF1LSx2m1AhZKYjAokZHz/A/AA "J – Try It Online") Consider input: ``` 0 1 0 0 0 1 1 1 1 ``` * `(1 3 3 1+/#:33)` Create a numeric matrix representing the ascii "cell": ``` 2 1 1 1 1 2 4 3 3 3 3 4 4 3 3 3 3 4 2 1 1 1 1 2 ``` * `*&$~{.[` Multiply dimensions of that times dimensions of input, ie, `4 6 * 3 3`, giving `12 18`, and extend our cell to those dimensions, which will always be slightly bigger than we need: ``` 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` * Our strategy will be to rotate the above matrix in 2 dimensions, one time for each 1, moving the cell into each require position. + `$...#:I.@,` Convert the positions of the ones into 2d coordinates: ``` 0 1 1 2 2 0 2 1 2 2 ``` + `_3 _5&*@` Multiply row-wise by "dimensions of cell, minus 1, negated". The negation is needed because we want to rotate right rather than left. ``` 0 _5 _3 _10 _6 0 _6 _5 _6 _10 ``` + `|.` Create multiple copies of our "extended" cell, rotating by those amounts: ``` 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` * `>./@` Max reduce these "planes" to create a single matrix, which handles the overlapping corners: ``` 0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0 2 1 1 1 1 2 1 1 1 1 2 1 1 1 1 2 0 0 4 3 3 3 3 4 3 3 3 3 4 3 3 3 3 4 0 0 4 3 3 3 3 4 3 3 3 3 4 3 3 3 3 4 0 0 2 1 1 1 1 2 1 1 1 1 2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` * `' -o/|'{~` Convert to ascii: ``` o----o |////| |////| o----o----o |////| |////| o----o----o----o |////|////|////| |////|////|////| o----o----o----o ``` [Answer] # [Perl 5](https://www.perl.org/) + `-pl`, 77 bytes ``` $"="..[6D";s!.!@{[$&?qw(o----o |////|)[0,1,1,0]:(".[6C")x4]}.[3A.!g;$\=".[3E" ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJFwiPVwiXGZcdTAwMWJbNkRcIjtzIS4hQHtbJCY/cXcoby0tLS1vIHwvLy8vfClbMCwxLDEsMF06KFwiXHUwMDFiWzZDXCIpeDRdfVx1MDAxYlszQVxiIWc7JFxcPVwiXHUwMDFiWzNFXCIiLCJhcmdzIjoiLXBsIiwiaW5wdXQiOiIxMDAxMDExMTEwMTAwMDAxMDAwMDAxMTAwMVxuMTAwMTAxMDAwMDEwMDAwMTAwMDAxMDAxMDFcbjExMTEwMTExMTAxMDAwMDEwMDAwMTAwMTAxXG4xMDAxMDEwMDAwMTAwMDAxMDAwMDEwMDEwMFxuMTAwMTAxMTExMDExMTEwMTExMTAwMTEwMDEifQ==) Contains unprintable characters and uses ANSI escape codes to reposition the cursor and output the required ASCII art. Long arrays may not display correctly in the browser (as the terminal is a fixed height and the cursor cannot move out of bounds). Happy to delete if this is not to spec! ## Explanation First, we set the list separator variable (`$"` - this is automatically added to string when a list is interpolated into it) to a string that will move the cursor down 1 line (form feed - `\x0c`) and back 6 characters (`\x1b[6D`). Then `s///`ubstitute each char (`.`) in (the implicit, stored in `$_`, via `-p`) input with an inline interpolated array (`@{[...]}`) that contains either the four parts of the box (`qw(o----o |////|)[0,1,1,0]`) or four repetitions of moving the cursor forward six characters (`("\x1b[6C")x4`), depending on whether or not the currently matched character (`$&`) is truthy. At the end of the string the cursor is moved back up three lines (`\x1b[3A`) and a literal backspace moves the cursor back one character (`\x08`). Finally, the output record separator (`$\`) is set to a string that moves the cursor to the beginning of the line three lines down (`\x1b[3E`), which is automatically printed (along with the modified input). [Answer] # JavaScript, 182 bytes ``` m=>m.map(g=r=>((p=(L=(` |`[r[0]]+r.map((d,x)=>d?`////|`:` `+` |`[r[x+1]|0]).join``+` `))[R='replace'](/\//g,'-')[R](/\|/g,'o'))[R](/ /g,(c,i)=>P[i]||' '))+(P=p,L)+L,P='').join``+P ``` Can probably be golfed a lot more. ``` f= m=>m.map(g=r=>((p=(L=(` |`[r[0]]+r.map((d,x)=>d?`////|`:` `+` |`[r[x+1]|0]).join``+` `))[R='replace'](/\//g,'-')[R](/\|/g,'o'))[R](/ /g,(c,i)=>P[i]||' '))+(P=p,L)+L,P='').join``+P ; console.log(f([ [1,1,1], [0,0,0] ])); console.log(f([ [0,1,0], [1,0,1] ])); console.log(f([ [1,0,1,0], [0,0,0,0], [1,1,1,0] ])); console.log(f([ [1] ])); console.log(f([ [1,0,1,0], [1,0,0,0], [0,0,0,1], [1,1,1,0] ])); ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~198~~ 197 bytes -1 byte thanks to @ceilingcat. --- Based on [@Matteo C.'s Python answer](https://codegolf.stackexchange.com/a/247113/80050). ``` #define F(_,t)for(_=t;_--;) i;j;I;J;f(*a,X,Y){char*s[3*X+1];F(i,4*X)asprintf(s+i,"%*c",Y*5,0);F(i,X)F(j,Y)if(a[i*Y+j])F(I,4)F(J,6)s[I+3*i][J+j*5]="/|-o"[2*!(I%3)+!(J%5)];F(i,j=3*X+1)puts(s[j+~i]);} ``` [Try it online!](https://tio.run/##RU9ta8IwEP7ur6gRIZdcmX0TttCvQvt5HypZkdBZl@Kq2I5tOPfT12WJnRwJD/e83F3lV3vV7oZh9rytdbv1VnSDPdSHE92kvdj4voCJFo3IRC5qyhQWuIZz9aJOrJMRK3hQihXVGLMCVHc86bavacc1kjmrCK5ZgguwigJWtDFmXVMlNVvzpjSdDGPz57iETmY8YrqUOW9YUqbk7ss/EBmyKc3mEfApzecJuGlNakfD8a3vaCcb/q1LEJfhVemWwnkyXvNIe/zAT/CskDy1xJv1HnkgYI5xlJiYlb0@kPell3rnBQa4sBW4ulwFoVxagWtbyUhFV8p57RupWAbh1XZLvqX/RyQycDLTMEsHGGEEFoYYjjC6wdgIYgeTvyQDL8NPVe/Vrhv8918 "C (clang) – Try It Online") Takes input as the matrix as a flattened array, the number of rows in the matrix, and the number of elements in each row. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 186 bytes ``` $args|%{$l=$m=' ' $_|%{if($_){$l=($l-replace'.$')+'o----o';$m=($m-replace'.$')+'|////|'}else{$l+=' '*5;$m+=' '*5}} $p+=$l*!$p &{-join($l|% t*y|%{($_,$p[$i++])[$_-eq32]})} $m;$m;$p=$l} $p ``` [Try it online!](https://tio.run/##rVPRboIwFH3vV3TkalvBDbbsZYaEF39g2ZsxjGjdWIogYOYifDu7pTpRsmRZvCHk9vTce07b3Cz9lHnxLpVqYEV9um8gyt@KarAH5UPiM8oIhLiMVxxCoVEOapzLTEULyW6BCZulY4yUTZDPIbnYrO4wKlZLVUgst3XL0SNyD1ldE8hsH9ToBjIy3I8/0niNGtWAlqMvVEZdB7IZxLY9FzMIx3LzcD@vBdYlE/1lWKybNDUhASfE4QEjVIcxZnLjo58bTofYY3SBDtuUGPz06wO9EhY4NOCu4zmucHSCqU48RDwhDge4hhKGETOtD2JuqxH89ZZ@MdJh9ABD7PS@OLLXHvnHRY/@DwVyxadp7Z0exz2a9lr0wjY5a07OG2myoBUd0H17pyB3mVyUculQSKIyj3c4cxCavVwWW1UiMMRRDMy22VmlOS6x7PlI4Qe2HtTw9iWPk@l6yUUt2vGxXtdWW2lNN9tI0TKlR@EnalGb9zriUJ3Mia4fUjff "PowerShell – Try It Online") Less golfed: ``` $args|%{ $line=$midl=' ' $_|%{ # for each row element if($_){ $line=($line-replace'.$')+'o----o' $midl=($midl-replace'.$')+'|////|' }else{ $line+=' '*5 $midl+=' '*5 } } $prev+=$line*!$prev # use $line as previous if $prev is empty &{ # run in new context to reset the local variable $i. -join($line|% toCharArray|%{ # output a new line, where ($_,$prev[$i++])[$_-eq32] # each space char from $line }) # replaced by related char from $prev } $midl # implicit output $midl # implicit output $prev=$line } $prev # implicit output ``` ]
[Question] [ As you most probably now, there are 2339 solutions to pentomino puzzle in a 6x10 grid. There are different labeling schemes for the 12 pentominoes, two of them are shown on the image below: [![enter image description here](https://i.stack.imgur.com/pjRVg.png)](https://i.stack.imgur.com/pjRVg.png) Image credit: Wikipedia For the purposes of the current task we will say that a normalized pentomino solution is a solution that uses the second labeling scheme (Conway’s). Example: ``` O O O O O S S S Z Z P P R R S S W W Z V P P P R R W W Z Z V U U X R T W Y V V V U X X X T Y Y Y Y Q U U X T T T Q Q Q Q ``` The piece with 5 squares in a row is denoted with letters `O`, according to the scheme. The same is true for all pieces. ## Task: Given a solution to the 6x10 pentomino in which the pieces are labeled with a random sheme, normalize it so that all pieces are labeled in Conway’s labeling scheme. You need to recognize the pieces and mark each square of a particular piece with the symbol of the piece. ## Input: The solution to be normalized, in any format that is convenient for you, for example: * A multiline string * A list of strings * A list of lists of characters and so on ## Output: The same solution (all the pieces positions and orientation preserved), but each piece labeled according to Conway’s labeling scheme. Note: The output MUST be PRINTED as a 6x10 grid of characters. Leading and trailing newlines and spaces are permitted. You can also print a space between the characters (but not empty lines), as in the example above. ## Test cases: 1. Input: ``` 6623338888 6222344478 66A234BB70 1AAA94B770 11A99BB700 1199555550 ``` Output: ``` UURTTTQQQQ URRRTVVVSQ UUXRTVZZSY PXXXWVZSSY PPXWWZZSYY PPWWOOOOOY ``` 2. Input: ``` 45ookkkk00 455ooogk00 4a55gggdd0 4aaa3gnnd. 4am333ndd. mmmm3nn... ``` Output: ``` OWSSQQQQPP OWWSSSRQPP OTWWRRRUUP OTTTXRZZUV OTYXXXZUUV YYYYXZZVVV ``` ## Winning criteria: The shortest solution in bytes in each language wins. Don’t be discouraged by the golfing languages. Explanations of the algorithms and implementations are welcome. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~54~~ ~~53~~ 50 bytes ``` ⍴⍴{'OXRYTPZQUWSV'[⌊5÷⍨⍋⍋,{×/+⌿↑|(⊢-+/÷≢)⍸⍵}¨⍵=⊂⍵]} ``` [Try it online!](https://tio.run/##Lc/PTsIwHAfwu0/hrRBkwP7hTDyMF9jY2rWr8bCwsBDGZoCLQS7GkIDM6MF4lpMPINF4MZE36YvM3za@6f58@mvaX4ObuBneBnEaNQdxMJuNBrl4eh2lYvXczofwFtknjAWymONjm/cJdT10JbYb7fAlsg@RPcI4WxzeWg2x/RWrl7ua2OyajRaU17u6yL5Ftl/@wcL9pdjcw@d6medz2HkB/2L9DscBpvAMRfZzgdIxEo8PaBiMYgQTsGi6PKnBxkjXZUVRziHoFOmyLCuqqnZL6Cag1@u2AR3TNA21163QMQ2jKFQwDK1IG9XnxY6EOBjjPgSqxHEc7HmeW4IwAOeuD7AZY9TjbgWbUVoUKlBqFfFR1aOqpekYUp6naqA0OiLQtCiKwrBCEChRkoRSiQncKwlLTCBKkkiSdOzRoq5bdGjbULUoyHWOwJRCz4RUwJg5nBOvhA8tc1LChzDO4WboHw "APL (Dyalog Classic) – Try It Online") Compute an invariant for each pentomino in the input: measure (∆x,∆y) from each of its squares to its centre of gravity, take abs(∆x) and abs(∆y), sum the x components and separately the y components, and multiply the two sums. This gives 12 distinct results. Then, find the index of each pentomino's invariant in the sorted collection of all invariants. Replace 0 with `'O'`, 1 with `'X'`, 2 with `'R'`, etc. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 37 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒĠZÆmạƊ€ḅı§AỤỤị“æṂ⁾+’Œ?¤+78Ọ,@FQṢƊyⱮY ``` A full program taking a list of strings (because we must print - otherwise remove the trailing `Y` and you have a monad taking a list of lists of numbers or characters which returns a list of lists of characters). **[Try it online!](https://tio.run/##y0rNyan8///opCMLog635T7ctfBY16OmNQ93tB7ZeGi548PdS8Co@1HDnMPLHu5setS4T/tRw8yjk@wPLdE2t3i4u0fHwS3w4c5Fx7oqH21cF/n///9oJRPT/PxsIDAwUOLSAfKA3Px0GC/R1DQ9PT0lBcpLTDROz8tL0YPwco2NjfNSILxcIDDOy9PT01OKBQA "Jelly – Try It Online")** ### How? I believe this works using the same categorisation of pentominos as [ngn's APL solution](https://codegolf.stackexchange.com/a/173909/53748), albeit in a slightly different way (I also don't know APL so I'm not that sure how similar the method is beyond the categorisation). (Note that `“æṂ⁾+’Œ?¤+78Ọ` is only a one-byte save over `“XRPTZWUYSVQO”`!) ``` ŒĠZÆmạƊ€ḅı§AỤỤị“æṂ⁾+’Œ?¤+78Ọ,@FQṢƊyⱮY - Main Link: list of lists of characters L ŒĠ - group multidimensional indices by value Ɗ€ - last three links as a monad for €ach i.e. f(x): Z - transpose x Æm - mean (vectorises) (i.e. the average of the coordinates) ạ - absolute difference with x (vectorises) (i.e. [dx, dy]) ı - square root of -1 (i) ḅ - convert from base (vectorises) (i.e a list of (i*dx+dy)s) § - sum each A - absolute value (i.e. norm of the complex number) Ụ - grade up (sort indices by value) Ụ - grade up (...getting the order from the result of A back, - but now with one through to 12) ¤ - nilad followed by links as a nilad: “æṂ⁾+’ - base 250 literal = 370660794 Œ? - permutation@lex-index = [10,4,2,6,12,9,7,11,5,8,3,1] ị - index into +78 - add seventy-eight Ọ - cast to characters (character(1+78)='O', etc...) Ɗ - last three links as a monad (i.e. f(L)): F - flatten Q - de-duplicate Ṣ - sort ,@ - pair (with sw@pped @rguments) (giving a list of 2 lists) Ɱ - Ɱap across L with: y - translate i.e. swap the letters as per the the pair) Y - join with new lines - implicit print ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 103 bytes ``` ""<>Riffle[(t=#)/.Thread[SortBy[Union@@t,Tr@Kurtosis@Position[t,#]&]->Characters@"UPSWZVRTQXYO"],"\n"]& ``` Takes input as a list of lists of characters. [Try it online!](https://tio.run/##dc1Ni8IwEIDhu78iTEEUoi6ot1WCe9yDXa0fa8wh2GrDblNIx4NIf3uttqT16/LAhHknkcQwiCSqncxcozTyDOBzPFP7/X/AWzhy2r2uF5pA@nweG5yc@EKrWDOG1DPs@2gwTlTC3FzM3zlSRzRFZ/wVSiN3GJiEwcKdrzbLmfez/p2CoLDVIJoZYeR8hgFQAsMrseXvBR8FKSX15kqD1Nsbh/eZvGuLzUN55Tb4lqesom9bbfHLK93HLLJFhb7/qmyicj0/Q@xQL3SxXJGmIrsA "Wolfram Language (Mathematica) – Try It Online") The main idea here is that for each character in the input, we find the coordinates where it occurs, take the kurtosis and sum its coordinates. This gives us an invariant for each piece. (The kurtosis is some mostly-irrelevant operator from statistics - the key is that it's invariant under translation, while reflection and rotation might switch the order of coordinates at most. We sum the coordinates, so the invariant never changes.) Anyway, apart from the weird invariant, this solution is similar to the others: we sort the characters and the pieces by each invariant, then replace each character by the corresponding character of `"UPSWZVRTQXYO"`: the pieces, sorted by kurtosis sum. Finally, `""<>Riffle[...,"\n"]` is the print-as-a-grid code. [Answer] # [Python 2](https://docs.python.org/2/), 191 bytes ``` def y(o):print"".join(['XPRTWZUYSVQO\n'[[w for v,w in sorted([sum(abs(u-sum(t)/5)for t in[[complex(r%11,r/11)for r,q in enumerate(o)if q==p]]for u in t),p]for p in o)].index(x)/5]for x in o]) ``` [Try it online!](https://tio.run/##HY3LbsMgFET3@QqEVAUkh8Ql3kTKN/T9JF7QgiltuRCMG/vrXfCszty5mglT@vJwPc9Kd2ginh5CtJAwZt/eAhHr19v7x5f3p7eH57ubE6yFuKDOR/RXXZAF1PuYtCKiHxyRHz0ZNoUS3Ta0fKX8I8Snd@FXjyRe1XUVt3W9ZLE6lwYNg9NRJp23bYfOx2No25IPJU20CosLxXnaMgsqV415YbmPy72l80QwxvvG@5@s3W61bzJ7s6BsGmOMUgWl5AZAsYyOcw4qo8viAIyxVS6h8z8 "Python 2 – Try It Online") Takes a multi-line string with a trailing newline and does six nested list comprehensions. **Ungolfed Version** ``` def pentomino_normalizer(input_string): # input_string is a multi-line string with a trailing newline results = [] # For saving the results of the for loop for current_char in input_string: # current_char = p in the golfed version # The python data type complex stores a real and a imaginary value and # is used for storing the x and y coordinates. # In the end, the positions list contains a complex number for every # occurence of current_char in the string # positions_list = t in the golfed version positions_list = [complex(i % 11, i / 11) for i, c in enumerate(input_string) if c == current_char] # average_pos is the midpoint of all occurences of current_char, # to get rid of translations average_pos = sum(positions_list)/5 # Calculates a value for each tile that is invariant under # translations and rotations, # simply the sum of all the distances between the midpoint # and the positions invariant = sum(abs(pos - average_pos) for pos in positions_list) # Saves the invariant value to a list results.append(invariant, current_char) # This new list contains the characters occuring in the string, sorted # by the invariant value. Because this was done with each char in the # input string, this lists contains every value five times and also # contains six newlines # at the end of the list sorted_results = [w for v, w in sorted(results)] # This code snippet maps each char from the input string to its according # output and prints to stdout chars = ['XPRTWZUYSVQO\n'[sorted_results.index(c)/5] for c in input_string] print "".join(chars) ``` ]
[Question] [ ### Input: Two strings without newlines or whitespaces. ### Output: Both input strings on separate lines, with spaces where necessary† for one of the two strings. And a third line with the characters `A`, `R`, `M` and , representing *added*, *removed*, *modified*, and *unchanged*. † We add spaces to either the top ***or*** bottom input string (if we have to). The goal of this challenge is to output with the least amount of changes (`ARM`) possible, also known as the [Levenshtein distance](https://people.cs.pitt.edu/~kirk/cs1501/Pruhs/Spring2006/assignments/editdistance/Levenshtein%20Distance.htm). ### Example: Let's say the input strings are `ABCDEF` and `AFBECD`, then the output would be this: ``` A B CDEF AFBECD A A RR ``` Here are some other possible invalid outputs as example (and there are a lot more): ``` ABCDEF AFBECD MMMMM A BCDEF AFBECD A MMMR AB CDEF AFBECD MAMMMR ABC DEF AFBECD MMAMMR ABC DEF AFBECD MMAA RR ABCDEF AFB ECD MMR MA AB CDEF // This doesn't make much sense, AFBECD // but it's to show leading spaces are also allowed AM A RR ``` None of these have only four changes however, so only `A B CDEF\nAFBECD \n A A RR` is a valid output for this challenge. ### Challenge rules: * You can assume the input strings won't contain any new-lines or spaces. * The two input strings can be of different lengths. * One of the two input strings should remain as is, except for optional leading/trailing spaces. * If your languages doesn't support anything besides ASCII, you can assume the input will only contain printable ASCII characters. * The input and output format are flexible. You can have three separate Strings, a String array, a single String with new-lines, 2D character array, etc. * You are allowed to use something else instead of `ARM`, but state what you've used (i.e. `123`, or `abc.`, etc.) * If more than one valid output is possible with the same amount of changes (`ARM`), you can choose whether to output one of the possible outputs or all of them. * Leading and trailing spaces are optional: ``` A B CDEF AFBECD A A RR ``` or ``` "A B CDEF\nAFBECD\n A A RR" ^ Note there are no spaces here ``` ### General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. ### Test cases: ``` In: "ABCDEF" & "AFBECD" Output (4 changes): A B CDEF AFBECD A A RR In: "This_is_an_example_text" & "This_is_a_test_as_example" Possible output (13 changes): This_is_an _example_text This_is_a_test_as_example MAAAAAAA RRRRR In: "AaAaABBbBBcCcCc" & "abcABCabcABC" Possible output (10 changes): AaAaABBbBBcCcCc abcABCab cABC R MM MMMR MM R In: "intf(){longr=java.util.concurrent.ThreadLocalRandom.current().nextLong(10000000000L);returnr>0?r%2:2;}" & "intf(){intr=(int)(Math.random()*10);returnr>0?r%2:2;}" Possible output (60 changes): intf(){longr=java.util.concurrent.ThreadLocalRandom.current().nextLong(10000000000L);returnr>0?r%2:2;} intf(){i ntr=( i n t)(M ath.r andom ()* 10 );returnr>0?r%2:2;} MR M MRRRRRR RRRR RRRRRR MMMRR MMMMRRR RRRRRRRR MRRRRRRRRR RRRRRRRRRR In: "ABCDEF" & "XABCDF" Output (2 changes): ABCDEF XABCD F A R In: "abC" & "ABC" Output (2 changes): abC ABC MM ``` [Answer] # JavaScript (ES6), ~~413~~ ... ~~343~~ 342 bytes *Saved 5 bytes by tweaking the loop indices, as suggested by @KevinCruijssen* Takes input as 2 strings in currying syntax. Returns an array of 3 strings. ``` b=>a=>{m=[];x=a.length;y=b.length;for(i=j=0,c=d='';i<=y;c+=R='R')m[i]=[[c,i++]];for(;j++<x;)m[i=0][j]=[d+=A='A',j];for(;i<y;i++)for(j=0;j<x;)[C]=m[[X,S]=m[i][j],[Y,I]=m[i+1][j],[Z,D]=m[i][++j],Q=[Z+R,D+1],i+1][j]=b[i]==a[j-1]?[X+' ',S]:S<I?D<S?Q:[X+'M',S+1]:D<I?Q:[Y+A,I+1];return[(g=s=>C.replace(/./g,c=>c==s?' ':b[i++],i=0))(A),g(R,b=a),C]} ``` ### Test cases ``` let f = b=>a=>{m=[];x=a.length;y=b.length;for(i=j=0,c=d='';i<=y;c+=R='R')m[i]=[[c,i++]];for(;j++<x;)m[i=0][j]=[d+=A='A',j];for(;i<y;i++)for(j=0;j<x;)[C]=m[[X,S]=m[i][j],[Y,I]=m[i+1][j],[Z,D]=m[i][++j],Q=[Z+R,D+1],i+1][j]=b[i]==a[j-1]?[X+' ',S]:S<I?D<S?Q:[X+'M',S+1]:D<I?Q:[Y+A,I+1];return[(g=s=>C.replace(/./g,c=>c==s?' ':b[i++],i=0))(A),g(R,b=a),C]} console.log(f('ABCDEF')('AFBECD').join`\n`); console.log(f('This_is_an _example_text')('This_is_a_test_as_example').join`\n`); console.log(f('AaAaABBbBBcCcCc')('abcABCabcABC').join`\n`); console.log(f("intf(){longr=java.util.concurrent.ThreadLocalRandom.current().nextLong(10000000000L);returnr>0?r%2:2;}")("intf(){intr=(int)(Math.random()*10);returnr>0?r%2:2;}").join`\n`); console.log(f('ABCDEF')('XABCDF').join`\n`); ``` ### Less golfed ``` b => a => { m = []; x = a.length; y = b.length; // initialize the leftmost column and the topmost row for(i = j = 0, c = d = ''; i <= y; c += R = 'R') m[i] = [[c, i++]]; for(; j++ < x;) m[i = 0][j] = [d += A = 'A', j]; // walk through the Levenshtein matrix for(; i < y; i++) for(j = 0; j < x;) [C] = m[ // C = current string, once updated [X, S] = m[i][j], // substitution [Y, I] = m[i + 1][j], // insertion [Z, D] = m[i][++j], // deletion Q = [Z + R, D + 1], // precomputed update for deletion i + 1 ][j] = b[i] == a[j - 1] ? [X + ' ', S] // unchanged character : S < I ? D < S ? Q : [X + 'M', S + 1] // deletion or substitution : D < I ? Q : [Y + A, I + 1]; // deletion or insertion return [ // g = helper function to format the output strings by inserting spaces (g = s => C.replace(/./g, c => c == s ? ' ' : b[i++], i = 0))(A), g(R, b = a), // final modification string, picked from the last visited cell C ] } ``` ### Example Below is the initial matrix for ***b = "foo"*** and ***a = "ok"***: ``` // 'o' 'k' [ [ [ '', 0 ], [ 'A', 1 ], [ 'AA', 2 ] ], [ [ 'R', 1 ], (undefined), (undefined) ], // 'f' [ [ 'RR', 2 ], (undefined), (undefined) ], // 'o' [ [ 'RRR', 3 ], (undefined), (undefined) ] ] // 'o' ``` and here is the final matrix after all iterations: ``` // 'o' 'k' [ [ [ '', 0 ], [ 'A', 1 ], [ 'AA', 2 ] ], [ [ 'R', 1 ], [ 'M', 1 ], [ 'MA', 2 ] ], // 'f' [ [ 'RR', 2 ], [ 'R ', 1 ], [ 'R A', 2 ] ], // 'o' [ [ 'RRR', 3 ], [ 'RR ', 2 ], [ 'R M', 2 ] ] ] // 'o' ``` The final modification string along with the Levenshtein distance are stored in the bottom-right cell. [Answer] # [Haskell](https://www.haskell.org/), ~~192~~ ~~181~~ ~~174~~ ~~161~~ ~~158~~ ~~150~~ ~~147~~ ~~143~~ 1581 bytes ``` e@(a:r)&f@(b:s)=snd$maximum[([1|' '<-s!!2],s)|s<-z(z(:))[a:" R",' ':b:"A",a:b:last("M":[" "|a==b])][r&f,e&s,r&s]] x&y=[x,y,"RA"!!(0^length x)<$x++y] z=zipWith ``` [Try it online!](https://tio.run/##jVBRa4NADH7Pr8iOYpXqWMuejlqqtsJgsuEeNhAfztauMrXFU7Cu@@3urBVa2rIl3CWQL1/yZc34VxjHdR1OZUYzRVpN5YByRefpspewMkqKxJO94b6P/bHG7@5GvsqVPR9rlVzJVFE8Rgm6RBV1GlBiEJWJGDOey8Qh1CNI9kzXA1/xvUxaqaHE1Uzivg@ltNO9Ut2p5WCwm0yIS3yo9Cravkf5uk5YlKKOyw0Cbov8Lc@eU7zHIo2jNOTYQ2KY1mxuE5REaptza0ZA025hmXDTDExzYQk/NLFgISjan/xjyEeT2zeRLLDaXRo2@NbgKaVXl3wpcsGA8iMu1iz9DLlCwUATGyC0IBSiDeHounhhcGT@U9LrhvMoiEPcHCcOH05HnvcDds3YBAQXHQfFcw6JCxd6unt0ekYn5Nji4IBBG4VAYW63@9mtrvULAIgiiMmg/dS/ "Haskell – Try It Online") Example usage: `"ABCDEF" & "AFBECD"`. Returns a list of three strings. This is an extension of my recursive solution to the ordinary [Levenshtein distance question](https://codegolf.stackexchange.com/a/142370/56433). ### Explanation: To compute the minimal modifications to get from `"xyz"` to `"yw"`, we focus on the first character of both strings. There are three possibilities: * *Remove:* Drop `x` from the first string and recursively compute the modifications to get from `"yz"` to `"yw"`. This yields the three lines `["yz","yw"," M"]`. Add `x` to the first one, a space to the second one and `R` to the third one. We get ``` xyz yw R M ``` * *Add:* Drop `y` from the second string and compute `"xyz" & "w"`, which returns the result `["xyz","w","MRR"]`. We need to add a space on the first line, `y` to the second and `A` to the third line: ``` xyz yw AMRR ``` * *Modified/Unchanged:* We can combine those two cases because both require to drop the first character of both strings and compute the minimal modifications between the remaining strings: `"yz" & "w"`. To the result `["yz","w","MR"]`, we add `x` on he first and `y` on the second line. Only for the last line we need to differentiate whether the initial characters are the same. If they are the same, a space is added to the third line, otherwise (as in this case because `x \= y`) an `M` is added: ``` xyz yw MMR ``` From those three candidates, we need to find the one with the fewest modifications. This is equivalent to having the most spaces on the third line. Therefore we convert each candidate `s` (a list of three strings) to a tuple `([1|' '<-s!!2],s)`, where `s` appears as second component and the first component is a list with as many elements as there are spaces in the third line of `s` (`s!!2` because of 0-indexing). As list element `1` is used, but the actual element is irrelevant as long as it is the same for all candidates. Altogether, this yields the list of tuples ``` [([1],["xyz"," yw","R M"]),([],[" xyz","yw","AMRR"]),([],["xyz","yw","MMR"])] ``` The build-in `maximum` selects the largest element of this list, where tuples are compared lexicographically, that is component-wise from left to right. As `[1]` is larger than `[]`, the first tuple is selected, and `snd` returns the second of component, that is the list of lines, of the tuple. --- 1 +15 bytes to fix a bug where `A`-changes at the end of a string would be displayed as `R`-changes [Answer] # [Python 2](https://docs.python.org/2/), ~~548~~ ~~536~~ ~~484~~ ~~5001~~ ~~488~~ ~~447~~ ~~3812~~ ~~373~~ ~~371~~ ~~357~~ 350 bytes ``` s,t=input() n,m=len(s),len(t) r=range L=[[(j,'RA'[i<1]*j)for j in r(i,m-~i)]for i in r(n+1)] for i in r(n): for j in r(m):M,R=L[i][j:j+2];A=L[i+1][j];v,V=min(A,R,M);x=('AR'[v in R],'M_'[s[i]==t[j]])[v in M];_=M;X=eval(x)[1]+x;L[i+1][j+1]=v+(x<'_'),X for i in r(len(X)):s=s[:i]+' '*('B'>X[i])+s[i:];t=t[:i]+' '*('R'==X[i])+t[i:] print s+'\n'+t+'\n'+X ``` [Try it online!](https://tio.run/##bVBbb5swFH7nV6BIk32Ch0K0J6g7Qdo@hRdUTZGohVziNkZgIuNETNP217PD6CUPw@gc@bucz/bxpzv0Zn2p@73idrFYXAbmuDbHk6PgGdbxVhk6AJuaA89yK82r8ra8LGnDSJGSUt9EYtnAS2/9xtfGt1Sz7usfDWKC9AyZIALhXQMQe/6Vp4M4ZwXfllqUTdwEa5Gk0y6IcC@SM/vBO21oygqWQzJyStKClOfJXAhG8oqUA3o5dygXMDO5SCqeJzuuzrKlI5SRCMbkfSoWfg7oeEMqAmx3fbrpujuAeOBDGWsREJ8sKcnI7Q4zIMCkWCQOsz7JgnA@s25ivaPVxvlDQJ4MCdzcdpcZxYf2PDWq2p8efvntQtJsc3f/QBhJH7L7zR3xyONBDxX@0lRqlN2xVZVTo0PJB4PA4Co5vAvQlUpcWfacZfUGF6rlc43D54oCjH@h8KvtzavljTzL8OR0G9a9qU/WKuPCx4NVcr/ta9kW0uz7LnxjKIQGT7BFK41WH98WEqvcyRp7u/puv6zjdfIbc9@CsFlOsQLNpTuE9t9ICsto9T/fXw "Python 2 – Try It Online") Uses `'ARM_'` instead of `'ARM '` Works by building up the Levenshtein matrix, ~~and then traversing backwards to find the operations~~. Now builds the operation-string at the same time as the Levenshtein matrix, as in [Arnauld's JS answer](https://codegolf.stackexchange.com/a/144482/38592) 1: More bytes, as it did not work if the first string was a single character. 2: Switched to building the combinations in the Levenshtein matrix. [Answer] # [Python 2](https://docs.python.org/2/), 310 bytes ``` from difflib import* a,b=input() U,j=[],' ' for g,s,t,x,y in SequenceMatcher(0,a,b).get_opcodes(): g,Y,T=g[0],y-x,t-s z,A,B=Y-T,a[s:t],b[x:y] if'q'<g:U+=[A+z*j,B+j*-z,'M'*min(T,Y)+'A'*z+'R'*-z] if'e'==g:U+=[A,B,j*Y] if'i'==g:U+=[j*Y,B,'A'*Y] if'e'>g:U+=[A,j*T,'R'*T] for e in[0,1,2]:print''.join(U[e::3]) ``` [Try it online!](https://tio.run/##RY@xboMwEIbn8BQoy4E5orTdrLpSsmdpyYAsC5HEEKNgE@xIwMtTp2la6abvv@9Ofze6s9Gv81z1pg1Pqqou6hCqtjO9I0GJB6Z0d3NRHOyxYVwghBBUpg9rtOhwwDFUOvyS15vUR7kr3fEs@2iN3oxXtXSF6Y7mJG0U02BRY44Zq/la4JgO6FIbLCbc4JblaYYlt9QJPPCBjiJYqAqu8F7TfcL4JplIg9ukIemEsAPSKh1lmMcJbIBMCXyCTx6SBMZ@LdxiQ/IHVn/YIx/cxfxpfDyFhmR4P5aJn5LSl@NrfMFXQbteaQewaoz/veeS0jcRz/MyOytb@Cl1IYey7S6ycHJwS/xPPLCuKO1zYfkN "Python 2 – Try It Online") Using `difflib.SequenceMatcher` that computes an alignment between two strings [Answer] # Mathematica, 250 ~~256~~ ~~259~~ ~~384~~ bytes ~0.00035 seconds for the java code case. ``` (i=o=p="";a=Array;r=StringLength;If[Length@#>0,g=#&@@#;h=#[[2]];u=r@g;v=r@h;i=i<>g;o=o<>h;w=Abs[v-u];k=a[" "&,w];If[u<v,i=i<>k,o=o<>k];p=p<>a["M"&,u~Min~v];p=p<>a[If[u>v,"R","A"]&,w],i=i<>#;o=o<>#;p=p<>a[" "&,r@#]]&/@SequenceAlignment[#,#2];{i,o,p})& ``` Usage: `f["ABCDE", "ABCDF"]` [Try it online!](https://tio.run/##PY/LasMwEEV/pUhgWlApZCuPkfMihQRKsxSzUFJZFq5lR5EdSml@3ZUSyOYuhnPPzLQq1LpVwR7VVMH0bIEQ3qXoUygovVc/3MM@eOvMVjsTav5eyY1WX4ICwNaeAzNAMyEor4FKOUPkA3hh@Biz5hZsXpho7fKi5hcoD2c5vg7IG1CSPJGMXTAph3xkN7ZhN7bBeESfFxHaRWi47qy7jo9hahQjI5@EkZJgstzr9L6KPtpphRcUMXsTe30atDvq8tsa12oXJGV0hvzXso71fy/Z9BEfDbKSpJwvlqt1sq/nq8WSIE7/ "Wolfram Language (Mathematica) – Try It Online") The code is based on a fact that `SequenceAlignment` works by default on > > With the default setting SimilarityRules->Automatic, each match > between two elements contributes 1 to the total similarity score, > while each mismatch, insertion, or deletion contributes -1. > > > Namely, the scoring is calculated by `M`, `A` and `R`, accordingly. Example: [![example](https://i.stack.imgur.com/Wak6u.png)](https://i.stack.imgur.com/Wak6u.png) [Answer] # [D](https://dlang.org/), ~~351~~ 345 bytes -6 bytes thanx to KevinCruijssen ``` string f(string a,string b){import std.algorithm;string x,y,z;size_t i,j,k;foreach(c;levenshteinDistanceAndPath(a,b)[1]){final switch(c)with(EditOp){case none:x~=a[i++];y~=b[j++];z~=" ";break;case substitute:x~=a[i++];y~=b[j++];z~="M";break;case insert:x~=" ";y~=b[j++];z~="A";break;case remove:x~=a[i++];y~=" ";z~="R";}}return x~"\n"~y~"\n"~z;} ``` [Try it online!](https://tio.run/##dVJdb5swFH3fr0BIk@wVoaSPtdgE@XhKtanqw6SsigyY4BSuI9ukJBH89fSS0KpZiw2@V77nHNvHTk8nY7WEtZORPuFen8T0KMut0tYxNvV5sVZa2rxkfbn29t6BGXkQK@tIb@M9s0xpwZOcJKwQOwEmt0LCVBrLIREhpH@4zQn3YrocP9FjJoEXjnmRtqNQjDmZpdL@3tJjwo1wQIG4q9uAL@XNzRPbt0G83HTZoQ1cx2UxrvbMzlBTxcZKW9lhwv0VQYIR2nbgTukaGV4htSjV7j/ZjtMhH1zWNFrYSoNTt@4/cNv9JRxYc9opmToll0Do8ZuD7YOd@EvFzrMvaKsogGTEDaPJdDZ3PTecR7PJ1KVnMfoJ95hLs8KPw0rUvNwWeAeitkh8r@CEsStu3gCDWiHHHkVxFCUT7KjB4wQ3chkHaRJshucqFKx1sOE77ldWFn6iIKm0FmD9xxxNTBcq4cUDh1SVfl8h1Afc7QKpZDx6bwvKLlbqn6Nf@vvt3S1rcDf9Qhh0QHCk5B6fka/PkoT@GI@@4g2e9s3hv102H8TxeNJdw0cDmtMr "D – Try It Online") ]
[Question] [ The task is to find a non-trivial factor of a composite number. Write code that finds a non-trivial factor of a composite number as quickly as possible subject to your code being no more than 140 bytes long. The output should just be the factor you have found. Your code can take input and give output in any way that is convenient including for example as arguments to a function. **Test cases which list all the factors (you only need to output one)** ``` 187: 11 17 1679: 23 73 14369648346682547857: 1500450271 9576890767 34747575467581863011: 3628273133 9576890767 52634041113150420921061348357: 2860486313 5463458053 3367900313 82312263010898855308580978867: 264575131106459 311111111111113 205255454905325730631914319249: 2860486313 71755440315342536873 1233457775854251160763811229216063007: 1110111110111 1000000000063 1111111999999 1751952685614616185916001760791655006749: 36413321723440003717 48112959837082048697 ``` I won't score your answer on the following difficult test case which may be of interest for testing: ``` 513231721363284898797712130584280850383: 40206835204840513073 12764787846358441471 ``` **Score** Your score is the combined time to factor all the test cases above with a penalty of 10 minutes for each failed factorization (all rounded to the nearest second). Your code should work for other integers too, that is shouldn't just hardcode these answers. I will stop your code after 10 minutes. If two people get the same score then the first answer wins. **Restrictions** Your code can't use any builtin or library function that performs integer factorization. You can assume the input takes less than 256 bits. All input numbers will be composite. **How will I time?** I will literally run `time ./myprog` on my Ubuntu system to do the timing so please also supply a complete program for me to run that includes any function you have defined. **A note for compiled languages** Compilation time must take no more than 1 minute on my machine. **Is it actually possible?** If you ignore the space constraints, then each one can be factored in less than 2 seconds on my computer using pure Python code + pypy. **So what is a non-trivial factoring algorithm?** [Pollard's rho algorithm](https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm) is fast and suitable for golfing. Of course there are plenty of other ways to [factor an integer](https://en.wikipedia.org/wiki/Integer_factorization) as well. Even faster is the [Quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve). It looks like a serious challenge to squeeze that into 140 bytes. **Leading scores** * **SEJPM**, 10 minutes penalty for the last test case + 16 seconds in **Haskell** [Answer] # Haskell, ~~100~~ ~~97~~ ~~91~~ ~~89~~ ~~87~~ ~~72~~ 67 Bytes ## [Try It Online!](https://tio.run/##LU3BDoIwFLv7FU3gAComHAgGmYkHD579gsEGLLIH2RaDCf8@EemhTZum7bh9yb73XulxMA7Pj3VSn@70VmYgLclFrXQ309p4hwW7BjT30sFiYnoQ0bSfDnlMFx5UsyiTthZRlfCYjuKaMjHXZWJRMQseWNQsWzj7D2muiEEMqwP4coEywfa2paNR5MIGkZFcIET3k7VaFHiQk600sfc@Pedf) *-3 bytes thanks to @flawr* *-6 bytes thanks to @flawr again* *-2 bytes thanks to @flawr yet again* *-2 bytes thanks to an optimized set of parameters* *-1 byte thanks to @flawrs yet another time* *-14 bytes thanks to requirement to only having to output one factor* *-5 bytes thanks to @AndersKaseorg* ``` f n|let s x=mod(x*x+7)n;a#b|d<-gcd(b-a)n,d>1=d|c<-s b=s a#s c=5#s 5 ``` This works for the first 5 test cases in unnoticable time. This will probably time-out on the largest test case. In general this will usually return one non-trivial factor in time proportional to the square root of the smallest factor. It will not work on every input because it doesn't vary the polynomial and detection of the exceptional case is hard to do in 140 bytes. It will also not output the full factorization, but rather a non-trivial factor and the division of the input by this factor. It will also not sort the factors by size. The method used is [Pollard-Rho-Factoring](https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm) with the standard starting value of 2 (with the standard `x^2+1` polynomial applied once) and the non-standard polynomial constant factor of 7 (because `1` didn't work with 1679) for all further evaluations. Full program (`factor.hs`): ``` import System.Environment(getArgs) f n|let s x=mod(x*x+7)n;a#b|d<-gcd(b-a)n,d>1=d|c<-s b=s a#s c=5#s 5 main= do args <- getArgs print$f (read $ head args :: Integer) ``` Compile as `$ ghc factor.hs` (needs `ghc` installed). Run as `$ ./factor <number>`. Example run: ``` $ ./factor 187 11 ``` --- Ungolfed code: ``` f n=g 5 (s 5) where s x=mod(x*x+7)n g a b = if d>1 then d else g(s a)(s(s b)) where d=gcd(b-a)n ``` Computes the non-trivial factor by calling `g` with initial values. The polynomial is pre-applied on 2 here and re-applied on the result (5) so that the input to `g` (in a ["where" clause](https://codegolf.stackexchange.com/a/127594/55329)) can always be readily used for the gcd-test. `g` (golfed version uses infix `#`) then tries to compute a non-trivial factor `d` (in the where clause in the un-golfed version, in-line in the golfed one) as the difference between the two inputs to `g`, if it succeeds returns said factor, else retries. Here it may generate `n` as the output if `a==b` and thus returns only a trivial factor, the proper approach to handle this would be to either vary the starting values upon this event or change the polynomial. [Answer] # [Pari/GP](https://pari.math.u-bordeaux.fr/), 137 bytes, ~5 seconds Using GP's built-in elliptic curve operations (and some underhanded parameter tuning): ``` ecm(n)=iferr(if(n%2==0,2,n%3==0,3,for(a=1,n,ellmul(ellinit(Mod([a,a^2-a-1],n)),[1,a],lcm([1..ceil(4^a^0.5)])))),e,gcd(n,lift(Vec(e)[3]))) ``` `ecm` is a function that (ought to) return a factor. **[Try it online!](https://tio.run/##LVHLbuMwDLz7K7QFUkiAEpASqce2/oS97iVIACO2CwGu6nXcQ1Hst2fpZHUZihwOKc3cLWX/Nt9uw@VdV9OWcVgWXUZdd65twTpbd34LvB0/Ft21aKsdpun9c9ICpZZV//ro9bGz3dntuz2ebDXGHtF2JzuJ6BEPh8tQJk3n7gwHNicjxw727dLraqcyrvr3cNGDOfqtdPtu6lW16tgohSnaDULMdyQfcqDkKYTkmGLie91TpMiRKUROmIIHxC3PLngCQkSPDOQgO4SAXhQejcl5dG7jQ8opMXtInCDHlMKd4IAdMzFlYO84egges@yB2dFjJ@c9cYwymckxYoAYfELRlWlB@ACPR0TGLBslDkgBAybOUgeM0iERM0CIlIV6av42zTpcV3FEfuJbUkr1Ej1Mernfy6j0D42vvXp@Vv1r3aDuevHKWCUmilu9@c@dl1JFzKqnn@rJqt5sA7p5nr70NsaqejVN8@ezrLd/ "Pari/GP – Try It Online")** ## Test: ``` ecm(n)=iferr(if(n%2==0,2,n%3==0,3,for(a=1,n,ellmul(ellinit(Mod([a,a^2-a-1],n)),[1,a],lcm([1..ceil(4^a^0.5)])))),e,gcd(n,lift(Vec(e)[3]))) { ns = [ 187, 1679, 14369648346682547857, 34747575467581863011, 52634041113150420921061348357, 82312263010898855308580978867, 205255454905325730631914319249, 1233457775854251160763811229216063007, 1751952685614616185916001760791655006749 ] } test(n) = { d = ecm(n); if (!(1<d && d<n && n%d==0), error(d)); print(n, ": ", d) } apply(test, ns) quit ``` ## Ungolfed: ``` ecm(n) = { iferr(if(n%2 == 0, 2, n%3 == 0, 3, for(a = 1, n, /* x^3 + A*x + B = y^2 */ E = ellinit(Mod([a, a^2-a-1], n)); /* [A, B] */ x0 = [1, a]; /* [x, y] */ B = ceil(4^a^0.5); /* ~ exp(sqrt(log(p))), p ~= exp(a) */ print("a=", a, ", B=", B); ellmul(E, x0, lcm([1..B])) ) ), ERR, gcd(n, lift(Vec(ERR)[3] /* = Mod(d, n) */)), errname(ERR)=="e_INV") } ``` Sadly, handling the factors 2 and 3 uses many bytes. Bytes that could have been used to add a stage 2: ``` ecm(n)=iferr(for(a=1,n,Y=X=ellmul(E=ellinit(Mod([a,1],n)),[0,1],(B=ceil(4^a^0.5))!);for(z=0,9*B,Y=elladd(E,Y,X))),e,gcd(n,lift(Vec(e)[3]))) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 81 bytes, 22 sec +10min(penalty) uses Pollards ρ-algorithm x(0)=33, f(x)=x^8+1 and searches only x(2k)-x(k) ``` (x@0=33;n=#;v=1;x@k_:=x@k=Mod[x[k-1]^8+1,n];While[(r=GCD[x[2v]-x@v,n])<2,v++];r)& ``` [Try it online!](https://tio.run/##DclNC4IwGADge38jCEWFfaC@tl5YGHQKunUYM0aJitNgyNi/X16ey7OYbewXs00fE1vbG3e1VgV9GDAmQRLkXKx4FB6pCHJ@n3EXH7@vCmouqO4go/mqxWucbK8Sh/f2thfzugjS75NeWO6zTAuXnuLTTesmBwmMU8YqTiiBBqAsOYESSFMDVHWMfw "Wolfram Language (Mathematica) – Try It Online") [Answer] # Axiom, 137 bytes 9 minutes ``` p(n:PI):PI==(j:=1;a:=3;s:=n^.2;repeat(b:=j:=nextPrime(j);repeat(b<s=>(b:=b*j);break);a:=powmod(a,b,n);d:=gcd(a-1,n);d>1 or j>n=>break);d) ``` above the function p() that would implement p-1 algo for factoring below what to copy in a file for test on p() function ``` -- one has to copy this below text in a file name for example file.input -- in one window where there is Axiom one could write -- )read C:\absolutepathwherethereisthatfile\file -- and call the function test() -- test() -- the first character of all function and array must be afther a new line "\n" )cl all )time on vA:=[187,1679,14369648346682547857,34747575467581863011,52634041113150420921061348357,82312263010898855308580978867,205255454905325730631914319249,1233457775854251160763811229216063007, 1751952685614616185916001760791655006749] p(n:PI):PI==(j:=1;a:=3;s:=n^.2;repeat(b:=j:=nextPrime(j);repeat(b<s=>(b:=b*j);break);a:=powmod(a,b,n);d:=gcd(a-1,n);d>1 or j>n=>break);d) -- this would try to factor n with p-1 Pollard method pm1(n:PI):PI== j:=1;a:=3;s:=n^.2 repeat b:=j:=nextPrime(j) repeat(b<s=>(b:=b*j);break) a:=powmod(a,b,n) d:=gcd(a-1,n);d>1 or j>n=>break d test()==(for i in 1..#vA repeat output [vA.i, p(vA.i)]) ``` results here: ``` (5) -> test() [187,11] [1679,73] [14369648346682547857,9576890767] [34747575467581863011,9576890767] [52634041113150420921061348357,2860486313] [82312263010898855308580978867,311111111111113] [205255454905325730631914319249,2860486313] [1233457775854251160763811229216063007,1111111999999] [1751952685614616185916001760791655006749,36413321723440003717] Type: Void Time: 496.78 (EV) + 53.05 (GC) = 549.83 sec ``` [Answer] # Axiom, 10 minutes + 31 seconds ``` A(a)==>a:=(a*a+7)rem n;z(n)==(p:=a:=b:=101;for i in 1..repeat(A(a);A(b);A(b);p:=mulmod(p,a-b,n);i rem 999<9=>(p:=gcd(p,n);p>1=>break));p) ``` z() is the function rho, one 137 bytes function; ungolfed z() and call it as rho(). It would suppose that gcd(0,n)=n so the loop stop and return for fail n. ``` )time on rho(n)== p:=a:=b:=101 for i in 1..repeat A(a);A(b);A(b) p:=mulmod(p,a-b,n) i rem 999<9=>(p:=gcd(p,n);p>1=>break) p va1:=[187,1679,14369648346682547857,34747575467581863011,52634041113150420921061348357,82312263010898855308580978867,205255454905325730631914319249,1233457775854251160763811229216063007, 1751952685614616185916001760791655006749] p1()==(for i in 1..#va1-1 repeat output [va1.i,z(va1.i)]) ``` results (z() is ok to all but the last number 1751952685614616185916001760791655006749 remain not factored (10 minutes) ) ``` (6) -> p1() [187,17] [1679,23] [14369648346682547857,1500450271] [34747575467581863011,3628273133] [52634041113150420921061348357,2860486313] [82312263010898855308580978867,264575131106459] [205255454905325730631914319249,2860486313] [1233457775854251160763811229216063007,1111111999999] Type: Void Time: 30.38 (EV) + 1.38 (GC) = 31.77 sec (8) -> z(1679) (8) 23 Type: PositiveInteger Time: 0 sec ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~100~~ 99 bytes, ~~45 40~~ 39 seconds + 10 minute penalty ``` import math def f(n): x=y=2;d=1 while d<2:y=y*y+1;x,y=1+x*x%n,y*y%n+1;d=math.gcd(x-y,n) return d ``` [Try it online!](https://tio.run/##VY7ZboJQEIbveQqSxgSqbWafOVoepilaTSoaQlN4enq4MXg3y79892k43zqe58v1fuuH8vo5nIv2eCpPVVfvi3JspoYObYNF@Xe@/BzL9oP2UzO9Tls8jLupwe34Om66Xb5sunxrmyXi/furrca3adfVRdkfh9@@K9v53l@6oTpVGF7XxWMzT@tV2JJJsJgFqXjoWs3i4uoq5hoYxoC4eisZCwgiMioIQSIEQ855TzFBjESLGyJFqDKEBiSPsLWOQElVVBIokzqDMabMiInkCZuYRd0zlQopooEbB@aWjGDZBrAEvzwMrpgybqihGBqGpqwD9OzMkyqA@dIx/wM "Python 3 – Try It Online") Uses Pollard-Rho with initial value 2 and polynomial x^2+1. ]
[Question] [ You must write a program or function that, when given a *nonempty* string **S** of **N** printable ASCII characters†, outputs a program that will exit with exit code **C**, where **C** is the ASCII codepoint at position 0 in **S**. This program you write will additionally output a program **P**, such that, when run, it exits with exit code **C′**, where **C′** is the ASCII codepoint at position 1 in **S**. Program **P** will output another program **P′**. This process repeats until there are no characters left in **S**. After this is done, you must output nothing, followed by an optional newline; and should exit with exit code 0. †The characters between `0x20` and `0x7e` inclusive. Some more rules: * Self-modifying programs are not allowed: you must output the source to STDOUT (or, return value initially) * You may not read your own source code. The shortest such program in bytes will win. For some rudimentary testing, [this ruby script](https://gist.github.com/ConorOBrien-Foxx/033e6d3e0c3755aea04fc02d18ecb15c) can be used. (The first argument is the way you invoke the script, the second is the program, and the third is the input string.) ## Hypothetical Example Say the program is `FOO`. When given the string "ABC", it outputs `BARA`. This program exits with code `65` and outputs `BARB`. This in turn exits with code `66` and ouputs `BARC`. This program exits with code `67` and outputs `BAR!`. This outputs nothing, and exits with code `0`. [Answer] # Python 2, ~~126~~ ~~101~~ 94 bytes In the process of making this, I found that Python code may not contain literal NUL bytes. ``` lambda i,s='''i=%r;s=%r try:print s%%(i[1:],s,i[0]) except:0 exit(ord(%r))''':s%(i[1:],s,i[0]) ``` [**Try it online**](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQqVNsq66unmmrWmRdDCS4SooqrQqKMvNKFIpVVTUyow2tYnWKdTKjDWI1uVIrklMLSqwMgIzMEo38ohQN1SJNTaB2q2I0pf8hRqRpZOYVlJZoaGr@V/dIzcnJVwcA) *(shows the exit code in the Debug info)* --- Note that each of the non-empty programs below has a trailing linefeed. For input `Hello`, the above outputs: ``` i='ello';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))' try:print s%(i[1:],s,i[0]) except:0 exit(ord('H')) ``` which prints ... which prints ``` i='o';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))' try:print s%(i[1:],s,i[0]) except:0 exit(ord('l')) ``` which prints ``` i='';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))' try:print s%(i[1:],s,i[0]) except:0 exit(ord('o')) ``` which prints nothing (the empty program) which prints nothing and exits with code 0. [Answer] # Python 3, 77 bytes ``` p='exit(0)' for c in input()[::-1]:p='print(%r);exit(ord(%r))'%(p,c) print(p) ``` This code takes input from STDIN and outputs the first program to STDOUT. If the input is `ABCDE`, the results are ``` 0 print('print(\'print(\\\'print("print(\\\\\\\'exit(0)\\\\\\\');exit(ord(\\\\\\\'E\\\\\\\'))");exit(ord(\\\\\\\'D\\\\\\\'))\\\');exit(ord(\\\'C\\\'))\');exit(ord(\'B\'))');exit(ord('A')) 65 print('print(\'print("print(\\\'exit(0)\\\');exit(ord(\\\'E\\\'))");exit(ord(\\\'D\\\'))\');exit(ord(\'C\'))');exit(ord('B')) 66 print('print("print(\'exit(0)\');exit(ord(\'E\'))");exit(ord(\'D\'))');exit(ord('C')) 67 print("print('exit(0)');exit(ord('E'))");exit(ord('D')) 68 print('exit(0)');exit(ord('E')) 69 exit(0) 0 ``` where each line contains the exit code and the output of the previously executed program (the first line is the first program). [Answer] # [Python 3](https://docs.python.org/3/), ~~115~~ ~~108~~ 100 bytes ``` i=input() r="%s" k="" for c in i:r%="print(%s\"%%s%s\");exit(%i)"%(k,k,ord(c));k+=k+"\\" print(r%"") ``` [Try it online!](https://tio.run/nexus/python3#JctBCoQwDEbhfU9Rfgg06AmU7D1Ed45CiLSSKnj7OsOsHnzwuoqW874SBxdQQzABwl49rlFL1MlJcLqWK1HLIGq/8Lw9@hVlULLRxuqftDLPNogNyBnh/zgB3PuyHUd9AQ "Python 3 – TIO Nexus") --- For the input `Hello`, the program prints: ``` print("print(\"print(\\\"print(\\\\\\\"print(\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\");exit(111)\\\\\\\");exit(108)\\\");exit(108)\");exit(101)");exit(72) ``` --- The program above prints: ``` print("print(\"print(\\\"print(\\\\\\\"\\\\\\\");exit(111)\\\");exit(108)\");exit(108)");exit(101) ``` and exits with code `72`. [Try it online!](https://tio.run/nexus/python3#@19QlJlXoqEEoWJgdAwSKwaDBwNK6HxN69SKzBINQ0NDTXQhAwtNdC6CY6gJY5sbaf7/DwA) --- The program above prints ``` print("print(\"print(\\\"\\\");exit(111)\");exit(108)");exit(108) ``` and exits with code `101`. [Try it online!](https://tio.run/nexus/python3#@19QlJlXoqEEoWJgdAwSCwSUYLSmdWpFZomGoaGhJjLXwEIThYNgG2r@/w8A) --- The program above prints: ``` print("print(\"\");exit(111)");exit(108) ``` and exits with code `108`. [Try it online!](https://tio.run/nexus/python3#@19QlJlXoqEEoWJgdEyMEghrWqdWZJZoGBoaaiI4BhaayOz//wE) --- The program above prints: ``` print("");exit(111) ``` and exits with code `108`. [Try it online!](https://tio.run/nexus/python3#@19QlJlXoqEEoWKUYpQ0rVMrMks0DA0NNeFsAwvN//8B) --- The program above prints nothing and exits with code `111`. [Try it online!](https://tio.run/nexus/python3#@19QlJlXoqGkpGmdWpFZomFoaKj5/z8A) --- The empty program prints nothing and exits with code `0`. [Try it online!](https://tio.run/nexus/python3) [Answer] # C, 156 bytes ``` char*s="char*s=%c%s%c;n=%d;char*t=%c%s%c;main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}";main(i,t)char**t;{printf(s,34,s,34,0,34,t[1],34);} ``` [Try it online!](https://tio.run/nexus/c-gcc#@5@ckVikVWyrBKVVk1WLVZOt82xVU6zBQiUwodzEzDwNzeo8m@KSopzUPI0STTW1gqLMvJI0jWIdYxMdMJGnbQiiSoCEpnVRaklpUZ5CSXRerHWtEsSATJ0STbC5WiXW1RjaDcCaow1jwfpr////7@jkDAA) (Open the debug-tab to see the exit code.) Takes input as a command line argument. For input "ABC", this outputs the program ``` char*s="char*s=%c%s%c;n=%d;char*t=%c%s%c;main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}";n=0;char*t="ABC";main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];} ``` which returns 65 and outputs ``` char*s="char*s=%c%s%c;n=%d;char*t=%c%s%c;main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}";n=1;char*t="ABC";main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];} ``` which returns 66 and outputs ``` char*s="char*s=%c%s%c;n=%d;char*t=%c%s%c;main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}";n=2;char*t="ABC";main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];} ``` which returns 67 and outputs ``` char*s="char*s=%c%s%c;n=%d;char*t=%c%s%c;main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}";n=3;char*t="ABC";main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];} ``` which outputs nothing and returns 0. [Answer] # Python 2, 67 bytes Based on [this answer](https://codegolf.stackexchange.com/a/118302/34718), but modified to use Python 2, with a trivial program `0` to print nothing and exit. ``` p=0 for c in input()[::-1]:p='print %r;exit(ord(%r))'%(p,c) print p ``` [**Try it online**](https://tio.run/nexus/python2#@19ga8CVll@kkKyQmQdEBaUlGprRVla6hrFWBbbqBUWZeSUKqkXWqRWZJRr5RSkaqkWamuqqGgU6yZpcENmC///VPVJzcvLVAQ) [Answer] # RPL, 73 bytes With hp8 code page. Turn on your HP48 or similar, or fire [droid48](https://play.google.com/store/apps/details?id=org.ab.x48). Do not forget to `-52 SF` for better visualization of the stack. I assume you have already pushed the string, e.g. `"ABC"`, on the stack. Then key in the following function: ``` → x«{LAST}x{DUP NUM 3ROLLD 2OVER SIZE DUP{SUB 2SWAP PUT}{4DROPN}IFTE}+ +» ``` (For convenience I suggest to push the α key twice before typing anything, hence locking alpha input mode. Latter just use the DEL key to cancel the automatically inserted closing delimiters. Simply use the ENTER key to validate. Do not forget the space after the stab operator.) This function immediately pushes on the stack a self-modifying program, under the form of a list. (But the function above does not modify itself). As the L in RPL originally stands for LISP, pressing the EVAL key will indeed evaluate this program. It returns the exit code on stack level two, and leaves itself, modified (yes, *here* it is questionable), for a latter EVAL. So press EVAL repeatedly until the program finally stops to drop itself on stack level one. The final exit code 0 thus appears on level one, with past exit codes above. If you forgot to `-52 SF`, you can navigate in the stack after each EVAL by pressing the ▴ key (leave this navigation mode with the ON key). The above function does accept strings with 0x0 chars inside, to create such strings `0 CHR` and `+` are your friends. The self modification consists of removing the used char from the embedded string (the `SUB 2 SWAP PUT` branch). Hence the dropped program is shorter after each EVAL. The `4 DROPN` branch ensures the *output nothing* instruction from the OP is respected, dropping among others the program itself. Of course all this assumes your note a `-55 SF` adept. Users of `-55 SF` shall be banned. Forever. I assume an RPL/2 solution exists, and could feature a real unix exit code, but afaik RPL/2 has limited introspection, and cannot evaluate lists. [Answer] # [sed](https://www.gnu.org/software/sed/), ~~467~~ 461 bytes Character codes are hard: ``` s:^:Y: :b s:ZY[ (2<FPZdnx]:0_Y: s:ZY[ )3=GQ[eoy]:1_Y: s:ZY[ *4>HR\fpz]:2_Y: s:ZY[]!+5?ISgq{]:3_Y: s:ZY[",6@JT^hr|]:4_Y: s:ZY[-#7AKU_is}]:5_Y: s:ZY[$.8BLV`jt~]:6_Y: s:ZY[%/9CMWaku]:7_Y: s:ZY[&0:DNXblv]:8_Y: s:ZY['1;EOYcmw]:9_Y: s:Y[ -']:3Z&: s:Y[(-1]:4Z&: s:Y[2-9:;]:5Z&: s:Y[<=>?@A-E]:6Z&: s:Y[F-O]:7Z&: s:Y[P-Y]:8Z&: s:Y[]Z\-`abc]:9Z&: s:Y[d-m]:10Z&: s:Y[n-w]:11Z&: s:Y[xyz{-~]:12Z&: tb s/([^_]+)_Y$/ q\1/ : s/[/\]/\\&/g s/([^_]+)_ (.*)/ s\/^\/\2\/;q\1/ /^\S/b ``` [Try it online!](https://tio.run/nexus/sed#TZDZVsIwFEXf@YqqWAoYQst8mVVwFhSntkkLBQQUKFBUBvXTrVFWqo9756x1Tq7rgAEq@MDyOaCpuiApuWpd64wXFKIme9jYYCx/dKV37SUF@c@G4oXja/I4WVFQPEu3woniSaM3XVOIeXZ7L1k6vTH6s3cKcc@inVT57NYcOB8UEp71R9L753fNp/knhaRnd3Hm4OK@9fxCIeVJMQqHlw/W8JVC2pMBOVupqe3RG4XMRrKtKMDmaOKGJCSzGZwUlIEsG8A5ly8US2VUYe1cVVGN1XKqI5X1caIaQc2W1WZtXHXQiB0qynGM2BRZ5rhYrtaI/U1WfsycXR5LumHScNBU/ViYEhn7WBLrmFBMiIh7/xKCFAkFseAQbBBMFIKzv3lGDWy5br87HNpf9mQ@sMeOi2bf "sed – TIO Nexus") Otherwise, the logic is rather straightforward: (1) escape special characters (there're two), (2) wrap in an additional `s/^/…/;q\1` layer, (3) repeat. Here's the output for `hello`: ``` s/^/s\/^\/s\\\/^\\\/s\\\\\\\/^\\\\\\\/q111\\\\\\\/;q108\\\/;q108\/;q101/;q104 ``` And a little script that I used: ``` #!/bin/bash set -uo pipefail IFS=$'\n' P=$(echo $1 | sed -rf q.sed) echo $P echo $1 | od -An -tuC for char in $(echo $1 | sed 's:.:&\n:g'); do P=$(echo | sed $P) printf ' %3d' $? done ``` [Answer] ## PowerShell, 172 156 bytes. ``` param($i) $s=@' if($i='{0}'){{ $s=@' {1}'@ $s-f($i-replace'^.'-replace"'","''"),"$s`n" $host.setshouldexit($i[0]) }} exit '@ $s-f$i.replace("'","''"),"$s`n" ``` The `h3l}'{l0` input will result the next output [Try it online!](https://tio.run/nexus/powershell#XYzBCsMgEETv@xmLsBESsfQcyH@UlkhrUbBNiBYKst9uDNhLb/NmmFdWs5lXJ7wEEceJwD8rjJQ1k8y5lfnENNU8HOOw2TWYu6Wbol9Gwh6JUPYo4vxGEG6JSUWbols@4WG/PtXrRV8lMMOB0IzCqybp/i2lFHTnwJSDxh0 "PowerShell – TIO Nexus") ``` if($i='h3l}''{l0'){ $s=@' if($i='{0}'){{ $s=@' {1}'@ $s-f($i-replace'^.'-replace"'","''"),"$s`n" $host.setshouldexit($i[0]) }} exit '@ $s-f($i-replace'^.'-replace"'","''"),"$s`n" $host.setshouldexit($i[0]) } exit ``` Which in the own turn will output [Try it online!](https://tio.run/nexus/powershell#rYxRCsIwEET/9xhLYAy0JeJ3ofcQRdFIAsGKG0EIe/aYir2Bf2/eMFPjbWPiiLBLCpTkYAsZGSfQrylOm1tl2Sqmxv1S9k//SOeLx3HAygzuGGDbsZHTncmEWfIgPkuYX@nq3zG36d4dLKnSEumPj9/DWj8 "PowerShell – TIO Nexus") ``` if($i='3l}''{l0'){ $s=@' if($i='{0}'){{ $s=@' {1}'@ $s-f($i-replace'^.'-replace"'","''"),"$s`n" $host.setshouldexit($i[0]) }} exit '@ $s-f($i-replace'^.'-replace"'","''"),"$s`n" $host.setshouldexit($i[0]) } exit ``` The last run will output nothing and exit code will be 0. [Try it online!](https://tio.run/nexus/powershell#@5@ZpqGSaauurlnNpVJs66DOBRWoNqgFisEEqw1r1R2AbF2QpG5RakFOYnKqepyeOoytpK6ko6SurqSpo6RSnJCnxKWSkV9colecWlKckV@ak5JakVkC1BptEKvJVVvLBeJyUdFEsIH//wMA "PowerShell – TIO Nexus") ``` if($i=''){ $s=@' if($i='{0}'){{ $s=@' {1}'@ $s-f($i-replace'^.'-replace"'","''"),"$s`n" $host.setshouldexit($i[0]) }} exit '@ $s-f($i-replace'^.'-replace"'","''"),"$s`n" $host.setshouldexit($i[0]) } exit ``` ]
[Question] [ A [sestina](https://en.wikipedia.org/wiki/Sestina) is a format of poem that follows an interesting pattern that we can generate. It has six stanzas of six lines each, where the last words of each line in the first stanza make up the line endings in each successive stanza, rotated in a set pattern. (There's also a three-line stanza at the end, but we won't worry about that.) Take a look at the first three stanzas of Elizabeth Bishop's creatively named *[Sestina](http://staff.washington.edu/rmcnamar/383/bishop.html)*: > > September rain falls on the house. > > In the failing light, the old grandmother > > sits in the kitchen with the child > > beside the Little Marvel Stove, > > reading the jokes from the almanac, > > laughing and talking to hide her tears. > > > She thinks that her equinoctial tears > > and the rain that beats on the roof of the house > > were both foretold by the almanac, > > but only known to a grandmother. > > The iron kettle sings on the stove. > > She cuts some bread and says to the child, > > > It's time for tea now; but the child > > is watching the teakettle's > small hard tears > > dance like mad on the hot black stove, > > the way the rain must dance on the house. > > Tidying up, the old grandmother > > hangs up the clever almanac > > > ... > > > Note how each line ends with one of the six words "house," "grandmother," "child," "stove," "almanac," or "tears." Not only that, but the words are ordered in the pattern 6–1—5–2—4–3, relative to the previous stanza. It ends up looking like a spiral: [![enter image description here](https://i.stack.imgur.com/GcLBR.png)](https://commons.wikimedia.org/wiki/File:Sestina_system_alt.svg) We're still a few years away from programmatically generating a full sestina, but we can create a template featuring the end words of each stanza in proper order. Write a program or function that, given the six line ending words, outputs the blueprint for a sestina, following these rules. Here is the expected result for the input `house grandmother child stove almanac tears`: ``` house grandmother child stove almanac tears tears house almanac grandmother stove child child tears stove house grandmother almanac almanac child grandmother tears house stove stove almanac house child tears grandmother grandmother stove tears almanac child house ``` The first stanza is the words in original order, the second stanza is in the order 6-1-5-2-4-3 from the first. The third stanza is that order relative to the second, and so on, all the way to stanza 6. Assume that the input words will always be only letters, uppercase or lowercase. You can take them as an array of strings or a single string delimited by a non-letter character (space, newline, etc.). In the output, lines are separated by newlines (`0x0A`), and stanzas separated by two newlines. A trailing newline is acceptable. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. That being said, it may be shorter to compress the whole poem's structure, but I'd like to see some solutions that base each stanza on the previous. [Answer] # Python, ~~72~~ 64 bytes ``` i,n=input(),'\n';exec"print n.join(i)+n;i=map(i.pop,[-1,0]*3);"*6 ``` Takes input through STDIN as a comma separated array of 6 strings and outputs to STDOUT in the format described in the post with an additional trailing newline. [Try It Online! (Ideone)](http://ideone.com/zT2SNZ) Also, I am not sure if this is okay to do, but here is a shorter answer in the form of an anonymous lambda function at **59 bytes** that takes in input in the same format as the above answer, and outputs the *program* needed to generate the correct output: ``` lambda i,n='\n':"print n.join(i)+n;i=map(i.pop,[-1,0]*3);"*6 ``` Therefore it must be called in the format `exec(<Function Name>(<Array>))`. Again, I am not sure if this is okay to do, so I am adding this as an extra, separate, non-competing answer until someone (maybe even OP) can hopefully clarify if this is okay or not, which I would really appreciate. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~18~~ 17 bytes ``` 0ch5:"t[6l5H4I7]) ``` Input is a cell array of strings, in the format ``` {'house' 'grandmother' 'child' 'stove' 'almanac' 'tears'} ``` [Try it online!](http://matl.tryitonline.net/#code=MGNoNToidFs2bDVINEk3XSk&input=eydob3VzZScgJ2dyYW5kbW90aGVyJyAnY2hpbGQnICdzdG92ZScgJ2FsbWFuYWMnICd0ZWFycyd9) ### Explanation ``` 0c % Push string with a single space, to be used as separator h % Input array of 6 strings implicitly and append the above string 5:" % Repeat 5 times t % Duplicate the array of strings (previous stanza plus separator) [6l5H4I7] % Push array [6 1 5 2 4 3 7]. The 7th string is the separator, and stays % at the end. The other strings are shuffled as required ) % Index into the array of strings % End implicitly % Display implicitly ``` [Answer] # Mathematica, 59 bytes ``` r=Riffle;""<>Flatten@r[NestList[RotateRight,#,5],""]~r~"\n"& ``` The core of this unnamed function is `NestList[RotateRight,#,5]`, which takes an input list of length 6 and creates a list of 6 lists, each rotated in the sestina way. Indeed, if a list of lists-of-strings is acceptable output, then `NestList[RotateRight,#,5]&` does the job in **26 bytes**. Then, `r[...,""]` inserts an empty string between each of the 6 lists; `Flatten` turns the whole thing into a single list of strings; `~r~"\n"` then inserts a newline between each of those strings; and `""<>` concatenates the whole thing into a single string. Thus the other 33 bytes are just to convert the structured output into a single string. [Answer] ## Batch, 99 bytes ``` @for %%w in (%*)do @if not .%%w==.%7 echo %%w @echo( @if not .%7==...... %0 %6 %1 %5 %2 %4 %3 .%7 ``` Explanation: Takes input as command-line parameters. The `%0` causes it to loop around, accumulating `.`s in the originally empty 7th parameter. The extra `.` is because `if` doesn't work on empty strings. [Answer] # Ruby, 51 bytes ``` ->z{z.map{z[1],z[3],z[5],z[4],z[2],z[0]=z+[""]}*$/} ``` Instead of iterating over the numbers `0..5` as below, we repeat 6 times by iterating over the elements of `z`. In normal usage such as `(0..5).map{|i|puts i}` the code `{}` reads the elements iterated over. In this case the permutations done by the code inside the `{}` do not read the elements iterated over, so we can iterate over the elements of `z` without this interfering with the permutations. # Ruby, 56 bytes Takes a 6 element array as a parameter ``` ->z{(0..5).map{z[1],z[3],z[5],z[4],z[2],z[0]=z+[""]}*$/} ``` alternate version taking 6 parameters ``` ->a,b,c,d,e,f{(0..5).map{b,d,f,e,c,a=a,b,c,d,e,f,""}*$/} ``` With each iteration of `map` we permute `z`. The original version plus a `""` to represent a break between stanzas becomes the output of the `map` (this seventh array element is not needed by the assignment so is ignored). `*$/` converts the arrays to a string, joining everything together with newlines. [Answer] ## Racket 115 bytes ``` (let p((o(list l))(m 0))(if(> n m)(p(cons(map(λ(x)(list-ref(list-ref o 0)x))'(5 0 4 1 3 2))o)(+ 1 m))(reverse o))) ``` Ungolfed: ``` (define(f l n) (let loop ((ol (list l)) (m 0)) (if (> n m) (loop (cons (map (λ (x) (list-ref (list-ref ol 0) x)) '(5 0 4 1 3 2)) ol) (add1 m)) (reverse ol)))) ``` Testing: ``` (f (list "house" "grandmother" "child" "stove" "almanac" "tears") 6) ``` Output: ``` '(("house" "grandmother" "child" "stove" "almanac" "tears") ("tears" "house" "almanac" "grandmother" "stove" "child") ("child" "tears" "stove" "house" "grandmother" "almanac") ("almanac" "child" "grandmother" "tears" "house" "stove") ("stove" "almanac" "house" "child" "tears" "grandmother") ("grandmother" "stove" "tears" "almanac" "child" "house") ("house" "grandmother" "child" "stove" "almanac" "tears")) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 620œ?$ÐĿY€j⁷Ḥ¤ ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=NjIwxZM_JMOQxL9Z4oKsauKBt-G4pMKk&input=&args=WyJob3VzZSIsImdyYW5kbW90aGVyIiwiY2hpbGQiLCJzdG92ZSIsImFsbWFuYWMiLCJ0ZWFycyJd)** ### How? Yey, a use of one of my additions to Jelly! (`œ?`) ``` 620œ?$ÐĿY€j⁷Ḥ¤ - Main link: list of words L ÐĿ - loop until no longer unique, collecting intermediate results $ - last two links as a monad œ? - permutation of right argument (initially L) at index 620 - 620 Y€ - join with line feeds for €each (the words of each stanza) j - join (the stanzas) with ¤ - nilad followed by link(s) as a nilad ⁷ - a line feed Ḥ - double (two line feeds) ``` ]
[Question] [ # Definition According to [Wikipedia](https://en.wikipedia.org/wiki/Cooke_and_Wheatstone_telegraph): > > The Cooke and Wheatstone telegraph was an early electrical telegraph system dating from the 1830s invented by English inventor William Fothergill Cooke and English scientist Charles Wheatstone. It was the first telegraph system to be put into commercial service. The receiver consisted of a number of needles which could be moved by electromagnetic coils to point to letters on a board. This feature was liked by early users who were unwilling to learn codes, and employers who did not want to invest in staff training. > > > It works like this: [![Scheme of Cooke and Wheatstone telegraph, five-needle](https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Cooke_Wheatstone_Telegraph_2.jpg/220px-Cooke_Wheatstone_Telegraph_2.jpg)](https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Cooke_Wheatstone_Telegraph_2.jpg/220px-Cooke_Wheatstone_Telegraph_2.jpg) In the middle are five needles, which can be deflected clockwise (as is the case of the middle needle) or anti-clockwise (as is the case of the last needle). In the picture above, the two deflected needles point to the letter `G`, which means that the letter being transmitted/received is the letter `G`. Note that the letters `C`, `J`, `Q`, `V`, `X`, `Z` are missing and thus have to be substituted with other letters. # Task You will receive a character in `ABDEFGHIKLMNOPRSTUWY` as input, and you will output the corresponding configuration of the five needles, with undeflected as `|`, deflected clockwise as `/`, and deflected anti-clockwise as `\`. # Testcases This covers **all** the possible inputs ``` input output A /|||\ B /||\| D |/||\ E /|\|| F |/|\| G ||/|\ (explanation: see above) H /\||| I |/\|| K ||/\| L |||/\ M \/||| N |\/|| O ||\/| P |||\/ R \|/|| S |\|/| T ||\|/ U \||/| W |\||/ Y \|||/ ``` ### Rules/Requirements * Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included. * If it is possible, provide a link to a site where your program can be tested. * Your program must not write anything to `STDERR`. * [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Your program can output in any case, but it must be printed (not an array or similar). ### Scoring Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice. ***`Eventually`***, the answer with the least bytes will win. # Submissions To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 87104; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # C, ~~124~~ ~~107~~ 98 bytes As a function: ``` x,i;W(char*v){for(i=strcspn(" MRUYH NSWEI OTBFK PADGL",v);x<5;++x)putchar(x^i%5?x^i/5?124:92:47);} // main(int c,char**v){W(v[1]);} ``` This works by using rotating the grid 45 degrees and looking up the row/column from the resulting block. --- As a full executable (107 bytes): ``` x;main(i,v)char**v;{for(i=strcspn(" MRUYH NSWEI OTBFK PADGL",v[1]);x<5;++x)putchar(x^i%5?x^i/5?124:92:47);} ``` --- An alternative full executable: (same bytecount but takes input from stdin and includes newline after output) ``` main(i){char*r=" MRUYH NSWEI OTBFK PADGL",b[]="|||||";i=strchr(r,getchar())-r;b[i%5]=47;b[i/5]=92;puts(b);} ``` Breakdown: ``` x; // Implicit int declaration main(i,v)char**v;{ // K&R function declaration to save a byte for(i=strcspn("<...>",v[1]); // Find index of input in lookup table x<5;++x) // Loop 0 to 4 putchar(x^i%5?x^i/5?124:92:47); // Print /, \ or | depending on value of i } ``` Alternate breakdown: ``` main(i){ char*r="<...>", // Store lookup table b[]="|||||"; // Malleable base string for return i=strchr(r,getchar())-r; // Find input in lookup table b[i%5]=47; // Set correct char in output to / b[i/5]=92; // Set correct char in output to \ puts(b); // Print result } ``` --- Bonus: 0-9 extension from the wikipedia page: ``` x;main(i,v)char**v;{for(i=strcspn(" MRUY6H NSW7EI OT8BFK P9ADGL 012345",v[1]);x<5;++x)putchar(x^i%6?x^i/6?124:92:47);} ``` --- Bonus bonus: a complete (if messy) program for both encoding and decoding messages: ``` #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdbool.h> static const char *REF = " MRUY6H NSW7EI OT8BFK P9ADGL 012345 "; char sub(char c) { c = toupper(c); if(c == 'C') { c = 'K'; } if(c == 'J') { c = 'G'; } if(c == 'Q') { c = 'K'; } if(c == 'V') { c = 'W'; } if(c == 'X') { c = 'S'; } if(c == 'Z') { c = 'S'; } return c; } void print_encoded(char c) { char b[] = "|||||"; const char *p = strchr(REF, sub(c)); if(!p) { return; } int i = p - REF; if(i) { if(i%6 < 5) { b[i%6] = '/'; } if(i/6 < 5) { b[i/6] = '\\';} } puts(b); } char decode(const char *m) { int pf = 5; int pb = 5; for(int x=0;x<5;++x) { if(m[x] == '/') { pf=x; } else if(m[x] == '\\') { pb=x; } else if(m[x] == '\0') { return '!'; } } return REF[pb*6+pf]; } int main(int c, const char **v) { int inArg; bool isDecode; if(c > 1 && (strcmp(v[1], "-h") == 0 || strcmp(v[1], "--help") == 0)) { printf("Usage:\n %s [-d] [<input>]\n\n", v[0]); printf("Converts input to/from Cooke and Wheatstone 5-needle encoding.\n\n"); printf("If no input arguments are given, takes input from stdin.\n\n"); printf("Parameters:\n"); printf(" -h --help Displays help.\n"); printf(" -d --decode Switches to decode mode.\n"); printf("\n"); return 0; } else if(c > 1 && (strcmp(v[1], "-d") == 0 || strcmp(v[1], "--decode") == 0)) { inArg = (c > 2 ? 2 : 0); isDecode = true; } else if(c > 1) { inArg = 1; isDecode = false; } else { inArg = 0; isDecode = false; } if(isDecode) { if(inArg == 0) { char ln[6]; while(scanf("%5s", ln) == 1) { putchar(decode(ln)); } } else { for(int p = inArg; p < c; ++p) { for(const char *q = v[p], *e = strchr(v[p], '\0'); q < e; q += 5) { while(*q == ' ') { ++q; } putchar(decode(q)); } } } putchar('\n'); } else { if(inArg == 0) { int c; while((c = getchar()) != EOF) { print_encoded(c); } } else { for(const char *p = v[inArg]; *p; ++p) { print_encoded(*p); } } } return 0; } ``` [Answer] ## CJam, 42 bytes ``` r"HEBAMRUYIFDNSWKGOTLP"5e!{_$"/\|"er}%_&er ``` [Test it here](http://cjam.aditsu.net/#code=r%22HEBAMRUYIFDNSWKGOTLP%225e!%7B_%24%22%2F%5C%7C%22er%7D%25_%26er&input=L) Although there's a lot of structure to the outputs I'm not entirely sure yet I can compute the results efficiently (in terms of bytes). So this is still a lookup table, but I'm generating the list of possible needle configurations via permutations of the list `[0 1 2 3 4]`. [Answer] # [MATL](https://github.com/lmendo/MATL), 50 bytes ``` '!#$kYAqof^EZC}40iA*9n4JK?45/J~v'6Y2'\|/'Za5eioZ)! ``` [**Try it online!**](http://matl.tryitonline.net/#code=JyEjJGtZQXFvZl5FWkN9NDBpQSo5bjRKSz80NS9KfnYnNlkyJ1x8LydaYTVlaW9aKSE&input=J0En) ### Short explanation The code decompresses the shown string (`'!#$...J~v'`) into a string containing `\`, `|` and `/`; reshapes it into an array where each column corresponds to a letter; and indexes that array with the input character. ### Long explanation The compressesed string has been obtained (offline) using base-3 to base-95 encoding. The data from the challenge has been arranged into a long string of `\`, `|` and `/`, where each group of `5` characters corresponds to a letter. This string is interpreted as the base-3 representation of some big number, which is converted to base-95, using all printable ASCII chars as digits. The result is the compressed string that appears in the code (`'!#$...J~v'`). The program starts decompressing this string, that is, converting from base-95 to base-3 with alphabet `\`, `|`, `/`. The decompressed string is reshaped into a 5-row 2D char array, in which each column representing a letter. Let us call this array `Λ`. This array will be indexed using the ASCII code point of the input letter. The array `Λ` includes two tricks: 1. It has been filled with dummy values for the five letters missing between `A` and `Y`; 2. It starts with `L` (not `A`) and then proceeds circularly. The reasons for these two tricks are as follows: 1. Letter `A` has code point `65`. The last letter that needs to be handled is `Y`, with code point `89`. So we need to handle a range of `25` values, even if some intermediate ones (such as letter `C`) don't exist. To facilitate indexing, the five missing letters between `A` and `Y` have been filled with a dummy representation, so they do have a column in `Λ`. Thus, `Λ` has size 5×25. 2. Modular indexing is used. So letter `A`, or number `65`, is the same as `65 mod 25`, that is `15`. Therefore `A` needs to be in column `15` of `Λ`, `B` in column `16`, ..., and `Y` in column `14`. ### Commented code ``` '!#$kYAqof^EZC}40iA*9n4JK?45/J~v' % Compressed string (in base-95) 6Y2 % Predefined literal 'AB...Z': source alphabet % for decompression '\|/' % Target alphabet for decompression Za % Change of base representation (decompress) 5e % Reshape into 5-row array `Λ` i % Input letter o % Convert to number (ASCII code point) Z) % Use as column index into `Λ` ! % Transpose into a row. Implicitly display ``` [Answer] # Python 2, ~~172~~ ~~152~~ ~~151~~ 79 bytes ``` lambda x:r'/|||\/|||/\|||/|\||/||\|/||'['APONM LKIHY GFEWU DBTSR'.find(x):][:5] ``` No algorithm, just a lookup table. *Saved 20 bytes thanks to @LeakyNun!* *Saved a byte thanks to @TheBikingViking!* *Saved a whopping **72** bytes thanks to @Keeta!* [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~37~~ 34 bytes Code: ``` "/\|||"œ€JÙ•3wxìeNðƒ2xGÑäß•36BIk<è ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Ii9cfHx8IsWT4oKsSsOZ4oCiM3d4w6xlTsOwxpIyeEfDkcOkw5_igKIzNkJJazzDqA&input=Rw). [Answer] ## JavaScript (ES6), ~~97~~ 89 bytes ``` c=>(n=`ABEHMDFINRGKOSULPTWY`.search(c),s=[...`|||||`],s[4-n%5]=`\\`,s[n>>2]=`/`,s.join``) ``` Edit: Saved 3 bytes by switching to a lookup table that doesn't need padding. Saved 5 bytes by setting array elements instead of trying to edit a string. Explanation: The table `ABEHMDFINRGKOSULPTWY` is organised so that if you split it into 5 groups of 4 adjacent letters then each letter in the group is on the same `/` slant in the diagram, while if you split it into 5 groups by taking the index modulo 5 then each letter in the group is on the same `\` slant in the diagram. These latter groups are in reverse order but that's easily handled by subtracting from 4. (Arranging the table so that the former groups were in reverse order cost more to fix.) [Answer] # VBA, 106 bytes ``` Function v(s):v="|||||":p=InStr(1,v &"MRUYH NSWEI OTBFK PADGL",s):Mid(v, p\5)="\":Mid(v, (p Mod 5)+1)="/" ``` Final byte is `enter` which auto-generates `End Function`. With acknowledgements to [the scheme @Dave devised](https://codegolf.stackexchange.com/a/87108/55561). Invoke in spreadsheet or in VBA Immediate window eg with `?v("K")` [Answer] # Mathematica, 129 bytes ``` ""<>(IntegerDigits[IntegerDigits[36^^3ucgb2abu46m2rewohw225q4lc6hczypueyb3,190][[LetterNumber@#]],3,5]/.{0->"|",1->"/",2->"\\"})& ``` Anonymous function. Takes a string as input and returns a string representing its code as output. Uses a relatively simple encoding scheme. [Answer] # Pyth, 27 bytes ``` @{.p"/|\||"x."AW Ú/Ç\x94E\x18µð££ ``` Replace the escapes `\x94`, `\x18` with the corresponding bytes. [Try it online](https://pyth.herokuapp.com/?code=%40%7B.p%22%2F|%5C||%22x.%22AW%0A%C3%9A%2F%C3%87%C2%94E%18%C2%B5%C3%B0%C2%A3%C2%A3&test_suite=1&test_suite_input=%27A%27%0A%27B%27%0A%27D%27%0A%27E%27%0A%27F%27%0A%27G%27%0A%27H%27%0A%27I%27%0A%27K%27%0A%27L%27%0A%27M%27%0A%27N%27%0A%27O%27%0A%27P%27%0A%27R%27%0A%27S%27%0A%27T%27%0A%27U%27%0A%27W%27%0A%27Y%27) ### How it works ``` @ index into this list: .p"/|\||" permutations of /|\|| { deduplicate at index: ."AW\nÚ/Ç\x94E\x18µð££" compressed string: EBAHIFDNSWKGOTLPMRU x Q index in that of input (or -1 for Y) ``` # Pyth, 32 bytes Without using any hard-coded lookup tables. ``` @o-xN\/xN\\{.p"/\|||"x-rG2"CJQVX ``` [Try it online](https://pyth.herokuapp.com/?code=%40o-xN%5C%2FxN%5C%5C%7B.p%22%2F%5C%7C%7C%7C%22x-rG2%22CJQVX&test_suite=1&test_suite_input=%27A%27%0A%27B%27%0A%27D%27%0A%27E%27%0A%27F%27%0A%27G%27%0A%27H%27%0A%27I%27%0A%27K%27%0A%27L%27%0A%27M%27%0A%27N%27%0A%27O%27%0A%27P%27%0A%27R%27%0A%27S%27%0A%27T%27%0A%27U%27%0A%27W%27%0A%27Y%27) ### How it works ``` @ index into this list: .p"/\|||" all permutations of /\||| { deduplicate o sort by the following key for N in the list: xN\/ index of / in N - xN\\ … minus index of \ in N at index: rG2 capitalized alphabet - "CJQVX" minus CJQVX x Q index in that of input ``` [Answer] # Python 2, ~~115~~ 111 bytes This is a simple implementation, but it could use some golfing. Suggestions welcome. ``` def f(c):s=["|"]*5;a=0xdb52384ebd9f46caa72899c838d50/25**(ord(c)-65)%25;s[a/5]="/";s[a%5]="\\";return''.join(s) ``` **Ungolfed:** ``` def f(c): s = ["|"] * 5 d = ord(c) - 65 # 0xdb52384ebd9f46caa72899c838d50 is our lookup number # 0040004100304231200043322110342300120124130214000304 # in hexadecimal a = 0xdb52384ebd9f46caa72899c838d50 / 25**d % 25 s[a/5] = "/" s[a%5] = "\\" return ''.join(s) ``` [Answer] # C, 78 bytes ``` i;f(x){for(i=5;i--;)putchar("|/\\|"["^\\ NXLFPH DBow{} gsyc q a"[x-65]>>i&3]);} ``` version shown is all printable ASCII, 79 bytes. The second `\\` can be replaced by any single byte that has the same last 6 bits as the `\` character 0x5C : 0x1C (if your compiler allows it), 0x9C or 0xDC. The input character is looked up in the magic string which contains values for `A` to `Y` (including spaces for the unsupported characters `CJQVX`.) The character from the lookup table is interpreted as five overlapping 2-bit codes where: ``` 01 = / 10 = \ 00 or 11 = | ``` **Commented code in test program** ``` /* magic string codes: bytes are 01XXXXXX A /|||\ 011110 ^ B /||\| 011100 \\ D |/||\ 001110 N E /|\|| 011000 X F |/|\| 001100 L G ||/|\ 000110 F H /\||| 010000 P I |/\|| 001000 H K ||/\| 000100 D L |||/\ 000010 B M \/||| 101111 o N |\/|| 110111 w O ||\/| 111011 { P |||\/ 111101 } R \|/|| 100111 g S |\|/| 110011 s T ||\|/ 111001 y U \||/| 100011 c W |\||/ 110001 q Y \|||/ 100001 a ABBCDEFGHIJKLMNOPQRSTUVWXY*/ i;f(x){for(i=5;i--;)putchar("|/\\|"["^\\ NXLFPH DBow{} gsyc q a"[x-65]>>i&3]);} j; main(){ j=getchar(); f(j); } ``` [Answer] # Ruby, 159 bytes ``` v=[1,2,3,4,7,8,9,13,14,19];w=v+v.map{|e|25+e};a="HEBAIFDKGLMRUYNSWOTP";b="\\/" x=w[a.index($*[0][0])];g="|"*5;y=(x>25)?0:1;g[(x/5)%5]=b[y];g[x%5]=b[1-y];puts g ``` ### Explanation: The positions of the deflected needles are mapped to 0..4, and thought as a base-5 number (2 digits). For A-L, the numbers are "as is"; for M-Z, add 25 to the number. The map is from variables `a` to `w`. Given the number corresponding to the letter, use its base-5 representation: the 5s digit for the first needle, the 1s digit for the second needle, and the 25s digit for the needles' directions. A program to encode an entire string, instead of one character, is just a bit longer: 172 bytes. ``` v=[1,2,3,4,7,8,9,13,14,19];w=v+v.map{|e|25+e};a="HEBAIFDKGLMRUYNSWOTP";b="\\/" $*[0].each_char{|c|x=w[a.index(c)];g="|"*5;y=(x>25)?0:1;g[(x/5)%5]=b[y];g[x%5]=b[1-y];puts g} ``` ]
[Question] [ For this challenge, you will be given an absolute path, and a "new" path (which can be absolute or relative), and you need to return the final path. For example, if your current directory was `/var/tmp/test`: `my_dir` or `my_dir/` should return `/var/tmp/test/my_dir` `../../my_dir` should return `/var/my_dir` `/my_dir/./` should return `/my_dir` `../../../../../` should return `/` To be more pedantic: * A directory is a non-empty string consisting of alphanumeric characters and the symbols `-`,`_`, or `.` * **A path is a list of 0 or more directories**, separated using `/`. An absolute path starts with a `/`, a relative path does not. Paths can include an ending `/`. You need to "resolve" the second path, given the first path. The process of resolving is: 1. Test if the second path is relative. If so, then insert the absolute path's directories to the beginning of the second path. 2. If any of the directories is `..`, then remove it and the preceding directory. If it is the first directory, then simply remove it. 3. If any of the directories is `.`, then remove it. 4. Output the final absolute path. You should not output an ending `/`. You do not need to handle incorrect input. The commands should work, whether or not the directories passed actually exist on your machine. You can assume that everything is a directory, even if it has an extension. # Test cases ``` Absolute New Output "/a/b/c" "d" -> "/a/b/c/d" "/a/b/c/" "d" -> "/a/b/c/d" "/a/b/c/" "d/" -> "/a/b/c/d" "/a/b/c" "/d" -> "/d" "/a/b/c" "/d/" -> "/d" "/../a/b/c/" "d" -> "/a/b/c/d" "/a/../b/c/" "d" -> "/b/c/d" "/a/b/../c" "d" -> "/a/c/d" "/a/b/c/.." "d" -> "/a/b/d" "/a/b/c/" ".." -> "/a/b" "/a/b/c" "../d" -> "/a/b/d" "/a/b/c" "/../d" -> "/d" "/a/b/c" "" -> "/a/b/c" "/a/b/c" "." -> "/a/b/c" "/a/b/c" "./d" -> "/a/b/c/d" "/a/b/c" "/./d" -> "/d" "/a/b/c" "d.txt" -> "/a/b/c/d.txt" "/a/b/c" "d." -> "/a/b/c/d." "/a/b/c" ".txt" -> "/a/b/c/.txt" "/a/b/c" ".txt/d" -> "/a/b/c/.txt/d" "/a/b/." "./././." -> "/a/b" "/direc" "tory" -> "/direc/tory" "/a-_.b/" "__._-." -> "/a-_.b/__._-." "/a/b" "../.." -> "/" "/a/b" "../../.."-> "/" "/a" "../../.."-> "/" "/" "" -> "/" "/" "a" -> "/a" "/.." "a" -> "/a" "/." "" -> "/" ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your submissions as short as possible in your favorite language! [Answer] ## [Retina](https://github.com/m-ender/retina), 44 bytes ``` +`.+ /| |/\.?/ / +1`/?[^/]*/\.\.|/\.?$ ^$ / ``` Input is expected to be the two paths separated by a single space. [Try it online!](http://retina.tryitonline.net/#code=JShHYAorYC4rIC98IHwvXC4_LwovCisxYC8_W14vXSovXC5cLnwvXC4_JAoKXiQKLw&input=L2EvYi9jIGQKL2EvYi9jLyBkCi9hL2IvYy8gZC8KL2EvYi9jIC9kCi9hL2IvYyAvZC8KLy4uL2EvYi9jLyBkCi9hLy4uL2IvYy8gZAovYS9iLy4uL2MgZAovYS9iL2MvLi4gZAovYS9iL2MvIC4uCi9hL2IvYyAuLi9kCi9hL2IvYyAvLi4vZAovYS9iL2MgCi9hL2IvYyAuCi9hL2IvYyAuL2QKL2EvYi9jIC8uL2QKL2EvYi9jIGQudHh0Ci9hL2IvYyBkLgovYS9iL2MgLnR4dAovYS9iL2MgLnR4dC9kCi9hL2IvLiAuLy4vLi8uCi9kaXJlYyB0b3J5Ci9hLV8uYi8gX18uXy0uCi9hL2IgLi4vLi4KL2EvYiAuLi8uLi8uLgovYSAuLi8uLi8uLgovLiAKL2EvYi9jIC4vLi4vLi8uLg) (The first line enables a linefeed-separated test suite.) [Answer] # Python, 53 bytes ``` from os.path import*;p=lambda a,n:normpath(join(a,n)) ``` [Answer] ## Batch, ~~282~~ ~~281~~ ~~279~~ 276 bytes ``` @echo off set a=\ set r=%~2 if "%r%"=="" set r=%~1 if not %r:~,1%==/ set r=%~1/%~2 for %%a in (%r:/= %)do call:x %%a if not %a%==\ set a=%a:~,-1% echo %a:\=/% exit/b :x if %1==. exit/b if not %1==.. set a=%a%%1\&exit/b if not %a%==\ for %%a in (%a:~,-1%)do set a=%%~pa ``` Annoyingly Batch expressions don't generally like empty variables. Edit: Saved 1 byte thanks to @CᴏɴᴏʀO'Bʀɪᴇɴ and 2 bytes thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ (and a bunch of bytes on other answers too, although alas uncredited). [Answer] # Python 2, ~~265~~ ~~260~~ 254 bytes ``` y=lambda:[x for x in raw_input().split("/")if x!=""and x!="."] a=y();n=y();m=len(a)-1 while m>0: if a[m]==".."and m>0:del a[m];del a[m-1];m-=1 elif a[m]=="..":del a[m] m-=1 for i in n: if i==".."and len(a)>0:del a[-1] else:a+=i, print"/"+"/".join(a) ``` [Answer] # Python, 142 137 bytes ``` def p(a,n,r=[],S="/"): for s in[s for s in((n[:1]!=S)*a+S+n).split(S)if"."!=s and s]:e=s!="..";r=[s]*e+r[1-e:] return S+S.join(r[::-1]) ``` [Answer] # Bash, 41 bytes This bash script has the side effect of creating directories if they don't exist, but it should meet the requirements. Thanks [Karl](https://codegolf.stackexchange.com/questions/85479/directory-calculation#comment209832_85500) and [Neil](https://codegolf.stackexchange.com/questions/85479/directory-calculation#comment209847_85500) for your improvements. ``` mkdir -p $1;cd $1;mkdir -p $2;cd "$2";pwd ``` Usage: *bash getpath.sh "absolute" "new"* If you don't like the stderr when second argument is an empty string, you can test for it as follows (48 bytes): ``` mkdir -p $1;cd $1;[ $2 ]&&mkdir -p $2&&cd $2;pwd ``` Previous 30 byte attempt (requires directories to exist): ~~*cd $1;[ $2 ]&&cd $2;echo `pwd`*~~ [Answer] ## C#, 43 bytes ``` (x,y)=>Path.GetFullPath(Path.Combine(x,y)); ``` Saved 1 byte thanks to @aloisdg `Path.Combine` puts the arguments together, and `Path.GetFullPath` resolves the `..\`s [Answer] # Node REPL, ~~8~~ 12 bytes ``` path.resolve ``` Luckily you don't have to `require()` standard modules in the REPL. ## Test Suite <https://repl.it/Cclo/1> (If the output at the end is `true`, it matched) [Answer] # Javascript, 210 bytes ``` function p(a,b){d='.';e=d+d;s='/';t='split';u='splice';r=(b[0]===s?[]:a[t](s)).concat(b[t](s));for(i=0;i<r.length;r[i]===e&&r[u](i?i-1:i,i?2:1)?(i&&i--):i++)(!r[i]||r[i]===d)&&r[u](i,1)&&i--;return s+r.join(s)} ``` [Here is test suite](https://repl.it/CdPQ/1) With linebreaks instead of semicolons: ``` function p(a,b) { d='.' e=d+d s='/' t='split' u='splice' r=(b[0]===s?[]:a[t](s)).concat(b[t](s)) for(i=0;i<r.length;r[i]===e&&r[u](i?i-1:i,i?2:1)?(i&&i--):i++) (!r[i]||r[i]===d)&&r[u](i,1)&&i-- return s+r.join(s) } ``` [Answer] # Java 7, 83 bytes ``` String p(String a,String b){return Paths.get(a).resolve(b).normalize().toString();} ``` `normalize` is needed to deal with relative references. `add` is used to handle the second path starting with `/`, which `Paths.get(a, b)` won't handle as specified. [Answer] # Bash, 38 bytes ``` [[ $2 = /* ]]||p=$1 realpath -sm $p/$2 ``` Doesn't require root privileges and makes no assumptions about existing or non-existing files, directories or symbolic links. Test it on [Ideone](http://ideone.com/4z04WP). ### How it works `[[ $2 = /* ]]` tests if the second command-line argument begins with `/`. If it doesn't, the path is relative and `p=$1` sets variable **p** to the first command-line argument. This way `$p/$2` is `/$2` if `$2` is an absolute path and `$1/$2` if it is a realtive one. Finally, `realpath -sm $p/$2` prints the canonical absolute path of `$p/$2`. The `-s` switch makes *realpath* ignore symbolic links, and the `-m` switch missing components. [Answer] # Ruby, 16 bytes Since apparently using [a method from the standard library](http://ruby-doc.org/core-2.3.1/File.html) is allowed: ``` File.expand_path ``` See the [test suite on repl.it](https://repl.it/CdLW/2). [Answer] # [GNU sed](https://www.gnu.org/software/sed/), ~~81~~ 59 + 1 = 60 bytes +1 byte for `-r` flag. Expects input on STDIN separates by a single space. ``` s:.+ /:: s:/? :/: : s:/$|[^/]+/+\.\.|\.(/|$):\1: t s:^/*:/: ``` [Try it online!](https://tio.run/##VZDBDoIwDIbve4oePKiENl578UGcLMA4cBHDdtCEZ3cWEFazZPn@9u@fpqHzKQXGAojZBKYrMLFZ8DDdKroXVFi0OFk80nQ4sb2widKu6CzOlKimhlrwZgXSRD8E8pmkiPhnFqknRao8RJWIuOWIKWdqsRt20MbMHuMrZrG7VXXmbQAlZ3mGfD92LcRhfEurdNgQOIeuXDPmzVDjqhTLilDPR1h@@AzP2A@PkMrxCw "sed 4.2.2 – Try It Online") ## Explanation ``` s:.+ /:: # If the second argument starts with a slash, drop the first argument s:/? :/: # Join the first and second arguments with a slash, dropping duplicate slashes : s:/$|[^/]+/+\.\.|\.(/|$):\1: # Drop trailing slashes, resolve double and single dots t # If the above substitution was made, branch to : s:^/*:/: # Ensure output begins with a single slash ``` [Answer] # [Zsh](https://www.zsh.org/), 15 bytes ``` a=$1/$2 <<<$a:a ``` The `:a` modifier does exactly this. [Try it online!](https://tio.run/##dZBNCsMgEIX3nmIWbuPQLtv0LKIZIYHSQCr05/LWOLFNo1FB@Jz3xnnvex8e/XB1MDlDYMBCdwYaxd15aBqQBqQN5iIPKI@ibVtpTibQeHMBDVrsIC3iSzDDfYZrxgVINYbMlPrKV36RFszOtCv7KrXzl/Sw6RstqPgLwz8GUNHWGA@38St7kPJPX7CKXyorWXRcMsh90xZIw@SWOj9OL9Y2WlnOALVWulEszlPFeedsShZPhL/xM0yuq1hMTmKJOLEP "Zsh – Try It Online") ]
[Question] [ ### Overview [**Pearls** (or Masyu)](http://en.wikipedia.org/wiki/Masyu) is a logic game played on a grid. There are black and white pearls placed on the grid. The object is to form a *single, closed loop* that travels through each pearl using only straight line segments and right angles. There are some rules that govern how the loop interacts with pearls: * White pearls must be traveled **straight** through, but the loop must **turn** in the previous *and/or* next cell in its path. * Black pearls must be **turned** upon, but the loop must travel **straight** through the next *and* previous cells in its path. * The loop must **not** cross or otherwise intersect itself. All cells have exactly zero or two loop entry/exits. An example puzzle from Wikipedia (and its solution): ![enter image description here](https://i.stack.imgur.com/YwlFP.png) ![enter image description here](https://i.stack.imgur.com/M1GLA.png) Your objective is to solve a given puzzle. If there are multiple possible solutions, it does not matter which one you give. ### Input Input will be an unsolved *square* grid. The example shown above would look like this: ``` ..w.w..... ....w...b. ..b.b.w... ...w..w... b....w...w ..w....w.. ..b...w... w...b....w ......ww.. ..b......b ``` `w` is a white pearl, `b` is a black pearl, and `.` is an empty cell. Assume input is valid. This means it is well formed, and at least one solution is possible. All valid puzzles are at least 3x3, and contain at least one pearl. ### Output Output is a string of coordinates representing the path. The upper left corner of the grid is `0 0`, upper right is `n-1 0`, where *n* is the width of the grid. A path is simply a series of ordered coordinates: ``` x1 y1 x2 y2 x3 y3 ... ``` The path is assumed to be closed, so you do not *need* to repeat the first coordinate at the end, but there is no penalty for doing so. The output should consist of *at least* all corners in the path. You do not have to output every cell on the path if there is no turn. For instance, the output for the example could start with: ``` 1 0 5 0 5 1 ... ``` or ``` 1 0 2 0 3 0 4 0 5 0 5 1 ... ``` Output should *not* contain any cell not in the path. You may start at any cell in the path. --- ### Snippet Here's a snippet you can use to visualize your solution. Just paste in the grid you're working on and the path you output. I'm aware that it's painful to look at my code, so I just suggest you don't ;) ``` function draw(){document.getElementById("output").innerHTML=gridSVG+pathSVG}function drawCoords(){coords=document.getElementById("coords").value;var e=prefix+'<path fill="none" d="';if(nums=coords.match(/[^\s]+/g),!(nums.length<2)){for(e+="M "+(nums[0]*scale+offset)+" "+(nums[1]*scale+offset),i=2;i<nums.length;i+=2)e+=" L "+(nums[i]*scale+offset)+" "+(nums[i+1]*scale+offset);e+=" L "+(nums[0]*scale+offset)+" "+(nums[1]*scale+offset),e+='" stroke="black" stroke-width="2"/>'+suffix,pathSVG=e,draw()}}function drawPath(){path=document.getElementById("path").value;var e=prefix+'<path fill="none" d="'+path+'" stroke="black" stroke-width="2"/>'+suffix;pathSVG=e,draw()}function drawGrid(){grid=document.getElementById("grid").value;var e=prefix;for(lines=grid.match(/[^\s]+/g),width=lines[0].length*scale,height=lines.length*scale,i=0;i<=lines.length;i++)e+='<path stroke="gray" d="M 0 '+i*scale+" L "+width+" "+i*scale+'"/>',e+='<path stroke="gray" d="M '+i*scale+" 0 L "+i*scale+" "+height+'"/>';for(j=0;j<lines.length;j++)for(line=lines[j],i=0;i<line.length;i++)"w"==line.charAt(i)&&(e+='<circle cx="'+(i*scale+offset)+'" cy="'+(j*scale+offset)+'" r="'+.8*offset+'" stroke="black" fill="white"/>'),"b"==line.charAt(i)&&(e+='<circle cx="'+(i*scale+offset)+'" cy="'+(j*scale+offset)+'" r="'+.8*offset+'" stroke="black" fill="black"/>');e+=suffix,gridSVG=e,draw()}var prefix='<svg height="400" width="400">',suffix="</svg>",scale=30,offset=scale/2,pathSVG="",gridSVG=""; ``` ``` svg{position: absolute;left: 50px;} ``` ``` Paste grid input here<br><input id="grid" type="textarea" size="80" oninput='drawGrid()' /><br><br>Paste path output here<br><input id="coords" type="textarea" size="80" oninput='drawCoords()' /><br><br><div id="output"></div> ``` --- ### Test Cases These test cases show one possible output for each input (except the last, which is shown unsolved). There may be other valid paths, you might go CW or CCW or start at a different point, etc. Solutions should be able to solve the test cases in seconds/minutes/hours, not days/weeks/eons. ![pearl-3](https://i.stack.imgur.com/T7Qen.png) ``` ... w.. ..b 0 0 1 0 2 0 2 1 2 2 1 2 0 2 0 1 ``` ![pearl-6](https://i.stack.imgur.com/1pIGB.png) ``` .wb..b ...... ..b... w.ww.. ...... b....b 0 0 2 0 2 2 4 2 4 1 3 1 3 0 5 0 5 5 3 5 3 4 4 4 4 3 1 3 1 4 2 4 2 5 0 5 0 2 1 2 1 1 0 1 ``` ![pearl-12](https://i.stack.imgur.com/q2Y8x.png) ``` .....w.b.w.. ww..b...b... .w.....b.... ...wbww..b.b ....b....... w.w......... ..w......b.b .....bb..... .....b.....w w.ww..b..... ...w......w. b..w.....b.. ``` [Answer] # Python - 1669 Still pretty long, but fast enough to run the last example in under a second on my computer. It's probably possible to make shorter at the cost of speed, but for now it is pretty much equivalent to the ungolfed code. Example output for last test case: ``` 0 11 1 11 2 11 3 11 4 11 4 10 3 10 2 10 1 10 1 9 2 9 3 9 4 9 4 8 3 8 3 7 4 7 5 7 5 6 5 5 6 5 6 6 6 7 7 7 8 7 8 8 7 8 6 8 5 8 5 9 5 10 5 11 6 11 6 10 6 9 7 9 8 9 8 10 7 10 7 11 8 11 9 11 9 10 9 9 10 9 10 10 10 11 11 11 11 10 11 9 11 8 11 7 10 7 10 8 9 8 9 7 9 6 10 6 11 6 11 5 11 4 11 3 10 3 9 3 9 4 9 5 8 5 8 4 8 3 8 2 8 1 9 1 10 1 10 0 9 0 8 0 7 0 7 1 7 2 6 2 5 2 5 1 6 1 6 0 5 0 4 0 3 0 2 0 2 1 3 1 4 1 4 2 4 3 5 3 6 3 7 3 7 4 6 4 5 4 4 4 4 5 4 6 3 6 3 5 3 4 3 3 3 2 2 2 2 3 1 3 1 2 1 1 1 0 0 0 0 1 0 2 0 3 0 4 0 5 0 6 1 6 1 5 1 4 2 4 2 5 2 6 2 7 1 7 1 8 0 8 0 9 0 10 ``` ![enter image description here](https://i.stack.imgur.com/DZbQB.png) Code: ``` I=raw_input().split('\n');X=len(I[0]);Y=len(I);R=range def S(g=0,c=0,x=0,y=0): if y>=Y:return 0 if g==0:g=[[-1]*X for i in R(Y)];c=[[-1]*X for i in R(Y)] o={'.':set(R(7)),'w':{1,2},'b':{3,4,5,6}}[I[y][x]].copy() o&={0,1,3,4}if y<1 or g[y-1][x]in[0,1,5,6]else{2,5,6} o&={0,2,4,5}if x<1 or g[y][x-1]in[0,2,3,6]else{1,3,6} if y>Y-2:o&={0,1,5,6} if x>X-2:o&={0,2,3,6} if y>0 and g[y-1][x]in[2,3,4]: if'b'==I[y][x]and g[y-1][x]!=2:return 0 if'b'==I[y-1][x]:o&={2} elif'w'==I[y-1][x]and g[y-2][x]==2:o&={5,6} if x>0 and g[y][x-1]in[1,4,5]: if'b'==I[y][x]and g[y][x-1]!=1:return 0 if'b'==I[y][x-1]:o&={1} elif'w'==I[y][x-1]and g[y][x-2]==1:o&={3,6} h=[r[:]for r in c] if y>0 and g[y-1][x]in[2,3,4]: if x>0 and g[y][x-1]in[1,4,5]: if c[y-1][x]==c[y][x-1]: if(6 not in o)+any(any(i!=c[y-1][x]and i!=-1 for i in r)for r in c)+any(I[v][u]!='.'and(v>y)+(u>x)for v in R(y,Y)for u in R(X)):return 0 g[y][x]=6 for v in R(y,Y): for u in R(X): if v!=y or u>x:g[v][u]=0 for y in R(Y): for x in R(X): if g[y][x]>0:break f=[];d=-1;u,v=p,q=x,y while(u,v)!=(p,q)or-1==d:f+=[u,v];d=([0,{0,2},{1,3},{2,3},{0,3},{0,1},{1,2}][g[v][u]]-{(d+2)%4}).pop();i,j={0:(u+1,v),1:(u,v-1),2:(u-1,v),3:(u,v+1)}[d];u,v=i,j return f else: for v in R(y+1): for u in R(X): if h[v][u]==c[y][x-1]:h[v][u]=c[y-1][x] h[y][x]=c[y-1][x] else:h[y][x]=c[y-1][x] elif x>0 and g[y][x-1]in[1,4,5]:h[y][x]=c[y][x-1] else:h[y][x]=max(max(r)for r in c)+1 for n in sorted(list(o))[::-1]: if n==0:h[y][x]=-1 if x>X-2:i,j=0,y+1 else:i,j=x+1,y g[y][x]=n;r=S(g,h,i,j) if r!=0:return r return 0 for i in S():print i, ``` Ungolfed: ``` class Grid: def __init__(self,input): self.input = input.split('\n') self.x = len(self.input[0]) self.y = len(self.input) self.options = {'.':{0,1,2,3,4,5,6},'w':{1,2},'b':{3,4,5,6}} def convert(self,grid): directions = [None,{0,2},{1,3},{2,3},{0,3},{0,1},{1,2}] for y in range(self.y): for x in range(self.x): if grid[y][x] != 0: break chain = [] start_pos = (x,y) dir = -1 pos = start_pos while dir == -1 or pos != start_pos: chain.extend(pos) x,y = pos next_dir = (directions[grid[y][x]]-{(dir+2)%4}).pop() if next_dir == 0: nx,ny = x+1,y elif next_dir == 1: nx,ny = x,y-1 elif next_dir == 2: nx,ny = x-1,y elif next_dir == 3: nx,ny = x,y+1 dir = next_dir pos = (nx,ny) return chain def solve(self,grid=None,chain_ids=None,pos=(0,0)): x,y = pos if y >= self.y: return None if grid is None: grid = [[-1]*self.x for i in range(self.y)] if chain_ids is None: chain_ids = [[-1]*self.x for i in range(self.y)] options = self.options[self.input[y][x]].copy() if y == 0 or grid[y-1][x] in [0,1,5,6]: options &= {0,1,3,4} else: options &= {2,5,6} if y == self.y-1: options &= {0,1,5,6} if x == 0 or grid[y][x-1] in [0,2,3,6]: options &= {0,2,4,5} else: options &= {1,3,6} if x == self.x-1: options &= {0,2,3,6} if y != 0 and grid[y-1][x] in [2,3,4]: if self.input[y][x] == 'b' and grid[y-1][x] != 2: return None if self.input[y-1][x] == 'b': options &= {2} elif self.input[y-1][x] == 'w': if grid[y-2][x] == 2: options &= {5,6} if x != 0 and grid[y][x-1] in [1,4,5]: if self.input[y][x] == 'b' and grid[y][x-1] != 1: return None if self.input[y][x-1] == 'b': options &= {1} elif self.input[y][x-1] == 'w': if grid[y][x-2] == 1: options &= {3,6} new_chain_ids = [[i for i in row] for row in chain_ids] if y != 0 and grid[y-1][x] in [2,3,4]: if x != 0 and grid[y][x-1] in [1,4,5]: if chain_ids[y-1][x] == chain_ids[y][x-1]: if 6 not in options: return None if any(any(i != chain_ids[y-1][x] and i != -1 for i in row) for row in chain_ids) or \ any(self.input[v][u] != '.' and (v!=y or u>x) for v in range(y,self.y) for u in range(self.x)): return None grid[y][x] = 6 for v in range(y,self.y): for u in range(self.x): if v != y or u > x: grid[v][u] = 0 return self.convert(grid) else: for v in range(y+1): for u in range(self.x): if new_chain_ids[v][u] == chain_ids[y][x-1]: new_chain_ids[v][u] = chain_ids[y-1][x] new_chain_ids[y][x] = chain_ids[y-1][x] else: new_chain_ids[y][x] = chain_ids[y-1][x] elif x != 0 and grid[y][x-1] in [1,4,5]: new_chain_ids[y][x] = chain_ids[y][x-1] else: new_chain_ids[y][x] = max(max(row) for row in chain_ids)+1 for n in sorted(list(options),key=lambda n: -n): grid[y][x] = n if n == 0: new_chain_ids[y][x] = -1 if x == self.x-1: nx,ny = 0,y+1 else: nx,ny = x+1,y result = self.solve(grid,new_chain_ids,(nx,ny)) if result is not None: return result input = """ .....w.b.w.. ww..b...b... .w.....b.... ...wbww..b.b ....b....... w.w......... ..w......b.b .....bb..... .....b.....w w.ww..b..... ...w......w. b..w.....b.. """.strip() def print_grid(grid): for y,row in enumerate(grid): s = "" for i in row: s += {-1:'xxx',0:' ',1:' ',2:' | ',3:' ',4:' ',5:' | ',6:' | '}[i] s += '\n' for x,i in enumerate(row): s += {-1:'x%sx',0:' %s ',1:'-%s-',2:' %s ',3:'-%s ',4:' %s-',5:' %s-',6:'-%s '}[i] % input.split('\n')[y][x] s += '\n' for i in row: s += {-1:'xxx',0:' ',1:' ',2:' | ',3:' | ',4:' | ',5:' ',6:' '}[i] s += '\n' print s result = Grid(input).solve() print result ``` [Answer] # C, 590 ~~640 760 880 963 1018~~ Brute force is quite fast for this. The 12x12 test runs under 10ms. Knowing that could opt for some language more appropriate for golfing. I don't assume the board is square as the larger puzzles tend not to be square. The `W` define sets the limit on the board dimensions. The actual limit is smaller `W - 2` as I use extra rows for borders to avoid boundary checks. ``` #define W 40 int Y,X,T,P,Q[W*W],D[]={-W,-1,1,W};char B[W*W],K[W*W],I[W]; t(x,d,s){for(P=0;B[x];x*=x!=*Q)s-=K[Q[P++]=x]-1, d=(54202126527627840ll>>2*(d*7+B[x+=D[d]]%8))&3;return x?0:s;} m(x){int c=K[x],u=B[x-W],U=u&7,l=B[x-1],L=l&7,r=0, i=U!=3&U!=4&L!=2&L!=4,o=(39>>U)&1?57:70;o&=(52>>L)&1?42:85; if(x/W>Y+1){for(;P--;)printf("%d %d ",Q[P]%W-1,Q[P]/W-1);exit(0);} if(u>7)o&=U>4?~64:~6;if(l>7)o&=L>4?~32:~10; for(o&=c?c>1?c>2?(r=8*i,96):(r=8,i*30):~0:1;o;r++,o/=2) if(o&1)if(B[x]=r,r%8!=1||!t(x,0,T))m(x+1);B[x]=0;} main(){for(;gets(I);Y++)for(X=0;I[X];X++) T+=(K[X+1+Y*W+W]=I[X]/36)-1;m(W);} ``` Test [me](http://ideone.com/7WFbtz). Here is a more challenging test case: ``` .b.....b.b.......b.. .....w.....b.w....w. ....w.........w..... ..bb.....w.w.b....b. .w.....b..b......w.. .....b.............. .b..........b.b..bw. ....w....w....b...w. .......bb...b...w... ..b.......w......... ....b.w.....w.b...b. w...b...w..b.w.w.... b.w....w............ ...b.w......b..b...b w......w.b.ww....... .b....b..........b.. ....b....w.bb.w...w. w..b......w...b..... b.....w.........w... ...b....w..w..b...w. ...................b .b..w..bb.b..b..w... ........w......b.... b....w......b..b.b.. ...b..bb.w.w........ ...b.......w......w. w...w.b.w.....b....b ............w..ww... ..b.b..b....b....... ....b.........w...b. .ww.......b.w.w..... b.....w..w.w...b.... ....ww..b.b.w....w.w .............bb..w.. .b....w.b.b........w ....bw..........b... ``` I was lucky my code finds the solution quite early in the run (<5min), but the full search takes much longer (67min). ![20x36](https://i.stack.imgur.com/C0z81.png) [Answer] # Lua, ~~830~~ ~~810~~ ~~765~~ ~~752~~ ~~739~~ ~~729~~ 710 Runs board1 and board2 just fine, but takes a while on board3. It could save 9 bytes by outputting *every* path instead of just the first... ``` b={}s={0,0,0}R=table.insert Z=unpack for l in io.lines()do w=#l for i=1,w do c=({b=1,w=2,['.']=3})[l:sub(i,i)]R(b,c)s[c]=s[c]+1 end end h=#b/w for e=0,w*h-1 do function g(p,d,X,t)local function G(I,r)T={Z(t)}a=b[I+1]T[a]=T[a]+1 P={Z(p)}D={Z(d)}R(P,I%w)R(P,I/w-I/w%1)R(D,r)l=#D for U=2,#p,2 do if I==p[U-1]+w*p[U]then return end end if I==e then if T[1]==s[1]and T[2]==s[2]then for k=1,l do K=D[k]M=D[(k-2)%l+1]N=D[k%l+1]O=D[(k+1)%l+1]if({K==N or K~=M or N~=O,K~=N or(K==M and N==O)})[b[1+P[2*k-1]+w*P[2*k]]]then return end end os.exit(print(table.concat(P,' ')))end else g(P,D,I,T)end end _=X%w<w-1 and G(X+1,1)_=X/w-X/w%1<h-1 and G(X+w,2)_=X%w>0 and G(X-1,3)_=X/w-X/w%1>0 and G(X-w,4)end g({},{},e,{0,0,0})end ``` ]
[Question] [ In this task you have to write a program that reads a regular expression and generates another program that outputs whether an input string is accepted by that regular expression. The output must be a program written in the same language as your submission. # Input The input is a regular expression *r* matching the following ABNF (the initial production rule is `REGEX`): ``` REGEX = *( STAR / GROUP / LITERAL / ALTERNATIVE ) STAR = REGEX '*' GROUP = '(' REGEX ')' LITERAL = ALPHA / DIGIT ALTERNATIVE = REGEX '|' REGEX ``` If the input does not match this grammar, the behavior of your program is undefined. # Interpretation Interprete the input as a regular expression, where `*` is the Kleene-star (meaning *repeat left argument zero or more times*), `|` is an alternative, `(` and `)` group and no operator at all concatenated. Grouping takes precedence over star, star takes precedence over concatenation, concatenation takes precedence over alternative. A string is said to be *accepted* if the regex matches the whole string. # Output The program's output is another program written in the same language as your submission that reads a string *s* in an implementation defined way at runtime, outputs whether *r* accepts *s* and then terminates. Output may be done in a user-defined way although there must be only two distinct outputs for accepted and rejected programs. You may assume that the input of your output program is never longer than 216-1 Bytes. # Restrictions Neither your submission nor any program generated by your submission may use builtin functionality or libraries that * match regexes * transform regular expressions * compile regular expressions * generate parsers from a grammar * simplify the problem in a way that your submission becomes trivial # Scoring The score of your submission is the number of characters it. The submission with the lowest score wins. # Testcases All testcases contain a regular expression, a set of accepted strings, a set of rejected strings and an example program in C99 which is a valid output of a (hyptothetical) C99 submission. ## (empty regular expression) ### Accepted strings 1. (empty input) ### Rejected strings 1. foo 2. bar 3. baz 4. quux ### Example program ``` #include <stdio.h> int main() { char input[65536]; gets(input); return input[0] != 0; } ``` ## `(b|)(ab)*(a|)` (`a` and `b` alternating) ### accepted strings 1. `a` 2. `ba` 3. `abababababa` 4. `abab` ### rejected strings 1. `afba` 2. `foo` 3. `babba` ### example program ``` #include <stdio.h> int main() { char input[65536]; int state = 0; for (;;) switch (state) { case 0: switch (getchar()) { case 'a': state = 1; break; case 'b': state = 2; break; case EOF: return 0; default: return 1; } break; case 1: switch (getchar()) { case 'b': state = 2; break; case EOF: return 0; default: return 1; } break; case 2: switch (getchar()) { case 'a': state = 1; break; case EOF: return 0; default: return 1; } break; } ``` ## `(0|1(0|1)*)(|A(0|1)*1)` (binary floating point numbers) ### accepted strings 1. 10110100 2. 0 3. 1A00001 ### rejected strings 1. 011 2. 10A 3. 1A00 4. 100A010 [Answer] ## C, 627 characters This program treats its first command-line argument as the input and generates C code as its output. ``` #define A(v) F[v]+strlen(F[v]) #define S sprintf char*B="&&f%d(s)||f%d(s)",*J="&&f%d(s+%d)",*r,F[256][65536];h=2;e(f,n,o,R,C,O,t,g){for(C=O=f;*r;++r)switch(*r){case 40:r++;e(g=h++,C=h++,0,0);r[1]^42?t=g:(t=C,S(A(t),B,g,C=h++),r++);o=!S(A(O),J,t,o);O=C;break;case 41:goto L;case'|':S(A(C),J,n,o);o=!S(A(O=f),"||1");break;default:r[1]^42?S(A(C),"&&s[%d]==%d",o++,*r,O^f||R++):(o=!S(A(O),J,t=h++,o),O=C=h++,g=h++,S(A(g),"&&*s==%d&&f%d(s+1)",*r++,t),S(A(t),B,g,C));}L:S(A(C),J,n,o);}main(int c,char**v){r=v[1];for(e(1,!S(*F,"&&!*s"),0,0);h--;)printf("f%d(char*s){return 1%s;}",h,F[h]);puts("main(int c,char**v){exit(f1(v[1]));}");} ``` Here is its output for `(0|1(0|1)*)(|A(0|1)*1)` (with newlines added): ``` f11(char*s){return 1&&s[0]==49&&f7(s+1);} f10(char*s){return 1&&s[0]==48&&f9(s+1)||1&&s[0]==49&&f9(s+1);} f9(char*s){return 1&&f10(s)||f11(s);} f8(char*s){return 1&&f7(s+0)||1&&s[0]==65&&f9(s+1);} f7(char*s){return 1&&f0(s+0);} f6(char*s){return 1&&f2(s+0);} f5(char*s){return 1&&s[0]==48&&f4(s+1)||1&&s[0]==49&&f4(s+1);} f4(char*s){return 1&&f5(s)||f6(s);} f3(char*s){return 1&&s[0]==48&&f2(s+1)||1&&s[0]==49&&f4(s+1);} f2(char*s){return 1&&f8(s+0);} f1(char*s){return 1&&f3(s+0);} f0(char*s){return 1&&!*s;} main(int c,char**v){exit(f1(v[1]));} ``` If you provide valid input as its first command-line argument, it returns exit status 1. Otherwise, it returns exit status 0. > > $ ./regexcompiler '(0|1(0|1)\*)(|A(0|1)\*1)' > floatprog.c > > $ gcc -o floatprog floatprog.c > > floatprog.c: In function ‘main’: > > floatprog.c:1:519: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] > > $ ./floatprog '1A00001' && echo invalid || echo valid > > valid > > $ ./floatprog '100A010' && echo invalid || echo valid > > invalid > > > Either program, if you fail to provide the command-line argument, dereferences a null pointer, causing a segmentation fault. A sufficiently long regex will overflow the buffers of this submission, and the size of input to a generated program is limited by the size of the stack. However, all the test cases work. Note that `e(g=h++,C=h++,0,0);` introduces undefined behavior. If, for example, generated programs do not compile, you can try replacing the statement with `h+=2;e(g=h-1,C=h-2,0,0);`, which is five characters longer. [Answer] ### Ruby, 641 651 543 characters ``` H=Hash.new{|h,k|[k]} d=[[i=0,0,[]]] o=[?(] L="t,u,v=d.pop;q,r,s=d.pop;o.pop<?|&&(H[r]<<=t)||(H[q]<<=t;H[r]<<=u);d<<[q,u,s+v]" gets.chop.chars.map{|c|c==?*&&(q,r,s=d.pop;H[r]|=[q,i+=1];d<<=[r,i,s];next) eval(L)while/[|)]/=~c ?o[-1]>?(:o[-1]==?. /[|(]/=~c&&d<<[i+=1,i,o<<c&&[]]||c!=?)&&d<<[i+=1,i+1,["s==#{o<<?.;i}&&c=='#{c}'&&#{i+=1}"]]||o[-1]=?.} eval(L)while o.size>1 H.map{H.map{|k,v|v.map{|v|H[k]|=H[v]}}} t,u,v=d[0] $><<"s=#{H[t]};gets.chop.chars.map{|c|s=s.map{|s|#{v*'||'}}-[!0];#{H.map{|k,v|"s&[#{k}]!=[]&&s|=#{v}"}*?;}};p s&[#{u}]!=[]" ``` This ruby version became quite long because of several corner cases in the regex parser (maybe I should try a different approach). It expects the regular expression on STDIN and outputs the corresponding ruby code for the matcher to STDOUT. The program directly generates code for a [NFA-ε](http://en.wikipedia.org/wiki/Nondeterministic_finite_automaton_with_%CE%B5-moves) which is then executed in the matcher. **Test case 1:** *(output includes additional newlines and indentation)* ``` >>> s=[0]; gets.chop.chars.map{|c| s=s.map{|s|}-[!0]; }; p s&[0]!=[] ``` **Test case 2:** ``` >>> (b|)(ab)*(a|) s=[0, 1, 2, 4, 9, 5, 10, 6, 11, 12, 14]; gets.chop.chars.map{|c| s=s.map{|s|s==2&&c=='b'&&3||s==6&&c=='a'&&7||s==8&&c=='b'&&9||s==12&&c=='a'&&13}-[!0]; s&[1]!=[]&&s|=[1, 2, 4, 9, 5, 10, 6, 11, 12, 14]; s&[3]!=[]&&s|=[3, 4, 9, 5, 10, 6, 11, 12, 14]; s&[0]!=[]&&s|=[0, 1, 2, 4, 9, 5, 10, 6, 11, 12, 14]; s&[5]!=[]&&s|=[5, 6]; s&[7]!=[]&&s|=[7, 8]; s&[9]!=[]&&s|=[9, 5, 10, 6, 11, 12, 14]; s&[4]!=[]&&s|=[4, 9, 5, 10, 6, 11, 12, 14]; s&[11]!=[]&&s|=[11, 12, 14]; s&[13]!=[]&&s|=[13, 14]; s&[10]!=[]&&s|=[10, 11, 12, 14] }; p s&[14]!=[] ``` **Another example:** ``` >>> a|bc s=[0, 1, 3, 4]; gets.chop.chars.map{|c| s=s.map{|s|s==1&&c=='a'&&2||s==4&&c=='b'&&5||s==6&&c=='c'&&7}-[!0]; s&[0]!=[]&&s|=[0, 1, 3, 4]; s&[3]!=[]&&s|=[3, 4]; s&[5]!=[]&&s|=[5, 6]; s&[2]!=[]&&s|=[2, 7] }; p s&[7]!=[] ``` *Edit:* Added a transition to fix the bug [PleaseStand](https://codegolf.stackexchange.com/users/163/pleasestand) noted in the comments. Also changed initialisation of state. ]
[Question] [ Given a list of words and a grid of letters, find all the words in the grid and remove any letters which are not part of any of the words. The words could be forwards, backwards, up, down or diagonal. You may assume that no word in the list will occur in more than one place in the grid. Input will always be: a list of words, 1 per line, followed by a blank line, followed by the grid of letters. ## Examples **Input** ``` ADA ALGOL ASSEMBLY BASIC COBOL DELPHI FORTRAN JAVA LABVIEW LOGO PASCAL PERL PHP PYTHON SMALLTALK VISUALC LLJKCABLFCI OROLOBOCOIM GELACSAPRSX LPSTAHWVTAV ANRLXLXQRBI IHPLEDOXAHS KJYAPHPYNOU FABMADANZJA EVISNOHTYPL AAYLBMESSAC WEIVBALOGOM ``` **Output** ``` LL K FC OR LOBOCOI GELACSAPRS LP T TAV A L RBI IHPLED A S J APHP N U A MADA A V SNOHTYPL AYLBMESSAC WEIVBALOGO ``` **Input** ``` BACKSPACE BOLD CLOSE COMPACTDISC COPY CPU CURSOR DELETE DESKTOP DVD EDIT ENTER EXIT FLOPPY FONT HARDWARE INTERNET KEYBOARD MONITOR MOUSE PASSWORD PASTE RETURN SAVE SOFTWARE START TEXT TOWER WORDPROCESSING IAUERAWTFOSICPN DGZPFLOPPYARFLU RSNOCURSORVZDBM AMNIUOMRNHEGUIN OTBNSRMONITORNT BEYTTSGPJBOLDRT YRQEAHEHARDWARE EOGRRNECECLOSEP KIONTYKTODTOWER ELCENSUPERPDKNN ATRTPRYKELPVIEJ GIEANPOTKSEDUSL NXCMPASSWORDRUC TEDITAGVSWJCTOV CWOYPGYQKNLVXMW ``` **Output** ``` UERAWTFOS DG PFLOPPYA R NOCURSORV A NI O E OT NS MONITOR B TTS P BOLD Y EA EHARDWARE E RRNECECLOSE K NT KTO TOWER E SUPER D TRTPRY ELPVIE IEANPOTKSED S XC PASSWORDRUC TEDITA O P MW ``` This is code-golf - shortest solution wins. Example wordsearches from [1](http://www.whenwewordsearch.com/word_search/computer_programing_languages/1899/word_search.jsp) and [2](http://www.wordsearchfun.com/51198_Computer_Terminology_wordsearch.html). [Answer] ## Perl - 230 chars Count includes 4 for "-ln " command-line options. ``` if(1../^$/){push@w,$_,''.reverse if$_}else{$a.="$_\n"}END{$_=$a;/.+/;$W=$+[0];y/A-Z/ /;chomp;for$w(@w){for$n(0,$W-1..$W+1){$r=join".{$n}",map"($_)",(@l=split//,$w);if($i=$a=~/$r/s){substr($_,$-[$i++],1,shift@l)while@l}}}print} ``` Ungolfed: ``` # -n: implicitly loop over input lines # -l: strip the newlines if ( 1 .. /^$/ ) { # from first line to empty line push @w, # record in @w $_, # the word ''.reverse # and its reverse if $_ # if it's not the empty line } else { $a .= "$_\n" # otherwise, add to the search array } END { $_ = $a; # make a copy for the output /.+/; $W = $+[0]; # compute array width y/A-Z/ /; # blank the output board chomp; # and remove the trailing newline, # because -l will add it back for us for $w (@w) { # for each word for $n (0, $W-1 .. $W+1) { # for each direction in E, SW, S, SE $r = join ".{$n}", # form a regexp with an appropriate # number of characters skipped between letters # (0 -> adjacent, so E; $W -> next line, so S; # off by one from $W for the diagonals), map "($_)", # capturing the letters of the word (for their offsets), (@l=split//,$w); # which we split up here if ( $i = $a =~ /$r/s ) { # if the word matches in this orientation substr( $_, # set the substring of the output $-[$i++], # at the offset this letter matched 1, # length 1 shift @l ) # to the corresponding letter while @l # (for each letter) } } } print # and print the output } ``` [Answer] ## Ruby 1.9, 214 210 206 182 177 173 172 166 ``` s,G=$<.read.split$/*2 O=G.tr'^ ',' ' (s+$/+s.reverse).split.map{|w|[0,l=G=~/$/,l+1,l-1].map{|d|(k=G=~/#{[*w.chars].*?.*d}/m)&&w.size.times{|i|O[k+d*i+i]=w[i]}}} $><<O ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 87 (or 83?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ||UεVX8FD»YåiY1:AuSð:1Y:}D€g©ËiεSÐ0:«NFÁ}}øíJ0δKõKë®à©FD®£€нJRsεN®‹i¦}}¦}\)]€Søε{θ}J®ä» ``` With the actual I/O as mentioned in the challenge description. [Try it online.](https://tio.run/##PVBNixQxEL3XP/EwsHuTuaWT6p70R5JNJd2TRQ8riAyIe1g8qNugXr34EwQ/YFkdPDgwsnjpvjf@hv0jY82OekilqOK9eu@dX5w9Wj3e7S4v47Rpl/dzNdyk8fMqHc/Fcxq/z4/TvFe3b78@Ga7Gd6tpM76no/lwbfLxTU/9uB2/lUfTj2rcVOP1sB4/DFdMsR4@MuT3r9JfTBszrG9f/1wNX/qe34N7D3lF43bavJq2fcmYT8PNbpcJWZETEiGztQJZW0KQtuFRUJok9y6BdBFk9GQ9KKwxIH9UBetAtQpQ6QBoAnrAJbd5bR2DcmsCLIRXnfAIer83GKDClFmeQmONDszY2Mg3nSDqLI@5YX6PIXoDJFoEsnm446AgfICASy6243N7gPNWIpE2BYAWEb3oQm5JS2dAFafuoEb4vI7gydiDj/ZUZQ2IxuhoG28WWERtwIbMkP8rjNVnmEKgwpX7cPh08icoFvjfFNrCsymJd7k5qDR7ThyMOujDWqKh6NA7VRkDIvjgfKqwdq3GEgqNwjgbKkIVqQazlM2/IHyUbJWjFUVLXSmDbUF2NrkinVSmbpdNt5vNnp3Pnp69fPEH) (For some reason, the `Á` is very slow on an inner list of characters instead of a string in this program, so `εSÐ0:«NFÁ}}` has been replaced with `εÐS0:«NFÁ}S}` (rotate first; then convert it to a list of characters) to speed things up substantially - it'll now output on TIO in roughly a second, instead of timing out without any output after 60 seconds.) With less strict I/O (first words-input as a list, second grid-input as a list of lines; output-grid as a list of lines as well), this would be **83 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead: ``` εVI8FD»YåiY1:AuSð:1Y:}D€g©ËiεSÐ0:«NFÁ}}øíJ0δKõKë®à©FD®£€нJRsεN®‹i¦}}¦}\)]€Søε{θ}J®ä ``` [Try it online](https://tio.run/##TVFNb9QwEL3zM3JDYqX2Vu3NsSdZ58Pjepxk07KHIiG0EqKHigOgSMCVCz8BiQ@pKqw4sNJWiEt8j/gN/SOL7bYSh2TezHie3zyfX5w9WT/d76dtK48yMf7u3dd1fzhnL8n9nB/280HcvP/@bLx0H9bT1n2kg/l4pTL3bqDB7dyP4mD6Vbpt6a7Gjfs0XnqKzfjZj/z9U5iLaavGzc3b6/X4bRj89/jhyrfI7abtm2k3FH7my35/mqSMl6QZh@RRkmIlfOAVUkg51r5hhSQeM92HoJvwbwyh8UBABRYioNKiDqgNJCCkDUFZCOdgGdOsQh1pMlQhXzAjOmYCgQwnFYRqCX2KvuNhjUraeFONTVSlGVGHselhvNuAbYzygFgbcsLM3rGSZSZQWljGgF2UEwi0QQ5EUuXJ6sFpIlkDhnU2Q5JcBzaRn@hbwcxkVVjbkMLb1dsTkda@wmolG6yNWkDeyDCFNlVk7nTHJVPoraVcF8HfqKY3x8AW8N/2gLnx23OI5gcbS@kt6r2n4l40VBwUNRqMFqUKdzFrrDZ9CZVuJRS@kktgSqMtCURDla@oJa/vPTMNj174t2F5S13BLbbhOTvsdd4fl6pql3WXrPaz2Yvz2fOz16/@AQ) (with the same modification as above so it won't time out). **Explanation:** In pseudo-code, I do the following steps: ``` Map over the list of words: Push the input-grid Loop 8 times: If the word is present horizontally left-to-right: Replace everything else with a space Rotate the grid 45 degrees counterclockwise Reduce/combine all grids of spaces and words ``` As for the actual code, of which most (50 bytes) is used to rotate the grid 45 degrees: ``` | # Get all inputs until an empty line is encountered, # resulting in the list of words | # Do it again, resulting in the grid U # Pop and store the grid in variable `X` ε # Map over each of the words: V # Pop and store the word in variable `Y` X # Push grid `X` 8F # Loop 8 times: D»Yå # Check if the word is in the grid: D # Duplicate the grid » # Join the lines with newline delimiter Yå # Check that this contains the word `Y` i # If this is truthy: Y1: # Replace the word temporarily with a 1 AuSð: # Replace all uppercase letters with a space 1Y: # Replace the 1 back to the word } # Close the if-statement D€g©ËiεSÐ0:«NFÁ}}øíJ0δKõKë®à©FD®£€нJRsεN®‹i¦}}¦}\) # Rotate the grid 45 degrees counterclockwise: D€g©Ë # Check if the grid is a rectangle: D # Duplicate the grid €g # Get the length of each row © # Save this list of lengths in variable `®` (without popping) Ë # Check whether these lengths are all equal i # If this is truthy: ε # Map over each row: S # Convert it to a list of characters Ð0:« # Append the row-length amount of 0s to the row Ð # Triplicate the row 0: # Pop two, and replace all characters to 0s « # Merge this list of 0s to the row NF # Loop the 0-based map-index amount of times: Á # Rotate the row once towards the right } # Close the loop } # Close the map øí # Now rotate 90 degrees clockwise: ø # Zip/transpose; swapping rows/columns í # Reverse each row J # Join the inner list of characters back to a string δ # Map over each row: 0 K # Remove all 0s from the row õK # Remove any empty rows ë # Else (it's a diamond-shape instead): ® # Push the list of lengths à # Pop and push its maximum © # Store this maximum as new variable `®` (without popping) F # Loop this maximum amount of times: D # Duplicate the list ®£ # Only leave the first max amount of values €н # Only leave the first character of each row J # Join these characters together to a string R # Reverse it s # Swap so the list is at the top again ε # Map over each row: N®‹i # If the map-index is smaller than max `®`: ¦ # Remove the first character } # Close the if-statement } # Close the map ¦ # Remove the first (now empty) row } # Close the loop \ # Discard the now empty list ) # Wrap all rows on the stack into a list ] # Close the open if-statement; loop; and map # (we now have a list space-grids, except for the found words) €S # Convert each inner grid to a flattened list of characters ø # Zip/transpose; swapping rows/columns ε # Map over each inner list: { # Sort; spaces at the front, potential letter(s) at the end θ # Pop and leave the last character } # Close the map J # Join everything together to one huge string ® # Push the last maximum `®` ä # Split the string into that many equal-sized parts » # Join the list of rows with newline delimiter # (after which it is output implicitly as result) ``` [Answer] **JavaScript:** 342 characters [Code-Golfed version:](http://jsfiddle.net/briguy37/utaf6/) ``` function a(b){c='\n';d=b.split(c+c);e=d[1].split(c);for(f=-1,g=[];h=e[++f];)for(i=-1,g[f]=[];h[++i];)for(j=-2,g[f][i]=' ';2>++j;)for(l=-2;2>++l;)for(k=0;m=d[0].split(c)[k++];)for(n=-1;o=m[++n];)for(p=f-n*j-j,q=i-n*l-l,r=0;(s=m[r++])&&(t=e[p+=j])&&(u=t[q+=l])&&s==u;)if(r==m.length)g[f][i]=o;for(i=0;v=g[i];)g[i++]=v.join('');return g.join(c)} ``` [Formatted version:](http://jsfiddle.net/briguy37/78HGh/) ``` function solveWordsearch(input){ var lineBreak = '\n'; var solver = input.split(lineBreak+lineBreak); var board = solver[1].split(lineBreak); for(row=-1,output=[]; line=board[++row];){ for(col=-1,output[row]=[]; line[++col];){ for(rowIncrement=-2,output[row][col]=' ';2>++rowIncrement;){ for(colIncrement=-2;2>++colIncrement;){ for(k=0; word=solver[0].split(lineBreak)[k++];){ for(charPosition=-1; wordChar=word[++charPosition];){ var startRowIndex=row-charPosition*rowIncrement-rowIncrement; var startColIndex=col-charPosition*colIncrement-colIncrement; for(wordIndex=0;(compareWordChar=word[wordIndex++])&&(compareBoardRow=board[startRowIndex+=rowIncrement])&&(compareBoardChar=compareBoardRow[startColIndex+=colIncrement])&&compareWordChar==compareBoardChar;){ if(wordIndex == word.length){ output[row][col]=wordChar; } } } } } } } } for(i=0;outLine=output[i];){ output[i++]=outLine.join(''); } return output.join('\n'); } ``` The concept behind this solution is to iterate over all positions on the board, initialize a 2D-array's values to ' ' for each position, and then consider all potential word directions and word offsets. If a matching word is found, the array's value for that position is updated to the correct letter. Finally, the array is converted to a string and returned. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~126~~ 114 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {S←-++`׬⋄{w𝕊g:g⊑∘↑˜¨¯2+∨´⥊w{H←⊒˜∊·⥊(↕≠𝕨)+⌜·/𝕨⊸⍷⋄(H˘∨1↓˘⊒˜⌽⁼˘·H˘⌾⍉⊒˜⌽˘' '⊸∾˘)⌾(⌽∘⍉⍟𝕩)g}⌜↕4}⟜>´(S⟨⟩⊸≡¨)⊸⊔𝕩⊔˜S𝕩=' '} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge1PihpAtKytgw5fCrOKLhHt38J2Vimc6Z+KKkeKImOKGkcucwqjCrzIr4oiowrTipYp3e0jihpDiipLLnOKIisK34qWKKOKGleKJoPCdlagpK+KMnMK3L/Cdlajiirjijbfii4QoSMuY4oioMeKGk8uY4oqSy5zijL3igbzLmMK3SMuY4oy+4o2J4oqSy5zijL3LmCcgJ+KKuOKIvsuYKeKMvijijL3iiJjijYnijZ/wnZWpKWd94oyc4oaVNH3in5w+wrQoU+KfqOKfqeKKuOKJocKoKeKKuOKKlPCdlaniipTLnFPwnZWpPScKJ30KCkYgIkJBQ0tTUEFDRQpCT0xECkNMT1NFCkNPTVBBQ1RESVNDCkNPUFkKQ1BVCkNVUlNPUgpERUxFVEUKREVTS1RPUApEVkQKRURJVApFTlRFUgpFWElUCkZMT1BQWQpGT05UCkhBUkRXQVJFCklOVEVSTkVUCktFWUJPQVJECk1PTklUT1IKTU9VU0UKUEFTU1dPUkQKUEFTVEUKUkVUVVJOClNBVkUKU09GVFdBUkUKU1RBUlQKVEVYVApUT1dFUgpXT1JEUFJPQ0VTU0lORwoKSUFVRVJBV1RGT1NJQ1BOCkRHWlBGTE9QUFlBUkZMVQpSU05PQ1VSU09SVlpEQk0KQU1OSVVPTVJOSEVHVUlOCk9UQk5TUk1PTklUT1JOVApCRVlUVFNHUEpCT0xEUlQKWVJRRUFIRUhBUkRXQVJFCkVPR1JSTkVDRUNMT1NFUApLSU9OVFlLVE9EVE9XRVIKRUxDRU5TVVBFUlBES05OCkFUUlRQUllLRUxQVklFSgpHSUVBTlBPVEtTRURVU0wKTlhDTVBBU1NXT1JEUlVDClRFRElUQUdWU1dKQ1RPVgpDV09ZUEdZUUtOTFZYTVci) One third of the code is parsing the input, the more interesting parts are outlined below: ``` {w𝕊g:g⊑∘↑˜¨¯2+∨´⥊w{H←⊒˜∊·⥊(↕≠𝕨)+⌜·/𝕨⊸⍷⋄(H˘∨1↓˘⊒˜⌽⁼˘·H˘⌾⍉⊒˜⌽˘' '⊸∾˘)⌾(⌽∘⍉⍟𝕩)g}⌜↕4} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge3fwnZWKZzpn4oqR4oiY4oaRy5zCqMKvMiviiKjCtOKlind7SOKGkOKKksuc4oiKwrfipYoo4oaV4omg8J2VqCkr4oycwrcv8J2VqOKKuOKNt+KLhChIy5jiiKgx4oaTy5jiipLLnOKMveKBvMuYwrdIy5jijL7ijYniipLLnOKMvcuYJyAn4oq44oi+y5gp4oy+KOKMveKImOKNieKNn/CdlakpZ33ijJzihpU0fQoKdzEg4oaQICJBREEi4oC/IkFMR09MIuKAvyJBU1NFTUJMWSLigL8iQkFTSUMi4oC/IkNPQk9MIuKAvyJERUxQSEki4oC/IkZPUlRSQU4i4oC/IkpBVkEi4oC/IkxBQlZJRVci4oC/IkxPR08i4oC/IlBBU0NBTCLigL8iUEVSTCLigL8iUEhQIuKAvyJQWVRIT04i4oC/IlNNQUxMVEFMSyLigL8iVklTVUFMQyIKZzEg4oaQIDEx4oC/MTHipYoiTExKS0NBQkxGQ0lPUk9MT0JPQ09JTUdFTEFDU0FQUlNYTFBTVEFIV1ZUQVZBTlJMWExYUVJCSUlIUExFRE9YQUhTS0pZQVBIUFlOT1VGQUJNQURBTlpKQUVWSVNOT0hUWVBMQUFZTEJNRVNTQUNXRUlWQkFMT0dPTSIKCncyIOKGkCAiQkFDS1NQQUNFIuKAvyJCT0xEIuKAvyJDTE9TRSLigL8iQ09NUEFDVERJU0Mi4oC/IkNPUFki4oC/IkNQVSLigL8iQ1VSU09SIuKAvyJERUxFVEUi4oC/IkRFU0tUT1Ai4oC/IkRWRCLigL8iRURJVCLigL8iRU5URVIi4oC/IkVYSVQi4oC/IkZMT1BQWSLigL8iRk9OVCLigL8iSEFSRFdBUkUi4oC/IklOVEVSTkVUIuKAvyJLRVlCT0FSRCLigL8iTU9OSVRPUiLigL8iTU9VU0Ui4oC/IlBBU1NXT1JEIuKAvyJQQVNURSLigL8iUkVUVVJOIuKAvyJTQVZFIuKAvyJTT0ZUV0FSRSLigL8iU1RBUlQi4oC/IlRFWFQi4oC/IlRPV0VSIuKAvyJXT1JEUFJPQ0VTU0lORyIKZzIg4oaQIDE14oC/MTXipYoiSUFVRVJBV1RGT1NJQ1BOREdaUEZMT1BQWUFSRkxVUlNOT0NVUlNPUlZaREJNQU1OSVVPTVJOSEVHVUlOT1RCTlNSTU9OSVRPUk5UQkVZVFRTR1BKQk9MRFJUWVJRRUFIRUhBUkRXQVJFRU9HUlJORUNFQ0xPU0VQS0lPTlRZS1RPRFRPV0VSRUxDRU5TVVBFUlBES05OQVRSVFBSWUtFTFBWSUVKR0lFQU5QT1RLU0VEVVNMTlhDTVBBU1NXT1JEUlVDVEVESVRBR1ZTV0pDVE9WQ1dPWVBHWVFLTkxWWE1XIgoKKHcxIEYgZzEp4ouIKHcyIEYgZzIpCgo=) ``` {w𝕊g:g⊑∘↑˜¨¯2+∨´⥊w{ ... }⌜↕4} w𝕊g: # A dyadic function taking: # - left argument w: word list # - right argument g: grid ↕4 # 0 1 2 3 { ... }⌜ # For each of those numbers on the right (specifying rotation) and ... w # each word on the left, call the inner function. # The inner function returns boolean matrices of the same shape of the input ∨´⥊ # Boolean OR of all the matrices g⊑∘↑˜¨¯2+ # For 1's in the matrix take a character from the grid, for 0's take a space. ``` The inner function rotates the grid (as many times as its right argument specifies: `⌽∘⍉⍟𝕩`), checks for words from left to right and on diagonals and then rotates the result back. **How to get get diagonals**: This method is mostly taken [from BQNcrate](https://mlochbaum.github.io/bqncrate/?q=diagonals%20into%20columns#). First a space is prepended to each row. Then each row is rotated by its index. Now words previously in the diagonals are in the columns, by transposing we get them in the rows. After marking the words, all the steps can be reversed: [Try with step-by-step results!](https://mlochbaum.github.io/BQN/try.html#code=c3RlcHMg4oaQICIx4oaTy5gi4oC/IuKKksuc4oy94oG8y5gi4oC/IsK34o2JIuKAvyLCt0jLmCLigL8iwrfijYki4oC/IuKKksuc4oy9y5gi4oC/IicgJ+KIvsuYIuKAvyLiiqIiCgp0ZXN0IOKGkCA+4p+oCiJ8fHx8IgoiQXx8fCIKInxEfHwiCiJ8fEF8Igrin6kKCj57ZuKGkOKAokJRTiAiSOKGkOKKksuc4oiKwrfipYoo4oaV4omgIiJBREEiIikr4oycwrcvIiJBREEiIuKKuOKNt+KLhCLiiL7wnZWp4ouE8J2VqeKLiEYgdGVzdH3CqCAx4oaT4oy94oi+wqjihpNzdGVwcwo=) [Answer] ## Scala 697, 666 649 ``` val(z,n)=io.Source.fromFile("F").getLines.toList.span(_.length>0) val m=n.tail val(w,h)=(m.head.length,m.size) def g(d:Int,e:Int,k:Int,g:Int,h:Int,i:Int,s:String)={ def f(x:Int,y:Int):Seq[(Int,Int)]={ val q=for(c<-(0 to s.size-1)) yield (y+c*i,x+c*k) if((q.map(p=>m(p._1)(p._2))).mkString==s)q else Nil} val t=for(x<-(d to e); y<-(g to h))yield f(x,y) t.flatten} def i(s:String)={val l=s.size g(0,w-l,1,0,h-1,0,s)++ g(0,w-1,0,0,h-l,1,s)++ g(0,w-l,1,l-1,h-1,-1,s)++ g(0,w-l,1,0,h-l,1,s)} def j(s: String)=i(s)++ i(s.reverse) val k=z.map(j).flatten (0 to h-1).map(r=>{(0 to w-1).map(c=>if(k.contains(r,c))print(""+m(r)(c))else print(" "));println()}) ``` ### degolfed: ``` object Golf { def main (args: Array[String]) = { val (words, matrix) = io.Source.fromFile ("./wordsearch.data").getLines.toList.span (_.length > 0) val m = matrix.tail val (w,h) = (m.head.length, m.size) // xi: x-increment, yi: y-increment def find (x: Int, y: Int, xi: Int, yi: Int, s: String): Seq [(Int, Int)] = { val points = for (c <- (0 to s.length-1)) yield (y + c*yi, x + c * xi) if ((points.map (p => m (p._1)(p._2))).mkString == s) points else Nil } def findInScope (xS: Int, xD: Int, xi: Int, yS: Int, yD: Int, yi: Int, s: String): Seq [(Int, Int)] = { val ppoints = for (x <- (xS to xD); y <- (yS to yD)) yield find (x, y, xi, yi, s) ppoints.flatten } def findRowColFallingClimbing (s: String) = { val l=s.length // horizontal: findInScope (0, w-l, 1, 0, h-1, 0, s) ++ // vertical: findInScope (0, w-1, 0, 0, h-l, 1, s) ++ // climbing /: findInScope (0, w-l, 1, l-1, h-1, -1, s) ++ // falling \: findInScope (0, w-l, 1, 0, h-l, 1, s) } def findBoth (s: String) = findRowColFallingClimbing (s) ++ findRowColFallingClimbing (s.reverse) val coords = words.map (findBoth).flatten (0 to h-1).map ( r => { (0 to w-1).map (c => if (coords.contains (r, c)) print ("" + m(r)(c)) else print (" ") ) println () }) } } ``` ]
[Question] [ For the purposes of this challenge, we define a postfix [regex](https://en.wikipedia.org/wiki/Regular_expression) dialect with alphabet `{1, 0}` and the following operations: * `1` and `0` match themselves literally. * `_` matches the empty string. * `!` always fails (i.e. it does not match anything). * `ab;` matches `a`, followed by `b`. * `ab|` matches both `a` and `b`. * `a+` matches one or more instances of `a`. The regex should always start matching from the start of the string, and stop matching at the end of a string (in other word, it is implicitly wrapped in `^$`). As an example, the following regex matches any string with an even number of `1`s: ``` 0+_|10+_|;10+_|;;+_|; ``` This is equivalent to the regex `0*(10*10*)*`. The following regex matches any nonempty string of ASCII letters, expressed in binary: ``` 110|010|10|10|10|;;;;1010|10|10|;;;10010|;10;|;;|;|;;+ ``` This is equivalent to the regex `(1.(0....|1(0...|10(0.|10))))*` (where `.` matches any character. You can test regexes with [this program](https://tio.run/##fZNRb5swEMff/SluqBKJolbklSRIXZ9atY3UaXupqsjAtaA6GBlnY1K@e3ZnE0IbOkdxzvf/Gd/9HQrZvKNSh0O5rbWxcKMra7S6uq5rVWbSlr9RiFxaCU8trOBWQDf2sB7EjzulBstfuswHyxtpeftTO8hdq/PcgzbIGVFL0yDEMfywpqze4DLhtM@uoECZwxW8apUrcMkQnl/gT4EG3dO6nGkbCOchlx1TfCZFLK1HpQ1L3NSo@o1V7vGzOpFxyrkphAtmuPEU5H@wPWPsxTjmoRlDzpwzZgMZaWiMNnABwc8K2xozizlkhTSSIgMBzGbwnL0IYbGxbCsZT5aezH2Qf1Ps1h66Pd4KTMjCmMtYwd2OFDrfEesBEY0S7J8nyDQ/PhHs4RnxqG3R1zFhCyWk0yHhFMmZJOlWaYezlV/jy33S4X0JE@/r9EMJuaZVCMvL097@bzo6Pj7K7aWjul5Df9Kmp/vo1KxD6FpGLue71uoomxaaY0c@7hwNAiG2sqxc8a5Wkql@/84sLxJ4Q3tfVv4FoU5JG2bKVxgeYQus@o7rnaVq7isIttJmReAEVA2OEJUGDx0O0Wyzn/O08POCJxHN5xF/@UO//wA). ## The Challenge Given a regex in the format described above, return a regex in this format that matches precisely those strings that are *not* matched by the input. One potential method to do this would be to convert the regex into a [nondeterministic finite automaton](https://en.wikipedia.org/wiki/Nondeterministic_finite_automaton), then convert that into a [deterministic finite automaton](https://en.wikipedia.org/wiki/Deterministic_finite_automaton), flip which states are designated as accept states, and then convert it back to a regex. ## Test Cases ``` format: input => potential output equivalent infix regex 0 => _101|+_|;| |1.* 1 => _001|+_|;| |0.* _ => 01|+ .+ ! => 01|+_| .* 01|+ => _ 01|+_| => ! [] (empty character class) 1001;;; => _01|01|01|;01|01|01|;;001|01|01|01|+_|;;;;01|101|01|01|+_|;;;;01|01|101|01|+_|;;;;01|01|01|001|+_|;;;;||||||| |.|..|...|0....*|.1...*|..1..*|...0.* ``` [Answer] # Dyalog APL, 166 bytes ``` {l←!!5*≢⍵⋄z←⊂''⋄n←,∘.,⍨⋄k←{⊃,/n\l/⊂⍵}⋄f←{⊃⊃{⍺∊';|':(2↓⍵),⍨⍺{';'=⍺:n/⍵⋄,/⍵}2↑⍵⋄⍺='_':⍵,⍨⊂z⋄'+'=⍺:⊂∘k∘⊃@1,⍵⋄⍺,⍵}/⌽1,⍵}⋄w←f⍵⋄⊃q/⍨{0=≢((z,k'01')~w∪f⍵)∪w∩f⍵}¨q←k'10!_|;+'} ``` The solution is a function that works by brute-forcing. It cannot be run in reasonable time nor with reasonable memory on any of the inputs, so no TIO link is provided; this is due to looping over every possible regex over the factorial of the factorial of 5 to the power of the input length. Note that the numbers involved go out of Dyalog's maximum number size for an input regex of length greater than 1. To test this, take a look at the function `f`, which returns a value that includes all matches less than the calculated upper bound `l`, and test it on the complementarity check `{0=≢ ... ⍵∩f⍵}`. Using smaller values of `l` can make the function provide wrong results, so note that before reducing its value. --- There is an upper bound for the minimum length of the complementary regex as a function of the length of the input regex, and an upper bound for the length of the longest string the two regexes need to be tested against to determine their complementarity. These parameters are used to brute force the complementary regex, by comparing the strings accepted by the input regex and the regex being tested for complementarity. We start by comparing the length of a regular expression to the number of states of its respective DFA. The [non-deterministic finite automaton (NFA)](https://en.wikipedia.org/wiki/Nondeterministic_finite_automaton) for the regex `1` is the following (using `(Sn)` to denote accepting states) ``` 1 Si-->(Sf) ``` The regex `_` representing an \$\epsilon\$-transition can be represented by an NFA that has less than 2 states, as can the regex `!` representing non-acceptance. ``` _ (Si) ``` ``` ! Si ``` Thus, a regex with only characters from `01_!` with length `n` will have an NFA with max size `n+1`. The regex `ab;`, where `a` and `b` are sub-regexes, denotes the concatenation of `a` and `b` and can be described as the following. (`Si#` denotes an initial state and `(S##)` denotes a final state.) ``` Si1-->...-->(Sf1) Si2-->...-->(Sf2) ; ε NFA= Si1-->...-->Sf1-->Si2-->...-->(Sf2) ``` The regex `a+` denotes one or more occurrences of `a`. ``` Si1-->...-->(Sf1) + ε +------------+ v | NFA= Si1-->...-->(Sf1) ``` This produces an NFA with the same size as that of `a`. Again, a regex with only characters from `01_!;` with length `n` will have an NFA with max size `n+1`. The regex `ab|` denotes an alternative of either `a` or `b`. ``` Si1-->...-->(Sf1) | Si2-->...-->(Sf2) Si1-->...-->(Sf1) NFA= Si2-->...-->(Sf2) ``` Both `Si1` and `Si2` are starting states in the above NFA. This does not fit the traditional definition of an NFA, where an NFA has only 1 starting state, but the size of the resulting [deterministic finite automaton (DFA)](https://en.wikipedia.org/wiki/Deterministic_finite_automaton) does not increase. If needed, the NFA for `+` can be changed so that there is an ε-transition from the final state to the second state, and the NFAs for `_` and `!` changed to have 2 states each, so that a traditional NFA can be constructed for alternation with ε-transitions between Si1 and Si2. An NFA resulting from alternation will be as large as the sum of the two sub-regexes that make it up. A regex of length `n` will have an NFA with a maximum size of `n+1`. By the [powerset construction](https://en.wikipedia.org/wiki/Powerset_construction), an NFA with size \$n\$ will result in a DFA with size \$2^n\$. So a regex of length \$n\$ will have a minimal DFA upper-bounded by \$2^{n+1}\$. A DFA can be inverted by simply switching the final and non-final states, so its complement will have the same number of states as itself. With this information, we need an upper limit on the size of the complementary regex as a function of the length of the number of states of the DFA. To do this, I use an algorithm to convert a DFA to a regex; the idea is to represent every possible path from Si to any other state, as well as accounting for loops by tracking every loop that starts and ends at Si, in a recursive manner. For every state that can be reached in 1 step from Si, the process is repeated and a path is constructed from this new state to every other state *except* the states that have already been encountered, i.e. Si in the first iteration, since loops back to Si would already be covered by tracking loops. An example of the construction can make this clearer. ``` 0<c0>;1<c1>;|+_| 0<r0>;1<r1>;<a>|| ; ``` This is a regex that represents a DFA that I will call the "base form". The base form for a state is a regex that traverses paths from that state to every state in the DFA except for, as we will see, states that have been explicitly excluded for a particular iteration. The accept/reject status of each path is denoted by `<a>`, being `_` for accept or `!` for reject. The second line of the regex accounts for this "breadth-first" filling, by transitioning to states that are 1 step way, and recursing the base form (as represented by `<r0>` and `<r1>`) on those states. Each time we recurse, we exclude the original "parent" state from the graph traversal to prevent the algorithm from infinitely looping. Loops in the regex are tracked in the first line, where, also, every possible path is traversed, halting when reaching the parent state, but these sub-regexes, as denoted by `<c0>` and `<c1>`, consider only the parent state to be the accepting state. At each level of recursion, the number of excluded states increases by 1, until every possible state is covered at which point the algorithm ends. The base form, without the recursive parts, is of length 16. Each iteration spawn 4 new sub-regexes, and there are as many iterations as states in the DFA. If a DFA has n states, an upper bound for the regex length is \$16 + 16×4 + 16×4×4 + ... + 16×4^{n-1}\$. This is a geometric series and can also be written as $$\frac{16}{3}\left(4^n-1\right)$$ Now given a regex with length s, the length of its complement is bounded by $$h=\frac{16}{3}\left(4^{2^{n+1}}-1\right)$$ (I felt that this upper bound could be improved to a mere exponential instead of a double exponential, potentially saving some bytes, but I was proven wrong by this [answer](https://cs.stackexchange.com/a/120548).) We can check if two regexes are equivalent by brute force, but to do that we need to know the upper limit of the input length to test. If the DFAs of the two regexes are a and b, we can construct another DFA c whose states are the Cartesian product of the states of a and b, so each state of DFA c can be labeled as a 2-tuple `(a_j,b_k)` where `a_j` and `b_k` are states of DFA a and b respectively. The transition of DFA c's state `(a_j,b_k)` under input letter `l` is the tuple of the transition of each state `a_j` and `b_k` in DFAs a and b respectively under letter `l`. The final states of DFA c are all the states `(a_j,b_k)` where either both `a_j` and `b_k` are final states or they are both non-final states. DFA c accepts a word if both DFAs a and b accept this word, i.e. DFAs a and b do not yield complementary results on this word. DFAs a and b are complementary iff DFA c does not accept any word. By the [pumping lemma](https://en.wikipedia.org/wiki/Pumping_lemma_for_regular_languages), to check for this, we only need to check of input word sizes up to the number of states of DFA c, minus 1. The size of the DFA of the complementary regex is `2^(h+1)` and that of the input regex is `2^(n+1)`. Thus we only need to check for input lengths up to `2^(h+1)×2^(n+1)-1`. $$2^{\frac{16}{3}\left(4^{2^{n+1}}-1\right)+1+n+1}-1$$ We need to find a golfy way to write a function that is always greater than the triple exponential above for n≥1. Factorials grow faster than exponentials and are 1 byte shorter and so can be useful. However, the factorial of 1 is still 1, so we cannot simply chain 3 factorials together. The first function can instead be an exponential `b*n`, APL for b to the power of n, after which two factorials can be added in place of the remaining double exponential, yielding `!!b*n`. \$b=3\$ is too small for the base case of n=1, \$b=4\$ is slightly smaller, but \$b=5\$ goes above the function. $$l=(5^{≢\omega}!)!$$ This gives the first statement of the APL code, `l←!!5*≢⍵` assign to the variable `l` the factorial `!` of the factorial `!` of `5` to the power of `*` the length `≢` of `⍵` the right argument. # The submission ``` {l←!!5*≢⍵⋄z←⊂''⋄n←,∘.,⍨⋄k←{⊃,/n\l/⊂⍵}⋄f←{⊃⊃{⍺∊';|':(2↓⍵),⍨⍺{';'=⍺:n/⍵⋄,/⍵}2↑⍵⋄⍺='_':⍵,⍨⊂z⋄'+'=⍺:⊂∘k∘⊃@1,⍵⋄⍺,⍵}/⌽1,⍵}⋄w←f⍵⋄⊃q/⍨{0=≢((z,k'01')~w∪f⍵)∪w∩f⍵}¨q←k'10!_|;+'} ``` The regex is parsed and its matches returned by the function `f`. It works on the reversed regex, and 'fold'ing ('reducing' in APL-speak) over it. It returns all matches of a regex, with the special case of the regex `a+` only returning up to the first `l` repetitions of sub-regex `a`, thus keeping the list of matches finite. By having this behaviour of `+`, all input matches up to a length of `l` are included in the result of `f`, i.e. nothing less than what is needed to test for complementarity. APL reduces from right to left, due to order of operations being from right to left. Each intermediate results of the reduce is formed by the matches of each sub-regex encountered thus far. For the initial case, a 1 is prepended to the regex before reversing it, after which the reduce operation is applied. ``` f←{⊃⊃{⍺∊';|':(2↓⍵),⍨⍺{';'=⍺:n/⍵⋄,/⍵}2↑⍵⋄⍺='_':⍵,⍨⊂z⋄'+'=⍺:⊂∘k∘⊃@1,⍵⋄⍺,⍵}/⌽1,⍵} ``` The right argument `⍵` contains the matches of each sub-regex encountered so far. The left argument `⍺` is the next character of the regex that is being processed. Each case of the regex character is checked using `=` equality or `∊` belongs-to when multiple cases can be joined into 1. Of particular note, `!` in the regex is treated the same as `0` or `1`, resulting in a match of the character `!`. Due to how the regexes are checked for complementarity, this works fine. Its exact mechanism is `⍺,⍵`, concatenate `⍺`, a single character being either of `0`, `1`, or `!`, with `⍵`. `_` matches the empty string, `z` in the APL code refers to `z←⊂''` present earlier in the entire submission; `⍵,⍨⊂z` the enclosed empty string, i.e. signifying that only the empty string is being matched, is prepended to `⍵`. The mechanism of `+` is dependent on the function `k←{⊃,/n\l/⊂⍵}`, which given a list of strings `⍵`, performs the Cartesian concatenation (Cartesian product, but using concatenation instead of set union) of `l` copies of `⍵`, where the Cartesian concatenation is defined earlier as `n←,∘.,⍨`. This is achieved using the `@` operator, applying the function `⊂∘k∘⊃` on the list of matches at index `1`, the `⊂` enclose and `⊃` pick functions are required due to the behaviour of `@`. Concatenation and alternation are considered together. On `2↑⍵` the list of the first two elements of `⍵`, `n/` (reduce by `n` Cartesian concatenation) is applied in the case of concatenation, and `,/` (reduce by concatenation). The remaining `⍵` is concatenated at the end of this result. After the execution of the reduce operation, its first set of matches is retrieved using `⊃`. The regex does not give errors even on incorrect regexes. The handling of `+` uses the `@` operator which expects the argument to be indexable. When `+` is by itself, `⍵` is the scalar `1`, so `@` on `1` would not work, but the `,` applied on `⍵` converts it into a list, preventing an error. `+` then takes the Cartesian concatenation of `1` with `l` copies of itself. `;` and `|` with too few arguments are implicitly handled by the functionality of the `↑` take function and the `↓` function. `2↑` takes the first 2 elements of the right argument, but if the right argument is shorter, the result is padded with sufficient prototype values, for example the prototype of a strictly numeric array is 0, while that of a character array is the space character `' '`. However, even with this treating of anomalous regexes, these regexes will not be returned by the entire complementary regex function as a complementary regex. This is due to the fact that they cannot be shorter than the respective shortest valid postfix regex, and even if these incorrect regexes are of the same length as the shortest valid regex, they are ordered lexicographically later than a valid regex, with the order being specified later while performing the complementarity check by `10!_|;+`, and only the first (again, ordered lexicographically) complementary regex is picked as a result to the function submission. ### Complementarity check The checking for complementarity is done by the following part. `q←k'10!_|;+'` generates all possible regexes up to a length of `l` (`k` computes this function as mentioned earlier) and assigns this to `q`. The ordering specified by this part is what prevents incorrect regexes from being returned by the function. For each of these strings `¨`, the following function is computed, (`⍵` denotes the right argument, in this case, each string for which the following function is applied on) ``` {0=≢((z,k'01')~w∪f⍵)∪w∩f⍵} ``` `w` is assigned earlier to the matches of the input regex. `w∩f⍵` computes the intersection of `w`, the matches of the input, with `f⍵`, the matches of `⍵`. For complementary regexes, this should be the empty set. `w∪f⍵` computes the union of `w` and `f⍵`. `~` performs set complement. `z` is `⊂''`, the enclosed empty string. `k'01'` computes all binary strings with length up ≤ `l`, so `z,k'01'` is a list containing all these binary strings, along with the empty string. The result of `(z,k'01')~w∪f⍵` is all the binary strings that are not present in `w∪f⍵`, so it contains the strings that are matches by neither the input regex nor `⍵`. For complementary regexes this should be the empty set. `((z,k'01')~w∪f⍵)∪w∩f⍵` is the union of the two sets above. This should be empty if the regexes are complementary. Its emptiness is checked by counting the number of elements contained within it using `≢`, and comparing this result with `0`. (Using `⍬` doesn't work because in Dyalog APL, empty lists can have different prototype lists.) This function explained above returns 1 is the regexes are complementary, and 0 if they are not. The first truthy regex is picked by `⊃q/⍨`, being returned by the function. ### Alternative approaches Initially, I thought that using the approach recommended in the challenge of doing the conversion regex → NFA → DFA → regex would yield a short solution in APL because of APL's strength with matrices (by storing the NFA/DFA as a 3-dimensional array, with each of its 2-dimensional arrays being adjacency matrices for transitions involving each input character and ε-transitions). I got to implement a part of this for the [regex matching challenge](https://codegolf.stackexchange.com/questions/197061) that popped up recently, but I got a solution much longer than what I had expected at over 250 bytes. It's the handling of individual matrix entries that made the program long, for example, I had to include specific transitions between specific states, like an ε-transition from state 1 to states 2 and 3 for alternation. However the handling of the entire array or its component matrices was short, as was needed to execute the NFA on the input string. And besides, all that the >250 byte program did was *only* to determine if 1 string matches the input regex. Maybe storing the NFA in a "sparse" format with list of lists of numbers representing states might end up being shorter that the matrix-oriented approach. I tried another approach to that regex matching challenge by listing all the matches of the input regex, with `+` repetitions bounded by the input length, and checking if the input string belongs to this list, which yielded a >140-byter, almost half the length of my previous approach. This approach ended up being adapted into function `f` of my submission to this challenge. Unlike the approach mentioned in the previous paragraph, this approach generates the list of all input matches, so I do not have to separately run the regex matching function on each of the possible inputs to see which ones it matches, thus saving a great deal of bytes. Moreover, I had also tried `⎕r`, Dyalog APL's PCRE replace function, for this challenge but that resulted in a postfix → PCRE converter at >110 bytes. Besides, similarly to the approach where I stored the NFA in an array, implementing the matching as well as finding all of the matches of this regex on all (bounded) input strings added too many bytes. It was when I stumbled upon [ankh-morpork's Prolog submission](https://codegolf.stackexchange.com/a/198266) to the regex decomposition challenge and by the power of Prolog DCGs that I started working on this regex complement challenge in Prolog. However my Prolog skills was not good enough to make it work, and seeing how my approach ended up becoming un-Prolog-y and more APL-y I switched to APL and started this solution with the knowledge I had gathered from attempting the regex matching challenge. This brute-force approach proved to be significantly short than any other approach I could think of, so I went ahead with this. I left the calculation of the upper bound to the very end, i.e. the `l←` bit, and golfed the rest of my program from an initial size of >210 bytes. The complementary check might be further golfable, perhaps there's a nice way to get rid of the parentheses, or an alternative logic. In function `f`, under the case when `⍺∊';|'`, I feel the `2↑⍵` and `2↓⍵` surrounding the code has a shorter alternative; I tried `@1 2⊢⍵`, but this results in an error for invalid regexes requiring me to use an error guard. [Answer] # [Python 2](https://docs.python.org/2/), ~~1996~~ 1960 bytes ``` lambda s:L(J(I(s))) _=set;Z=sorted;x,y,z={0},{1},{2} A=lambda a,b,c:{e for d in b for e in a[c][d]} def B(a,b):b=_(b);c=b|A(a,b,2);return B(a,c)if b<c else c C=lambda a,b:any(c in a for c in b) def D(a): b,c,d,e=a;f=_();g=tuple(Z(B(e,{c})));h=_();i={0:{},1:{},2:{}};j=[g] while j: l=j.pop() if l in f:continue f.add(l);C(d,l)and h.add(l) for k in i:i[k][l]=_() for k in[0,1]:m=tuple(Z(B(e,A(e,l,k))));j.append(m);i[k][l].add(m) return f,g,h,i def E(b,a):c,d,e,f=b;return{(a,g)for g in c},(a,d),{(a,g)for g in e},{k:{(a,g):{(a,h)for h in f[k][g]}for g in f[k]}for k in f} def F(a,b):c,d,e,f=E(a,0);g,h,i,j=E(b,1);l=f.copy();[l[k].update(j[k])for k in l];[l[2][m].add(h)for m in e];return c|g,d,i,l def G(a,b):c,d,e,f=E(a,0);g,h,i,j=E(b,1);l=f.copy();[l[k].update(j[k])or l[k].update({0:_(),1:_()})for k in l];l[2][0]|={d,h};[l[2][m].add(1)for m in e|i];return c|g|x|y,0,y,l def H(a):b,c,d,e=a;f=_(d);g={k:e[k].copy()for k in e};[g[2][h].add(c)for h in f];return _(b),c,f,g def I(s): a=[] for c in s: if c in'10_!':a.append({'1':(x|y|z,0,y,{0:{0:z,1:z,2:z},1:{0:y,1:z,2:z},2:{0:_(),1:_(),2:_()}}),'0':(x|y|z,0,y,{0:{0:y,1:z,2:z},1:{0:z,1:z,2:z},2:{0:_(),1:_(),2:_()}}),'_':(x|y,0,x,{0:{0:y,1:y},1:{0:y,1:y},2:{0:_(),1:_()}}),'!':(x,0,_(),{0:{0:x},1:{0:x},2:{0:_()}})}[c]) elif c in'|;':a[-2:]=[{'|':G,';':F}[c](a[-2],a[-1])] else:a[-1]=H(a[-1]) return D(a[-1]) def J(a):b,c,d,e=a;f={};[f.update({(g,h):f.get((g,h),'!')+str(k)+'|'})for k in e for g in e[k]for h in e[k][g]];return b,c,b-d,f def K(a,b,c,d): for e in a-{c,d}: g={f:b[(f,t)]for f,t in b if t==e!=f};h={t:b[(f,t)]for f,t in b if f==e!=t};i={(f,t):b[(f,t)]for f,t in b if f!=e!=t} for f in g: for t in h:j=i.get((f,t),'!');i[(f,t)]=g[f]+b.get((e,e),'!')+'+_|;'+h[t]+';'+j+'|' b=i l,m,n,o=[b.get(pair,'!')for pair in[(c,c),(c,d),(d,d),(d,c)]];return l+'+_|'+(m+';'+o+l+'+_|;'+m+';'+n+'|+_|;')*(c!=d) def L(a):b,c,d,e=a;return''.join(K(b,e,c,f)for f in d)+'!'+'|'*len(d) ``` [Try it online!](https://tio.run/##pVbbjqM4EH3PVxBpJezBHUEenbVWPZee2Zn5gmHZiIshJATYQLRJE769p8rmlstIK21Loe1y1alD1Skn5bneFPnyrSqyY50WufjrLfP3QeQbFf9OvpI/SUUpna1FJevVD1EVh1pGqxM7s1fR2C1rHPgs29mz6MJ8FrCQN9KIi4MRGWluBGopcem7oedGXjuLZGy8J@BLeSDWJKCrUASXZ7SwJV0dZH085MojpGlsBL@HhswqaYSzD5NE3M/PJFTAKodaBlShfyQ@5TMDyLCISeGvYshDV4moj2UmyQ/ynkjWhC283WqjjlJ4Id60zMHHEh7taivcxJsZ/27STBpbgDMysV2URUkorIFYhhljHhZ5neZHCcZ44UcRyejqA4lYRv08MjadCU@B5Q5jUp66O8/NPEw9OXBt5nh8f8XyGT4Z21Gkul34ZSnziOyBsEZQ6HsA6aoWs4RtWKqq8IkEDOqgasBiEXSVbaCwCcWcCZIJWwaGiLIbu4Te7rg2qn8bdbZRL43JE68dnNHQDu8X6x6/6B73@T/B1oYmID@2FcjOoatMxIuwKM/QAzcDlMWxjPxaki2s6YCYeXi69Ny9fmPNZa94er1iwksCqVKWqeyf/3d2yDC1gUCgXaAQeLZX1BQz27uIJmKb9pqpM2F6SadcL6fLmdkwTJrvF9TstWIjlCw0QSILTXNIKyFPgnk2Ok846c6QBYcLEEEUKgXOM@jYFy7oepiZims548Z07PXc5H4vtMZ0TE6A6OVVUcUhsfkrFOEVpuRVzYvNz@N@yadlgi0Wq6XMtB/gnG9wXv8DzlrjAMppgnKeMDnfRqu4OcZBFFp13KmLOY3@4NnCLYUzKbO@JJcVFMR9WnJPuI15MflnZoLpBT0JHngMno5HPRVWSa624gvR5mE2P/YG7MXX23Y30NB40BoBoVIeLxJZE7XGN6BWVR/IjlrAYqJAfd3qoQWlDDqQekoHNWC24ClisSLwTd23kB8lMV7STw2YWpQESC/mgUtiVlMFCgt9pUNlaiHkXMQtXJ9N/UuvWHnVLV6vyuPXnnPt2d2GMR4kyEJtld@Gb0WqC4IQqiBwDWo8kbixZwX6WDLZ1cu01tA@a@PWngVNs7ZYOkANRDozMrZnOSuEq8NKPz2oKMyIG7yRSQhfQoxgmRjc6foZ0rGomcphWmSvEhRW1ifVhhwyqj19R8K5iHT3v193X2OZ5mJbpDn5BneTxLGlQykieJW5ieTfZTKHi@Et3ZfwdQzSminANC@P9bou1geZyJOec/iraj/cGcLAge9qOc68/lMyF8LASdf@/fCDhQ5u3Tygo33naD92XN85Pvab3/ktHzteekc1jvheJvmDm4Y1WD1Yg9tocZSFmt4jvNUd3hRnQHgYa42xDobeMOnyWqaK7cRi/n3n8ZupG7j363AjK6IbyYy@g/3sFkVGDnKh3MhNt/WWYhDVaAAV7gasLN2ntXBsu1dFkQHh/ldfH66OykOa13ikdv8c5VGqMpujgNYooIOfJ5IoYDpqqQJfFaN@JtljD7VRnmrsrltZoBhga4HCvNGpOoahrBDjvhjGfLQCOzRNFZwXdR/Ou3cwX/w045DmIMsDDMRspouiVN0t7XHpWBOzgyN7vZ/sLMeCcX77CQ "Python 2 – Try It Online") Since [user41805 came up with a very short but only theoretically-working solution](https://codegolf.stackexchange.com/a/199524/78410), here is a practical one (practical as in "you can actually observe the output for small inputs"). The TIO link also includes a kind of test-battery to check for complement-ness. It should be theoretically possible to solve [Complement of POSIX ERE](https://codegolf.stackexchange.com/q/24352/78410) by reusing large chunks of code here, but I don't think I'll tackle it anytime soon. Feel free to solve it and take the [200 bounty](https://codegolf.meta.stackexchange.com/a/17337/78410). ## Ungolfed, and how it works The code is mainly divided into three parts: construct an NFA from the input regex, convert it to a DFA and invert its accept states, and convert it back to a regex. ### Preliminary definitions ``` from collections import namedtuple NFA = namedtuple('NFA', ['nodes', 'start', 'accept', 'trans']) DFA = namedtuple('DFA', ['nodes', 'start', 'accept', 'trans']) ``` The definitions for NFA and DFA are there just to help reading the code. `NFA` and `DFA` have the same field names, but the `trans` fields contain different data structures. ### Input regex to NFA ``` def step_once(trans, nodes_from, step): return {n for x in nodes_from for n in trans[step][x]} def e_closure(trans, nodes_from): nodes_from = set(nodes_from) nodes_to = nodes_from | step_once(trans, nodes_from, '') while nodes_from != nodes_to: nodes_from = nodes_to nodes_to = nodes_from | step_once(trans, nodes_from, '') return nodes_to def is_accept(accept, nodes): return any(node in accept for node in nodes) def to_dfa(nfa): new_nodes = set() new_start = tuple(sorted(e_closure(nfa.trans, {nfa.start}))) new_accept = set() new_trans = {0:{}, 1:{}, '':{}} stack = [new_start] while stack: node_set = stack.pop() if node_set in new_nodes: continue new_nodes.add(node_set) if is_accept(nfa.accept, node_set): new_accept.add(node_set) for k in new_trans: new_trans[k][node_set] = set() for k in [0, 1]: node_step = e_closure(nfa.trans, step_once(nfa.trans, node_set, k)) node_step = tuple(sorted(node_step)) stack.append(node_step) new_trans[k][node_set].add(node_step) return NFA(new_nodes, new_start, new_accept, new_trans) ``` `to_dfa` eliminates ϵ-moves and non-deterministic moves from the given ϵ-NFA. The algorithm is pretty standard: starting from the ϵ-closure of the start state, record all the reachable state sets by traversing through 0- and 1-moves followed by ϵ-closure. ``` one = NFA({0,1,2}, 0, {1}, { 0: {0:{2}, 1:{2}, 2:{2}}, 1: {0:{1}, 1:{2}, 2:{2}}, '': {0:set(), 1:set(), 2:set()} }) zero = NFA({0,1,2}, 0, {1}, { 0: {0:{1}, 1:{2}, 2:{2}}, 1: {0:{2}, 1:{2}, 2:{2}}, '': {0:set(), 1:set(), 2:set()} }) empty = NFA({0,1}, 0, {0}, { 0: {0:{1}, 1:{1}}, 1: {0:{1}, 1:{1}}, '': {0:set(), 1:set()} }) null = NFA({0}, 0, set(), { 0: {0:{0}}, 1: {0:{0}}, '': {0:set()} }) ``` The NFA definitions for the four base regexes `10_!` respectively. ``` def prefix(nfa, a): new_nodes = {(a,node) for node in nfa.nodes} new_start = (a,nfa.start) new_accept = {(a,node) for node in nfa.accept} new_trans = {k: {(a,node): {(a,dest) for dest in nfa.trans[k][node]} for node in nfa.trans[k]} for k in nfa.trans} return NFA(new_nodes, new_start, new_accept, new_trans) ``` `prefix` helper function converts an NFA into an equivalent one, but with each node key `n` wrapped into a 2-tuple `(a,n)`. This is used for combining two NFAs to avoid key collisions. In Python, a tuple is hashable whenever all of its elements are hashable (thus appropriate for a dict key). ``` def concat(a, b): a = prefix(a, 0) b = prefix(b, 1) new_nodes = a.nodes | b.nodes new_start = a.start new_accept = b.accept new_trans = a.trans.copy() for k in new_trans: new_trans[k].update(b.trans[k]) for a_acc in a.accept: new_trans[''][a_acc].add(b.start) return NFA(new_nodes, new_start, new_accept, new_trans) def branch(a, b): a = prefix(a, 0) b = prefix(b, 1) new_nodes = a.nodes | b.nodes | {0, 1} new_start = 0 new_accept = {1} new_trans = a.trans.copy() for k in new_trans: new_trans[k].update(b.trans[k]); new_trans[k].update({0:set(), 1:set()}) new_trans[''][0] |= {a.start, b.start} for acc in a.accept | b.accept: new_trans[''][acc].add(1) return NFA(new_nodes, new_start, new_accept, new_trans) def plus(nfa): new_nodes = set(nfa.nodes) new_start = nfa.start new_accept = set(nfa.accept) new_trans = {k: nfa.trans[k].copy() for k in nfa.trans} for acc in new_accept: new_trans[''][acc].add(new_start) return NFA(new_nodes, new_start, new_accept, new_trans) ``` Three combiner functions corresponding to `ab;`, `ab|`, `a+` respectively. `ab;`: Connect the accept states of `a` to the start state of `b` through ϵ-moves. ``` e S1 ... A1 -----> S2 ... A2 ``` `ab|`: Introduce the overall start and accept states, and connect them through ϵ-moves like the following. ``` e e -----> S1 ... A1 -----> S { } A -----> S2 ... A2 -----> e e ``` `a+`: Connect the accept states back to the start states through ϵ-moves. ``` S ... A | | \<----/ e ``` Finally, we combine all of them to convert the input regex into a deterministic NFA. ``` def input_to_nfa(s): stack = [] for c in s: if c == '1': stack.append(one) elif c == '0': stack.append(zero) elif c == '_': stack.append(empty) elif c == '!': stack.append(null) elif c == '|': stack[-2:] = [branch(stack[-2], stack[-1])] elif c == ';': stack[-2:] = [concat(stack[-2], stack[-1])] elif c == '+': stack[-1] = plus(stack[-1]) return to_dfa(stack[-1]) ``` ### NFA to DFA ``` def nfa_to_dfa(nfa): nodes = nfa.nodes start = nfa.start accept = nfa.nodes - nfa.accept trans = {} for k in nfa.trans: for node_from in nfa.trans[k]: for node_to in nfa.trans[k][node_from]: trans[(node_from, node_to)] = trans.get((node_from, node_to), '!') + str(k) + '|' return DFA(nodes, start, accept, trans) ``` Invert the accept states by set difference, and convert the data structure of the transition table so that it is suitable for regex construction. ### DFA to regex ``` # dfa-style trans def path_to_regex(nodes, trans, node_from, node_to): for node in nodes - {node_from, node_to}: left_nodes = {f: trans[(f,t)] for f,t in trans if t == node != f} right_nodes = {t: trans[(f,t)] for f,t in trans if f == node != t} loop = trans.get((node, node), '!') new_trans = {(f, t): trans[(f,t)] for f,t in trans if f != node != t} for f in left_nodes: for t in right_nodes: existing = new_trans.get((f, t), '!') new_trans[(f,t)] = left_nodes[f] + loop + '+_|;' + right_nodes[t] + ';' + existing + '|' trans = new_trans ff, ft, tt, tf = [trans.get(pair, '!') for pair in [(node_from, node_from), (node_from, node_to), (node_to, node_to), (node_to, node_from)]] if node_from == node_to: return ff + '+_|' return ff + '+_|' + ft + ';' + tf + ff + '+_|;' + ft + ';' + tt + '|+_|;' def dfa_to_regex(dfa): regexes = [path_to_regex(dfa.nodes, dfa.trans, dfa.start, acc) for acc in dfa.accept] if not regexes: return '!' return ''.join(regexes) + '|' * (len(regexes) - 1) ``` For each pair of `start -> accept` states, eliminate all the other states by regex chaining and convert the result into a single regex. If we have multiple accept states, link the resulting regexes by `|`. If we have zero accept states, return a single '!'. ``` def solution(s): return dfa_to_regex(nfa_to_dfa(input_to_nfa(s))) ``` Solves the entire task by chaining the three core functions. ]
[Question] [ Your task: given an integer `n`, generate an embedded hexagon pattern following the below rules, to the nth depth. An embedded hexagon has the basic shape of this: (`n=0`) ``` __ / \ \__/ ``` Embedded Hexagons `n=1` and `n=2`: ``` ____ / \ \ /\__/ \ \ / \____/ ________ / \ \ \ /\__/ \ \ /\ / \ / \____/ \ \ / \ / \ / \________/ ``` The length of each side is 2 times the length of the same side in the previous depth times two. The top and bottom sides are 2 characters long when `n=0` and the rest start out as 1 character long. The non top-bottom side lengths should be `2^n` long ([OEIS: A000079](https://oeis.org/A000079/ "OEIS: A000079")) and the top and bottom sides should follow the rule `2^(n+1)` (same OEIS). The current hexagons are 0-indexed, you may chose to use 1-indexed if you want. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~40~~ 29 bytes *11 bytes saved thanks to @Neil by changing the while loop to a for-loop amongst other tricks* ``` FN«AX²ιβ×__β↓↘β←↙β↑←×__β↖β→↗β ``` [Try it online!](https://tio.run/nexus/charcoal#@/9@z7L3e9YdWv1@z8L3e3Yc2nRu57lNh6fHx5/b9Kht8qO2GSB6wqO2mSB6IpAJk5sGIiY9apt@btP//8YA "Charcoal – TIO Nexus") ### Explanation (outdated) This program starts with generating the largest hexagon, and then does the smaller ones one-by-one in a while loop (1-indexed). For reference, `α` is the input number, `β` is the variable that contains `2^(α-1)` and `ι` is the iterating variable in the loop. ``` Nα # Take input and store in α Wα« # While α do: ×_X²ι # Write "_"*(2**ι); this forms the top edge of the hexagon ↓ # Go down AX²⁻ι¹β # Assign 2**(ι-1) to β ↘β← # Write \ β times in a SE direction (top right edge) and then go left ↙β↑ # Write / β times in a SW direction (bottom right edge) and then go up ←×_X²ι # Write the bottom edge ↖β→↗β # Just like before, write the top and bottom left edges A⁻α¹α # Decrement α # Now the pointer is at the top left corner of the hexagon, # from where the other smaller hexagons will soon be generated ``` [Answer] # [Haskell](https://www.haskell.org/), ~~230~~ ~~217~~ 207 bytes EDIT: * -13 bytes: @xnor saw that my `#` could be just `max`. * -10 bytes: And also that `zipWith` and `p` could be merged into a `?` operator, and that I'd (somehow!) reimplemented `replicate`. `m` takes an `Integer` and returns a `String`. ``` m n=unlines.foldr1 o$((2^n)&).(2^)<$>[0..n] l&t|a<-c[l,2*t]" _",b<-[c[l-i,1,2*t+2*i-2,1,l-i]" / \\ "|i<-[1..t]]=a:b++r(r<$>o[a]b) c=(concat.).z replicate o=max?' '?"" f?e=z f.(++repeat e) r=reverse z=zipWith ``` [Try it online!](https://tio.run/nexus/haskell#FYzRboQgFETf@QpCzC6selvtWyP1M/rg0gbZa3oTBMPSpjH775Y@zczJzKyWgqaQMVmXqxUS2tux8qC/g6eAd1iiv6WOx0rK/iOok4KiaqjepmeAYJg/5YcdWjf5pr9kI/inaOahnQpoqen@Yd1fqO2LL6QUnvj1ysWDSqkDyMZo@zrXdZKpvMbJmlkxp6WLwdkMCnaecPNUArKoV/s7nvl5FIItI@qdLyDLGDe0maNiSSf8wXRHtuudtnfKX8fx8gc "Haskell – TIO Nexus") # How it works * `m` is the main function. It uses `&` to generate the hexagons with proper padding, then folds them together with `o`. * `l&t` generates a small hexagon of side length `t`, padded inside a large one of side length `l`, as a list of `String` lines. + `a` is the top line of the hexagon, with the underscores. + `b` is a list of the other lines in the upper half of the hexagon. The lines of `b` are centered in the padding, which is rectangular; this allows the next step to work. + The bottom half of the hexagon is `a` overlaid on top of `b` with `o`, then reversed (both order of lines and within each line). * `c` takes two arguments, a list of lengths and a string, and generates a string that has as many copies of each character in the original as the corresponding length, e.g. `c[1,3,2]"abc" == "abbbcc"`. It is used in `&` to generate the lines. * `o` takes two arguments representing pictures as lists of lines, and overlays the first, smaller one on top of the second one. + It is used both to combine hexagons and to add the bottom to each hexagon. + It essentially works by using `?` twice to pad the first picture with infinitely many spaces both downwards and rightwards, then zipping together corresponding characters with `max`, which selects the non-space character if there is one. * `(f?e)l m` pads a list `l` by appending infinitely many 'e' elements, then zips the resulting list and the list `m` with the `f` function. [Answer] ## JavaScript (ES6), 258 bytes ``` f=(n,s=` `.repeat(1<<n),p=(n?f(n-1):` `).replace(/(.*)\n/g,s+`$1 `+s)+s,t=`_`.repeat(2<<n))=>(s+t+s+` `+s.replace(/ /g,"$'/$'$' $`$`$`$`\\$'\n")).replace(/ /g,(c,i)=>p[i+(1<<n>>1)])+s.replace(/ /g,"$`\\$`$` $'$'$'$'/$`\n").replace(/ +\/( *)\n$/,t+`/$1 `) ``` ``` <input type=number min=0 oninput=o.textContent=f(+this.value)><pre id=o> ``` Explanation: For hexagons after the first, the previous hexagon is first generated and padded on each side (this relies on the output being a rectangle). (For the first heading, some dummy padding is created.) The top and top sides of the hexagon are generated, and all the spaces merged with the previous hexagon. (There's some trickery in order to get the hexagons to line up; this would be easier if extra margins were allowed.) The bottom sides of the hexagon are generated analogously to the top sides, and the bottom of the hexagon is then filled in. Care has to be taken to return rectangular output, including a trailing newline, for the recursion to work. [Answer] # PHP, 337 Bytes 0 Indexing ``` $h=array_fill(0,1+2*$v=2**($c=$argn),str_pad("",4*$v));for(;1+$c;$c--)for($i=0;$i<$e=2**$c*2+1;$i++){$z=$e-$i<2;$y=$i&&$i<$e/2;$x=$i>=$e/2&$i<$e-1;$h[$i]=substr_replace($h[$i],$s=str_pad(!$y?$z|$x?"\\":"":"/",$e-1+$z-$y+$y*$i*2-$x+$x*2*($e-$i),$z|!$i?"_":" ").(!$y?$z|$x?"/":"":"\\"),$v-$z-$y*$i-$x*($e-$i),strlen($s));}echo join("\n",$h); ``` [Try it online!](https://tio.run/nexus/php#TZBNboMwEIXX4RSJNYr8g0tA7SaOy0GaKnJdJ7hCBJk2AtqcnY5Blbqy35s334x9KNuqnc7X4IytaDDNxdFd@sRMByZcGvadJFBpE4IZTmdf11jMRcHhpgvOKVi9xNLuM5xa804JSR@xyphKEEpVLsAqsFKyWYPXOwX@AC72g@WFyFELgYNWMGpwEquFgkGD327nZIayR/ms433xZK4wX72Af9Xd11ucHlxbG@vo4qZY7vTfVskK4SU5HsmewlCSLJ79YhDCWBoDCBUwShgEDBw8LyT0Anpe4DvjWktq/NmAL8kJG9cEDfZAN8jeIDYSswjcL@CMxBa4yZmKSAT@Y@FytWsodPGz7omz1XX9cfUNJceGpFChO5so0VD3afoF "PHP – TIO Nexus") Expanded ``` $h=array_fill(0,1+2*$v=2**($c=$argn),str_pad("",4*$v)); # fill array with maximal width for(;1+$c;$c--) # greatest hexagon to lowest for($i=0;$i<$e=2**$c*2+1;$i++){ # loop through the rows $z=$e-$i<2;$y=$i&&$i<$e/2;$x=$i>=$e/2&$i<$e-1; # booleans last first ad second half $h[$i]=substr_replace($h[$i], # replace substring $s=str_pad( $z?"\\":($y?"/":($x?"\\":"")), $e-1+$z-$y+$y*$i*2-$x+$x*2*($e-$i), $z|!$i?"_":" " ).(!$z?!$y?$x?"/":"":"\\":"/"), # with string for smaller hexagon $v-$z-$y*$i-$x*($e-$i), # at offset strlen($s)); } echo join("\n",$h); # Output ``` ]
[Question] [ ### Introduction Of course, we've got a lot of [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges, so here is another one. The Kimberling sequence ([A007063](http://oeis.org/A007063)) goes as following: ``` 1, 3, 5, 4, 10, 7, 15, 8, 20, 9, 18, 24, 31, 14, 28, 22, ... ``` This is produced by shuffling the normal iteration: ``` [1] 2 3 4 5 6 7 8 ``` The first term of the sequence is `1`. After that, we reshuffle the sequence until all the terms on the left are used. The shuffling has the pattern `right - left - right - left - ...`. Since there are no terms at the left of the `1`, there is no shuffling. We get the following: ``` 2 [3] 4 5 6 7 8 9 ``` On the ith iteration, we discard the ith item and put that in our sequence. This is the **2nd** iteration, so we discard the **2nd** item. The sequence becomes: `1, 3`. For our next iteration, we are going to shuffle the current iteration with the pattern above. We take the first unused item at the right of the ith item. This happens to be `4`. We will append this to our new iteration: ``` 4 ``` Now we're going to take the first unused item at the left of the ith item. This is `2`. We will append this to our new iteration: ``` 4 2 ``` Since there are no items left at the left of the ith item, we'll just append the rest of the sequence to the new iteration: ``` 4 2 [5] 6 7 8 9 10 11 ... ``` This is our **3rd** iteration, so we'll discard the **3rd** item, which is `5`. This is the third item in our sequence: ``` 1, 3, 5 ``` To get the next iteration, just repeat the process. I've made a gif if it isn't clear: [![enter image description here](https://i.stack.imgur.com/5HcEJ.gif)](https://i.stack.imgur.com/5HcEJ.gif) The gif took me longer than writing the actual post ### Task * Given an non-negative integer **n**, output the first **n** terms of the sequence * You may provide a function or a program * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! ### Test cases: ``` Input: 4 Output: 1, 3, 5, 4 Input: 8 Output: 1, 3, 5, 4, 10, 7, 15, 8 Input: 15 Output: 1, 3, 5, 4, 10, 7, 15, 8, 20, 9, 18, 24, 31, 14, 28 ``` **Note:** The commas in the output are not necessary. You may for example use newlines, or output a list, etc. [Answer] # Julia, ~~78~~ 71 bytes ``` n->[(i=j=x;while j<2i-3 j=i-(j%2>0?1-j:j+2)÷2;i-=1end;i+j-1)for x=1:n] ``` This is an unnamed function that accepts an integer and returns an integer array. To call it, assign it to a variable. The approach here is the same as that described on OEIS. Ungolfed: ``` # This computes the element of the sequence function K(x) i = j = x while j < 2i - 3 j = i - (j % 2 > 0 ? 1 - j : j + 2)÷2 i -= 1 end return i + j - 1 end # This gives the first n terms of the sequence n -> [K(i) for i = 1:n] ``` Saved 7 bytes thanks to Mauris! [Answer] # Pyth, 22 bytes ``` JS*3QVQ@JN=J.i>JhN_<JN ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=JS%2A3QVQ%40JN%3DJ.i%3EJhN_%3CJN&input=10) Simply performs the shuffling technique described in the OP. ### Explanation: ``` JS*3QVQ@JN=J.i>JhN_<JN JS*3Q assign the list [1, 2, ..., 3*input-1] to J VQ for N in range(Q): @JN print J[N] .i interleave >JhN J[N+1:] with _<JN reverse J[:N] =J assign the resulting list to J ``` [Answer] # APL, ~~56~~ 44 bytes ``` {⍵<⍺+⍺-3:(⍺-1)∇⍺-4÷⍨3+(1+2×⍵)ׯ1*⍵⋄⍺+⍵-1}⍨¨⍳ ``` This is an unnamed monadic train that accepts an integer on the right and returns an array. It's roughly the same approach as [my Julia answer](https://codegolf.stackexchange.com/a/67569/20469). The innermost function is a recursive dyadic function that returns the *n*th term in the Kimberling sequence, given *n* as identical left and right arguments. ``` {⍵<⍺+⍺-3: ⍝ If ⍵ < 2⍺ - 3 (⍺-1)∇⍺-4÷⍨3+(1+2×⍵)ׯ1*⍵ ⍝ Recurse, incrementing a and setting ⍝ ⍵ = ⍺ - (3 + (-1)^⍵ * (1 + 2⍵))/4 ⋄⍺+⍵-1} ⍝ Otherwise return ⍺ + ⍵ - 1 ``` With that in hand, we're able to get individual terms of the sequence. However, the problem then becomes that this is a *dyadic* function, meaning it requires arguments on both sides. Enter the `⍨` operator! Given a function `f` and an input `x`, `f⍨x` is the same as `x f x`. So in our case, referring to the aforementioned function as `f`, we can construct the following monadic train: ``` f⍨¨⍳ ``` We apply `f` to each integer from 1 to the input, yielding an array. Saved 12 bytes thanks to Dennis! [Answer] # Mathematica 130 bytes ``` (n=0;s={};Nest[(n++;AppendTo[s,z=#[[n]]];Flatten[TakeDrop[#,1+2(n-1)]/.{t___,z,r___}:> Riffle[{r},Reverse@{t}]])&,Range[3*#],#];s)& ``` We begin with a list consisting of the range from `1` to `3x`, where `x` is the desired number of Kimberling sequence terms. At each step, `n`, `TakeDrop` breaks the the current list into a front list of `2n+1` terms (where the work is done) and rear list (which will be later joined with the reworked front list). The front list is matched with the following pattern, `{t___,z,r___}` where z is the Kimberling term at the center of the front list. `r` is `Riffle`'d with the reverse of `t` and then the rear list is appended. `z` is removed and appended to (`AppendTo`) the growing Kimberling sequence. `n` is incremented by `1` and the current list is processed by the same function via `Nest.` --- **Example** ``` (n=0;s={};Nest[(n++;AppendTo[s,z=#[[n]]];Flatten[TakeDrop[#,1+2(n-1)]/.{t___,z,r___}:> Riffle[{r},Reverse@{t}]])&,Range[3*#],#];s)&[100] ``` > > {1, 3, 5, 4, 10, 7, 15, 8, 20, 9, 18, 24, 31, 14, 28, 22, 42, 35, 33, > 46, 53, 6, 36, 23, 2, 55, 62, 59, 76, 65, 54, 11, 34, 48, 70, 79, 99, > 95, 44, 97, 58, 84, 25, 13, 122, 83, 26, 115, 82, 91, 52, 138, 67, > 90, 71, 119, 64, 37, 81, 39, 169, 88, 108, 141, 38, 16, 146, 41, 21, > 175, 158, 165, 86, 191, 45, 198, 216, 166, 124, 128, 204, 160, 12, > 232, 126, 208, 114, 161, 156, 151, 249, 236, 263, 243, 101, 121, 72, > 120, 47, 229} > > > [Answer] # Python 2, 76 bytes ``` for a in range(input()): b=a+1 while-~b<2*a:b=a-(b^b%-2)/2;a-=1 print a+b ``` ## Explanation This is the OEIS formula after many golf-y transformations! It worked out *beautifully*. The original code was ``` i=b=a+1 while b<2*i-3:b=i-(b+2,1-b)[b%2]/2;i-=1 print i+b-1 ``` I first got rid of `i`, replacing it with `a+1` everywhere and expanding the expressions: ``` b=a+1 while b<2*a-1:b=a+1-(b+2,1-b)[b%2]/2;a-=1 print a+b ``` Then, rewrote `b<2*a-1` as `-~b<2*a` to save a byte of whitespace, and moved the `+1` into the selection, division by 2, and negation: ``` while-~b<2*a:b=a-(b,-b-1)[b%2]/2;a-=1 ``` Then, `-b-1` is just `~b`, so we can write `(b,~b)[b%2]`. This is equivalent to `b^0 if b%2 else b^-1` using the XOR operator, or alternatively, `b^b%-2`. ``` while-~b<2*a:b=a-(b^b%-2)/2;a-=1 ``` [Answer] # Pyth, ~~29~~ 25 bytes ``` VQ+.W<hHyN-~tN/x%Z_2Z2hNN ``` Jakube saved 4 bytes, but I have no clue how to read the code anymore. Here is the old solution: ``` VQKhNW<hKyN=K-~tN/x%K_2K2)+KN ``` Translation of my Python answer. I'm not very good at Pyth, so maybe there's still ways to shorten this. ``` VQ for N in range(input()): KhN K = N+1 W<hKyN while 1+K < 2*N: =K-~tN/x%K_2K2) K = (N--) - (K%-2 xor K) / 2 +KN print K + N ``` ]
[Question] [ <https://en.wikipedia.org/wiki/Losing_chess> This is basically [Chess Tournament](https://codegolf.stackexchange.com/questions/37251/chess-tournament), but for antichess ;) Antichess is one of the many [chess variants](https://en.wikipedia.org/wiki/List_of_chess_variants) that have been invented. The goal is to lose all your pieces (this may seem a little odd, but it's called antichess for a reason). ## The rules The rules of antichess are very similar to standard chess - but with a few fairly minor differences. The goal as I mentioned above is to lose all your pieces. To make this happen, if your opponent has an opportunity to capture one of your pieces, that is the only move he can make. If you give him multiple chances in one turn, the other player may choose his turn. Another thing that is changed is that the king has no special powers - as in you cannot checkmate your opponent, and you can't force him into check. The following changes to the standard game will also apply (they help simplify the game): * [*En passant*](http://en.wikipedia.org/wiki/En_passant) will be ignored. * [*Castling*](http://en.wikipedia.org/wiki/Castling) isn't possible. * The [*Fifty-move rule*](http://en.wikipedia.org/wiki/Fifty-move_rule) applies automatically (meaning the game ends in a draw). * Pawns will be able to choose what they promote to. * If a player needs longer than 2 seconds to move, he will lose the game. * Returning an invalid move will result in losing the game. * **To win, your opponents must capture all your pieces**. * White begins the game. * White is placed "at the bottom" of the field (y=0), black is located at the top (y=7). * Accessing other resources than your bot (internet, files, other bots, ...) is prohibited. ## Scoring * Winning grants you 3 points, a draw 1 point and losing 0 points. * Each submission will play against each other submission 10 times (5 times as white, 5 as black). ## Writing your bot ### Controller code is here: <https://github.com/JJ-Atkinson/SimpleAntichessKOTH> You can write your bot in either Java or Groovy. To write a bot you must extend the `Player` class. The player class has one abstract method `Move getMove(Board board, Player enemy, Set<Move> validMoves)`. Here is a quick rundown on useful methods: ### `Player`: * `List<Piece> getPieces(Board board)`: Return all your pieces that are on the board. * `PieceUpgradeType pieceUpgradeType`: If/when one of your pawns reaches the end of the board, you will need to define this to the type of piece you want to upgrade to. You have the choice of `ROOK`, `KNIGHT`, `QUEEN`, `BISHOP`, and `KING`. ### `Board`: * `Field getFieldAtLoc(Location loc)`: Return the `Field` at the location. This has a matching `getAt` method so that if you are using groovy you can write `board[loc]`. * `Field getFieldAtLoc(int x, int y)`: Return the `Field` at the location. This has a matching `getAt` method so that if you are using groovy you can write `board[x, y]`. * `Board movePiece(Player player, Move move)`: Make a move on the board so you can see how it would play out. It returns the new board. If you want to see your opponents pieces, just write `enemy.getPieces(board)`. To add your bot to the lineup add the following line to `PlayerFactory`: ``` put(YourBot.class, { new YourBot() } ) ``` ## Debugging your bot: I have included a couple of tools to aid in debugging your bots. To see your game played out live you can set the `Game#DEBUG` flag to true. You will get an output something like this: ``` Game started. Players: [OnePlayBot(WHITE), SacrificeBot(BLACK)] ... BLACKs turn. validMoves: [Move(Piece(BLACK, PAWN, Loc(0, 6)), Loc(0, 5)), ...] board: RKBQIBKR PPPPPPPP -------- -------- -------- p------- -ppppppp rkbqibkr captureless turns: 1 chosen move: Move(Piece(BLACK, PAWN, Loc(7, 6)), Loc(7, 4)) Game over? false ============================== WHITEs turn. validMoves: [Move(Piece(WHITE, ROOK, Loc(0, 0)), Loc(0, 1)), ...] board: RKBQIBKR PPPPPPP- -------- -------P -------- p------- -ppppppp rkbqibkr ... ``` (White is upper case, the king is shown with `i`) If your console supports utf-8 special chars, you can even show the board with the chess chars by using `Board#USE_UTF8_TO_STRING`: ``` ♜♞♝♛♚♝—♜ ♟—♟♟♟♟♟♟ ———————— —♟—————— ———————— ♙——————— —♙♙♙♙♔♙♙ ♖♘♗♕—♗♘♖ ``` (it looks better with a mono spaced font) To prevent a flood of unwanted output, you should change the `Main#main` function to something like this: ``` new Game(new MyBot(), new SacrificeBot()).run() ``` Put your bot on the left to play as white, put it on the right to play as black. ## Building the controller: The controller is written in groovy, so you must have java and groovy installed. If you don't want to install groovy you can use the gradle build file that comes with the controller (this has not been tested). If you don't want to use groovy *or* gradle you can use the latest release jar (<https://github.com/JJ-Atkinson/SimpleAntichessKOTH/releases>). If you do this you need to make your own `main` method and add your bot manually to the player factory. Example: ``` PlayerFactory.players.put(YourBot.class, { new YourBot() } ) new Runner().runGames(); ``` (Note that you can still set the debug flags and stuff) **Any and all bug finding is appreciated!** ## Scores: ``` SearchBot -> 101 SacrificeBot -> 81 MeasureBot -> 37 RandomBot -> 28 OnePlayBot -> 24 ``` **Please note that I'm always willing to have new submissions!** [Answer] # SearchBot Slowest bot so far, but still faster than 2 seconds per move and it beats all currently posted bots. It looks at what happens after any of the valid moves and what could happen after any move after those moves and decides what would be the best outcome. Unfortunately it cannot search deeper because it would take more than 2 seconds then. ``` package com.ppcgse.koth.antichess.player import com.ppcgse.koth.antichess.controller.Board import com.ppcgse.koth.antichess.controller.Color import com.ppcgse.koth.antichess.controller.Location import com.ppcgse.koth.antichess.controller.Move import com.ppcgse.koth.antichess.controller.Piece import com.ppcgse.koth.antichess.controller.PieceType import com.ppcgse.koth.antichess.controller.PieceUpgradeType import com.ppcgse.koth.antichess.controller.Player import groovy.lang.Tuple /** * Created by ProgramFOX on 12/22/15. */ class SearchBot extends Player { {pieceUpgradeType = PieceUpgradeType.KING} @Override Move getMove(Board board, Player opponent, Set<Move> validMoves) { return getMoveInternal(board, this, opponent, validMoves, 2)[0] } Tuple getMoveInternal(Board board, Player whoseTurn, Player opponent, Set<Move> validMoves, Integer depth) { def bestScore = null def currentlyChosenMove = null validMoves.each { m -> def opponentPiecesValueBefore = opponent.getPieces(board).sum { getPieceValue(it.getType()) } def newBoard = board.movePiece(whoseTurn, m) def opponentPiecesValueAfter = opponent.getPieces(newBoard).sum { getPieceValue(it.getType()) } if (opponentPiecesValueAfter == null) { opponentPiecesValueAfter = 0 } def score = opponentPiecesValueAfter - opponentPiecesValueBefore if (whoseTurn.getTeam() == Color.BLACK) { score = -score } if (depth > 1) { def validMovesNow = genValidMoves(opponent, whoseTurn, newBoard) def goDeeper = true if (validMovesNow == null || validMovesNow.size() == 0) { def toAdd = -999 if (whoseTurn.getTeam() == Color.BLACK) { toAdd = -toAdd } score += toAdd goDeeper = false } if (goDeeper) { score += getMoveInternal(newBoard, opponent, whoseTurn, validMovesNow, depth - 1)[1] } } if (bestScore == null) { bestScore = score currentlyChosenMove = m } if ((whoseTurn.getTeam() == Color.WHITE && score > bestScore) || (whoseTurn.getTeam() == Color.BLACK && score < bestScore)) { bestScore = score currentlyChosenMove = m } } return new Tuple(currentlyChosenMove, bestScore) } Double getPieceValue(PieceType pieceType) { switch (pieceType) { case PieceType.KING: return 1 case PieceType.PAWN: return 1.5 case PieceType.KNIGHT: return 2.5 case PieceType.BISHOP: return 3 case PieceType.ROOK: return 5 case PieceType.QUEEN: return 9 default: return 0 } } // Copied from Game.groovy and a bit modified. // I actually need this. Set<Move> genValidMoves(Player player, Player enemy, Board board) { def allMoves = player.getPieces(board).collect { [it, it.getValidDestinationSet(board)] } def attackMoves = allMoves .collect { pair -> def piece = pair[0] def dests = pair[1] [piece, dests.findAll { board.getFieldAtLoc(it as Location)?.piece?.team == enemy.team }] }.findAll { it[1] } if (attackMoves.isEmpty()) return allMoves.collect { Piece piece = it[0] as Piece return it[1].collect { loc -> new Move(piece, loc as Location) } }.flatten() as Set<Move> else return attackMoves.collect { Piece piece = it[0] as Piece return it[1].collect { loc -> new Move(piece, loc as Location) } }.flatten() as Set<Move> } } ``` [Answer] # [SacrificeBot](https://github.com/JJ-Atkinson/SimpleAntichessKOTH/blob/68d3067fd06560bd4a1dc6dee3643788e476d62c/src/main/groovy/com/ppcgse/koth/antichess/player/SacrificeBot.groovy) This bot will check all the moves that the other player has and will check to see if any of them intersect (i.e. the piece will be killed). (This does a heck of a lot better than I ever expected ;) ``` package com.ppcgse.koth.antichess.player import com.ppcgse.koth.antichess.controller.Board import com.ppcgse.koth.antichess.controller.Color import com.ppcgse.koth.antichess.controller.Location import com.ppcgse.koth.antichess.controller.Move import com.ppcgse.koth.antichess.controller.Piece import com.ppcgse.koth.antichess.controller.PieceType import com.ppcgse.koth.antichess.controller.PieceUpgradeType import com.ppcgse.koth.antichess.controller.Player import java.util.concurrent.ThreadLocalRandom /** * Created by Jarrett on 12/19/15. */ class SacrificeBot extends Player { {pieceUpgradeType = PieceUpgradeType.ROOK} @Override Move getMove(Board board, Player enemy, Set<Move> validMoves) { def enemyPieces = enemy.getPieces(board) def pawnMoves = getPawnsMoves(board, enemyPieces) def enemyPlayerValidMoves = (enemyPieces .collect { it.getValidDestinationSet(realBoard) } .flatten() as List<Location>) enemyPlayerValidMoves += pawnMoves def sacrificeMove = validMoves .find {enemyPlayerValidMoves.contains(it.destination)} if (sacrificeMove) return sacrificeMove else return randomMove(validMoves) } def randomMove(Set<Move> validMoves) { return validMoves[ThreadLocalRandom.current().nextInt(validMoves.size())]; } def getPawnsMoves(Board board, List<Piece> allPieces) { def direction = getTeam() == Color.BLACK ? 1 : -1; def pawns = allPieces.findAll {it.type == PieceType.PAWN} def pawnAttacks = (pawns.collect { [it.loc.plus(-1, direction), it.loc.plus(1, direction)] }.flatten() ).findAll { ((Location) it).isValid() } return pawnAttacks as List<Location> } } ``` [Answer] # [OnePlayBot](https://github.com/JJ-Atkinson/SimpleAntichessKOTH/blob/cdf293ef94f49b0d8bd9e252be6aa62c5ac4bd2b/src/main/groovy/com/ppcgse/koth/antichess/player/OnePlayBot.groovy) Dead simple bot with only one play. It will upgrade to a rook. ``` package com.ppcgse.koth.antichess.player import com.ppcgse.koth.antichess.controller.Move import com.ppcgse.koth.antichess.controller.PieceUpgradeType import com.ppcgse.koth.antichess.controller.Player import com.ppcgse.koth.antichess.controller.ReadOnlyBoard public class OnePlayBot extends Player { {pieceUpgradeType = PieceUpgradeType.ROOK} @Override public Move getMove(ReadOnlyBoard board, Player enemy, Set<Move> moves) { return new ArrayList<Move>(moves).get(0); } } ``` [Answer] # [RandomBot](https://github.com/JJ-Atkinson/SimpleAntichessKOTH/blob/cdf293ef94f49b0d8bd9e252be6aa62c5ac4bd2b/src/main/groovy/com/ppcgse/koth/antichess/player/RandomBot.groovy) This is the manditory random bot. It will always upgrade to a rook. ``` package com.ppcgse.koth.antichess.player import com.ppcgse.koth.antichess.controller.PieceUpgradeType import com.ppcgse.koth.antichess.controller.Player import com.ppcgse.koth.antichess.controller.Move import com.ppcgse.koth.antichess.controller.ReadOnlyBoard import java.util.concurrent.ThreadLocalRandom; public class TestBot extends Player { {pieceUpgradeType = PieceUpgradeType.ROOK} @Override public Move getMove(ReadOnlyBoard board, Player enemy, Set<Move> moves) { return moves[ThreadLocalRandom.current().nextInt(moves.size())]; } } ``` [Answer] # MeasureBot This is the bot that I started with; I was working on expanding it but then I came across the deep-clone bug, and then I thought "well, let's just submit this bot already, it does perform better than RandomBot and OnePlayBot, and I can always submit a new bot later", so here it is: ``` package com.ppcgse.koth.antichess.player import com.ppcgse.koth.antichess.controller.Board import com.ppcgse.koth.antichess.controller.Move import com.ppcgse.koth.antichess.controller.Piece import com.ppcgse.koth.antichess.controller.PieceType import com.ppcgse.koth.antichess.controller.PieceUpgradeType import com.ppcgse.koth.antichess.controller.Player import java.util.concurrent.ThreadLocalRandom /** * Created by ProgramFOX on 12/21/15. */ class MeasureBot extends Player { {pieceUpgradeType = PieceUpgradeType.KING} @Override Move getMove(Board board, Player opponent, Set<Move> validMoves) { def opponentPieces = opponent.getPieces(board) def mustCapture = opponentPieces.find { it.loc == validMoves[0].destination } != null def chosen = null if (mustCapture) { def piecesThatCanBeTaken = opponentPieces.findAll { validMoves.collect { it.getDestination() }.contains(it.loc) } def lowestAmount = getPieceValue(piecesThatCanBeTaken.sort { getPieceValue(it.getType()) }[0].getType()) def piecesWithLowestValue = piecesThatCanBeTaken.findAll { getPieceValue(it.getType()) == lowestAmount } def chosenOnes = validMoves.findAll { m -> piecesWithLowestValue.find { it.loc == m.destination } != null } chosen = chosenOnes.sort { getPieceValue(it.piece.getType()) }.reverse()[0] } else { chosen = randomMove(validMoves); } return chosen } Double getPieceValue(PieceType pieceType) { switch (pieceType) { case PieceType.KING: return 1 case PieceType.PAWN: return 1.5 case PieceType.KNIGHT: return 2.5 case PieceType.BISHOP: return 3 case PieceType.ROOK: return 5 case PieceType.QUEEN: return 9 default: return 0 } } def randomMove(Set<Move> validMoves) { return validMoves[ThreadLocalRandom.current().nextInt(validMoves.size())]; } } ``` MeasureBot looks if it needs to capture something: if it does not, it just makes a random move. If it does, it will decide what piece to take: it will choose one with a lower piece value because those can capture fewer of its own pieces. And if there are multiple ways to take a piece with the lowest possible value, it will capture it with the piece with the highest possible value: if it does this, it will bring the capturing piece closer to other pieces (in the beginning of the game, at least) and you'd rather lose a higher-valued piece than a lower-valued one. This is a list of the piece values I used: * King: 1 * Pawn: 1.5 * Knight: 2.5 * Bishop: 3 * Rook: 5 * Queen: 9 When a pawn promotes, it will always promote to a king, because it's the lowest-valued piece. ]
[Question] [ # The Problem I have a bunch of regular expressions that I need to use in some code, but I'm using a programming language that doesn't support regex! Luckily, I know that the test string will have a maximum length and will be composed of printable ASCII only. # The Challenge You must input a regex and a number `n`, and output every string composed of printable ASCII (ASCII codes 32 to 126 inclusive, to `~`, no tabs or newlines) of length less than or equal to `n` that matches that regex. You may **not** use built-in regular expressions or regex matching functions in your code at all. Regular expressions will be limited to the following: * Literal characters (and escapes, which force a character to be literal, so `\.` is a literal `.`, `\n` is a literal `n` (equivalent to just `n`), and `\w` is equivalent to `w`. You do not need to support escape sequences.) * `.` - wildcard (any character) * Character classes, `[abc]` means "a or b or c" and `[d-f]` means anything from d to f (so, d or e or f). The only characters that have special meaning in a character class are `[` and `]` (which will always be escaped, so don't worry about those), `\` (the escape character, of course), `^` at the beginning of the character class (which is a negation), and `-` (which is a range). * `|` - the OR operator, alternation. `foo|bar` means either `foo` or `bar`, and `(ab|cd)e` matches either `abe` or `cde`. * `*` - match the previous token repeated zero or more times, greedy (it tries to repeat as many times as possible) * `+` - repeated one or more times, greedy * `?` - zero or one times * Grouping with parentheses, to group tokens for `|`, `*`. `+`, or `?` The input regex will always be valid (i.e., you do not have to handle input like `?abc` or `(foo` or any invalid input). You may output the strings in any order you would like, but each string must appear only once (don't output any duplicates). # The Test Cases Input: `.*`, `1` Output: (empty string), , `!`, `"`, ..., `}`, `~` Input: `w\w+`, `3` Output: `ww`, `www` Input: `[abx-z][^ -}][\\]`, `3` Output: `a~\`, `b~\`, `x~\`, `y~\`, `z~\` Input: `ab*a|c[de]*`, `3` Output: `c`, `cd`, `ce`, `aa`, `cde`, `ced`, `cdd`, `cee`, `aba` Input: `(foo)+(bar)?!?`, `6` Output: `foo`, `foo!`, `foofoo`, `foobar` Input: `(a+|b*c)d`, `4` Output: `ad`, `cd`, `aad`, `bcd`, `aaad`, `bbcd` Input: `p+cg`, `4` Output: `pcg`, `ppcg` Input: `a{3}`, `4` Output: `a{3}` # The Winner This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win! [Answer] # Python v2.7 ~~1069~~ ~~1036~~ ~~950~~ ~~925~~ ~~897~~ ~~884~~ ~~871~~ ~~833~~ 822 This answer seems rather long for a code golf, but there are a lot operators that need to be handled and I know what purpose each byte in this answer does. Since there is no existing answer I submit this as a target for other users to beat. See if you can make a shorter answer :). The two main functions are `f` which parses the regex starting at the `i`th character, and `d` which generates the matching strings, using `r` the sub-regexes we can recursed into, 'a' the array representing the part of the current sub-regex not yet processed, and a string suffix `s` which represents the part of the string generated so far. Also check out the [sample output](https://github.com/gmatht/joshell/tree/master/golf/regex/regex_good.txt) and a [test harness](https://github.com/gmatht/joshell/tree/master/golf/regex/regex.sh). ``` import sys;V=sys.argv;n=int(V[2]);r=V[1];S=len;R=range;C=R(32,127) Z=[];z=-1;D='d(r,p,';F='for j in ' def f(i,a): if i>=S(r):return a,i c=r[i];x=0;I="|)]".find(c) if c in"([|":x,i=f(i+1,Z) if I+1:return([c,a,x],[a],[c,a])[I],i if'\\'==c:i+=1;x=c+r[i] return f(i+1,a+[x or c]) def d(r,a,s): if S(s)>n:return while a==Z: if r==Z:print s;return a=r[z];r=r[:z] e=a[z];p=a[0:z] if'|'==a[0]:d(r,a[1],s);d(r,a[2],s) elif']'==a[0]: g=a[1];N=g[0]=='^';g=(g,g[1:])[N];B=[0]*127;O=[ord(c[z])for c in g] for i in R(0,S(g)): if'-'==g[i]:exec F+'R(O[i-1],O[i+1]):B[j]=1' else:B[O[i]]=1 for c in C:N^B[c]<1or d(r,Z,chr(c)+s) elif' '>e:d(r+[p],e,s) else:c=p[:z];exec{'.':F+'C:'+D+'chr(j)+s)','?':D+'s);d(r,p[:z],s)','*':F+'R(0,n+1):d(r,c,s);c+=[p[z]]','+':"d(r,p+['*',p[z]],s)"}.get(e,D+'e[z]+s)') d(Z,f(0,Z)[0],"") ``` Note that tabs in the original solution have been `expand`ed. To count the number of characters in the original use `unexpand < regex.py | wc`. [Answer] # Haskell ~~757 705 700 692 679~~ 667 ``` import Data.List data R=L Char|A R R|T R R|E h=[' '..'~'] k(']':s)a=(a,s) k('^':s)_=l$k[]s k('-':c:s)(a:b)=k([a..c]++b)s k('\\':c:s)a=k s$c:a k(c:s)a=k s$c:a l(a,b)=(h\\a,b) c#E=L c c#r=A(L c)r o(a,b)=(foldr(#)E a,b) t%0=E t%n=A(t%(n-1))$T t$t%(n-1) d s n=m(fst$r s)[[]] where{m E a=a;m(L c)a=[b++[c]|b<-a,length b<n];m(A r s)x=nub$(m r x)++m s x;m(T r s)a=m s$m r a;r s=w$e s E;w(u,'|':v)=(\(a,b)->(A u a,b))$r v;w x=x;e(')':xs)t=(t,xs);e s@('|':_)t=(t,s);e s@(c:_)t=g t$f$b s;e[]t=(t,[]);g t(u,v)=e v$T t u;f(t,'*':s)=(t%n,s);f(t,'+':s)=(T t$t%n,s);f(t,'?':s)=(A t E,s);f(t,s)=(t,s);b('(':s)=r s;b('\\':s:t)=(L s,t);b('.':s)=o(h,s);b('[':s)=o$k s[];b(s:t)=(L s,t)} ``` output: ``` ghci> d ".*" 1 [""," ","!","\"","#","$","%","&","'","(",")","*","+",",","-",".","/","0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","[","\\","]","^","_","`","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","{","|","}","~"] ghci> d "w\\w+" 3 ["ww","www"] ghci> d "[abx-z][^ -}][\\\\]" 3 ["x~\\","y~\\","z~\\","b~\\","a~\\"] ghci> d "ab*a|c[de]*" 3 ["aa","aba","c","ce","cd","cee","cde","ced","cdd"] ghci> d "(foo)+(bar)?!?" 6 ["foo!","foobar","foo","foofoo"] ghci> d "(a+|b*c)d" 4 ["ad","aad","aaad","cd","bcd","bbcd"] ghci> d "p+cg" 4 ["pcg","ppcg"] ghci> d "a{3}" 4 ["a{3}"] ``` Explanation: this one's a textbook regex implementation. R is the regex type, with constructors A (alternate), L (literal), T (then) and E (empty/epsilon). The usual 'Star' doesn't appear because I inline it as alternates during the parse (see '%'). 'm' runs the simulation. The parser (start at 'r s=....') is just recursive descent; 'k' parses ranges. The function '#' expands ranges into alternations. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 586 bytes The built in backtracking ability of Prolog makes it an awesome choice for this challenge. By taking advantage of backtracking, generating strings for a regex becomes exactly the same task as testing if a string is matched by a regex. Unfortunately, much of my golfing effort went into writing a shorter regex parsers. The actual task of decomposing a regular expression we easily golfed. ``` R-L-S:-R*A,-(B,A,[]),setof(Z,(0/L/M,length(C,M),C+B+[],Z*C),S). -R-->e+S,S-R. R-T-->{R=T};"|",e+S,u+R+S-T. Z+Y-->(".",{setof(C,32/126/C,R)};"[^",!,\E,"]",{setof(C,(32/126/C,\+C^E),R)};"[",\R,"]";"(",-R,")";{R=[C]},([C],{\+C^`\\.[|+?*(`};[92,C])),("*",{S=k*R};"+",{S=c+R+k*R};"?",{S=u+e+R};{S=R}),({Y=c+Z+S};c+Z+S+Y). \C-->{C=[H|T]},+H,\T;{C=[]};+A,"-",+B,\T,{setof(C,A/B/C,H),append(H,T,C)}. +C-->[92,C];[C],{\+C^`\\]-`}. S+e+S. [C|S]+D+S:-C^D. S+(B+L+R)+T:-B=c,!,S+L+U,U+R+T;S+L+T;S+R+T. S+k*K+U:-S=U;S+K+T,S\=T,T+k*K+U. A/B/C:-between(A,B,C). A^B:-member(A,B). A*B:-string_codes(A,B). ``` [Try it online!](https://tio.run/##bVFNb9pAEL3zK5o97XpmTANVpGK5CG8iIYVcvOYAtim2MRSFYAREVMX@7XQMVYoUfFjP@9idebubbbEqFrQ7LE8nnwZkOuRbPSTpYQ/DWOEu3xdzOUb5tTlovuAqXy/2v6TGF4UaPAhjHFtaoVF2g3yiHzkYNOTbDZ8ChkffDSpHlAJr4R18MBTYjTGMWJTCFni8dNDYbjXvWw9Njb7iHeFE4B1GTyjiK4/8MEWgJ0/qn1dg5NdGR0iBxKUSDncOdVyh5BWPtX0aRXZYQteS08oJv7dQx0qhFBY3MO6r5fNRcK4znvOCu2f8Djkw4sqveMdxxI4xmMo5/2DE4SNdp9Vu2C8D7gp9jAKnxnHlQA8FCQSPuf9Zek2Pc/QVJptNvp7JPgaoVWU3oD7qMp9zPXxMU1YNz2LsRqhLE8Mj8IPpyWNNSw8G4CsIOuS5GV@eYTzEIWcJnLquV65r76v1DMMOGXfI3DMEaCI3wODC243zaB1K8/0hz9eyhx5PxvTE69Bb/pbm25qrGYuZ3X67XC9@ZsUs313402m@XM@S1UoaFLYl6J4MDth/RR@i6ACC2p@VMEl/0584nHyhKg4j/uKbviS1kjILZ3ls3dTlvCgUyDTZqu5dV9DDDUsCZWplaibo22d1A9nippAc29VtoUw@wv4F "Prolog (SWI) – Try It Online") # Ungolfed Code ``` generate_string(R, L, S) :- % parse regex string_codes(R, RC), regex_union(RE, RC, []), % bound string length between(0, L, M), length(SC, M), % find string match(SC, RE, []), string_codes(S, SC). % Parsers %%%%%%%%% regex_union(R) -->regex_concat(S), regex_union1(S, R). regex_union1(R,T) --> [124], regex_concat(S), regex_union1(regex_union(R,S), T). regex_union1(R, R) --> []. regex_concat(R) --> regex_op(S), regex_concat1(S, R). regex_concat1(R, T) --> regex_op(S), regex_concat1(regex_concat(R,S), T). regex_concat1(R, R) --> []. regex_op(regex_kleene(R)) --> regex_lit(R), [42]. regex_op(regex_concat(R,regex_kleene(R))) --> regex_lit(R), [43]. regex_op(regex_union(regex_empty,R)) --> regex_lit(R), [63]. regex_op(R) --> regex_lit(R). regex_lit(regex_char([C])) --> [C], {\+ regex_ctrl(C)}. regex_lit(regex_char([C])) --> [92], [C]. regex_lit(regex_char(CS)) --> [46], {findall(C, between(32,126, C), CS)}. regex_lit(regex_char(DS)) --> [91], [94], !, class_body(CS), [93], {findall(C, (between(32, 126, C), \+ member(C, CS)), DS)}. regex_lit(regex_char(CS)) --> [91], class_body(CS), [93]. regex_lit(R) --> [40], regex_union(R), [41]. class_body([C|T]) --> class_lit(C),class_body(T). class_body(CS) --> class_lit(C0), [45], class_lit(C1), class_body(T), {findall(C, between(C0, C1, C), H), append(H,T,CS)}. class_body([]) --> []. class_lit(C) --> [C], {\+ class_ctrl(C)}. class_lit(C) --> [92], [C]. class_ctrl(C) :- string_codes("\\[]-", CS), member(C, CS). regex_ctrl(C) :- string_codes("\\.[]|+?*()", CS), member(C, CS). % Regex Engine %%%%%%%%%%%%%% % The regex empty matches any string without consuming any characters. match(S, regex_empty, S). % A regex consisting of a single character matches any string starting with % that character. The chanter is consumed. match([C|S], regex_char(CS), S) :- member(C, CS). % A union of two regex only needs to satisify one of the branches. match(S, regex_union(L,R), T) :- match(S, L, T); match(S, R, T). % A concat of two regex must satisfy the left and then the right. match(S, regex_concat(L, R), U) :- match(S, L, T), match(T, R, U). % The kleene closure of a regex can match the regex 0 times or it can the regex % once before matching the kleene closure again. match(S, regex_kleene(_), S). match(S, regex_kleene(K), U) :- match(S, K, T), S \= T, match(T, regex_kleene(K), U). ``` ]
[Question] [ (The word frame in the following text does not mean an actual frame, it is used as a placeholder for an undefined time unit) # The task Imagine you have a keyboard layout with only letters like so: ``` q w e r t y u i o p a s d f g h j k l z x c v b n m ``` Whenever you press a key, for example `f`, the keyboard lights up the keys around it each frame like this (unordered, each line is a separate frame): ``` F RTGVCD YHBXSE UJNWAZ IKMQ OL P ``` As you can see, each frame lights up the keys around the ones that were lit previously, but not the ones that have already been lit up before. After you have determined which keys need to be pressed each frame, you need to visualize them. For each frame, you print out the default keyboard layout (with all of the whitespace), but with the lit up keys uppercased. In our example: ``` q w e r t y u i o p a s d F g h j k l z x c v b n m q w e R T y u i o p a s D f G h j k l z x C V b n m q w E r t Y u i o p a S d f g H j k l z X c v B n m q W e r t y U i o p A s d f g h J k l Z x c v b N m Q w e r t y u I o p a s d f g h j K l z x c v b n M q w e r t y u i O p a s d f g h j k L z x c v b n m q w e r t y u i o P a s d f g h j k l z x c v b n m ``` # Rules 1. Input will be a single letter, you can choose whether it will be capitalized or not. 2. Output can be either: a. An array of multiline strings representing each second of the visualized keyboard b. A single multiline string with each frame of the visualized keyboard separated by at least one newline 3. You can output a trailing newline or/and the final keyboard visualization when no keys are lit anymore # Test cases ``` Input: F Output: q w e r t y u i o p a s d F g h j k l z x c v b n m q w e R T y u i o p a s D f G h j k l z x C V b n m q w E r t Y u i o p a S d f g H j k l z X c v B n m q W e r t y U i o p A s d f g h J k l Z x c v b N m Q w e r t y u I o p a s d f g h j K l z x c v b n M q w e r t y u i O p a s d f g h j k L z x c v b n m q w e r t y u i o P a s d f g h j k l z x c v b n m Input: Q Output: Q w e r t y u i o p a s d f g h j k l z x c v b n m q W e r t y u i o p A s d f g h j k l z x c v b n m q w E r t y u i o p a S d f g h j k l Z x c v b n m q w e R t y u i o p a s D f g h j k l z X c v b n m q w e r T y u i o p a s d F g h j k l z x C v b n m q w e r t Y u i o p a s d f G h j k l z x c V b n m q w e r t y U i o p a s d f g H j k l z x c v B n m q w e r t y u I o p a s d f g h J k l z x c v b N m q w e r t y u i O p a s d f g h j K l z x c v b n M q w e r t y u i o P a s d f g h j k L z x c v b n m Input: Z Output: q w e r t y u i o p a s d f g h j k l Z x c v b n m q w e r t y u i o p A S d f g h j k l z X c v b n m Q W E r t y u i o p a s D f g h j k l z x C v b n m q w e R t y u i o p a s d F g h j k l z x c V b n m q w e r T y u i o p a s d f G h j k l z x c v B n m q w e r t Y u i o p a s d f g H j k l z x c v b N m q w e r t y U i o p a s d f g h J k l z x c v b n M q w e r t y u I o p a s d f g h j K l z x c v b n m q w e r t y u i O p a s d f g h j k L z x c v b n m q w e r t y u i o P a s d f g h j k l z x c v b n m ``` [Answer] # [Haskell](https://www.haskell.org/), 229 bytes ``` e=zip[0..] x!y=abs$x-y k=e["Q W E R T Y U I O P"," A S D F G H J K L"," Z X C V B N M"] f c=filter(any(<"a").words)[unlines[[[z..]!!sum[32|z>'@',max(2*y!i)(y!i+x!j)/=d*2]|(x,z)<-e m]|(y,m)<-k]|(i,l)<-k,(j,h)<-e l,c==h,d<-[0..9]] ``` [Try it online!](https://tio.run/##JY9ZT4NAAITf@RUDaQLUBQ0@mbDGs16tVz27IWblkC0LJRwRSH@7CPoy@WbmYTIxL5NQyr4PaSdytmfbntKoLeWf5aSxWiWhIdMe8IpzPOIJ73jGFe5wrxENx1jiDDNc4BLXuMF8DLHCG07xghPcYqF5SgSfRkJWYWHwrDVcjWum/b0pgtJkdSZFFpaMsW4YVtWyTtm@s@0O9SOdpLwxnGmrCtMYZKdR1@YuDaaOtzUa0pmuFSIduCXpwMlAgsiRiLEm8V8tiU9pTALXGo8deF6fcpGBItgoQF6IrMIEEfSZPviU54sP5HW1rIp59l@sdKX/8SPJv8re8vP8Fw "Haskell – Try It Online") `f` takes an uppercase char argument and returns a list of multiline strings. It loops over the keyboard layout looking for `(i,j)`, the position of the given character. When it finds it, for each `d<-[0..9]` it generates a string (`unlines[…]`) of the keyboard with all letters *not* `d` hex-steps away lowercased. It never takes longer than 10 steps for the wave to leave the keyboard, so this is OK. Finally, strings that don't contain any uppercase letters are filtered away from the result. I calculate the hex distance between two points on the keyboard as: \$ \max\left(2|y\_1-y\_2|, |x\_1-x\_2|+|y\_1-y\_2|\right)\$. Here are some distances around a point under this metric: ``` 6666666 6 6 6 6 654444456 6 4 4 4 6 65432223456 6 4 2 2 4 6 6543210123456 --> on staggered grid: 6 4 2 0 2 4 6 65432223456 6 4 2 2 4 6 654444456 6 4 4 4 6 6666666 6 6 6 6 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 82 bytes ``` ≔⪪”&±=K≕⦃Vj@η⟲.w\`o:7➙1”¶υ≔⊟Φυ№ιθηΦEχEυ⁺× μ⪫⭆λ⎇⁼ι⌈↔⊟E⟦⟦⁻μ⌕υη⁻ξ⌕ηθ⟧⟧⊞OπΣπ↥νν ⊙ι⊙λ№αν ``` [Try it online!](https://tio.run/##NY@9bsMwDIT3PoXgiQZUoJ0zGUUzFDBqIOkUZ1AcNVIqU7J@Ujsv71KOy4XQ8Xj81CnhOyvMPFch6AvCzhkdoRh@pY9T0ta1KML5@6KuP6bF@9jdTtgXnBUtFiVnqdw8rZuNdbDVJkoPibM3mzCC5mwoS/Ip8jVek7RaauHg9YWz3MnemBRgr3sZoGAU39POh9XEE2nrkl2Gs730KPwE70MSJuT0Woy6Tz1Up2BNinKhyO7DodZImT1nW43nfENlkIc6rqpa@I5HAkhBfTrpRbQeHGc7CnXlUpx9OZp0IkhAemGWiPIxq3DKILmZ/2@LxUS1mef7/Hwzfw "Charcoal – Try It Online") Link is to verbose version of code. Takes input in lower case. Explanation: ``` ≔⪪”&±=K≕⦃Vj@η⟲.w\`o:7➙1”¶υ ``` Get the list `qwertyuiop`, `asdfghjkl`, `zxcvbnm` by splitting a compressed string. ``` ≔⊟Φυ№ιθη ``` Find the element of the above list that contains the input. ``` Eχ ``` Create a list of lists corresponding to each step away from the input on the staggered grid from 0 to 9. ``` Eυ⁺× μ⪫⭆λ⎇⁼ι⌈↔⊟E⟦⟦⁻μ⌕υη⁻ξ⌕ηθ⟧⟧⊞OπΣπ↥νν ``` Uppercase the letters that are the desired distance from the input on the staggered grid, then stagger the result by prefixing each line with an increasing number of spaces and double-spacing the letters. ``` Φ...⊙ι⊙λ№αν ``` Only print those lists that contain an uppercase letter. The formula I'm using for distance is the maximum of \$|x\_2-x\_1|\$, \$|y\_2-y\_1|\$ and \$|x\_2-x\_1+y\_2-y\_1|\$ their sum, where \$y\$ is the (0-indexed) row counting down and \$x\$ is the (skewed) column: ``` 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~59~~ ~~57~~ 50 bytes Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -3 bytes! Input is in lowercase, the program prints the keyboards separated by empty lines. Outputs the final dark keyboard for some keys. Uses the distance metric from [Lynn's answer](https://codegolf.stackexchange.com/a/214288/64121). ``` žVðæ.ιSðý©Ik19‰¸Þ2Ý18Ýâαε¬sO;‚à}>ZFD®sÅÏu}19ô»,¶?< ``` [Try it online!](https://tio.run/##AVcAqP9vc2FiaWX//8W@VsOww6YuzrlTw7DDvcKpSWsxOeKAsMK4w54yw50xOMOdw6LOsc61wqxzTzvigJrDoH0@WkZEwq5zw4XDj3V9MTnDtMK7LMK2Pzz//3E "05AB1E – Try It Online") **Commented**: ``` # keyboard creation žV # push ["qwertyuiop", "asdfghjkl", "zxcvbnm"] ð # push a space æ # push the powerset ["", " "] .ι # interleave both lists S # split into a list of characters δý # join with spaces © # store this value in the register I # push the input k # the index of the input in the keyboard string 19‰ # divmod by 19 to get [y, x]-coordinates ¸Þ # cycle this value forever 2Ý # push [0..2] 18Ý # push [0..18] â # cartesian product to get a list of all coordinates α # take the element-wise difference [dy, dx] for each coord # apply distance metric ε } # map over the absolute differences: ¬ # get the first element dy s # swap back to [dy, dx] O # sum it ; # halve it ‚ # pair into a list [dy, (dy+dx)/2] à # take the maximum > # increment every value # so that the input position has value 1 (only truthy value) # generate the outputs Z # take the maximum of the distances F # iterate that many times: D # duplicate the distance list ® # push the keyboard string s # swap to the distance list ÅÏ } # apply where truthy (==1) u # uppercase 19ô # split into groups of 19 » # join by newlines , # print ¶? # print a newline <# decrement distance list ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 64 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “¤Äı’b3’s2 +Ɱ¢ẎfØqŒṪ¤Q ḢØqœiWÇƬḟ"ṖẎ$Ƥ$LƇœịØqżŒu$µyⱮØqK€2Żẋ@⁶¤;") ``` A monadic Link accepting a list of 1 character which yields a list of keyboards, each keyboard being a list of lists of characters (including the spacing given in the examples). **[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDSw63HNn4qGFmkjGQKDbi0n60cd2hRQ939aUdnlF4dNLDnasOLQnkerhjEYg7OTP8cPuxNQ93zFd6uHMaUJHKsSUqPsfaj05@uLsbpGDP0UmlKoe2VgINAXK9HzWtMTq6@@GubodHjdsOLbFW0vx/uD0SKJr1qHHfoW2Htv3/XwIA "Jelly – Try It Online")** (Footer joins the resulting keyboards with newline characters and joins the result with pairs of newline characters to display like the examples.) ]
[Question] [ # Inspired by, and in memory of, our beloved genius, [![John Scholes, 1948-2019](https://i.stack.imgur.com/lIqGd.png "John Scholes, 1948-2019")](https://www.dyalog.com/news/131/420/John-Scholes.htm) # [R.I.P.](http://johnscholes.rip/) He [invented](https://dyalog.tv/Dyalog18/?v=y33XDD6ANt0 "Dfns - Past, Present and Future") and implemented [dfns](http://dfns.dyalog.com/ "D-functions") — his magnum opus and the subject of the challenge. For the interested: [latest full dfns documentation](http://help.dyalog.com/latest/index_Left.htm#CSHID=Language%2FDefined%2520Functions%2520and%2520Operators%2FDynamicFunctions%2FDynamic%2520Functions%2520and%2520Operators.htm%7CStartTopic=Content%2FLanguage%2FDefined%2520Functions%2520and%2520Operators%2FDynamicFunctions%2FDynamic%2520Functions%2520and%2520Operators.htm) and [videos with John](http://johnscholes.rip/video/). ## Task Given an ASCII source code, answer in which of the following four categories it belongs: 1. Dyadic dop 2. Monadic dop 3. Dfn 4. Other You may return any four consistent values, but please state your mapping if it isn't obvious. ### Details You may assume that the source code always begins with an opening curly brace `{` and ends with a closing curly brace `}`. Recursively nested braces can occur (e.g. `{{{}}}`), but categories 1–3 can never have brace nesting depth go below 1 (so `{}{}` is "Other") and all braces must be balanced (so `{{}` is "Other"). Characters in the following contexts on a line are ignored: 1. To the right of `#` (a comment): `significant#ignored` 2. Enclosed in single quotes `'`…`'` (i.e. in a string): `significant'ignored'significant` (This applies to `#` too: `'#'significant`) 3. To the right of an unpaired quote `'` (pairing quotes from the left): `significant'ignored` In curly brace level one (i.e. excluding nested braces): * Dyadic dops contain the uninterrupted phrase `ww` * Monadic dops do not contain `ww`, but do contain `aa` * Dfns contain neither `ww` nor `aa` ## Test cases ### Dyadic dops ``` {ww} ``` ``` { www } ``` ``` { ''ww' } ``` ``` {aa ww} ``` ``` {'#''#'ww?aa} ``` ### Monadic dops ``` {aa} ``` ``` {aaaa} ``` ``` {aa{ww}'ww'} ``` ``` {w#w' aa' } ``` ``` {aaw*w} ``` ``` {w'\'aa\''} ``` ### Dfns ``` {} ``` ``` {a a} ``` ``` {aA} ``` ``` { {aa} } ``` ``` {w w''w# w} ``` ``` {{ }} ``` ``` {w\'aa\'} ``` ### Other ``` {}{} ``` ``` {{} ``` ``` {}} ``` ``` {ww}} ``` ``` {} {} ``` ``` {ww}{} ``` ``` {#} ``` ``` {' '} ``` [Answer] # JavaScript (ES6), ~~145 ... 138~~ 136 bytes Returns \$0\$ for *dyadic dops*, \$1\$ for *monadic dops*, \$2\$ for *dfns* and \$3\$ for *other*. ``` s=>[...s].map(c=>s=(n=` aw}{#'`.indexOf(c))?n>5?i^=2:i?0:n>4?i=1:n>3?d++:n>2?x+=!d--:(o|=n<0|d|s!=c?0:n,c):i=0,o=i=0,x=d=-1)|x|~d?3:2>>o ``` [Try it online!](https://tio.run/##fZLPTsMwDMbve4ptPaSla7U/cCm4EdKuaA9AQYuSFoJGUi0TKWrLq5cUhAQiXg6x5M@2fl@cF/bGDD/K@pQoLcqhgsFAfp@mqXlIX1kdcsgNhAr2E2b7NiD7VCpRNrsq5FFEVX5F5SOsM0mXmcovqYSVixsq4tjFNW1imIkkyULdgbpZdqIzM@Bj8YJHmYTlQsN4NyAgWUVd030IusnWea4HrpXRhzI96KeQbN@ZkHwqdG1IdD35rVXhvLW2n0eefKGm7lhrC4UVEGItwWTGClUobDoJXC9l7Fv9I5M7rc4S/3T9z@PKaHOk9es2GH0wdsaMvbA@1m2lvIzImCkGeIu98egWo3KrsW4HgQv@Atff@6h3p@fy6MVGwJF0j3BZRHBOWrQFUQLkA7nv96UMnw "JavaScript (Node.js) – Try It Online") ## Alternate versions * [**131 bytes**](https://tio.run/##hZLPTsMwDMbve4qxHtKytdofuBTcCGlXtAegoEVJC0HDmdYJF63l1UsqEAJp83KII31fHP/svKp3Vemd3e5jdKboSugqyKrkTW1D7Q8QIqwHitpDINaJRVPUqzLUUSQxu5b2CeapldMUsytpYebjQprx2Me5rMdwYeI4DV0DeDttTFNdgO7NEx2lFqYTB/1eg4F4FjV182nkIp1nmeu0w8ptimTjnkOx/FDG6qFx20pEN4O/Whk@JEkyOhC1o8fohJjj0C8iypF1CUEkWI9SOebIPiYCn0Uq9WP55xH3Ds@i/F49Lp6R@070GIyJgp5SqXOodElHIZYlniyeSzhkK79jR9N3hS3Xz5b8/AIfGJfP1B5lWu1fit1JKA6L01quYOJUD3vgL3NywP1P/8@/5e4L) by taking an array of characters as input * [**132 bytes**](https://tio.run/##fZLRSsMwFIbvfYq5XqR1y1g7hixyGpTdii9QhNC0WpknY5mmss5Xr@lEUMxZL9L0fDnh@5u8qHdly12z3XM0uupr6C3kd291Xe1im8xe1TZGyC0gT@cS@WIlGzkXfrL0X2m2OI1LGZsOdGc5nmCariQCrK5FNsVEtBO41JwLPZmIBlLRPELmJ/OpgWFsQQNPk67tPrVciCzPTV8atGZTzTbmKWbrD6WbcqTN1rLk5uI3q@PxwbnjOAnUCxz5xzlXILWAMecYhZUqsEBqdxb5XqnUN/2D2b3Bs8Y/Xf/rNBliDrZh7qIhh1JnwrgrF3Jd1xh0JLYZUYK31D8e0lJW/micP4PIv8ILfP8xZP2wf652QW1CnCgfCS9HAJ/kQLYQJCIukL9@J9J/AQ) by using *Buffer()* (Node.js) ## How? The input string is parsed character by character. ### Translation of characters into codes Each character \$c\$ is translated into a code \$n\$ according to the following table: ``` character | code | triggered operation -----------+------+--------------------------------------------------------- \n | 0 | i = 0 a | 1* | o |= n < 0 | d | s != c ? 0 : n w | 2* | o |= n < 0 | d | s != c ? 0 : n } | 3* | x += !d-- { | 4* | d++ # | 5* | i = 1 ' | 6 | i ^= 2 other | -1* | same as 'a' or 'w', but always fails because of 'n < 0' ``` Codes marked with a '\$\*\$' have no effect when \$i\neq 0\$. ### Variables describing the parser state The following variables are used during the parsing: * \$o\$: a bitmask keeping track of encountered phrases + bit 0: a valid phrase `aa` has been encountered + bit 1: a valid phrase `ww` has been encountered * \$i\$: a bitmask telling whether some characters should be ignored + bit 0: we're currently located inside a comment + bit 1: we're currently located inside a string (this bit is still updated within a comment, but this is harmless) * \$s\$: the result of the previous iteration * \$d\$: the current depth of nested braces (starting at \$-1\$) * \$x\$: the number of times we went from depth \$0\$ to depth \$-1\$, minus \$1\$ ### Final result We output \$3\$ if \$x\$ is not equal to \$0\$ or \$d\$ is not equal to \$-1\$. Otherwise, we output \$0\$, \$1\$ or \$2\$ according to the value held in \$o\$. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~50 48 46~~ 45 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ỵµṣ”'m2Kṣ”#Ḣ)KµċⱮƤØ{IF©<-oµ⁾waż¤ẇ€‘Ḅ«5×®¬Ḅ⁼1¤ ``` A monadic Link accepting a list of characters which yields: ``` 5 - Dyadic dop 4 - Monadic dop 3 - Dfn 0 - Other ``` **[Try it online!](https://tio.run/##y0rNyan8///h7i2Htj7cufhRw1z1XCNvCEv54Y5Fmt6Hth7pfrRx3bElh2dUe7odWmmjm39o66PGfeWJR/ccWvJwV/ujpjWPGmY83NFyaLXp4emH1h1aA2Q/atxjeGjJ////lZSUYriqy7nK1ZXz8ksUEhWS83NzU/NK1MuVYazikqLMvHSFzDwkWRidm1@UqoBFAReXcn5eTiWSANCK6sTE2rT8/OqKiuqqqtrapMQivXL1cqBELdAVAA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##VY7PSgMxEMbv8xRLcghKPSh4E8SLIH2E2kMOXqTicZAQaIvgwQewFy@6F3EpCC5ULR5m1fdIXiSdbBubDYH5981vvsuL0egmBPf1TrX7ePbjR3V10F9n0i2edvpU/9z7t/lf2czM2Sm9HO1dU@0n36h/l1S6zzs/rfx45ha39HrYPNCcKs79ZLlPZWja6bQKYTAQBtEKKHpCiHMwUPBDRLBcb7tKIapuT2uAuLpuGSVZcqy1FUPoMTVm7UDrLI3HIiq7iJLJWm/pLMNdTJy0WvxDTnK78U7XFwKyWwnY6Rqwsd4wEzVFu4nsLoNb/skTT5JYZhIFqsUOVw "Jelly – Try It Online"). uses Python quoting to avoid the possibility of evaluating input as a Python set or dictionary ### How? ``` Ỵµṣ”'m2Kṣ”#Ḣ)KµċⱮƤØ{IF©<-oµ⁾waż¤ẇ€‘Ḅ«5×®¬Ḅ⁼1¤ - Link: list of characters - breaking long Link up... Ỵµṣ”'m2Kṣ”#Ḣ)K - Replace any strings or comments with (single) spaces Ỵ - split at newline characters µ ) - monadic chain for each: ṣ”' - split at apostrophe characters m2 - modulo 2 slice (i.e. every other part starting with the first - - that is, non-string code. Will remove strings from within comments) K - join with spaces ṣ”# - split at octothorp characters Ḣ - head (i.e. non-comment code) K - join with spaces µċⱮƤØ{IF©<-oµ - Replace characters of code at depth > 1 with the integer 1 µ µ - monadic chain, call previous result A: Ø{ - literal ['{','}'] Ƥ - for prefixes of A: Ɱ - map across right argument with: ċ - count I - deltas (i.e. [count('}') - count('{')] for each prefix) F - flatten (i.e. count('}') - count('{') for each prefix) - -- i.e -1*depth of each character of A; closing braces at depth+1 © - (copy this list of depths to the register for later use) <- - less than -1? (vectorises) o - logical OR with A (vectorises, replacing deep code with 1s) ⁾waż¤ẇ€‘Ḅ«5×®¬Ḅ⁼1¤ - Categorise the result, R ¤ - nilad followed by link(s) as a nilad: ⁾wa - literal ['w', 'a'] ż - zip with itself = [['w','w'],['a','a']] ẇ€ - for €ach: is a sublist of R? i.e. one of: [0,0] [1,0] [0,1] [1,1] ‘ - increment (vectorises) [1,1] [2,1] [1,2] [2,2] Ḅ - unbinary 3 5 4 6 «5 - minimum with five 3 5 4 5 ¤ - nilad followed by link(s) as a nilad: ® - recall depths from the register ¬ - logical NOT (vectorises) (0->1, other depths->0) Ḅ - unbinary ⁼1 - equal one -- i.e. depths ends with a 0 and contains no other zero × - multiply ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~309~~ ~~293~~ 284 bytes We can get away with only using 3 variable names at a time, so we'll call them `a`, `p`, and `l`. ``` import StdEnv,Text,Data.List a=isInfixOf o zip2[2,2] @ =['\''] $p#p=join@[foldl((\[a:p]_|p>[]=a++[';':join@(tl p)]=split['#']a!!0)o split@)l l\\l<-mklines p] #l=[(?a- ?l,p)\\a<-inits p&[p:l]<-tails p] |{p\\(a,p)<-l|a<2}<>"{}"=0|a['ww']l=1|a['aa']l=2=3 ?l=sum[1\\'{'<-l]-sum[1\\'}'<-l] ``` [Try it online!](https://tio.run/##XZBBb9swDIXP0a9gm2KyV7tNs5tnJRnWHgIUSIEU2EESBiKxO220LcRK3S7JX59nOekw9Ebyfe@J4ooyLNuiWm8pgwJN2ZrCVhsHS7e@K5@jx@zFRbfo8Ore1I6hMPW8zM3LIocKfhs7luNorNkMhOSKc80u7NCKn5UpZzKvaE1BoCQmVn/f24nUAi8vJf/Mk54IHIENtagtGSf5kGs8OxuFFfSDWUhASlEaF7/IlFkNVrMhCRlMMYYpRTZUCtPYlMZ12gdpE9Jp7NBQj@53VqkAOyyNaY/p@JBOzneHczHao@RNwzWJG18i@nIsPrEpiXpbyBul@I53Lh2/tYe@bfNNVcDytXZZcTVfwOlWSTJfRPCUua8/cBNB9ow0X7Clw05r2GAIgSnt1kXQhCA894XIo7VXr69F918sgyCdhP6GIfQ0Gwi4OJXsf0@SwMdv1YbWEE8gkH6oo9MoZO/Su7dX/VJNyAZd4nG3t109sQcPgBDA1Yj3UCD10XBy1//s79I96oGkp3pTu2tYw3kzZM3hzyonfKrbeH7f3r6WWJjVsXkgdHm1Kf4C "Clean – Try It Online") Defines the function `$ :: [Char] -> Int` and some helpers, giving the mapping: * `0`: Other * `1`: Dyadic dop * `2`: Monadic dop * `3`: Dfn Expanded (first version), and with more than 3 variable names: ``` $ s # s // remove strings and comments = join [';'] [ // join the second argument with semicolons limit ( // take the first repeated element of iterate // an infinite list of applications of the first argument ( ( \(p, q) = p ++ case q of // join the first half with a modified second half ['\'\'': q] = [';': q] // replace two quotes with a semicolon [c, _: q] = [c: q] // drop the character after a quote or hash _ = [] // leave unmatched strings unchanged ) o span // split the string on the first occurrence of \c = c <> '\'' && c <> '#' // a quote or hash ) l // applied to l ) \\ l <- mklines s // for line l in s split at newlines ] # b // generate a map of nesting levels = [ ( // the pair of ?i - ?t, // the nesting level c // the character c ) \\ i <- inits s // for init i of s & // synchronously iterated with [c: t] <- tails s // character c at the start of tail [c:t] of s ] // determine what the code is | {c \\(n, c) <- b | n < 2} // if the string made of characters with nesting level of less than 2 <> "{}" // is not the same as the paired braces at the beginning and end = 0 // return zero | m ['ww'] b // if there are two consecutive 'w's at nesting level 2 = 1 // return 1 | m ['aa'] b // if there are two consecutive 'a's at nesting level 2 = 2 // return 2 = 3 // otherwise return 3 ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 91 bytes ``` m`'.*?('|$)|#.* ¶ s(+`(?!^)\{[^{}]*\}(?!$) ¶ ^(?!\{[^{}]*\}$).+ 3 ^.+ww.+ 2 ^.+aa.+ 1 ..+ 0 ``` [Try it online!](https://tio.run/##RU5JDsIwDDzXryhKkbtIEcsDKv7AjVLFBw4c4ABIPqT5Vh/QjwXHoSKK7JmxZ5LX7XN/Ujy7ZXaFs8tsYVu7ApY5Phzatq9xqprJ2FYkeNedq/vN2Az@MvpwbYcgtGrSbBT0l6vGdnCE0XbMgg4JEQnag5W6i9EzBwAPpRxmBiWIzKiQCPICGpTL3BNlPde1p5hkSoyNmInWAG41gHFAogF1RSdl9p70SU3UPWB53oCaPATVslWd6tWSRxxyoP8x7Ua/DOL4Ag "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation: ``` m`'.*?('|$)|#.* ¶ ``` Remove strings and comments. ``` s(+`(?!^)\{[^{}]*\}(?!$) ¶ ``` Remove matched brackets, working out from the innermost, but leave the first and last brackets. ``` ^(?!\{[^{}]*\}$).+ 3 ``` If we don't have matched brackets then this is Other. ``` ^.+ww.+ 2 ``` Otherwise if we have `ww` then this is Dyadic Dop. ``` ^.+aa.+ 1 ``` Otherwise if we have `aa` then this is Monadic Dop. ``` ..+ 0 ``` Otherwise if this is anything not covered above then this is Dfn. ]
[Question] [ # Challenge Origami (folding paper) is a creative form of art. As far as I know, master of Origami prefers square paper. Let's start from beginning - convert a rectangular paper to a square one. So the paper is divided into squares. We remove the biggest square which shares one shorter edge with the current shape, step by step (see the picture below). And if the remaining part after one step is less or equal than `0.001 * (area of the original paper)`, the paper cannot be divided any further. It is possible that nothing remains at last. Your task is to calculate how many squares are made during the process. The square in the last step that makes the paper unable to be divided is counted into the output. Example (a paper of `1.350` width/height), output is 10: [![slice example](https://i.stack.imgur.com/UTU9b.png)](https://i.stack.imgur.com/UTU9b.png) # Input and Output Input: width / height ratio for the rectangular paper, one decimal (or an integer without the dot) from `1.002` to `1.999` with a minimal step of `0.001`. You may also use any other reasonable format describing the ratio. Just mention it in your answer. Output: square count, one integer. # Example I/O A mapping format is used to keep the page tidy, while your code doesn't need to support a list input nor to be a mapping function. ``` 1.002 => 251 1.003 => 223 1.004 => 189 1.005 => 161 1.006 => 140 1.007 => 124 1.008 => 111 1.009 => 100 ``` [List of all answers](http://pastebin.com/e4UfWpvd) Thanks to @LuisMendo, here is the graph of answers. [![graph](https://i.stack.imgur.com/HNyUs.png)](https://i.stack.imgur.com/HNyUs.png) # Remarks * This is a code-golf so shortest code wins * Pay attention to standard loopholes * It's your freedom to decide how to deal with input and output but they should follow standard restrictions. By the way... * Comment if you have anything unclear about the challenge * Personally I would suggest your answer contains a explanation if you are using a golfing language * Thanks to @GregMartin, read his answer for a good mathematical explanation for the challenge. # Example Code Here is a ungolfed version of C++ code: ``` #include <iostream> #include <utility> int f (double m) { double n = 1, k = 0.001; int cnt = 0; k *= m; // the target minimum size while(m*n >= k) { m -= n; // extract a square if(n > m) std::swap(n, m); // keep m > n ++ cnt; } return cnt; } int main() { double p; std::cin >> p; std::cout << f(p); return 0; } ``` All calculations related in the example code need an accuracy of 6 decimal digits, which is covered in `float`. [Answer] # [Haskell](https://www.haskell.org/), ~~71 70 65 63 62 61 58~~ 56 bytes Thanks to @xnor for a some ingenious improvements! ``` (n#m)e|e>n*m*1e3=0|n<m=m#n$e|d<-n-m=(d#m)e+1 n!m=n#m$n*m ``` [Try it online!](https://tio.run/nexus/haskell#@6@Rp5yrmVqTapenlatlmGpsa1CTZ5Nrm6ucp5Jak2Kjm6eba6uRAlKjbciVp5hrC1SvAlT7PzcxM0/BVqGgtCS4pMgnT0FFoTgjvxxIaRgaGBgpAgkDzf8A "Haskell – TIO Nexus") [Answer] ## JavaScript (ES6), ~~59~~ 58 bytes ``` f=(m,n=!(k=m/1e3,c=0))=>m*n<k?c:(c++,m-=n)<n?f(n,m):f(m,n) ``` ### Test ``` f=(m,n=!(k=m/1e3,c=0))=>m*n<k?c:(c++,m-=n)<n?f(n,m):f(m,n) console.log(f(1.002)) console.log(f(1.003)) console.log(f(1.004)) console.log(f(1.005)) console.log(f(1.006)) console.log(f(1.007)) console.log(f(1.008)) console.log(f(1.009)) ``` [Answer] ## Mathematica, ~~64~~ 53 bytes ``` ({t=1,#}//.{a_,b_}/;1000a*b>#:>Sort@{++t;a,b-a};t-1)& ``` An imperative (C-style) solution is exactly the same length: ``` (For[t=a=1;b=#,1000a*b>#,If[a>b,a-=b,b-=a];++t];t-1)& ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 19 bytes ``` `SZ}y-htG/p1e-3>}x@ ``` The input is an array with the two numbers defining the original ratio, such as `[1, 1.009]`. (It is not necessary that the numbers be sorted or that one of them be 1.) [Try it online!](https://tio.run/nexus/matl#@58QHFVbqZtR4q5fYJiqa2xXW@Hw/3@0oY6CoZ6BgWUsAA "MATL – TIO Nexus") ### Explanation ``` ` % Do...while loop S % Sort array. Takes 1×2 array as input (implicit) the first time Z} % Split array into its 2 elements: first the minimum m, then the maximum M y % Duplicate m onto the top of the stack. The stack now contains m, M, m - % Subtract. The stack now contains m, M-m h % Concatenate into [m, M-m]. This is the remaining piece of paper t % Duplicate G/ % Divide by input, element-wise p % Product of array. Gives ratio of current piece's area to initial area 1e-3> % True if this ratio exceeds 1e-3. In that case the loop continues } % Finally (execute after last iteration, but still within the loop) x % Delete last piece of paper @ % Push current loop counter. This is the result % End (implicit) % Display (implicit) ``` [Answer] # C (GCC/Clang), ~~61~~ 59 bytes ``` c,k;f(m,n){for(k=m*n;m*n/k;m>n?(m-=n):(n-=m))++c;return c;} ``` Input is two integers (width & height) without dot, such as `f(1999,1000)`. I hope someone could save one byte pushing C into the 58-byte club. ;) [Answer] # C, 59 bytes ``` s,a,n=1e3;C(m){for(a=m;m*n>a;s++)m>n?m-=n:(n-=m);return s;} ``` [Try It online](https://tio.run/##NczBDoIwEATQO1/RkGh2pU2K3twUD3xJU8Fw2LVp8UT49oqKc5q8TCaYRwilZO21uHa4UA@My/hM4B0Tn6TzlJsGuZMbGydXEOMYKQ3zK4nKtJZJZsV@EsBqqdSWD0T61hy8jFAf7rVWx4g/jGlb/LWHiLvvn5aqtbTWnt8) The input is an integer which is the width / height ratio in thousandths (eg. 1002 for 1.002:1). ### Ungolfed version ``` int C(int m) { int n = 1000; int a = m; int s = 0; while (m * n > a) { if (m > n) m -= n; else n -= m; s++; } return s; } ``` ]
[Question] [ **EDIT: I will be accepting an answer Monday, 2/15/2016. May the bytes be ever in your favor!** In his ["Print the N-Bonacci Sequence" challenge](https://codegolf.stackexchange.com/questions/70476/print-the-n-bonacci-sequence?noredirect=1#comment172535_70476), @DJMcGoathem describes the N-bonacci sequences, wherein the previous *N* numbers are summed, instead of the traditional 2 of the Fibonacci sequence (said to be the "*duo*nacci sequence"). He then asked to take two inputs, X and N, then output the *X*th *N*-nacci number. I propose the opposite. Given a sequence, output which *N*-nacci sequence it is a subset of. I say "subset of" because: * A) these sequences are infinite * B) if given the start of the sequence, you could just count the number of leading 1s **In the case that it could belong to multiple *N*-nacci sequences, chose the lowest one.** **In the case that it does not belong to any *N-nacci* sequence, then your program may do anything other than print something that could be mistaken for output.** These behaviors include (but are not limited to): infinite loop, error, crash, delete itself (\*cough cough\* [vigil](https://github.com/munificent/vigil) \*cough cough\*), or create a black hole (as long as this black hole does not produce anything that could be mistaken for valid output). **For the sake of this challenge, these sequences start with 1.** This means any *N*-nacci sequence starts with *N* ones. Furthermore, *N* must be a positive integer. So no **-1**-nacci, etc. Test cases: ``` 1,1,1 -> 1 49, 97 -> 7 55, 89, 144 -> 2 1 -> 1 6765 -> 2 12, 23, 45, 89 -> 12 100, 199 -> 100 ``` [Answer] ## Ruby, 94 I'm quite surprised how far I've been able to golf this within the same algorithm! I started with over 200! ``` ->a{1.step.find{|s|x=[1]*(s+z=a.size) x<<x[-s,s].inject(:+)while x.max<a.max&&s>1 x[-z,z]==a}} ``` Ungolfed: ``` l=->a{ # ooh! a built-in infinite incrementer! 1.step.find{|s| # if n == 1, z is important, otherwise s. x=[1]*(s+z=a.size) ## add the next nacci number until we hit or overshot max. ## if s == 1, we don't increment, so don't bother x<<x[-s,s].inject(:+)while x.max<g&&s>1 # eval to true if there's a match, false if not x[-z,z]==a } } ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 46 bytes ``` {∧/0<⍵:⊃⊃⍸A⍷↑{⍵((+/↑),⊢)⍣{</+/¨A⍵}⍵⍴1}¨⍳⊃A←⌽⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRx3J9A5tHvVutHnU1g1DvDsdHvdsftU2sBgpqaGjrA5maOo@6Fmk@6l1cbaOvrX9oBVDF1logftS7xbD20IpHvZuBOh0ftU141LMXJPU/DcTu7QObtwao6tB6Y6Axj/qmBgc5A8kQD8/g/2kKQBZQnaECEHLBeCaWCpbmcJ6pqYKFpYKhiQlc5FFXkyEyx8TQAsE3NFIwMlYwAWlCiBkYKBhaIvimCiYKxnCegQIQckHY6grqcHGggxUOrTcCYkOELAA "APL (Dyalog Unicode) – Try It Online") Anonymous prefix function, taking a vector of integers. ### How? ``` ∧/0<⍵: ⍝ If the given sequence contains any non-positive integers, then return nothing. Otherwise... A←⌽⍵ ⍝ Set A to be the reverse of the given sequence {...}¨⍳⊃ ⍝ For each n in 1 to last element of given sequence, we generate the n-bonacci sequence in reverse order: ⍵⍴1 ⍝ Initialize a vector of n 1s (first n terms of the n-bonacci sequence) ⍣ ⍝ Do: ⍵((+/↑),⊢) ⍝ Prepend the sum of the most-recent (first) n elements of the vector to the rest of the vector ⍝ While {</+/¨A⍵} ⍝ the sum of the n-bonacci sequence generated so far is less than the sum of A ⍝ (this doesn't terminate prematurely because: ⍝ For n=1, this produces k+2 1s if A consists of k 1s ⍝ Otherwise, worst-case is that A has 1 element ⍝ For n=2, F_0+F_1+F_2 ... + F_{k-2} = F_k (identity) ⍝ F_0 + ... F_{k-1} > F_k, and APL terminates the ⍣-loop in the next step, ⍝ after F_k generated ⍝ For n>2, F_0+F_1+F_2 ... + F_{k-2} < F_k, so an excess of terms are generated ⍝ ) ↑ ⍝ Mix to form a matrix, where the n-th row is the n-bonacci sequence ⍸A⍷ ⍝ Find the (row, column) positions of A in the matrix ⊃⊃ ⍝ Take the row of the first one (which would have minimum n) ``` [Answer] # Python 2, 176 bytes ``` def r(n,x):i,f=n,[1]*n;exec"f+=sum(f[i-n:]),;i+=1;"*(x-n);return f l=input() m=max(l)+len(l) for i in range(1,m): if any(l==r(i,m)[b:b+len(l)]for b in range(m)):print i;break; ``` Note that this requires input in this format: ``` [1, 1, 2, 3...] ``` rather than ``` 1, 1, 2, 3... ``` Fairly straightforward solution, just to get things rolling. I'll work more on golfing it down once somebody else answers. This uses a slightly modified version of the N-Bonnaci generator from [@Data's answer](https://codegolf.stackexchange.com/a/70482/31716), so props to him. Then for each N-Bonnaci in range of the input, checks if the input is a subsequence of it. [Answer] # Lua, ~~324~~ 323 Bytes When I see other submission, I feel like there's something wrong with my code... But then, I remember that's Lua, and there's isn't all these fancy functionnalities :'( It was a lot of fun, took me some time actually. **Edit: Saved 1 byte with a simple trick: using a `::label::`+`goto label` instead a infinite loop done with `while''`.** ``` function f(l)c=2 y,z=table.remove,os.exit while(l[1]<2)do y(l,1)if(#l<1)then print(1)z()end end ::q:: a={}for i=1,c do a[i]=1 end b={}for i=1,#l do b[i]=l[i]end while(a[#a]<b[1])do x=0 for i=(#a-c+1>0 and #a-c+1 or 1),#a do x=x+a[i]end a[#a+1]=x if a[#a]==b[1]then y(b,1)end if #b<1 then print(c)z()end end c=c+1 goto q end ``` ### Ungolfed and Explanations Lua has no way to define a set, subset, or even check if an array/table contains a value without using its index/key. That's why i've decided to remove elements from the array I take as a parameter. that's how I keep record of which elements has already been computed, and if it matched. ``` function f(l) c=2 y,z=table.remove,os.exit -- Create pointers on table.remove and os.exit -- saves a total of 9 bytes while(l[1]<2) -- loop used to remove leading 1 do y(l,1) if(#l<1) -- we also check if it was a 1-only array then print(1) -- if so, we print 1 and exit z() end end ::q:: -- label q, start of the infinite loop a={}for i=1,c do a[i]=1 end -- fill an array with c 1s b={}for i=1,#l do b[i]=l[i]end -- copy the sequence array while(a[#a]<b[1]) -- while max(a)<min(b) do x=0 for i=(#a-c+1>0 -- iterate from index a.length-c to and #a-c+1 -- to a.length or 1),#a do x=x+a[i] -- summing a's elements end a[#a+1]=x -- append x to a if a[#a]==b[1]then y(b,1)end -- if x is equal ot a member of the sequence -- remove it if #b<1 then print(c)z()end -- if b is empty, it means the subset is in a -- we print c and exit end -- else we loop again c=c+1 -- with c+1 goto q -- return to the start of this block end ``` You can try [Lua online](http://www.lua.org/cgi-bin/demo), and you can copy/paste the following code sample to run some tests. As this function exit when it founds the answer (infinite loop otherwise), you will have to change the index of `test[]` used (don't forget lua is 1-indexed :)). ``` function f(l)c=2 y,z=table.remove,os.exit while(l[1]<2)do y(l,1)if(#l<1)then print(1)z()end end ::q:: a={}for i=1,c do a[i]=1 end b={}for i=1,#l do b[i]=l[i]end while(a[#a]<b[1])do x=0 for i=(#a-c+1>0 and #a-c+1 or 1),#a do x=x+a[i]end a[#a+1]=x if a[#a]==b[1]then y(b,1)end if #b<1 then print(c)z()end end c=c+1 goto q end test={{1,1,1}, {49, 97}, {55, 89, 144}, {1}, {6765}, {12, 23, 45, 89}, {100, 199}} print(f(test[1])) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes ``` (n=1;While[!SubsetQ[LinearRecurrence[s=1~Table~n,s,Max@l],l=#],n++];n)& ``` [Try it online!](https://tio.run/##VYy9CoMwFEb3PkVKobR4B2OjNkjAB2ihf9AhOES5aCBm0AiFUl89lS4lfNs5nK9XrsNeOd0o34rrpNGVfmcFLZ6dNijX96ke0V3lSVtUww2baRjQNihHQeeHqg3OFkY4q1dpKjBiU4GNoqqw@62/DNo6UrbyTWHZp1r9CePA84CkKZAjB0IZC3jYZXmWhjoBkhyAsF8eqjhe7vgCvf8C "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ ## The size of the moon mystery I am sure you have heard that the moon changes its size. When you're in love and you're lucky, the moon is almost twice in size compared to normal situations. Some people say the reason is the atmosphere which acts as a lens. Others think that it is only a matter of comparison to other objects such as trees nearby. Whatever explanation you read, it's quite subjective. ## The size of the moon science Ok, we're programmers, aren't we? We rely on facts, right? So here's the experiment: 1. Take a nice camera which supports setting time and aperture manually. 2. Set your camera to maximum zoom level. 3. Go out, take some photographs of the moon in order to detect the best settings so that the moon is sharp and lighting is just fine. 4. Remember the settings 5. Take photos of the moon with those settings every time you think the moon is large or small. 6. Calculate the size of the moon in pixels The camera won't lie, would it? By counting the bright pixels we can effectively measure the size of the moon - at least in pixels. If the size is the same across all photos, then it's a bug in our brain. If the size differs, then there's room for speculation * the moon really grows (but what does it eat?) * there's an atmospherical lens effect * the moon has an elliptical curve and is sometimes nearer, sometimes further away from earth * ... But I'll leave that open until your task is completed. Of course you want to know in advance if your software can calculate the moon size accurately. ## The task Given a few optimized pictures of the moon, please calculate the size of the moon. The optimization is: the pixels are either black or white. Nothing in between. No antialiasing. That makes it easy, doesn't it? The caveat: the moon is not always full, you know ... it can be a sickle! But even in shape of a sickle, the size of the moon is larger. So you'll calculate the full size, please. * Your program takes a PNG as input, e.g. as file name command line argument, piped into `stdin` or as a Bitmap object (of a standard framework library) if you write a function instead of a program. * Your program works with any reasonable input bitmap size, not necessarily square. Minimum width and height of 150 pixels are guaranteed. * The full moon covers at least 25% of the picture. * Your program outputs the calculated size of the moon in pixels as if it were a full moon. * We assume that the moon is a perfect sphere. * The exact size is always an integer number, but you can output a decimal number if your calculation returns that. * The accuracy should be between 98% and 102%. (That's rather a guess than something I could guarantee to be achievable. If you think it's too hard to reach, please leave a comment.) **Update**: * The center of the moon isn't necessarily in the middle of the picture. * The minimum visible area is 5% of the moon or 1.25% of the total number of pixels. * The picture is taken in a way that the whole moon would fit the image, i.e. the total number of pixels is an upper boundary for the moon size. * The moon will not be cropped / clipped. ## The samples You can generate your own samples using [the blend file](http://46.38.245.27/stackoverflow/Moon.blend) if you like. I have created the following pictures for you. You can count pixels in a PNG file using [WhitePixelCounter.exe](http://46.38.245.27/stackoverflow/WhitePixelCounter.exe) (needs .NET) to check whether the image contains black and white pixels only and how many of them. The following 256x256 pixel images differ in the amount of white pixels, but should all result in a calculated moon size of 16416 pixels. ![Full moon](https://i.stack.imgur.com/fK3wF.png) ![Moon](https://i.stack.imgur.com/jjjLK.png) ![Moon](https://i.stack.imgur.com/NMRLI.png) ![Moon](https://i.stack.imgur.com/0pBfD.png) ![Moon](https://i.stack.imgur.com/d9xG8.png) ![Moon](https://i.stack.imgur.com/B10R3.png) And these 177x177 pixel images should return 10241 pixels. The images are basically the same, but this time a camera with a different focal length was used. ![Moon](https://i.stack.imgur.com/EFfkg.png) ![Moon](https://i.stack.imgur.com/BsQnh.png) ![Moon](https://i.stack.imgur.com/ddsi1.png) ![Moon](https://i.stack.imgur.com/FPTjB.png) ![Moon](https://i.stack.imgur.com/nK2P6.png) ![Moon](https://i.stack.imgur.com/0UaEe.png) Non-square and non-centered samples with a result of 9988: ![Moon in a non-square frame](https://i.stack.imgur.com/rufye.png) ![Moon in a non-square frame](https://i.stack.imgur.com/2PSpe.png) ![Moon in a non-square frame](https://i.stack.imgur.com/gFsjD.png) ![Moon in a non-square frame](https://i.stack.imgur.com/dq1Su.png) ![Moon in a non-square frame](https://i.stack.imgur.com/mU9ky.png) Oh, I don't have a reference implementation for now and I even don't know whether I am able to implement something. But in my brain there is a strong belief that tells me it must be mathematically solvable. ## The rules This is Code Golf. The shortest code on 2015-03-30 gets accepted. [Answer] # Mathematica ~~126 119~~ 109 bytes Mathematica can measure the elongation of a component in an image. A full moon, being perfectly symmetric, has an elongation of 0, on a scale of 0 to 1. A diminishing moon becomes increasingly elongated, to a maximum of roughly 0.8. `0.998 -0.788 x-0.578 x^2` was the empirically determined model (based on the large photos) for `predicting the fullness of the moon (by area), given its elongation. I adjusted the model to `1- 0.788 x -0.578 x^2` so that with exactly zero elongation (full moon) the model will return 1 for the pixel scale factor. It saves 4 bytes and still stays within the accuracy limits. This model is used for any size images. The moon image does not need to be centered. It also does not need to cover a fixed proportion of the photo. Here are the data points (elongation, displayedMoonPixels/fullMoonPixels) for the large images and the parabolic model that was generated to fit the data. Linear models fit ok, but the quadratic model is dead on, within limits (see below). Here the data are from the large pictures. So is the model ![large crescents](https://i.stack.imgur.com/Ztr6I.png) --- Below, the data (the red points) are from the small pictures. The model (the blue curve) is the one generated by the large pictures, the same one as displayed above. The smallest crescent has 7.5% the area of a full moon. (The smallest crescent among the large photos is 19% of a full moon.) If the quadratic model had been based on the small photos the fit below would be better, only because it accommodated the small crescent. A robust model, that would stand up under a wide range of conditions, including very small crescents, would be better made from a larger variety of pictures. The closeness of fit shows that the model was not hard-coded for the given pictures. We can be fairly certain that the elongation of a moon is independent of the size of the photo, as one would expect. ![small crescents](https://i.stack.imgur.com/xFHE3.png) `f` takes the image, `i`, as input and outputs the predicted size of the full moon, in pixels. It works for off-center shots. As the data below show, it all of the test cases except one. The moons were arranged from full to most diminished. ``` i_~c~t_ := Max@ComponentMeasurements[i, t][[All, 2]]; f@i_ := i~c~"Count"/(1 - 0.788 x - 0.578 x^2 /. x -> i~c~"Elongation") ``` More than one image component may turn up in a photo. Even a single pixel separated from the others will be considered a distinct component. For this reason, it is necessary to search "all" components, to find the one that has the greater number of pixels. (One of the small photos has more than one image component.) **Large pictures** Predictions of moon size made from the large photos were uniformly accurate. ``` {"predicted size of full moon", f[#] & /@ large} {"accuracy", %[[2]]/16416} ``` > > {"predicted sizes of full moon", {16422., 16270.9, 16420.6, 16585.5, 16126.5, 16151.6}} > > > {"accuracy", {1.00037, 0.991161, 1.00028, 1.01033, 0.982367, 0.983891}} > > > --- **Small pictures** Predictions of moon size made from the small photos were uniformly, with one great exception, the final picture. I suspect the issue stems from the fact that the crescent is very narrow. ``` {"predicted sizes of full moon", f[#] & /@ small} {"accuracy", %[[2]]/10241} ``` > > {"predicted sizes of full moon",{10247.3, 10161., 10265.6, 10391., 10058.9, 7045.91}} > > {"accuracy", {1.00061, 0.992192, 1.0024, 1.01465, 0.982221, 0.68801}} > > > [Answer] # J, ~~227~~ 207 bytes (maximal error 1.9%) My main idea is that if we can find 3 points on the contour of the moon which are on the contour of the full moon too we can [compute the circumcircle](http://en.wikipedia.org/wiki/Circumscribed_circle#Triangles) of these points. That circumcircle will be to full moon. If we find two white points with maximal distance those will always be such points as they will be either a real diagonal in the full moon or the endpoints of the crescent. ~~We can find the pair of points with the greatest distance in any graph by selecting the point furthest from any given starting point and then selecting the point furthest from the selected one.~~ We find a third point with a maximal value of the products of the distances from the previous points. This will always be on the contour and on the outer side of a crescent or the bigger side of a gibbous. The diameter of the circumcircle is computed as the length of one side divided by the sinus of the opposite angle. The time-complexity of this method is linear in the size of the input image. ## Code ``` f=.3 :0 load'graphics/png' i=.readpng y p=.(,i=_1)#|:,"%.0 1|:,"0/&>/<@i."*$i s=.%:+/|:*:(-1|.]) (([,],:m@(*&d))(m@d))(m=.p{~(i.>./)@])(d=.+/@:*:@((|:p)-])) 0{p o.*:-:({.s)%0 o.((+/-2*{.)*:s)%2**/}.s ) ``` The function expects the input filename as a string. (For a (little) more readable version check revision history.) ## Code explanation * p is a list of white pixel coordinates (called points in the future) * function d computes distances between elements of p and a given point * the second part of the definition of s creates a 3-point list: + A is the furthest point from the first point in the list + B is the furthest point from A + C is a point with a maximal value of distance form A times distance from B * s is the side-lengths of triangle ABC * the last line computes the area of the circumcircle of ABC which is the full moon ## Results The largest error is 1.9%. Images are in the same order as in the question. ``` Output Accuracy ---------------- 16407 0.999453 NB. Large images 16375.3 0.997523 16223.9 0.988301 16241.5 0.989369 16262.6 0.990654 16322.1 0.994279 10235.3 0.999445 NB. Small images 10235.3 0.999444 10221.2 0.998067 10220.3 0.997978 10212 0.997169 10229.6 0.99889 9960.42 0.997239 NB. Offset images 9872.22 0.988408 10161.8 1.0174 9874.95 0.988681 9805.9 0.981768 ``` [Answer] # Matlab ~~162~~ 156 (not quite in the current error margin) First of all: The accuracy is under 2% for all but one image in each of the two series, where it is greater (about 5% and 14%). My approach was finding the two pixels of the moon that are the furthest away from each other, and then using this as an estimate for the diameter. ``` a=imread(input('')); %read input image b=a(:,:,1)>0; %binarize red channel s=size(b); %get size of the image [x,y]=meshgrid(1:s(1),1:s(2)); z=(x+i*y).*b;z=z(z~=0); %find the coordinates of all white pixels (as a list) o=ones(size(z(:)))*z(:)'; disp(max(max(abs(o-o.').^2))*pi/4); %calculate the maximum of the distance between each possible pair and evaluate area formula ``` These are the accuracy results (reltative deviation `1 - (predicted size / real size)`) ``` 0.0006 0.0025 0.0169 0.0500 0.0521 0.0113 0.0006 0.0006 0.0026 0.0472 0.1383 0.0131 ``` [Answer] ## C# - 617 This solution does not work for all images, because on one of the images, the slope (m) becomes infinity. The principle was mentioned before: 1. Find two points with maximum distance (red) 2. Imagine a line between them (red) 3. Imagine a line with rectangular angle in the middle (green) 4. Find white points on the green line 5. Use the one with maximum distance from other points (green) 6. Calculate the area of a circle from three points ![Explanation](https://i.stack.imgur.com/9hqgC.png) The problematic case is this one, where the slope is infinity. It is possible to workaround by rotating the image 90° or in code, loop over the `y` axis instead of `x`. ![Problematic moon](https://i.stack.imgur.com/xnkSi.png) ``` double A(Bitmap b){var a=new List<P>();for(var y=0;y<b.Height;y++)for(var x=0;x<b.Width;x++)if(b.GetPixel(x,y).R>0)a.Add(new P{x=x,y=y});double c=0.0,d=0.0,e=0.0,f=0.0,g=0.0,n=double.MaxValue;foreach(var h in a)foreach(var i in a){var t=Math.Sqrt(Math.Pow(h.x-i.x,2)+Math.Pow(h.y-i.y,2));if(t>c){d=h.x;f=i.x;e=h.y;g=i.y;c=t;}}c=(f-d)/(e-g);for(int x=0;x<b.Width;x++){int y=(int)(c*x+((e+g)/2-c*(d+f)/2));if(y>=0&&y<b.Height&&b.GetPixel(x,y).R>0){var s=(g-e)/(f-d);var q=(y-g)/(x-f);var j=(s*q*(e-y)+q*(d+f)-s*(f+x))/(2*(q-s));var k=-(j-(d+f)/2)/s+(e+g)/2;var l=(j-d)*(j-d)+(k-e)*(k-e);if(l<n)n=l;}}return Math.PI*n;} ``` The minimum accuracy is * +1,89% for the 256 pixel images * -0.55% for the 177 pixel images * -1.66% for the non-square images ]
[Question] [ After [@MartinBüttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) achieved [exactly 10,000 reputation](http://chat.stackexchange.com/transcript/message/16950428#16950428), we now have three full rows of 10k users on the [users page](https://codegolf.stackexchange.com/users?tab=Reputation&filter=all)! Now, since we're all programmers here, we like to automate things instead of doing them manually. Your challenge is to write a program to automatically congratulate new 10k users. ## Specification ### Input The input will be `n` lines of space-separated numbers. (If you would like, you may also take a single comma-separated list of space-separated numbers, if that makes your code shorter.) For example: ``` 10 20 30 40 50 15 25 35 45 55 20 30 40 50 60 ``` Or: ``` 10 20 30 40 50,15 25 35 45 55,20 30 40 50 60 ``` Each list of numbers represents a list of users' reputation values on a single day. ### Output The output will be the same amount of `n` lines (or a comma-separated list of the same length). Each line / list item will be: * `:D` if there was a user whose reputation just became >= 10,000. + Multiple space-separated `:D`s if there were multiple users who met or passed the 10,000 rep count. For example, `:D :D :D` for 3 new 10k users. * `:(` and then halt further output if the input is ambiguous or impossible (more on this in the next section). * nothing if neither of these conditions is true. ### Ambiguity It is possible that the input is ambiguous. For the purposes of this challenge, we assume that: * The reputation cap is 200 per day, ignoring accepts and bounties and the like for the sake of the challenge. * Users may not lose reputation (again for simplicity and for the challenge). Input is considered ambiguous when it is impossible to determine which reputation values correspond to which user. For example, in the input `10 20,30 40`, you can't tell whether the 10-rep user became the 30-rep user or the 40-rep user. Input is considered impossible when the users from one day could not possibly have become the users from the next day. For example, in the input `10 20,310 320`, this situation is clearly impossible because the users could not have gained 300 reputation in a day. Users losing reputation is also impossible. ### Edge cases * The initial reputation values can start at anything (i.e. a user can start with 1337 reputation). * There is no output for the first line / list item. * The input will always be syntactically valid, meaning that the reputation values will always be positive integers, there will always be the same amount of reputation values per line / list item, etc. * The reputation values are not sorted; they may be in any order. ## Test cases Input: `9900,10000` Output: `:D` Input: `9900 9950 9910,10100 9950 9910,10300 10150 10110` Output: `:D,:D :D` Input: `10 20 30,42 10 20,10 242 20,442 42 10,0 0 0,442 42 10` Output: `,,,:(` Input: `10 20,15 25,15 25` Output: `,,` Input: `9999 9998 9997,10000 9998 9997,10000 10000 9997,10300 10000 10000` Output: `:D,:D,:(` Input: `100,90,80,70` Output: `:(` Input: `10000 10000 10000 9999,10000 10000 10000 10000,10010 10020 10030 10040` Output: `:D,:(` Input: `9999 9998 9997 9996,10196 10197 10198 10199,10399 10199 10197 10196` Output: `:D :D :D :D,` [Answer] ## Ruby, 209 bytes **Edit:** I switched to Ruby which shortened this by about 30%. See the edit history for the original Mathematica version. I suppose the main savings come from Ruby's `permutation` not ignoring switched positions of identical elements (which I had to trick Mathematica into). This uses the newline-separated format. ``` gets.split(' ').map{|s|s.split.map &:to_i}.each_cons(2){|a,b|a.permutation.map{|q|q.zip(b).map{|x,y|y-x}}.reject{|d|d.any?{|x|x<0||x>200}}.size!=1?abort(':('):(puts':D '*(a.count{|d|d<1e4}-b.count{|d|d<1e4}))} ``` The gist is this: * Get all consecutive pairs of days. * Get all permutations of the former day, and subtract each of these from the current day. * Ditch all results which contain differences that are negative or greater 200. * If the number of remaining permutations isn't 1, output `:(`. * Otherwise, output as many `:D` as there are new 10k users. * At the end, drop all days after the first `:(`. Less golf: ``` gets.split("\n").map{|s| s.split.map &:to_i }.each_cons(2){|a,b| a.permutation.map{|q| q.zip(b).map{|x,y| y-x } }.reject{|d| d.any?{|x| x<0||x>200 } }.size!=1 ? abort(':(') : (puts ':D '*(a.count{|d|d<1e4}-b.count{|d|d<1e4})) } ``` I think that's one beautiful chain of enumerators. :) PS: Is it weird that *I* was the first one to submit an answer to this? [Answer] # Haskell, ~~254 249 244 232~~ 228 ``` import Data.List t=m(9999<) p(a:b:r)=(a,b,r)%(filter(all(`elem`[0..200]))$nub$m(zipWith(-)b)$permutations a) p _="" (a,b,r)%(_:[])=(concat$m(const":D ")$t b\\t a)++'\n':p(b:r) _%_=":(" m=map main=interact$p.m(m read.words).lines ``` A little explanation: The algorithm is very similar to that used by MartinBüttner, except the `nub` that I spent some thought on. Note that a list difference is used for working out how many more reputation values are 10000 or larger on day n+1 compared to day n: `t b\\t a`. I also agree with MartinBüttner on the interpretation of the specs and that some of the examples above are wrong, even to the point that example #2 is wrong (should be `:(`). ]
[Question] [ In Chess, it's possible for the game to end after 4 moves (2 each) with a [Fool's Mate](http://en.wikipedia.org/wiki/Fool's_mate). Your goal is to find the Fool's Mate of [Halma](http://en.wikipedia.org/wiki/Halma): the 2-player game of Halma that minimises the number of turns played. There are over 1056 board states, and I've seen the branching factor surpass 1000, so chances are no one will find the optimal solution. Instead, you're trying to find the best solution you can. You should submit a list of moves, and any code you used to generate those moves. ## Explanation of the Game Halma is similar to Chinese Checkers, but played on a 16\*16 square board. Initially, the board looks like this: ![Starting Board](https://i.stack.imgur.com/WRatf.png) The goal of the game is to move all your pieces to the starting positions of your opponent's pieces. On a player's turn, he/she may: * Pass the turn * Move one of his/her pieces to an adjacent empty space. Adjacent spaces include diagonals. * Take one of his/her pieces and do the following any number of times: Jump the piece over an adjacent piece, landing it on the space opposite the piece jumped over. Here's an example to illustrate the 2nd type of move. ![Jumps](https://i.stack.imgur.com/6lWZG.gif) ## Rules Submit a list of legal moves which result in the game ending. Submit any code you used to generate the list. If you obtain a better result from someone else's code, post the result in a comment or edit their post with the new results. Each move must be either `None` to pass the turn, or `(x1,y1,x2,y2)` to move a piece, where `(x1,y1)` are the coordinates of the piece to move and `(x2,y2)` are the destination of that piece (for jump moves, ignore intermediate coordinates). The coordinates start at `(0,0)` at the top left corner. x-coordinates increase to the right, y-coordinates increase downward. Moves should be separated by newlines. You can use [this python script](http://pastebin.com/KDUswHt7) to verify your moves. Use `python halma_verify.py < file` to verify moves in `file`. Shortest list wins. [Answer] # The shortest game of halma is 49 moves [49 move solution](https://rawgit.com/thospel/personal-halma/master/solutions/halma-X16Y16Army19Rule8_49.html) [Proof there is no 48-move solution](https://rawgit.com/thospel/personal-halma/master/failures/halma-X16Y16Army19Rule8_48.html) [Code used for this solution](https://github.com/thospel/personal-halma) The code now supports pass Notice that the 47 move solution in the paper is for the army transfer problem, not for the shortest game of halma I'll hopefully get to doing a proper writeup this weekend ]
[Question] [ Generate a 4x12 grid of letters / spaces: Each die should appear precisely once, location randomly chosen. Locations should be approximate a uniform random permutation of the dice. Display a random (again, approximately uniform) face of each die. Left-justify the face in the 3-character window. For example, ``` A E A A E C D E D A Qu E E A H D ``` Is a non-randomized board in the format I want. Trailing space is allowed. The dice: ``` A A E E G N E L R T T Y A O O T T W A B B J O O E H R T V W C I M O T U D I S T T Y E I O S S T D E L R V Y A C H O P S H I M N Qu U E E I N S U E E G H N W A F F K P S H L N N R Z D E I L R X ``` Amusing fact: there is only 1 K in the set. What other letter exclusively shares that die? This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the program with the shortest bytecount wins! [Answer] ## GolfScript, 116 bytes Since the scoring is in bytes, I figure that means we can use *all* bytes in the solution. Going outside the printable ASCII set allows a somewhat shorter solution than [Peter Taylor's](https://codegolf.stackexchange.com/a/4861), at the cost of making the code harder to display here. Without the unprintable data, my code looks like this: ``` '57 BYTES OF BINARY DATA HERE'256base 26base 6/{;9.?rand}${6rand=65+.81=' u '2/=}%8/n* ``` It's pretty similar to Peter Taylor's solution, and I admit to shamelessly borrowing bits of it (such as the `.81=' u '2/=` trick), although I think I managed to shorten his shuffle slightly, even after spending an extra ~~char~~ byte for better randomness. The binary string in the beginning of the script contains unprintable characters, and so cannot be directly pasted here. Instead, I'll provide the script as a hex dump: ``` 0000000: 2701 8302 7c56 97d5 ec9c 52e3 462e 44d7 '...|V....R.F.D. 0000010: a8d2 81c9 6115 fc80 4da4 6cd3 b06f a6d8 ....a...M.l..o.. 0000020: 4e7e 2029 12a9 f331 0b83 3481 de36 81e2 N~ )...1..4..6.. 0000030: 41b4 534d dee8 13f7 ccfd 2732 3536 6261 A.SM......'256ba 0000040: 7365 2032 3662 6173 6520 362f 7b3b 392e se 26base 6/{;9. 0000050: 3f72 616e 647d 247b 3672 616e 643d 3635 ?rand}${6rand=65 0000060: 2b2e 3831 3d27 2020 7520 2732 2f3d 7d25 +.81=' u '2/=}% 0000070: 382f 6e2a 8/n* ``` On Linux, or any system with the `xxd` utility installed, this hex dump can be turned back into a working 116-byte GolfScript program by passing it through `xxd -r`. **Edit:** Replaced `999rand` with `9.?rand` for *much* better randomness. The shuffle should now be about as close to perfect as the underlying RNG allows. [Answer] ## Python 2.7, ~~253 229~~ 215 chars ``` from random import* j=0 for x in map(choice,sample("AAEEGN ELRTTY AOOTTW ABBJOO EHRTVW CIMOTU DISTTY EIOSST DELRVY ACHOPS HIMNQU EEINSU EEGHNW AFFKPS HLNNRZ DEILRX".split(),16)):j+=1;print x+' u'[x=='Q']+'\n'[j%4:], ``` Most of the characters are just the dice themselves. I didnt want to spend too much time trying to reduce it too much minor edit: removed 2 unnecessary bytes (extra spaces) edit2: down to 229 edit3: down to 215 [Answer] ## GolfScript (141 139 137 charsbytes) Of which 94 expand to the string containing the dice. Figure doesn't include the unnecessary newline inserted to make it wrap so that the code can be seen without scrolling: ``` 'Y ISY XIAOOW VYAAEEGNABBJOOEHRTVWCIMOTUEIOSSTACHOPSHIMNQUEEINSUEEGHNWAFFKPSHLNNRZ'n/'TTELRD'* 6/{[6rand=99rand\]}%${1=.81=' u '2/=}%8/n* ``` [Answer] ## Ruby, ~~201~~ 197 chars ``` %W(AAEEGN ELRTTY AOOTTW ABBJOO EHRTVW CIMOTU DISTTY EIOSST DELRVY ACHOPS HIMNQU EEINSU EEGHNW AFFKPS HLNNRZ DEILRX).sample(16).map{|c|c[rand 6]}.each_slice(4){|x|puts x.join(" ").gsub(/Q ?/,"Qu")} ``` (and it's a one-liner) Edit 1: Used %W() to avoid the .split and a pair of quotes. Edit 2: Made it to spec (two spaces between each output column) [Answer] ## Powershell, 234 characters ``` $d=(0..15|%{@{'AAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTYEIOSSTDELRVYACHOPSHIMNQUEEINSUEEGHNWAFFKPSHLNNRZDEILRX'[6*$_+(random)%6]=random}.GetEnumerator()}|sort Value|%{$_.Key}) 0..3|%{($d[($_*4)..($_*4+3)])-join" "-replace'Q ','Qu'} ``` Here's the same code with extra whitespace, in an attempt at improving readability :-) ``` ######################################### # roll the 16 dice and shuffle them # ######################################### $d=( 0..15 | % { @{ 'AAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTYEIOSSTDELRVYACHOPSHIMNQUEEINSUEEGHNWAFFKPSHLNNRZDEILRX'[6*$_+(random)%6]=random }.GetEnumerator() } | sort Value | % { $_.Key } ) ############################################ # add the 16 results to the 4 by 4 grid # ############################################ 0..3 | % { ($d[($_*4)..($_*4+3)]) -join " " -replace 'Q ','Qu' } ``` I'm not aware of a built in `shuffle` feature in powershell, so I turned each result into a key-value pair - the key equalling a dice result and the value equalling a random number. Then it was just a case of sorting these pairs by the value then outputting the keys. [Answer] ## Perl, 179 chars ``` @d=(Qu,map"$_ ",HIMNUAAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTYEIOSSTDELRVYACHOPSEEINSUEEGHNWAFFKPSHLNNRZDEILRX =~/./g);print+(splice@d,6*int rand@d/6,6)[rand 6],@d%24?$":$/while@d ``` Here's a verbose version of the program: ``` my $fullset = "HIMNUAAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTY" . "EIOSSTDELRVYACHOPSEEINSUEEGHNWAFFKPSHLNNRZDEILRX"; my @dice = ("Qu"); push @dice, "$_ " for split //, $fullset; while (@dice) { my @die = splice @dice, 6 * (int rand @dice / 6), 6; print $die[rand 6]; print @dice % 24 ? " " : "\n"; } ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 85 bytes ``` «3꘍Ẋʀɖ>¯ɖ\4ȧḊ#⅛F>ẇ#₂⟑†ql~-ṡ²<vŻ%)∆₆U÷↵ʁʀeµṘbD{⇧½⁰ṙ⟩ĊI3≥⁰?λ«16/v℅Ṗ℅4ẇƛ÷W‛ j;⁋⇧‛Q ‛QuV ``` [Don't try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AB3%EA%98%8D%E1%BA%8A%CA%80%C9%96%3E%C2%AF%C9%96%5C4%C8%A7%E1%B8%8A%23%E2%85%9BF%3E%E1%BA%87%23%E2%82%82%E2%9F%91%E2%80%A0ql%7E-%E1%B9%A1%C2%B2%3Cv%C5%BB%25%29%E2%88%86%E2%82%86U%C3%B7%E2%86%B5%CA%81%CA%80e%C2%B5%E1%B9%98bD%7B%E2%87%A7%C2%BD%E2%81%B0%E1%B9%99%E2%9F%A9%C4%8AI3%E2%89%A5%E2%81%B0%3F%CE%BB%C2%AB16%2Fv%E2%84%85%E1%B9%96%E2%84%854%E1%BA%87%C6%9B%C3%B7W%E2%80%9B%20%20j%3B%E2%81%8B%E2%87%A7%E2%80%9BQ%20%E2%80%9BQuV&inputs=&header=&footer=) Because it breaks the interpreter trying to handle 16! permutations of the dice at once. Would work given enough memory + time though. [Try this one that doesn't shuffle online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AB3%EA%98%8D%E1%BA%8A%CA%80%C9%96%3E%C2%AF%C9%96%5C4%C8%A7%E1%B8%8A%23%E2%85%9BF%3E%E1%BA%87%23%E2%82%82%E2%9F%91%E2%80%A0ql%7E-%E1%B9%A1%C2%B2%3Cv%C5%BB%25%29%E2%88%86%E2%82%86U%C3%B7%E2%86%B5%CA%81%CA%80e%C2%B5%E1%B9%98bD%7B%E2%87%A7%C2%BD%E2%81%B0%E1%B9%99%E2%9F%A9%C4%8AI3%E2%89%A5%E2%81%B0%3F%CE%BB%C2%AB16%2Fv%E2%84%854%E1%BA%87%C6%9B%C3%B7W%E2%80%9B%20%20j%3B%E2%81%8B%E2%87%A7%E2%80%9BQ%20%E2%80%9BQuV&inputs=&header=&footer=) ``` «...« # Compressed string 16/ # Into 16 pieces v℅ # Random choice from each Ṗ℅ # Shuffle 4ẇ # Split into four pieces ƛ ; # Foreach... ÷W # To list of characters ‛ j # Joined by double spaces ⁋⇧ # Joined by newlines and uppercased ‛Q ‛QuV # Replace `Q ` with `Qu` ``` [Answer] # [Perl 5](https://www.perl.org/), 157 bytes ``` @d{JobaotwHTVErHnZlRIXDeLtYrDELVyDItsHOPCafKPsIeUneagWeHnQUHImCIOUtEOsI=~s/[a-z]/\U$&$&/gr=~/.{6}/g}++;print$_=(/./g)[rand 6],/Q/?u:$",++$-%4?$":$/for keys%d ``` [Try it online!](https://tio.run/##BcHdCoIwGADQVxGZUWh9N@WFIQYqbBWokfZjEguXRDZjW4RJvbqd82SinvX9ouyWzYU26o23WSgwP9Ybsg/YWh1EEK6zNiBK4ij26XUVS8JSzmi1Y5gnKSYPn0SpCiNJ3J@EnI4/BZxSNEADqIT7g0lnf6H6mub8KW5cobM7hAlUo1xQXmp2YUEC3stBumWaaGxMPaQ7CK6N0O6slUbZ938 "Perl 5 – Try It Online") ## Explanation This solution builds up the dice from the long string, replacing occurrences of lowercase letters with two of their uppercase companions (`s/[a-z]/\U$&$&/gr`) resulting in an ordering of 16 sets of 6 characters (`/.{6}/g`) which are then used as hash keys and set to `1` (`@d{...}++`). Since keys aren't stored in a particular order in Perl, this gives the ordering of the dice the required randomness. Then for each of the `keys` in `%d`, `print` a `rand`omly selected char from the list, either `u` or `$"` (which defaults to space) depending on whether or not the randomly selected letter was `Q`, and either `$"` or `$/` (which defaults to newline) depending on whether or not we're working on a multiple of 4. I quite enjoyed playing with the ordering to maximise saved characters, making sure that each dice ends with a letter that the next starts with and keeping other doubles in the middles of each set of 6. 68 bytes of data, but the decoding is a little expensive. Maybe it'll help someone else though! [Answer] # Batch 252 bytes Note: script = 243 bytes + 9 bytes required to invoke script with Delayed expansion enabled from cmd.exe: ``` Cmd/Von/Cboggle.bat ``` **boggle.bat** ``` @Set c=0&For %%G in (AAEEGN ELRTTY AOOTTW ABBJOO EHRTVW CIMOTU DISTTY EIOSST DELRVY ACHOPS HIMNQU EEINSU EEGHNW AFFKPS HLNNRZ DEILRX)Do @Set D=%%G&Set/ac+=1&For /f %%i in ('Set/A!random!%%6')Do @<nul Set/p=!D:~%%i,1! &If !c!==4 (Echo(&Set c=0) ``` ]
[Question] [ ## Background A **staircase polyomino** is a polyomino made of unit squares whose shape resembles a staircase. More formally, a staircase polyomino of size \$n\$ is defined as follows: * A staircase polyomino of size 1 is a single unit square. * A staircase polyomino of size \$n\$ is the same as that of size \$n-1\$ with a horizontal bar of length \$n\$ attached to the bottom, left-aligned. Let's call them just **staircases** for brevity. For example, here are the staircases of size 1 to 4: ``` # # ## # ## ### # ## ### #### ``` ## Challenge Given a positive integer \$n\$, calculate the number of ways the staircase of size \$n\$ can be tiled with one or more staircases. Multiple staircases of same size can be used in a tiling, and the staircases can be rotated. So the following are valid tilings for \$n=4\$: ``` A BC DEF GHIJ A AA AAA AAAA A AA BBC BDCC ``` Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases Generated using [this Python 3 reference solution](https://tio.run/##fVPLboMwELzzFVtVKlBMFZJLFZX@SMSBBFOspjYyjhRa5dvp7kICBLUXwDuzM/vAdesqozddV8gSykCHWw8OxtiigRR@grNoQyiNhTMoDTbXHxI5HGlnEVUi5S2F9uJBreRBUv4u85jaqG85shOho4R8YJ838k8bSlo49cGpGVjjkkGE0DiJr1qCE8lk4K2ZN7BGzwVvM@f9K0tv7pU@MiqNu01TSEAesT8GBJfJzzU/Nzia66AizMbyI3MW0EbmzufCp/3Vs@GjWe7DzBaSTddQM6EmfAhimTVNsF/1jfzSGOuCT9mmX0qHHjzWVmkX9CCe6Sex8nCyjQw@rCoEHHJdqCJ3shGI1q5K/WeflzvkclDAPRvFqAhtHENblHUnqyEZ4yP5hq4QrVDHHbGtEd@tsqn2LtlmvQx2wXWG8JDyoSrCmRhyqoIGMSti2iLE7LhzPENHM0T3oUTUgydwYTY0H1HzEN3NyB2nMP1iS5sl647Ub0rAdRdUjZpeqleaej9zJcCP332BF1qFYdf9Ag). ``` 1 -> 1 2 -> 2 3 -> 8 4 -> 57 5 -> 806 6 -> 20840 7 -> 1038266 ``` [Answer] # JavaScript (ES10), ~~250 ... 228~~ 227 bytes ``` n=>(e=g=(a,[x]=a)=>+e?e=0:(x&=-x)?a.map((_,s)=>[b=1<<s,...s?[1,b+=~-b,b]:[]].map((m,d)=>d|x>>s&&g(a.flatMap(S=(v,y)=>(S|=y>s?v:(e|=(v^=M=x*m>>!d*s)&M,m^=1<<[s+~y,y+1,s-y,y][d],v))?v:[])))):n++)([...Array(n)].map(_=>2**n---1))|n ``` [Try it online!](https://tio.run/##Xc5NboMwEAXgfU@RbtAYbAI0SSOUMeoBWGVpOZEJP2oFJsIRAgnl6tQV2RRvLH3v2TM/qlfm1n3fH0y3eTGXOGvkUGCFoKgYJCqC3CuSAoMYBgfZQBLlN@oOcKXGZiLD8HQy1Pd9k4iQZh4@WUYzGQspl2JDc1vMp4Fz4zgVKL@s1SO10Rmhp6MN4TzhyE3Sx1BMFi@Y4uA2nL/nriFOSpvL3xhhvOdIRy@khtlbilzSnhD7TEhiT6w9j4Cwu3x1nRpBk2WFK/LIdTVjLCRk0vOt1aatC79uKyjB2ma73YRv/zlaOFrxx8LHFe8W3n@ufP@qB4dVcHh9Hxx3wfwL "JavaScript (Node.js) – Try It Online") ### How? The size-\$n\$ staircase is described with an array \$a[\:]\$ of \$n\$ bit masks, going from the longest to the shortest row. For \$n=4\$, this gives: ``` # # # # 0b1111 = 15 . # # # 0b0111 = 7 . . # # 0b0011 = 3 . . . # 0b0001 = 1 --> a = [ 15, 7, 3, 1 ] ``` At each iteration, we remove all the leading empty rows in \$a[\:]\$ and look for the least significant non-zero bit \$x\$ in the first non-empty row. Note that \$x\$ is not set to the index of this bit, but to the corresponding power of \$2\$. For each \$s\in[0\:..\:n-1]\$ we try to cover the main staircase with another staircase of size \$s+1\$ anchored to the non-zero bit, and whose rows are described with the bit mask \$m\$. If \$s=0\$, we only try the orientation \$d=0\$. Otherwise, we try \$d=0\$ to \$d=3\$. The table below describes for each value of \$d\$: * the initial value of \$m\$ * the index of the bit that must be inverted in \$m\$ to generate the next row * the shift applied to \$m\$ The non-zero bit to which the staircase is anchored is marked with an `A`. In all cases, \$m\$ is first multiplied by \$x\$ before being shifted. All examples are given with \$x=16\$ and \$s=2\$. ``` x d = 0 . . . . . . . . y = 0 A init. : 2 ** s y = 1 # # bit : s + ~y (i.e. s - y - 1) y = 2 # # # shift : >> s x d = 1 . . . . . . . . y = 0 A init. : 1 y = 1 # # bit : y + 1 y = 2 # # # shift : none x d = 2 . . . . . . . . y = 0 # # A init. : 2 * (2 ** s) - 1 y = 1 # # bit : s - y y = 2 # shift : none x d = 3 . . . . . . . . y = 0 # # A init. : 2 * (2 ** s) - 1 y = 1 # # bit : y y = 2 # shift : none ``` **Note:** Given that the bits to the right of the non-zero bit are all cleared by definition and given that we go from top to bottom, the anchor point of the covering staircase is unambiguously defined for each orientation. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~91~~ ~~88~~ ~~87~~ ~~83~~ ~~81~~ 78 bytes ``` ≔⊕Nθ⊞υEθ⁻X²θX²ιF⊖θFθFE²Eθ×÷⊖X²θX²⁺ινX²⁺κ∧λνF⟦λ⮌λ⟧FθFυF¬⊙ξ&π§μ⁻ρν⊞υEξ|ρ§μ⁻ςνILυ ``` [Try it online!](https://tio.run/##ZVA9b8JADN35FTf6pOuCujGlZUFqaVSxoQ5p4oLFxUnuI9Bfn/oKhLR4eed3fu9ZLveFK5vCDkPmPe0YVlw6rJEDVvJuY1jH@hMdaG1UpxezPPo9RKNeixY6AeLoIW@OMjJPE0aNDWmpxeyrcQqWeLPttFa/ZHfB5DUfLTdUo5fssKSeKvwjnQRNk3IrS5BRrO/pg1EZV2DPv6nOoVth3rFH5xGs/vi3UrzgugmQ8TecjHqicCSPyawVz7DiCk9QX2/gxgA1vdFN@ObSzJ2uv@rkto44wHPhA7wg74KYJH4YHoeH3v4A "Charcoal – Try It Online") Link is to verbose version of code. This has so many loops that I reached the `v` variable for the first time ever. Explanation: ``` ≔⊕Nθ ``` Input the size of the staircase and increment it. ``` ⊞υEθ⁻X²θX²ι ``` Create a staircase of that size in such a way that the hole is at the origin. The hole is one size lower, which is the original size we wanted. This becomes our initial tiling (which represents tiling the original staircase with size 1 staircases). The staircase is represented as an array of bit masks. ``` F⊖θ ``` Consider all staircase sizes greater than 1. (Size 1 staircases are considered by simply assuming that they will be used to fill any hole remaining for each potential tiling.) ``` Fθ ``` Consider all horizontal translations. ``` FE²Eθ×÷⊖X²θX²⁺ινX²⁺κ∧λν ``` Consider the horizontally translated staircase and its horizontal reflection (actually obtained by shearing). ``` F⟦λ⮌λ⟧ ``` Also consider the vertical reflections of those staircases. (This works because the vertical translations are cyclic.) ``` Fθ ``` Also consider all cyclic vertical translations of those staircases. The vertical translation is cyclic so that translations that move the piece too far horizontally will still always overlap the staircase. ``` Fυ ``` Loop through all of the tilings collected so far. ``` F¬⊙ξ&π§μ⁻ρν ``` If the staircase fits in the hole in this position, then... ``` ⊞υEξ|ρ§μ⁻ςν ``` ... append the result of placing it in the hole to the list of tilings. (Note that Charcoal will find this result in the list again, but of course won't be able to place it twice.) ``` ILυ ``` Output the number of tilings discovered. Example of avoiding placing a staircase in an impossible position: ``` \ \\ \\\ \\\\/ // ``` As an example, the double reflection of the size 2 staircase could be moved by 3 horizontally and vertically which would normally cause it to fall outside the original staircase, missing the hole completely. However, the vertical translation is cyclic, so the actual result is as follows: ``` X/ \\ \\\ \\\\/ ``` This is therefore detected as an illegal tiling. ]
[Question] [ For the purpose of this question a meandering curve is one that follows the general direction from left to right, but makes repeatedly n+1 turns at 90 degrees to the left and then n+1 turns to the right (for n>0). In fact the meander itself will have `n` segments. The turns are denoted with `+`. The width of the meanders (the distance between two `+`) is 3 at the horizon (`---`) and 1 at the vertical (`|`) Here are the single segments a meandering curve with sizes n from 1 to 5: ``` +-------------------+ | | +---------------+ | +-----------+ | | | | | | | +-----------+ | +-------+ | | | +---+ | | | | | | | | | | | | | | +-------+ | +---+ | | +---+ | | | +---+ | | | | | | | | | | | | | | | | | +---+ +---+ | +---+ | | +-------+ | | +-----------+ | | | | 1 | | 2 | | 3 | | 4 | | 5 ---+ +-------+ +-----------+ +---------------+ +-------------------+ + ``` ## Challenge: Given two positive numbers `n` and `m`, draw `m` segments of a meandering curve with size `n`. You can write a full program or a function. ## Input: `n` > 0 The size of the curve `m` > 0 Number of segments to draw ## Output: An ASCII representation of the meandering curve. ## Examples: ``` n = 3 m = 2 +-----------+ +-----------+ | | | | | +---+ | | +---+ | | | | | | | | | +---+ | | +---+ | | | | | | -----------+ +-----------+ + n = 2 m = 5 +-------+ +-------+ +-------+ +-------+ +-------+ | | | | | | | | | | +---+ | +---+ | +---+ | +---+ | +---+ | | | | | | | | | | | -------+ +-------+ +-------+ +-------+ +-------+ + n = 4 m = 4 +---------------+ +---------------+ +---------------+ +---------------+ | | | | | | | | | +-------+ | | +-------+ | | +-------+ | | +-------+ | | | | | | | | | | | | | | | | | | +---+ | | | +---+ | | | +---+ | | | +---+ | | | | | | | | | | | | | | | | | | +-------+ | | +-------+ | | +-------+ | | +-------+ | | | | | | | | | | ---------------+ +---------------+ +---------------+ +---------------+ + ``` ## Winning criteria: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in each language wins. Please explain your code, if you have time to do it. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~52~~ ~~34~~ 33 bytes ``` Nθ↶FNF⊗⊕θ«+⊖⊗×⊕﹪κ²∨↔⁻θ∧κ⊖κ¹¿›κθ↷↶ ``` [Try it online!](https://tio.run/##VU/LDoIwEDzLVzScthEP4tETiYkxESXGH@CxSENppbRcjN9eW6IRTvuYmd2ZsslVKXNu7Uk8jb6YrkAFPd0HGRulPmOtwQ21VATmDErJtDtIU3CsHFYq7FBo1/cOfAWrTDGhIVyHTv8dDvhn/ZR31uGw0KeyMlxCG5GY0ohcFSTFACkTZoA@IomoPDa/1VLqmVtf/DdWEzgqzLVz6qje0BTnxh6Nz0OQD0gWCd/W7oLYbkb@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the size of the meander. ``` ↶ ``` Pivot upwards as the drawing starts at the right and works left. ``` FN ``` Loop over the desired number of meanders. ``` F⊗⊕θ« ``` Loop over the segments of the meander. ``` + ``` Print a `+`. ``` ∨↔⁻θ∧κ⊖κ¹ ``` Compute the `k`th element of the list \$ n, n, n-1, n-2 ... 3, 2, 1, 1, 1, 2, 3, ... n \$. ``` ⊖⊗×⊕﹪κ²... ``` Alternate between doubling and quadrupling the lengths since the horizontal lines are twice as long, but decrement the result before printing to take account of the `+` that was just printed. ``` ¿›κθ↷↶ ``` Pivot appropriately for the next segment. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~108~~ ~~101~~ 95 bytes ``` ' -+|'[⊃,/⎕⍴⊂b/⍨3 1⍴⍨≢⍉b←⌽⊖2@a⌽1@(a←⊂0 0)⊖0,⊃{((4|-⊖⍉⍵),⍉¯2↑⍉⍵)⍪(2/⍪⍳2),¯2↑⍵}/⎕⍴⊂46 16 47⊤⍨3⍴4] ``` [Try it online!](https://tio.run/##rVTBTsJAEL33K/Y2rW2lLRUTT/yHeihIDbEJpngxlAsYlOoSOehd4sFw8aDEhMSLnzI/UqeAaWy7mIKbNDvz9u3s7OvMOueefnLpeK1Tve457XazHuHoodnCwb0h4c21GwHT1QAOMexrJVpC/o5hr1ZC/lJmZuzxFxxOkA9rtAfvPjF8tKoOGWZVdmIo7BnMUAg2NArSkWU70MmjHchnikbz16uFg/EKQD6VLQo/Rf5mKdrP2qybnG5XmFlh9j6Gz3EaBNrHESUrufF5fATElHd3FJpi0wfafkS5zgHDiUmpQbcDGhkftFr3wYXognZ2iIbDJ3@RdN@lHOYH0DoDvL0C12l6FGZOFL8rSQ22vBkwxlQ9GWraB6mhJdSAJSNI@1mquooYpP0sVfj9pgojZqnCPFPUdbePfZDKzCJ5x4182dSidr6kQVFbLEwhOytasElWWUHVTTQCyWJ7a8QW/alCmLim8@qlEJbfA3pO1RbG8nuG5fRMYezvzt0YW1/sW90i2wD/orP4Jdm6OsQvz9Y1vWwem9mL5vkG "APL (Dyalog Classic) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~559 540 523 511 494 484 476 468 456 447~~ 443 bytes ``` #define S memset l,o,p,q,r;g(c,d,n)char*d;{q=~c;for(p=n*2;q%2*p;bcopy(n*2-p--?"| |":"+---+",d-q*l*p,5));p=n-1;c--%2?S(S(d-~l-r*!q,45,r++)-2*l,45,r=n*4-1),d[r*=q-1]='|',d[r-l]=d[r+l]=43,p&&g(c%4,memcpy(q?d+p*4+l:d-l-n*4,q?"+ |":"| +",5),p):p&&g(c%4,d,p,d[-q]=45,d[q*=l]=43,*(d-=q*(n*2*l-l-2)-2)=32);}f(n,m){char b[(o=n-~n)*(l=n*4+5)];g(0,strcpy(S(S(b,32,l*o),45,l)+l-6,"+ +"),n);for(o*=m;b[o/m*l-1]=0,o--;o%m||puts(""))printf(b+o/m*l);} ``` [Try it online!](https://tio.run/##ZZDBbtswDIbvfQrVQ1pRItHGsXeIIOQhcgxyqKW4DSBbkpMdhrh59Yz22gFDTiR/iL@@n47enbvdfvhDe@wPYiu6Q3c6nB8CRkyYcTDv0qHHHtzH26C8uWR7daaNg0y2V6XJi1Il07iYfkueKRFtilEIMRbrQhORLtBTVkElrAEMb9HSOKJFudnKrfR0DTSox4xVjYPWQKUKc8/2FS0B/W5QNtNyb5/H52misLdcNJdqhenpiREXFTK5Y4i88TqpSoe1p0DsgXlT6C@gCYyBasAE63@bnqP6HWX2q7nJyv61Vkxns5pyqcBmJcOBXZVgPlvZYweX6Sii2cnIqa49KBkmal3Dnu/2iqfzMCFNORtclRhUhClbAB3oJ85YugC@7nzRqGxnml186fg7zvuKkcjERTeO6df5JIsCIA3H/tzKRs@vmOTGs@jejr0EcXkQopVLZMLvBTNL5b20upeqe6n@X/q8/QE "C (gcc) – Try It Online") Slightly less golfed ``` #define S memset l,o,p,q,r; g(c,d,n)char*d;{ q=~c; for(p=n*2;q%2*p;bcopy(n*2-p--?"| |":"+---+",d-q*l*p,5)); p=n-1; c--%2? S(S(d-~l-r*!q,45,r++)-2*l,45,r=n*4-1), d[r*=q-1]='|', d[r-l]=d[r+l]=43, p&& g(c%4,memcpy(q?d+p*4+l:d-l-n*4,q?"+ |":"| +",5),p) : p&& g(c%4,d,p,d[-q]=45,d[q*=l]=43,*(d-=q*(n*2*l-l-2)-2)=32); } f(n,m){ char b[(o=n-~n)*(l=n*4+5)]; g(0,strcpy(S(S(b,32,l*o),45,l)+l-6,"+ +"),n); for(o*=m;b[o/m*l-1]=0,o--;o%m||puts("")) printf(b+o/m*l); } ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~371~~ ~~354~~ ~~346~~ ~~328~~ ~~298~~ 290 bytes ``` import sys v=sys.argv s=int(v[1]) n=range r=" |" t=" +---" h="-"*4 e=" "*4 def C(l):print(l*int(v[2])) for i in n(-(-s//2)):q=s-i+~i;R=r*i;C(R+t+h*q+"+"+R);C(R+r+e*q+R+r) for i in n(s//2):q=s//2-i;R=r*~-q;w=2*i+s%2;C(R+t+h*~-w+"+"+r*(q+((i>0)|s%2)));C(R+e*-~w+R+2*r) C(h*~-s+"---+ +") ``` -20B Thanks to ceilingcat [Try it online!](https://tio.run/##VY/BasMwDIbvfgpjKFg2Wre0uzS4l7xBrqOHwtzG0DmJbRIKJa/uyQkMhkC/@KX/Aw3P1PX@kLP7GfqQeHxGNhnqb9dwn1g0zic5fX1cgHkTrv5uWTCCc/4SLK2DRkTBOiNQqCOz5BX9tjfeyAechlAID7VxqgsAu/WBO@489xIlxv2@AjiNJqLTi6tbE5SrG9nqpDs1akHVwmoEbckg/cdYASVPilt@wbGeTaWcjrvqj7XgvNKCkqOW0p3f4UV7gI1uFS4z0StF/EaW@6gFfafLlwJyzp/58As "Python 3 – Try It Online") Pre-golfing: ``` import sys import math def draw_curve(curve_size, curve_count, out=sys.stdout): for i in range(math.ceil(curve_size / 2)): for j in range(curve_count): out.write(" |" * i) out.write(" +---") out.write("----" * (curve_size - 2 * i - 1)) out.write("+") out.write(" |" * i) out.write("\n") for j in range(curve_count): out.write(" |" * (i + 1)) out.write(" " * (curve_size - 2 * i - 1)) out.write(" |" * (i + 1)) out.write("\n") for i in range(curve_size // 2): for j in range(curve_count): out.write(" |" * (curve_size // 2 - i - 1)) out.write(" +---") out.write("----" * (2 * i - (0 if curve_size % 2 else 1))) out.write("+") out.write(" |" * (curve_size // 2 - i + (1 if i or curve_size % 2 else 0))) out.write("\n") for j in range(curve_count): out.write(" |" * (curve_size // 2 - i - 1)) out.write(" " * (2 * i + (2 if curve_size % 2 else 1))) out.write(" |" * (curve_size // 2 - i + 1)) out.write("\n") for j in range(curve_count): out.write("----" * (curve_size - 1)) out.write("---+ +") if __name__ == "__main__": draw_curve(int(sys.argv[1]), int(sys.argv[2])) ``` [Answer] # [Dash](https://wiki.debian.org/Shell) - POSIX Shell script, 528 bytes [Try it online!](https://tio.run/##dVPbjtowEH3nK06DJW7LLiFFiEV5QCutVIkPgJaqePEAUY2dxklXLc2309gJCd1V8xCN5xx7Zs7MCG6Ol0v7w8NLpB7MsdVC8bVxJBlTgn2mdmmkFfY6AZ0yydNIHcAVeJLwX3dIjwTJ1SHjB4LQZKB0iu9KvyJK3Vtxt3cG/eQSC3b282/sPM7DDgs689zh63BUBrUhPiNS2Br6ATbezoUukSIfQftIkQsXa2OiF1kYPE0pUebxSpKRSUNPRAm5pAc7nakUb8/39/deeWPHDYH5RczyDL@3DDtJgMxH8Rd@Zz6vkLFDphaRJT6FCBo8cLjvIwssQZS0ANYlJg3vY8mbIJtATi0vKdlT67GAmDbsScmeIZtC2pcCNNkFzlUgliBmnfIOGb6rVLOCLqygbGmlBP7f2oO2bY1UqqGIBIlGtfoeVwKxLLq7O/Kk5LohqAii6HNl4ikcXk2nscd8r1EZSPq9Vci63dXA7/XqagF59Q//9Wf93tr6147/FG7@3IDiCg7fg06Nyo7BVmDrYrLAnipn3qrLe02ilMrauIHUdszNVY2m2rtGjzgmZSE3lYafqBHNPcFNCpJ0omLoLKUzqHrkJP/UjPp50e5/4cPfX/Nt0ygIsMVVW63o1o3BO8BZ1fLS7qhdRJdxsRaKXiND9Zat69DjEYY@Rk1YC69qeITZ7CYlt8XPobfxNqxY5pVd5nW@8bz5MmTnZc7Oz49D5K03qbl0PLa0tFYNXS6X4BL8BQ "Dash – Try It Online") golfed: ``` Y=0;p(){ eval A${1}_${2}='$3';};for Z in `seq $2`;do case $1 in 1)L='r3 u1 r3 d1';;2)L='r7 u1 l3 u1 r7 d3';;3)L='r11 u3 l3 d1 l3 u3 r11 d5';;4)L='r15 u5 l7 d1 r3 d1 l7 u5 r15 d7';;5)L='r19 u7 l11 d3 r3 u1 r3 d3 l11 u7 r19 d9' esac;for A in $L;do d(){ C=-;case "$1" in r*)X=$((X+1));;l*)X=$((X-1));;u*)Y=$((Y+1));C=\|;;d*)Y=$((Y-1));C=\|;;esac;p $X $Y $2 $C;};for I in `seq ${A#*[a-z]}`;do d $A;done;d $A +;done;done;for Y in `seq 20 -1 0`;do for X in `seq 0 99`;do eval F="\"\$A${X}_${Y}\"";L=${L}${F:- };done;echo "$L";L=;done ``` ungolfed: ``` #!/bin/sh # helper function for emulating an array, the language does not know it p(){ eval A${1}_${2}='$3';} Y=0 for Z in `seq $2`;do # define the possible patterns: # list="direction+count direction+count ..." case $1 in 1)L='r3 u1 r3 d1';; 2)L='r7 u1 l3 u1 r7 d3';; 3)L='r11 u3 l3 d1 l3 u3 r11 d5';; 4)L='r15 u5 l7 d1 r3 d1 l7 u5 r15 d7';; 5)L='r19 u7 l11 d3 r3 u1 r3 d3 l11 u7 r19 d9' esac for A in $L;do # helper function for going into needed direction # and plot char into array d(){ C=- case "$1" in r*)X=$((X+1));; l*)X=$((X-1));; u*)Y=$((Y+1));C=\|;; d*)Y=$((Y-1));C=\|;; esac p $X $Y $2 $C } # write char as long as needed into array, # append in the same direction as last element the '+' for I in `seq ${A#*[a-z]}`;do d $A done d $A + done done # echo the array linewise for Y in `seq 20 -1 0`;do for X in `seq 0 99`;do eval F="\"\$A${X}_${Y}\"";L=${L}${F:- } done echo "$L";L= done ``` [Answer] # [Python 2](https://docs.python.org/2/), 261 bytes ``` n,m=input() i=0;h,v,p,s=map(tuple,'hv+ ');k=p;R=[h+s] exec"h,v=v,h;R=zip(*R)[::-1];R=[s+R[0][:-1]+k+h+p]+[s+r+s+v for r in R[1:]]+[h*2*i+h+p+s+p];i+=1;k=v;"*n for r in[[(3-i%2*2)*{h[0]:'-',v[0]:'|'}.get(c,c)for i,c in enumerate(l)]*m for l in R]:print''.join(r) ``` [Try it online!](https://tio.run/##NVC9bsMgEJ7DU6BIFdjgKHaiDLYY07WS1Q0xpC4tNDZGGLtNmz67C0gdOH1/dyfO3rwaTbV246tkDiG0GjowbezscQY02zeKLtTSiQ0Xi/1se0mRWghEWXNltmkZV2QSQH7JbhuibKEqiN/a4rzNeF0XpYihibR8L3ik5EoUsYIEzZGJLPBtdNBBbWDLy1oEQ@VVrmMo2FY0mrAyLFuabW7Af5hzfCj0Q5VXWf6jwuwaFYguCdzR7@5detzRLot5Tbs4Xpp5kO7iJe4zkQ9pb5/2ito6bTxCu49RG@yyNXEYbgESalIF4T7gU@lewmc3yxpsvLuFuom/h/GEIMBOWg/PT49n50YX3RcnL1eQmiGEpCgKEsE9PhBZVKO9lrQCFS3BgR7AkZ7AiR7XPw "Python 2 – Try It Online") 5 bytes from [this tip](https://codegolf.stackexchange.com/a/169511/69880) by [Esolanging Fruit](https://codegolf.stackexchange.com/users/61384/esolanging-fruit). ]
[Question] [ A cyclic number is a number of "n" digits that when multiplied by 1, 2, 3,...n, results in the same digits but in a different order. For example, the number 142,857 is a cyclic number since 142,857 x 2 = 285,714, 142,857 x 3 = 428,571, 142,857 x 4 = 571,428, and so on. Given an integer input, determine if it is a cyclic number by outputting a truthy value if it is, and a falsy value if not. Also, to be clear, the input can contain leading 0's: e.g. 0344827586206896551724137931 This is due to the fact that if leading zeros are not permitted on numerals, then 142857 is the only cyclic number in decimal. Since it is code-golf, shortest answer in bytes wins! [Answer] # [Actually](https://github.com/Mego/Seriously), 18 bytes ``` ;;ru@≈*♂$♂S♂≈╔@S≈= ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/9/auqjU4VFnh9ajmU0qQBwMxEDuo6lTHIKBtO3//0oGphYWRsamRpYmhobmZibmSgA "Actually – Try It Online") (expects quoted input) Explanation: ``` ;;ru@≈*♂$♂S♂≈╔@S≈= ;; duplicate input twice ru range(1, len(input)+1) @≈ convert input to an integer * multiply input by each element in range ♂$♂S♂≈ convert each product to a string, sort the digits, and convert back to int ╔ uniquify: remove duplicate elements @S≈ sort input and convert to int = compare equality ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 6 bytes Thanks to *Emigna* for saving 3 bytes! ``` ā*€{ïË ``` Explanation: ``` ā # Push range(1, len(input) + 1) * # Multiply by the input €{ # Sort each element ï # Convert to int to remove leading zeros Ë # Check if all elements are equal ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#BcE7EYBQDARAP1T5XC6JNiposcIMIh5KMBJ25z2277z39axrRpSN1rCAeVqVekS7mbhXl0tIIRFJS9UiIMxsUn8 "05AB1E – TIO Nexus") [Answer] # Python, 86 bytes ``` lambda n:all(sorted(n)==sorted(str(int(n)*i).zfill(len(n)))for i in range(2,len(n)+1)) ``` [Try it online!](https://repl.it/IV8r/2) Input numbers as strings. [Answer] # PHP, 64 Bytes ``` for(;$i++<9;)$r+=($c=count_chars)($argn)==$c($argn*$i);echo$r>1; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/f7a770a17415bbc9b9b3a5d484afac92e49d30a5) [Answer] # Haskell, 36 33 32 45 bytes ``` c n=let l=length n in(10^l-1)`div`read n==l+1 ``` Example usage: ``` *Main> c "142857" True ``` I don't think this algorithm needs any explanation. [TOL](https://tio.run/##y0gszk7Nyfn/P1khzzYntUQhB0jmpZdkKOQpZOZpGBrE5egaaiakZJYlaORoG2ra2halJqYo5P3/DwA) Thanks for suggestions: Generic Display Name, Laikoni. Thanks for correction: Antony Hatchkins. **EDIT** Nope, fails on "33". [Answer] # dc, 24 25 bytes ``` [1]sa0?dZd10r^1-r1+/rx=ap ``` Prints "0" if the number is not cyclic, otherwise "1". Requires the number to be entered as a string. Example usage: ``` $ echo "[052631578947368421]" | dc -e '[1]sa0?dZd10r^1-r1+/rx=ap' 1 $ echo "[052631578947368422]" | dc -e '[1]sa0?dZd10r^1-r1+/rx=ap' 0 ``` [TOL](https://tio.run/nexus/dc#@x9tGFucaGCfEpViaFAUZ6hbZKitX1Rhm1jw/z8A) Explanation: Same algorithm as my Haskell submission. EDIT Nope, fails on "33". [Answer] ## Mathematica, 81 bytes ``` Length@Union@PadLeft[Sort/@IntegerDigits[ToExpression@#*Range@StringLength@#]]<2& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvvfJzUvvSTDITQvMz/PISAxxSc1rSQ6OL@oRN/BM68kNT21yCUzPbOkODok37WioCi1uBikUFkrKDEvPdUhuKQoMy8daoZybKyNkdr/AKBQiYJDmoOSgYmxibmFkZmBhZmlqZmpkaG5saWhsdJ/AA "Mathics – Try It Online") input string **Input** > > "010309278350515463917525773195876288659793814432989690721649484536082474226804123711340206185567" > > > **Output** > > True > > > [Answer] # [Scala 3](https://www.scala-lang.org/), 85 bytes ``` n=>(2 to n.size).forall(i=>n.sorted==(BigInt(n)*i).toString.padTo(n.size,'0').sorted) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bY-9TsMwFIXF2pEnuMpSG9Eo_ncqORLdGJigU9XBtEllFOzKMSBAfRKWMsDCE8HTEJFOqMs9uud-50j37bNb2dayr0U28eHJRp8tf05Ow-1dvUpwZZ2H1xHAum7gvl-QjZtuChcx2ufFdYrOb5Z4CnPvEpg_EmDbu6n1qEEZ4VQLlWH8_1AIrSkTtOSEKMmPI1QyIpQuuWJSc0qOQZxxpakstCyFFJQoVhJ2DGSca6qElrSQupRCEEU5Yapkh97dqB-PtoVmCmh4zVSzENraegzm4yE1E_0996ZCFFIAn3fupcZ5E6JtW-RM1TshpnptDJq5zaVPyOMzh_MUhrp8a9c3AQ3B83ExxocAHsrfd4Pu94P-Ag) ]
[Question] [ ## Background On this site, we occasionally have questions requiring programs to be "radiation hardened"; this means that the program has to be able to survive the deletion of one or more bytes, no matter which bytes are deleted. As is common for tasks that frequently get set in programming challenges, it's natural to want to make a language that's particularly good at these challenges. Given that the natural way to make this is to add some metadata that makes it possible to reverse corruption, it's actually not really a language that needs designing, but an encoding; the idea is to transform each input to a sequence of bytes, in such a way that even if the sequence is slightly irradiated, it's possible to extract the original input. ## The task Write two programs or functions, E (an encoder) and D (a decoder), such that: * E takes two arguments, a sequence of octets (which we'll call "*input*" in this specification) and a nonnegative integer "*radiation*", and outputs a sequence of octets "*encoding*"; * D takes one argument, a sequence of octets ("*encdng*"), and outputs a sequence of octets "*reconstruction*"; * If you run both E and D (with *encdng*, the input to D, chosen by deleting no more than *radiation* elements from *encoding* (not necessarily contiguously)), then *reconstruction* will be equal to *input* no matter which characters were deleted to form *encdng*. ## Clarifications * If you submit functions, you don't have to call them `E` and `D`; you can choose whatever name is most suitable for your language. * An "octet" is basically an integer from 0 to 255 inclusive, which you can encode as an integer, a character, or whatever's appropriate for your language. * E and D must be entirely deterministic (i.e. giving them the same inputs will always produce the same output, where "inputs" is defined as *input* and *radiation* for E, or *encdng* for D). In particular, E may not communicate information to D via a side channel. * The deletions are performed by deleting one element of the sequence; think of opening the seuqence in an editor, placing the cursor at an arbitrary point, and pressing Backspace. If an element appears multiple times, it's possible that only one copy of the element will be deleted (i.e. other instances of the same octet won't be affected). * Although the score is only calculated on the basis of fairly short *input*, your program must work in theory for any *input* and *radiation*. In particular, it must work no matter which octets appear in *input*. (Sorry, people who would like the ability to use unprintable characters that they know won't appear in the input, but I need to ensure that the input's incompressible so that the challenge is about radiation hardening rather than compression.) * You can submit either one file that defines two functions; two files which each define a function or which are both full programs; or three files, two of which implement D and E respectively (either via being full programs or via defining a function), and the third which is a header file or library common to both D and E. Regardless of which form of submission you use, your programming language implementation must be able to understand both programs without further arguments like file locations (or else you must pay a byte penalty for invoking your implementation in an unusual way, as per our standard rules). ## Victory condition For each *length* and *radiation*, let *f*(*length*,*radiation*) be the total lengths of the *encoding*s that correspond to all *input* with length *length*, and the given *radiation*. (That is, *f*(*length*,*radiation*) = sum*input* has length *length* length(E(*input*,*radiation*)).) Then let *g*(*length*,*radiation*) equal *f*(*length*,*radiation*) ÷ 256*length*. In other words, *g* is the average length of the encoded output, for a given length of input and a given radiation hardening requirement. (In theory you could calculate this by brute force, but it would likely take implausibly long to work out your score that way. I'm expecting most submissions will be able to make a mathematical argument as to what their score is. If you're not sure, post an approximate score and you or someone else can calculate it in more depth if another entry posts a similar score.) Your score is equal to the sum of *g*(*length*,*radiation*) for all *radiation* in the range 0 to 9 inclusive, and all *length* in the range 0 to 99 inclusive, plus (mostly to avoid hardcoding, or to keep the competition going if someone discovers a mathematically perfect encoding; this is likely to be a minimal factor otherwise) the total number of bytes in your submission to the challenge (plus the standard penalties for things like requiring unusual interpreter flags or specific filenames). The winner is the entry with the lowest score (tiebroken by the first entry to submit). [Answer] ## CJam, score ≤ 286,516 + 54 + 36 = 286,606 ### Encoder ``` {_{1\+_:e>)_0a+@@b0\{{)_256b_,\e`,-}g}*256b+\)e*}{*}?} ``` [Try it online!](https://tio.run/nexus/cjam#@2@soOSRqWSVyVUdX20Yox1vlWqnGW@QqO3gkGQQU12tGW9kapYUrxOTmqCjW5teqwXiasdopmrVVmvV2tdy1RX8/w8A "CJam – TIO Nexus") ### Decoder ``` {_{e`1f=(\256b{256b_,\e`,=},,\b1>}&} ``` [Try it online!](https://tio.run/nexus/cjam#@x9taGCmgIwNoNDcBIEMDYyRcSwXV3V8dWqCYZqtRoyRqVlSNYiI14lJTdCxrdXRiUkytKtVq@XiqrNK/v8fAA "CJam – TIO Nexus") Both of these take and return a list integers. The TIO links include conversion from/to strings for convenience. Note that these are incredibly inefficient for longer strings. If you want to try a few more characters, I recommend using characters with small character codes. The basic idea for creating a radiation-hardened encoding involves two steps: 1. Find an encoding which never contains two consecutive identical octets. 2. Repeat each octet in the encoded string **r + 1** times, where **r** is the radiation level. This way, the radiation can't completely delete one run of identical characters, so that we can decode the string by taking one character from each run and then decoding step 1. So the only interesting part is finding an encoding that never yields repeated octets. The basic idea is to use something like [A043096](https://oeis.org/A043096) as a number system. That is, to encode an integer **N**, we simply count up in some base **b**, skipping all numbers with repeated octets. I believe the amount of numbers that can be represented in this way with up to **d** digits is the same as the amount of numbers that can be represented in bijective base **b-1** (since, when you want to write such a number, you can choose between **b-1** digit for each position without violating the constraint). Of course, to obtain maximal compression we will use **b = 256**. To turn the input into an integer, we can use base conversion as well. If I wasn't lazy, I'd use a bijective base for the input, but for now I'm just prepending a `1` (to ensure there are no leading zeros) and then use the smallest possible base that such that all octets in the input are less than the base. This base is then prepended to the encoding (so that the decoder knows which base to use) and separated from the remaining number by a 0-octet (this works because the remaining number will never start with a zero). As a minor optimisation, the empty string remains an empty string. The reason I haven't computed an exact score above is that I'm only computing an upper bound for how long each input will be based on its length and its maximal octet. However, for these two parameters, there will often be two different output lengths, and I haven't bothered figuring out yet where the tipping point between them occurs. I've also used the length of usual base 255 instead of bijective base 255 to estimate that length, which is again slightly bigger than it needs to be. The exact Mathematica code I used for the computation is the following: ``` num[l_, 1] = 0; num[l_, base_] := num[l, base] = base^l - Sum[num[l, b], {b, base - 1}] Sum[ num[l, b]*(r + 1)*(2 + IntegerLength[2*b^l - 1, 255])/256^l, {r, 0, 9}, {l, 1, 99}, {b, 2, 256} ] N@% ``` `num[l, b]` should give the the number of strings of length `l` with maximum octet `b-1` (except for `b == 1`, where I've hardcoded it to `0` because I'm always using at least base `2`). [Answer] # bash + GNU utilities, score ~~294506~~ 283468 *Edit 1: Fixes a problem that @Leo noticed -- thank you!* *Edit 2: Improved the encoding method for the radiation parameter, for a better score.* Encoder (97 bytes): ``` for((j=0;j<$1;j++)){ p+=p\;;} (sed 's/\(.\)\1/\1a\1a/g'<<<$1;cat)|xxd -p -c1|sed ${p-;}|xxd -r -p ``` Decoder (121 bytes): ``` read n n=`sed 's/\(.\)\1*/\1/g'<<<$n` sed -r "s/( ..)\1{0,${n//a}}/\1/g"<<<' 0a '`xxd -p -c1`|sed 's/^ [^ ]*//'|xxd -r -p ``` For the encoder: Octet sequence passed as characters in stdin, radiation parameter r passed as an argument. For the decoder: Input passed as characters in stdin. For both: Output on stdout. The encoder prepends to the input data the digits of r, with a character 'a' inserted between each pair of consecutive identical digits, followed by a single newline. It then copies all the input (starting with the prepended characters), replacing each character by r+1 copies of that character. The decoder undoes this, going through each of the remaining characters x in its input, skipping up to r consecutive identical copies of x following x, and printing what remains. The prepended data has no repeated characters, so it can be decoded before r is known. At that point, r is known, and that value is needed to decode the rest of the data correctly. You can check that this works even if the original input has repeated identical characters. --- Score computation: Suppose the input has length L and the radiation parameter is r (which is at most 9 for the scoring computation, so it fits in one digit and therefore has no consecutive repeated characters). The prepended data is 2 bytes (digit, newline), so the output is (r+1)(L+2) bytes for the encoded stream. So g(L,r) = (r+1)(L+2). It follows that the total score can be computed as [![enter image description here](https://i.stack.imgur.com/z6GFR.png)](https://i.stack.imgur.com/z6GFR.png) [Answer] # Perl + Math::{ModInt, Polynomial, Prime::Util}, score ≤ 92819 ``` $m=Math::Polynomial;sub l{($n,$b,$d)=@_;$n||$d||return;$n%$b,l($n/$b,$b,$d&&$d-1)}sub g{$p=$m->interpolate([grep ref$_[$_],0..$map{$p->evaluate($_)}0..$}sub p{prev_prime(128**$s)}sub e{($_,$r)=@_;length||return'';$s=$r+1;s/^[␀␁]/␁$&/;@l=map{mod($_,p$s)}l(Math::BigInt->from_bytes($_),p$s);$@l+$r>p($s)&&return e($_,$s);$a=0;join'',map{map{chr$_+$a}l($_->residue,128,$s,($a^=128))}g(@l)}sub d{@l=split/([␀-␡]+)/,$_[0];@l||return'';$s=vecmax map length,@l;@l=g map{length==$s&&mod($m->new(map{ord()%128}split//)->evaluate(128),p$s)}@l;$$_=$m->new(map{$_->residue}@l)->evaluate(p$s)->to_bytes;s/^␁//;$_} ``` Control pictures are used to represent the corresponding control character (e.g. `␀` is a literal NUL character). Don't worry much about trying to read the code; there's a more readable version below. Run with `-Mbigint -MMath::ModInt=mod -MMath::Polynomial -MNtheory=:all`. `-MMath::Bigint=lib,GMP` is not necessary (and thus not included in the score), but if you add it before the other libraries it'll make the program run somewhat faster. ## Score calculation The algorithm here is somewhat improvable, but would be rather harder to write (due to Perl not having the appropriate libraries). Because of this, I made a couple of size/efficiency tradeoffs in the code, on the basis that given that bytes can be saved in the encoding, there's no point in trying to shave off every point from golfing. The program consists of 600 bytes of code, plus 78 bytes of penalties for command-line options, giving a 678 point penalty. The rest of the score was calculated by running the program on the best-case and worst-case (in terms of output length) string for every length from 0 to 99 and every radiation level from 0 to 9; the average case is somewhere in between, and this gives bounds on the score. (It's not worth trying to calculate the exact value unless another entry comes in with a similar score.) This therefore means that the score from encoding efficiency is in the range 91100 to 92141 inclusive, thus the final score is: ### 91100 + 600 + 78 = 91778 ≤ score ≤ 92819 = 92141 + 600 + 78 ## Less-golfed version, with comments and test code This is the original program + newlines, indentation, and comments. (Actually, the golfed version was produced by removing newlines/indentation/comments from this version.) ``` use 5.010; # -M5.010; free use Math::BigInt lib=>'GMP'; # not necessary, but makes things much faster use bigint; # -Mbigint use Math::ModInt 'mod'; # -MMath::ModInt=mod use Math::Polynomial; # -MMath::Polynomial use ntheory ':all'; # -Mntheory=:all use warnings; # for testing; clearly not necessary ### Start of program $m=Math::Polynomial; # store the module in a variable for golfiness sub l{ # express a number $n in base $b with at least $d digits, LSdigit first # Note: we can't use a builtin for this because the builtins I'm aware of # assume that $b fits into an integer, which is not necessarily the case. ($n,$b,$d)=@_; $n||$d||return; $n%$b,l($n/$b,$b,$d&&$d-1) } sub g{ # replaces garbled blocks in the input with their actual values # The basic idea here is to interpolate a polynomial through all the blocks, # of the lowest possible degree. Unknown blocks then get the value that the # polynomial evaluates to. (This is a special case of Reed-Solomon coding.) # Clearly, if we have at least as many ungarbled blocks as we did original # elements, we'll get the same polynomial, thus we can always reconstruct # the input. # Note (because it's confusing): @_ is the input, $_ is the current element # in a loop, but @_ is written as $_ when using the [ or # operator (e.g. # $_[0] is the first element of @_. # We waste a few bytes of source for efficiency, storing the polynomial # in a variable rather than recalculating it each time. $p=$m->interpolate([grep ref$_[$_],0..$#_],[grep ref,@_]); # Then we just evaluate the polynomial for each element of the input. map{$p->evaluate($_)}0..$#_ } sub p{ # determines maximum value of a block, given (radiation+1) # We split the input up into blocks. Each block has a prime number of # possibilities, and is stored using the top 7 bits of (radiation+1) # consecutive bytes of the output. Work out the largest possible prime that # satisfies this property. prev_prime(128**$s) } sub e{ # encoder; arguments: input (bytestring), radiation (integer) ($_,$r)=@_; # Read the arguments into variables, $_ and $r respectively length||return''; # special case for empty string $s=$r+1; # Also store radiation+1; we use it a lot # Ensure that the input doesn't start with NUL, via prepending SOH to it if # it starts with NUL or SOH. This means that it can be converted to a number # and back, roundtripping correctly. s/^[␀␁]/␁$&/; #/# <- unconfuse Stack Exchange's syntax highlighting # Convert the input to a bignum, then to digits in base p$s, to split it # into blocks. @l=map{mod($_,p$s)}l(Math::BigInt->from_bytes($_),p$s); # Encoding can reuse code from decoding; we append $r "garbled blocks" to # the blocks representing the input, and run the decoder, to figure out what # values they should have. $#l+=$r; # Our degarbling algorithm can only handle at most p$s blocks in total. If # that isn't the case, try a higher $r (which will cause a huge increase in # $b and a reduction in @l). @l+$r>p($s)&&return e($_,$s); # Convert each block to a sequence of $s digits in base 128, adding 128 to # alternating blocks; this way, deleting up to $r (i.e. less than $s) bytes # will preserve the boundaries between each block; then convert that to a # string $a=0; # we must initialize $a to make this function deterministic join'',map{map{chr$_+$a}l($_->residue,128,$s,($a^=128))}g(@l) } sub d{ # decoder: arguments; encdng (bytestring) # Reconstruct the original blocks by looking at their top bits @l=split/([␀-␡]+)/,$_[0]; @l||return''; # special case for empty string # The length of the longest block is the radiation parameter plus 1 (i.e. # $s). Use that to reconstruct the value of $s. $s=vecmax map length,@l; # Convert each block to a number, or to undef if it has the wrong length. # Then work out the values for the undefs. @l=g map{ # Convert blocks with the wrong length to undef. length==$s&& # Convert other blocks to numbers, via removing any +128 and then # using Math::Polynomial to convert the digit list to a number. mod($m->new(map{ord()%128}split// #/# <- fix syntax highlighting )->evaluate(128),p$s) }@l; # Remove the redundant elements at the end; now that they've reconstructed # the garbled elements they have no further use. $#l-=$s-1; # Convert @l to a single number (reversing the conversion into blocks.) $_=$m->new(map{$_->residue}@l)->evaluate(p$s) # Convert that number into a string. ->to_bytes; # Delete a leading SOH. s/^␁//; #/# <- unconfuse Stack Exchange's syntax highlighting # Finally, return the string. $_ } ### Testing code use Encode qw/encode decode/; # Express a string using control pictures + IBM437, to make binary strings # easier for a human to parse sub format_string { ($_)=@_; $_ = decode("Latin-1", $_); s/[\0-\x1f]/chr (0x2400 + ord $&)/eag; s/\x7f/chr 0x2421/eag; s/[ -~\x80-\xff]/decode("IBM437",$&)/eag; encode("UTF-8","\x{ff62}$_\x{ff63}") } sub test { my ($string, $radiation, $samples) = @_; say "Input: ", format_string($string); my $encoding = e($string, $radiation); say "Encoding: ", format_string($encoding); say "Input length ", length($string), ", encoding length ", length($encoding), ", radiation $radiation"; my $decoding = d($encoding); $decoding eq $string or die "Mistake in output!"; say "Decoding: ", format_string($decoding), " from ", format_string($encoding); # Pseudo-randomly generate $samples radiation-damaged versions. srand 1; for my $i (1..$samples) { my $encdng = $encoding; for my $r (1..$radiation) { substr $encdng, int(rand(length $encdng)), 1, ""; } my $newdecoding = d($encdng); say "Decoding: ", format_string($newdecoding), " from ", format_string($encdng); $newdecoding eq $string or die "Mistake in output!"; } say ""; length $encoding; } test "abcdefghijklm", 1, 10; test "abcdefghijklm", 2, 10; test "abcdefghijklm", 5, 10; test "abcdefghijklm", 10, 10; test "\0\0\0\0\0", 1, 10; test "\5\4\3\2\1", 2, 10; test "a", 10, 10; my %minlength = (); my %maxlength = (); for my $length (0..99) { my ($min, $max) = ("", ""); $length and ($min, $max) = ("\2" . "\0" x ($length - 1), "\1" . "\377" x ($length - 1)); for my $radiation (0..9) { $minlength{"$length-$radiation"} = test $min, $radiation, 1; $maxlength{"$length-$radiation"} = test $max, $radiation, 1; } } say "Minimum score: ", vecsum values %minlength; say "Maximum score: ", vecsum values %maxlength; ``` ## Algorithm ### Simplifying the problem The basic idea is to reduce this "deletion coding" problem (which is not a widely-explored one) into an erasure coding problem (a comprehensively explored area of mathematics). The idea behind erasure coding is that you're preparing data to be sent over an "erasure channel", a channel that sometimes replaces the characters it sends with a "garble" character that indicates a known position of an error. (In other words, it's always clear where corruption has occurred, although the original character is still unknown.) The idea behind that is pretty simple: we divide the input up into blocks of length (*radiation* + 1), and use seven out of the eight bits in each block for data, whilst the remaining bit (in this construction, the MSB) alternates between being set for an entire block, clear for the entire next block, set for the block after that, and so on. Because the blocks are longer than the radiation parameter, at least one character from each block survives into the output; so by taking runs of characters with the same MSB, we can work out which block each character belonged to. The number of blocks is also always greater than the radiation parameter, so we always have at least one undamaged block in the encdng; we thus know that all blocks that are longest or tied for longest are undamaged, allowing us to treat any shorter blocks as damaged (thus a garble). We can also deduce the radiation parameter like this (it's the length of an undamaged block, minus 1). ### Erasure coding As for the erasure coding part of the problem, this uses a simple special case of the Reed-Solomon construction. This is a systematic construction: the output (of the erasure coding algorithm) is equal to the input plus a number of extra blocks, equal to the radiation parameter. We can calculate the values needed for these blocks in a simple (and golfy!) way, via treating them as garbles, then running the decoding algorithm on them to "reconstruct" their value. The actual idea behind the construction is also very simple: we fit a polynomial, of the minimum possible degree, to all the blocks in the encoding (with garbles interpolated from the other elements); if the polynomial is *f*, the first block is *f*(0), the second is *f*(1), and so on. It's clear that the degree of the polynomial will equal the number of blocks of input minus 1 (because we fit a polynomial to those first, then use it to construct the extra "check" blocks); and because *d*+1 points uniquely define a polynomial of degree *d*, garbling any number of blocks (up to the radiation parameter) will leave a number of undamaged blocks equal to the original input, which is enough information to reconstruct the same polynomial. (We then just have to evaluate the polynomial to ungarble a block.) ### Base conversion The final consideration left here is to do with the actual values taken by the blocks; if we do polynomial interpolation on the integers, the results may be rational numbers (rather than integers), much larger than the input values, or otherwise undesirable. As such, instead of using the integers, we use a finite field; in this program, the finite field used is the field of integers modulo *p*, where *p* is the largest prime less than 128*radiation*+1 (i.e. the largest prime for which we can fit a number of distinct values equal to that prime into the data part of a block). The big advantage of finite fields is that division (except by 0) is uniquely defined and will always produce a value within that field; thus, the interpolated values of the polynomials will fit into a block just the same way that the input values do. In order to convert the input into a series of block data, then, we need to do base conversion: convert the input from base 256 into a number, then convert into base *p* (e.g. for a *radiation* parameter of 1, we have *p* = 16381). This was mostly held up by Perl's lack of base conversion routines (Math::Prime::Util has some, but they don't work for bignum bases, and some of the primes we work with here are incredibly large). As we're already using Math::Polynomial for polynomial interpolation, I was able to reuse it as a "convert from digit sequence" function (via viewing the digits as the coefficients of a polynomial and evaluating it), and this works for bignums just fine. Going the other way, though, I had to write the function myself. Luckily, it isn't too hard (or verbose) to write. Unfortunately, this base conversion means that the input is typically rendered unreadable. There's also an issue with leading zeroes; this program uses the simple (but not perfectly efficient) method of prepending a 1 octet to the program if it starts with a 0 or 1 octet (and reversing the translation when decoding), thus avoiding the issue altogether. It should be noted that we can't have more than *p* blocks in the output (otherwise the indexes of two blocks would become equal, and yet possibly need to produce different outputs form the polynomial). This only happens when the input is extremely large. This program solves the issue in a very simple way: increasing *radiation* (which makes the blocks larger and *p* much larger, meaning we can fit much more data in, and which clearly leads to a correct result). One other point worth making is that we encode the null string to itself, because the program as written would crash on it otherwise. It's also clearly the best possible encoding, and works no matter what the radiation parameter is. ## Potential improvements The main asymptotic inefficiency in this program is to do with the use of modulo-prime as the finite fields in question. Finite fields of size 2n exist (which is exactly what we'd want here, because the blocks' payload sizes are naturally a power of 128). Unfortunately, they're rather more complex than a simple modulo construction, meaning that Math::ModInt wouldn't cut it (and I couldn't find any libraries on CPAN for handling finite fields of non-prime sizes); I'd have to write an entire class with overloaded arithmetic for Math::Polynomial to be able to handle it, and at that point the byte cost might potentially overweigh the (very small) loss from using, e.g., 16381 rather than 16384. Another advantage of using power-of-2 sizes is that the base conversion would become much easier. However, in either case, a better method of representing the length of the input would be useful; the "prepend a 1 in ambiguous cases" method is simple but wasteful. Bijective base conversion is one plausible approach here (the idea is that you have the base as a digit, and 0 as not a digit, so that each number corresponds to a single string). Although the asymptotic performance of this encoding is very good (e.g. for an input of length 99 and a radiation parameter of 3, the encoding is always 128 bytes long, rather than the ~400 bytes that repetition-based approaches would get), its performance is less good on short inputs; the length of the encoding is always at least the square of the (radiation parameter + 1). So for very short inputs (length 1 to 8) at radiation 9, the length of the output is nonetheless 100. (At length 9, the length of the output is sometimes 100 and sometimes 110.) Repetition-based approaches clearly beat this erasure-coding-based approach on very small inputs; it might be worth changing between multiple algorithms based on the size of the input. Finally, it doesn't really come up in the scoring, but with very high radiation parameters, using a bit of every byte (⅛ of the output size) to delimit blocks is wasteful; it would be cheaper to use delimiters between the blocks instead. Reconstructing the blocks from delimiters is rather harder than with the alternating-MSB approach, but I believe it to be possible, at least if the data is sufficiently long (with short data, it can be hard to deduce the radiation parameter from the output). That would be something to look at if aiming for an asymptotically ideal approach regardless of the parameters. (And of course, there could be an entirely different algorithm that produces better results than this one!) ]
[Question] [ **The Challenge** Given the two uppercase hexadecimal strings (both 6 characters long, XXXXXX and YYYYYY) representing RGB values (ranging from `000000` to `FFFFFF` inclusive), and a positive non-zero integer N, display a linear transition of the N+2 colors generated from XXXXXX to YYYYYY that would result in a color gradient. ## **Example** Input ``` FF3762 F08800 9 ``` Output *Please note in our example, I've requested 9 interim steps between the two colors, therefore 11 lines will be displayed from initial color to the final color* ``` FF3762 FD3F58 FC474E FA4F44 F9573A F75F31 F66727 F46F1D F37713 F17F09 F08800 ``` ## **Caveats** While I've gone with a simple linear process of deriving the integer values for the interim colors before converting them back into hexadecimal, your methods may vary. Please consider [the various ways one could round up/down your numbers](https://codegolf.meta.stackexchange.com/questions/5582/things-to-consider-when-creating-a-challenge/5608#5608) accordingly. ## **Testing** To make this interesting, I've provided a snippet to allow testing of your code, inclusive of a button to provide you with two random colors to test your code against. Displaying your results is optional, but it's encouraged! ``` c1=()=>('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6); $("#col").click(function(){ alert("Your two colors are: "+c1()+" and "+c1()+"."); }); $("#colors").blur(function(){ $("#test").empty(); var colArr = $("#colors").val().split("\n"); for(c in colArr){ $("#test").append('<div class="tester" style="background-color:#'+colArr[c]+';">'+colArr[c]+'</div>') } }); ``` ``` .tester{height: 20px; width: 60px;padding: 4px;border: 1px solid black;} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="col">Your two colors</button><br /> <textarea id="colors"></textarea> <div id="test"> </div> ``` 1) You can access two random colors for your test by clicking on the "Your two colors" button. 2) The number of interim steps will be the same as the number of characters in your PPCG username inclusive of spaces, in the case of "WallyWest" it would be 9 (as per my example above). 3) Run your code with the two colors and the number and once you have your generated list, you have the option of pasting your output into the textarea and tabbing away from it to get your generated color gradient. My example is shown here: [![Gradients](https://i.stack.imgur.com/36dL9.png)](https://i.stack.imgur.com/36dL9.png) I must admit, that looks pretty awesome! Please note: As I mentioned, showing your testing of your output using the snippet is optional, but it's encouraged! :) ## **Output** The list output must be in the form of N+2 sets of 6 digit hex numbers separated by line feeds (\n) as shown in my example above. Output can be in the form of separate lines, space/comma separated list, an array or whatever is best suited for your language... *(Thanks @nimi for the heads up)* Please remember, that if you plan on testing your code with the snippet, however you separate each "color" is up to you. ## **Rules** This is code-golf, so the shortest solution in bytes will be crowned the winner. [No loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny), naturally. Input must accept the two strings and a number (which as I said will be equivalent to the number of letters in your username on PPCG, thus your resulting output will always be a minimum of three lines long. [Answer] ## JavaScript (ES6), 130 bytes ``` g= (f,t,n)=>[...Array(++n+1)].map((_,i)=>f.replace(/../g,(e,j)=>((`0x${e}`*(n-i)+`0x${t[j]+t[j+1]}`*i)/n|256).toString(16).slice(1))) ; p=_=>g(f.value,t.value,+n.value).map(e=>o.insertRow().insertCell().appendChild(document.createTextNode(e)).parentNode.bgColor=e); ``` ``` <input id=f value=e14f09><input id=t value=9a04f6><input id=n value=4 type=number><input type=button onclick=p() value=Go!><table id=o bgcolor=black cellpadding=4> ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 44 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) Prompts for **N**, then **B**eginning-color, then **E**nding-color. Needs `⎕IO←0` which is default on many systems. ``` h[↑⌊B∘+¨(⍳2+N)×(-/E B←(h←⎕D,⎕A)∘⍳¨⍞⍞)÷1+N←⎕] ``` `h[`...`]` index into **h** (which has a value when we finish evaluating the the bracket's content)  `N←⎕` prompt for numeric **N** (4)  `1+` add one to **N** (5)  `(`...`)÷` use that to divide the result of...   `⍞⍞` prompt for two character strings ["7E0E7E","FF3762"]   `(`...`)∘⍳¨` find the indices of the each string's characters in...    `⎕D,⎕A` **D**igits followed by **A**lphabet    `h←` assigned to **h**   now we have "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"   `E B←` assign the indices to **E** and **B** [[7,14,0,14,7,14],[15,15,3,7,6,2]]   `-/` subtract and enclose **B** from **E** [[-8,-1,-3,7,1,12]]   the result so far is [[-1.6,-0.2,-0.6,1.4,0.2,2.4]]  `(`...`)×` multiply this by...   `2+N` two plus **N** (6)   `⍳` first integers [0,1,2,3,4,5]  this gives us [[0,0,0,0,0,0],[-1.6,-0.2,-0.6,1.4,0.2,2.4],[-3.2,-0.4,-1.2,2.8,0.4,4.8],...]  `B∘+¨` add **B** to each [[15,15,3,7,6,2],[13.4,14.8,2.4,8.4,6.2,4.4],[11.8,14.6,1.8,9.8,6.4,6.8],...]  `⌊` round down [[15,15,3,7,6,2],[13,14,2,8,6,4],[11,14,1,9,6,6],...]  `↑` make list of lists into table ``` [[15,15, 3, 7, 6, 2] [13,14, 2, 8, 6, 4] [11,14, 1, 9, 6, 6] [10,14, 1,11, 6, 9] [ 8,14, 0,12, 6,11] [ 7,14, 0,14, 7,14]] ``` here we index into **h**, giving ``` [["F","F","3","7","6","2] ["D","E","2","8","6","4] ["B","E","1","9","6","6] ["A","E","1","B","6","9] ["8","E","0","C","6","B] ["7","E","0","E","7","E]] ``` which is the same as ``` [["FF3762"] ["DE2864"] ["BE1966"] ["AE1B69"] ["8E0C6B"] ["7E0E7E"]] ``` and prints as ``` FF3762 DE2864 BE1966 AE1B69 8E0C6B 7E0E7E ``` [![gradient](https://i.stack.imgur.com/eLx7L.png)](https://i.stack.imgur.com/eLx7L.png) [TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%u2359%u2359%20%u2206%u2190%28%27FF3762%27%20%277E0E7E%27%29%204%20%u22C4%20h%5B%u2191%u230AB%u2218+%A8%28%u23732+N%29%D7%28-/E%20B%u2190%28h%u2190%u2395D%2C%u2395A%29%u2218%u2373%A8%u2359%u2359%29%F71+N%u2190%u2206%5D&run) [Answer] # Pyth - 35 bytes Horribly golfed, just gave up. ``` j++hQsMCm.HMsM:F+dc-FdvzCmiR16cd2Qe ``` [Try it online here](http://pyth.herokuapp.com/?code=j%2B%2BhQsMCm.HMsM%3AF%2Bdc-FdvzCmiR16cd2Qe&input=%227cb472%22%2C+%2293fb8a%22%0A8&debug=0). Example: [![example](https://i.stack.imgur.com/n9flD.png)](https://i.stack.imgur.com/n9flD.png) [Answer] ## PowerShell v2+, ~~176~~ ~~159~~ 150 bytes ``` param($a,$b,$n)$x=$a-split'(..)'-ne'';$a;++$n..1|%{$j=$_;-join($x=$x|%{"{0:x2}"-f(+"0x$_"-[int]((+"0x$_"-"0x$(($b-split'(..)'-ne'')[$i++%3])")/$j))})} ``` Takes the input as two strings and a number, then converts the start string into an array of strings split on every two characters, stores that into `$x`. We then output `$a` as our starting section, and loop from `++$n` to `1` (to ensure proper fenceposting). Each iteration, sets helper `$j` to the current number (used later for ensuring we've got the right number of steps between where we're currently at to our destination) and calculates the next step based on a loop through `$x`. Each inner loop is just an assignment. We're setting `$x` at the appropriate place equal to a new string `"{0:x2}"` using the `-f`ormat operator. The `x2` here specifies a two-digit hexadecimal output, and the input is the right-hand side of the `-f` operator. PowerShell has a native hexadecimal-to-decimal operator `0x`, so this lengthy parens-nested expression is using that operator to convert the current hex to numbers, subtracting to find the difference yet to go (done by dynamically splitting `$b` here just like we did to `$a`, and using modulo to select the right element), dividing by `$j` steps remaining, casting to an `[int]` (PowerShell does banker's rounding by default), and subtracting that step-count from the current hex to get what our next hex needs to be. The result of that calculation is stored back into `$x` as three hex elements. That's encapsulated in parens to create a copy on the pipeline, and `-join`ed together into a single string. All those resultant strings are left on the pipeline, and output via implicit `Write-Output` happens at program execution. --- ### Example I was given **0ba7c5** and **6c0e50** for my two colors, and **TimmyD** has 6 characters in it. ``` PS C:\Tools\Scripts\golfing> .\rgb-gradients-generation.ps1 '0ba7c5' '6c0e50' 6 0ba7c5 1991b4 277ba3 356592 434f82 513971 5f2361 6c0e50 ``` [![Gradient Example](https://i.stack.imgur.com/EUojb.png)](https://i.stack.imgur.com/EUojb.png) [Answer] # [MATL](http://github.com/lmendo/MATL), 31 bytes ``` 2+1yhjjh2e!1ZA3e!b:1&Ynk8W5Y2Za ``` This uses linear interpolation with rounding down. Input format is ``` 9 FF3762 F08800 ``` [**Try it online!**](http://matl.tryitonline.net/#code=MisxeWhqamgyZSExWkEzZSFiOjEmWW5rOFc1WTJaYQ&input=OQpGRjM3NjIKRjA4ODAw) ### Graphical output, 31 bytes ``` 2+1yhjjh2e!1ZA3e!b:t2YG1&Ynk2ZG ``` This is the result for inputs ``` 5 FF3762 F08800 ``` [![enter image description here](https://i.stack.imgur.com/gBF4n.png)](https://i.stack.imgur.com/gBF4n.png) Try it in [**MATL Online**](https://matl.io/?code=2%2B1yhjjh2e%211ZA3e%21b%3At2YG1%26Ynk2ZG&inputs=5%0AFF3762%0AF08800&version=19.1.0)! The interpreter is currently experimental. If you don't get any output refresh the page and press "Run" again. [Answer] # Python 2, 189 bytes ``` w='[int(%s[i:i+2],16)for i in range(0,6,2)]' def f(a,b,n): l=lambda x,y:'%02x'%int((x*(n-i)+y*i)/n);c,d,e=eval(w%'a');f,g,h=eval(w%'b');n+=1 for i in range(n+1):print l(c,f)+l(d,g)+l(e,h) ``` [![gradient screenshot](https://i.stack.imgur.com/7JBWS.png)](https://i.stack.imgur.com/7JBWS.png) [Answer] # [Groovy] Final Update (199 Bytes) - As per request ## Non-golf ``` def g(a,b,n){ (0..(1.0/n)).collect{ c-> x={s->s.split("(?<=\\G.{2})").collect{Integer.parseInt(it,16)}}; (0..2).collect { (int)(x(a).get(it)*n*c+x(b).get(it)*(1-n*c)) }.collect { String.format("%X", it) }.join() } } g('FFFFFF','000000',1/10​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​)​​​​​​​​​​​​​​ ``` ## Golf ``` g(a,b,n){(0..(1.0/n)).collect{c->x={s->s.split("(?<=\\G.{2})").collect{Integer.parseInt(it,16)}};(0..2).collect {(int)(x(a).get(it)*n*c+x(b).get(it)*(1-n*c))}.collect{String.format("%X",it)}.join()}} ``` Try the final here: <https://groovyconsole.appspot.com/script/5130696796405760> --- # OLD VERSIONS BELOW, DECLINED BY OP --- # Groovy (123 Bytes) ## Golf ``` def g(r,g,b,r2,g2,b2,s){(1..(1.0/s)).collect{c->[(int)(r*s*c+r2*(1-s*c)),(int)(g*s*c+g2*(1-s*c)),(int)(b*s*c+b2*(1-s*c))]}} ``` ## Non-golf ``` def g(r,g,b,r2,g2,b2,s){ (1..(1.0/s)).collect { c -> [(int)(r*s*c+r2*(1-s*c)),(int)(g*s*c+g2*(1-s*c)),(int)(b*s*c+b2*(1-s*c))] } } ``` ## Inputs ``` r,g,b -> Starting RGB Color r2,g2,b2 -> Ending RGB Color s -> Gradient step ``` ## Output Example ``` (00,00,00,255,255,255,.5) ``` results in ``` [ [255, 255, 255] [127, 127, 127] [0, 0, 0] ] ``` Try it yourself: <https://groovyconsole.appspot.com/script/5184465357766656> # With Hex Conversions Included Guess I'm kind of cheating as well... Here's the script with using hex: ## New code with hex conversions: ``` ​ def g(r,g,b,r2,g2,b2,s){ (0..(1.0/s)).collect { c -> String.format("%X", ((int)(r*s*c+r2*(1-s*c)))) + String.format("%X", ((int)(g*s*c+g2*(1-s*c)))) + "" + String.format("%X", ((int)(b*s*c+b2*(1-s*c)))) } } g(126,34,166,218,26,33,0.0625)​ ``` ## 188 characters when golfed: ``` def g(r,g,b,r2,g2,b2,s){(0..(1.0/s)).collect {c->String.format("%X",((int)(r*s*c+r2*(1-s*c))))+String.format("%X",((int)(g*s*c+g2*(1-s*c))))+String.format("%X",((int)(b*s*c+b2*(1-s*c))))}} ``` ## Output for 000000 to FFFFFF and 16 (Username Length) ``` g(00,00,00,255,255,255,0.0625).each{println it}​ ``` [![Monochromatic Gradient with 1/16 Steps](https://i.stack.imgur.com/wAwlq.png)](https://i.stack.imgur.com/wAwlq.png) [Answer] ## R, 68 bytes There is a built-in function that interpolates two colours: ``` a=scan(,'') colorRampPalette(paste0("#",a[1:2]))(as.numeric(a[3])+2) ``` Input: ``` d9e7a5 3ef951 15 ``` Output: a vector with values ``` "#D9E7A5" "#CFE89F" "#C5E99A" "#BBEA95" "#B2EB90" "#A8EC8A" "#9EED85" "#95EE80" "#8BF07B" "#81F175" "#78F270" "#6EF36B" "#64F466" "#5BF560" "#51F65B" "#47F756" "#3EF951" ``` Colour specification in R requires a hash symbol. [![Colour ramp](https://i.stack.imgur.com/pIuMi.png)](https://i.stack.imgur.com/pIuMi.png) Let’s plot something, like a function: ``` filled.contour(outer(1:20, 1:20, function(x,y) sin(sqrt(x*y)/3)), col = colorRampPalette(paste0("#",a[1:2]))(as.numeric(a[3])+2)) ``` [![sin(sqrt(x*y)/3)](https://i.stack.imgur.com/CDXX5.png)](https://i.stack.imgur.com/CDXX5.png) [Answer] # C, 175 169 168 bytes ``` i;j;x[6];f(a,b,n)char*a,*b;{char*f="%2x%2x%02x";for(n++;i<=n;i++,puts(""))for(j=sscanf(a,f,x,x+1,x+2)-sscanf(b,f,x+3,x+4,x+5);j++<printf(f+6,x[j]+(x[j+3]-x[j])*i/n););} ``` Ungolfed: ``` int i, j; int x[3], y[3]; f(char *a, char *b, int n) { sscanf(a, "%2x%2x%2x", &x[0], &x[1], &x[2]); sscanf(b, "%2x%2x%2x", &y[0], &y[1], &y[2]); for(i = 0, n++; i <= n; i++) { for(j = 0; j < 3; j++) printf("%02x", x[j] + (y[j] - x[j]) * i / n); puts(""); } } ``` Thanks to @h-walters for shaving off 5 bytes! [Answer] # sh + ImageMagick, 81 bytes ``` convert -size 1x$((2+$3)) gradient:#$1-#$2 -depth 8 txt:-|grep -o "[A-F0-9]\{6\}" ``` usage: ``` > ./grad.sh FF3762 F08800 9 FF3762 FE3F58 FC474E FB4F45 F9573B F86031 F66827 F5701D F37814 F2800A F08800 ``` ("-depth 8" is not necessary if your IM is compiled with 8bpp as the default) ]
[Question] [ The seam carving algorithm, or a more complex version of it, is used for content-aware image resizing in various graphics programs and libraries. Let's golf it! Your input will be a rectangular two dimensional array of integers. Your output will be the same array, one column narrower, with one entry removed from each row, those entries representing a path from top to bottom with the lowest sum of all such paths. ![Seam carving illustration](https://i.stack.imgur.com/MINAE.png) <https://en.wikipedia.org/wiki/Seam_carving> In the above illustration, each cell's value is shown in red. The black numbers are the sum of a cell's value and the lowest black number in one of the three cells above it (pointed to by the green arrows). The white highlighted paths are the two lowest sum paths, both with a sum of 5 (1+2+2 and 2+2+1). In a case where there are two paths tied for the lowest sum, it does not matter which you remove. Input should be taken from stdin or as a function parameter. It can be formatted in a manner convenient to your language of choice, including brackets and/or delimiters. Please specify in your answer how the input is expected. Output should be to stdout in an unambiguously delimited format, or as a function return value in your language's equivalent to a 2d array (which might include nested lists, etc). Examples: ``` Input: 1 4 3 5 2 3 2 5 2 3 5 2 4 2 1 Output: 4 3 5 2 1 4 3 5 3 5 2 3 or 3 2 5 3 5 4 2 1 5 2 4 2 Input: 1 2 3 4 5 Output: 2 3 4 5 Input: 1 2 3 Output: (empty, null, a sentinel non-array value, a 0x3 array, or similar) ``` EDIT: The numbers will all be non-negative, and every possible seam will have a sum that fits in a signed 32 bit integer. [Answer] # CJam, ~~51~~ 44 bytes ``` {_z,1$,m*{_1>.-W<2f/0-!},{1$.=:+}$0=.{WtW-}} ``` This is an anonymous function that pops a 2D array from the stack and pushes one in return. Try the test cases online in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%2F%3A~%20e%23%20Split%20input%20at%20linefeeds%20and%20interpret%20each%20line.%0A%0A%7B_z%2C1%24%2Cm*%7B_1%3E.-W%3C2f%2F0-!%7D%2C%7B1%24.%3D%3A%2B%7D%240%3D.%7BWtW-%7D%7D%0A%0A%25%3Ap%20%20%20e%23%20Execute%20the%20anonymous%20function%20for%20each%20line%20and%20print%20the%20results.&input=%5B%5B1%204%203%205%202%5D%20%5B3%202%205%202%203%5D%20%5B5%202%204%202%201%5D%5D%0A%5B%5B1%202%203%204%205%5D%5D%0A%5B%5B1%5D%20%5B2%5D%20%5B3%5D%5D).1 ### Idea This approach iterates over all possible combinations of row elements, filters out those that do not correspond to seams, sorts by the corresponding sum, select the minimum and removes the corresponding elements from the array.2 ### Code ``` _z, e# Get the length of the transposed array. Pushes the number of columns (m). 1$, e# Get the length of the array itself. Pushes the number of rows (n). m* e# Cartesian power. Pushes the array of all n-tuples with elements in [0 ... m-1]. { e# Filter: _1> e# Push a copy of the tuple with first element removed. .- e# Vectorized difference. W< e# Discard last element. 2f/ e# Divide all by 2. 0- e# Remove 0 from the results. ! e# Push 1 if the remainder is empty and 0 otherwise. }, e# Keep only tuples which pushed a 1. e# The filtered array now contains only tuples that encode valid paths of indexes. { e# Sort by: 1$ e# Copy the input array. .= e# Retrieve the element of each row that corresponds to the index in the tuple. :+ e# Add all elements. }$ e# 0= e# Retrieve the tuple of indexes with minimum sum. .{ e# For each row in the array and the corresponding index in the tuple: Wt e# Replace the element at that index with -1. W- e# Remove -1 from the row. } ``` --- 1 Note that CJam cannot distinguish between empty arrays and empty strings, since strings are just arrays whose elements are characters. Thus, the string representation of both empty arrays and empty strings is `""`. 2 While the time complexity of the algorithm shown on the Wikipedia page should be of **O(nm)** for an **n×m** matrix, this one's is at least of **O(mn)**. [Answer] # Haskell, 187 bytes ``` l=length f a@(b:c)=snd$maximum$(zip=<<map(sum.concat))$map(zipWith((uncurry((.drop 1).(++)).).flip splitAt)a)$iterate((\e@(f:_)->[f-1:e,f:e,min(f+1)(l b-1):e])=<<)[[y]|y<-[0..l b-1]]!!l c ``` Usage example: ``` *Main> f [[1,4,3,5,2],[3,2,5,2,3],[5,2,4,2,1]] [[4,3,5,2],[3,5,2,3],[5,4,2,1]] *Main> f [[1],[2],[3]] [[],[],[]] *Main> f [[1,2,3,4,5]] [[2,3,4,5]] ``` How it works, short version: build a list of all paths (1), per path: remove corresponding elements (2) and sum all remaining elements (3). Take the rectangle with the largest sum (4). Longer version: ``` Input parameters, assigned via pattern matching: a = whole input, e.g. [[1,2,4],[2,5,6],[3,1,6]] b = first line, e.g. [1,2,4] c = all lines, except first, e.g. [[2,5,6],[3,1,6]] Step (1), build all paths: iterate((\e@(f:_)->[f-1:e,f:e,min(f+1)(l b-1):e])=<<)[[y]|y<-[0..l b-1]]!!l c [[y]|y<-[0..l b-1]] # build a list of single element lists # for all numbers from 0 to length b - 1 # e.g. [[0],[1],[2]] for a 3 column input. # These are all possible start points \e@(f:_)->[f-1:e,f:e,min(f+1)(l b-1):e] # expand a list of paths by replacing each # path with 3 new paths (up-left, up, up-right) (...)=<< # flatten the list of 3-new-path lists into # a single list iterate (...) [...] !! l c # repeatedly apply the expand function to # the start list, all in all (length c) times. Step (2), remove elements map(zipWith((uncurry((.drop 1).(++)).).flip splitAt)a) (uncurry((.drop 1).(++)).).flip splitAt # point-free version of a function that removes # an element at index i from a list by # splitting it at index i, and joining the # first part with the tail of the second part map (zipWith (...) a) $ ... # per path: zip the input list and the path with # the remove-at-index function. Now we have a list # of rectangles, each with a path removed Step (3), sum remaining elements zip=<<map(sum.concat) # per rectangle: build a pair (s, rectangle) # where s is the sum of all elements Step (4), take maximum snd$maximum # find maximum and remove the sum part from the # pair, again. ``` [Answer] # IDL 8.3, 307 bytes Meh, I'm sure this won't win because it's long, but here's a straightforward solution: ``` pro s,a z=size(a,/d) if z[0]lt 2then return e=a d=a*0 u=max(a)+1 for i=0,z[1]-2 do begin e[*,i+1]+=min([[u,e[0:-2,i]],[e[*,i]],[e[1:*,i],u]],l,d=2) d[*,i]=l/z[0]-1 endfor v=min(e[*,-1],l) r=intarr(z[1])+l for i=z[1]-2,0,-1 do r[0:i]+=d[r[i+1],i] r+=[0:z[1]-1]*z[0] remove,r,a print,reform(a,z[0]-1,z[1]) end ``` Ungolfed: ``` pro seam, array z=size(array, /dimensions) if z[0] lt 2 then return energy = array ind = array * 0 null = max(array) + 1 for i=0, z[1]-2 do begin energy[*, i+1] += min([[null, energy[0:-2,i]], [energy[*,i]], [energy[1:*,i], null]], loc ,dimension=2) ind[*, i] = loc / z[0] - 1 endfor void = min(energy[*,-1], loc) rem = intarr(z[1]) + loc for i=z[1]-2, 0, -1 do rem[0:i] += ind[rem[i+1], i] rem += [0:z[1]-1]*z[0] remove, rem, array print, reform(array, z[0]-1, z[1]) end ``` We iteratively create the energy array and track which direction the seam goes, then construct a removal list once we know the final position. Remove the seam via 1D indexing, then reform back into the array with the new dimensions. [Answer] # JavaScript (*ES6*) 197 ~~209 215~~ Step by step implementation of the wikipedia algorithm. Probably can be shortened more. Test running the snippet in Firefox. ``` // Golfed F=a=>(u=>{for(r=[i=p.indexOf(Math.min(...p))];l--;i=u[l][i])(r[l]=[...a[l]]).splice(i,1)}) (a.map(r=>[r.map((v,i)=>(q[i]=v+~~p[j=p[i+1]<p[j=p[i-1]<p[i]?i-1:i]?i+1:j],j),q=[++l]),p=q][0],p=[l=0]))||r // LESS GOLFED U=a=>{ p = []; // prev row u = a.map( r => { // in u the elaboration result, row by row q=[]; t = r.map((v,i) => { // build a row for u from a row in a j = p[i-1] < p[i] ? i-1 : i; // find position of min in previous row j = p[i+1] < p[j] ? i+1 : j; q[i] = v + ~~p[j]; // values for current row // ~~ convert to number, as at first row all element in p are 'undefined' return j;// position in u, row by row }); p = q; // current row becomes previous row return t; }); n = Math.min(...p) // minimum value in the last row i = p.indexOf(n); // position of minimum (first if there are more than one present) r = []; // result // scan u bottom to up to find the element to remove in the output row for(j = u.length; j--;) { r[j] = a[j].slice(); // copy row to output r[j].splice(i,1); // remove element i = u[j][i]; // position for next row } return r; } // TEST out=x=>O.innerHTML += x + '\n'; test=[ [[1,4,3,5,2],[3,2,5,2,3],[5,2,4,2,1]], [[1,2,3,4,5]], [[1],[2],[3],[4]] ]; test.forEach(t=>{ out('Test data:\n' + t.map(v=>'['+v+']').join('\n')); r=F(t); out('Golfed version:\n' + r.map(v=>'['+v+']').join('\n')) r=U(t); out('Ungolfed version:\n' + r.map(v=>'['+v+']').join('\n')) }) ``` ``` <pre id=O></pre> ``` [Answer] # Pip, 91 bytes This won't win any prizes, but I had fun working on it. Whitespace is for cosmetic reasons only and is not included in the byte count. ``` { p:{(zaj-1+,3RMv)} z:a w:,#(a0) Fi,#a Fjw Ii z@i@j+:MN(pi-1) s:z@i Ti<0{ j:s@?MNs a@i@:wRMj s:(p--i) } a } ``` This code defines an anonymous function whose argument and return value are nested lists. It implements the algorithm from the Wikipedia page: `a` (the argument) is the red numbers, and `z` is the black numbers. Here's a version with test harness: ``` f:{p:{(zaj-1+,3RMv)}z:aw:,#(a0)Fi,#aFjwIiz@i@j+:MN(pi-1)s:z@iTi<0{j:s@?MNsa@i@:wRMjs:(p--i)}a} d:[ [[1 4 3 5 2] [3 2 5 2 3] [5 2 4 2 1]] [[1 2 3 4 5]] [[1] [2] [3]] ] Fld P(fl) ``` Results: ``` C:\> pip.py minSumSeam.pip -p [[4;3;5;2];[3;5;2;3];[5;4;2;1]] [[2;3;4;5]] [[];[];[]] ``` And here's the rough equivalent in Python 3. If anyone wants a better explanation of the Pip code, just ask in the comments. ``` def f(a): z = [row.copy() for row in a] w = range(len(a[0])) for i in range(len(a)): for j in w: if i: z[i][j] += min(z[i-1][max(j-1,0):j+2]) s = z[i] while i >= 0: j = s.index(min(s)) del a[i][j] i -= 1 s = z[i][max(j-1,0):j+2] return a ``` ]
[Question] [ A near-repdigit number is a positive integer where all the digits are the same, except one. For example 101 and 227 are near-repdigits. A near-repdigit prime is a near-repdigit that is also prime. For example: 101, 113, 131, 151, 181, 191, 199, 211, 223, 227, 229, 233, 277, 311, 313, 331, 337, 353, 373, 383, 433, 443, 449, 499, 557, 577, 599, 661, 677, 727, 733, 757, 773, 787, 797, 811, 877, 881, 883, 887, 911, 919, 929, 977, 991, 997, 1117, 1151, 1171, 1181, 1511 These are all near-repdigit primes. The smallest near-repdigit prime has two digits, but it is an open mathematical question whether there exists a near-repdigit prime for every possible number of digits larger than 2. It is conjectured, by me, that the answer is in fact yes. # Task For each integer `n` where `n >= 2`, compute a near-repdigit prime with `n` digits. Your code can either output a near-repdigit prime with 2, 3, ... digits or, as they are easily compressible, output a compressed representation of each number. For example, any near-repdigit can be represented by four smaller numbers. The first is the number of digits, the second the majority digit, the third the minority digit and the fourth the location of the minority digit. You can choose whichever representation you prefer. ## Primality testing There are [many different ways](https://en.wikipedia.org/wiki/Primality_test) to test if a number is prime. You can choose any method subject to the following conditions. * You can use any primality test that is guaranteed never to make a mistake. * You can use any well-known primality test which hasn't been proved to be correct but for which there is no known example number for which it gives the wrong answer. * You can use a probabilistic primality test if the probability of giving the wrong answer is less than 1/1000. I will test your code for 5 minutes on my ubuntu 22.04 machine, but please quote how high you get on your machine in your answer. This challenge is judged per language. In the *very* unlikely event that you find a number of digits n for which there is no near-repdigit prime, I will award a 500-rep bounty and you will get mathematical immortality. # Results so far * **n=1291** by Kirill L. in **Julia** * **n=1291** by c-- in **C** with gmp * **n=1232** by jdt in **C++** with gmp * **n=972** by Kirill L. in **Julia** * **n=851** by alephalpha in **Pari/GP** * **n=770** by ZaMoC in **Wolfram Language** (not tested on my PC) * **n=722** by gsitcia in **Pypy/Python** * **n=721** by jdt in **C++** * **n=665** by c-- in **C++** * **n=575** by Seggan in **Kotlin** * **n=403** by Arnauld in **nodejs** * **n=9** by py3\_and\_c\_programmer in **Python** [Answer] # [Julia](https://julialang.org) n = 972 (single-threaded) ``` using Primes, ThreadPools function nrdprime(n) a = fill(0, n) for j = 1:9 a[1:n] .= j for k = n:-1:1, l = 0:9 if j == l continue end if l == 0 && k == 1 continue end a[k] = l if iseven(a[n]) continue end x = parse(BigInt, join(a)) if isprime(x) print("$n $j $l $k\n") return x end a[k] = j end end println(n, " has no answer") end @qthreads for i = 2:2000 nrdprime(i) end ``` Uses Primes.jl package (`import Pkg; Pkg.add("Primes")`). According to the source code, it relies on Miller-Rabin algorithm implementation from libgmp library. UPDATE: Added multithreading with ThreadPools.jl (`import Pkg; Pkg.add("ThreadPools")`). Compared to Base.Threads module, using a pool allows scheduling calculations in a more convienient way for our use case. In order to take advantage of concurrency, run the program with `julia --threads N`, setting the number N in accordance with your CPU specification. The output was changed to compressed form (`n major minor position`) and I also tweaked the code a bit to reduce the number of array allocations, but it looks like this isn't really a bottleneck. [Try it online!](https://tio.run/##ZZDBbsMgDIbvfYpfOVQgZRLZrUi97LZnqHpALdmcMFMRsuXtMzMaVVMv2P79@Qc8zIHcuvYzXzJFBqfrLdGXV6yxA/qYMOCIzh5ajJKwfels1yJIbuxBEID6whxFu0TOxLOH5@vWCqVlsN@XeXF6hpx49RSCGlqwrtJpPIsaNhOa/Ldn5U581s8Gi6A3lyav3ujjnXOLIZLQWj/m66@WqgBScg6suEWDRgbuMdzjuIHJ5zkxlr@yXljPfw6fbgJHOJ5@fGr0TpC17I7kZa@2M8Y8Nku6OKy/ "Julia 0.4 – Try It Online") for `n` up to about 550 in 1 min, using an ancient version of Julia that still has primes-related functionality integrated in base, and thus available on TIO. [Answer] # [C++ (gcc)](https://gcc.gnu.org/) with boost, n = 595 ~354 digits in 60 seconds on TIO. ~595 digits in 5 minutes on my Windows machine, compiled with MSVC. ``` #include <atomic> #include <chrono> #include <iostream> #include <mutex> #include <thread> #include <unordered_map> #include <boost/multiprecision/miller_rabin.hpp> namespace mp = boost::multiprecision; std::atomic<int> digits{ 2 }; std::mutex mtx; std::unordered_map<int, mp::cpp_int> results; mp::cpp_int calcPrimes(int n) { char buf[10000] = { 0 }; for (int i = '1'; i <= '9'; i+=2) { std::memset(buf, i, n); for (int j = '0'; j <= '9'; j++) { if (j != i) { for (int k = 0; k < n; k++) { if (k > 0 || j > '0') { buf[k] = j; mp::cpp_int num(buf); if (miller_rabin_test(num, 10)) { return num; } buf[k] = i; } } } } } return 0; } void threadJob() { for (;;) { int n = digits.fetch_add(1); auto result = calcPrimes(n); mtx.lock(); results[n] = result; mtx.unlock(); } } int main() { int count = 1; const auto start = std::chrono::steady_clock::now(); const auto tc = std::thread::hardware_concurrency(); std::vector<std::thread> threads; for (int j = 0; j < tc; j++) threads.emplace_back(threadJob); for (;;) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); mtx.lock(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - start); for (const auto& result : results) { std::cout << std::setfill(' ') << std::setw(3) << result.first << ": " << result.second; std::cout << " time: " << seconds.count() << " sec, count: " << count++ << "\n"; if (result.second == 0) { std::cout << "Mathematical Immortality!!!"; exit(1); } } results.clear(); mtx.unlock(); } for (int j = 0; j < tc; j++) threads[j].join(); } ``` [Try it online!](https://tio.run/##lVRNb9swDL37V6gZsNjIR5MWO8x2ct@AYbt3haHISiPHkgxJ7ge6/PVllGUncpq0mA6JRfGRTxQfSVVNHgjZ7z8xQco6pyjFRnJGlsHRQjZKCulbmNRGUcx9G68NffYNZgMuuW@phVQ5VTTPOK78g5WEgNe8Lg2rFCVMMymuOStLqjKFV0xMNxUAAoE51RUmFPEKLVADi@M@LgkCbfI4dvdImTBLlLMHZvQrukG7xJ02bBE3z@2@R82CxpAijklVZU0ERTVk0RDcMyOCS/JLMSAV2q2IgtcAwSIbrNCqXt/NZ7Dugeormtnc9nAtFWrcGdiH82ECHyl8fbVfo8VN1Hi5QHY5vpRrakKIOUZsDJmSw/khXmHjzSBKcYhXjEbRwfEY0i62RmGBrhaIRT1736uXYAsJZgn8pUjAnx/7MrrLtUVLqMGfP8BuaWlGZz3P4@2y5dzaUhbJRR//bUTNbbmiy96Wld9kmaHahIAbo/ksii7iLnO0S1FTK2HTX868@/iW7Dz6LbJvOe7cl/ttOc2SYBcEj5LlyInzu1yFXc82r5wkp93XlBL4OAlN19SQTYbzPJx7lcW1ka1EwNVThd@nILZpKck29GytrO6EvbLb9AG18CE7y98y4piJMGppNkqUtbC5586RSKGNo6UNVvakkZEbZXGsDdz@JSM2eBwL@dRl8ICGdChXrDgGVedPWNEMvEitFBXkpQM2jo@UGKlSD7RsK61PtF84KYFSIc@JTlvElPKqhFmXrTBU4PBgUfLec7Wpmc460rqktMrAPexVwDY@0xRukuvwC7T7@w/lSuncT4uZ1wobmLwZwdqk/To7xDL8qPpo4h7qdK4d3@Nz12Bx1zXRiRJdDlkblKZuAyNzDfcMh2gY@can8LbZu0DTNVO6AQ1iNPDsjn1yOckAHgv6vEW1l502vRhGzgGMY9edrVfzPRo1p7/FIHkzlHvJ0QL65KMB3ef0A5sN5fAioEP0jXOpDC6Zebm6uhq8HSr0mZmels9NEU@qU1JSrMLofZn@b6/fFffTQlpN2xG13/8l6xI/6P3k5@1@Ujmnfw "C++ (gcc) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), at least n=116 ``` ƛkdn1-v*9ʀẊ'ƒc¬;9ʀẊƛf÷$Ṁ;U'⌊=$⌊æ∧;h ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwixptrZG4xLXYqOcqA4bqKJ8aSY8KsOznKgOG6isabZsO3JOG5gDtVJ+KMij0k4oyKw6biiKc7aCIsIiIsIjIwMCJd) A simple modification of my answer to a CMC for near-rep numbers of length 8. It can do up to n=116 in a minute on the online interpreter. Maybe more depending on where you run it. The score here is cumulative total. If you want individual limits of `n`, it can handle at least n=200 in less than 10 seconds with a few modifications. I'll explain this properly a bit later, but basically: `kd7v*9ʀẊ` gets the Cartesian product of each digit from 0 to 9 repeated n times and the range [0, 9]. `'ƒc¬;` keeps items where the digit from the range isn't in the string (because this Cartesian product is [repeated digit, number to insert at every position]) `9ʀẊ` is once again Cartesian product with range [0, 9]. It gives a list of [[repeated digit, number to insert], location to insert] `ƛf÷$Ṁ;` flattens each list, swaps the order of the number to insert and the position and performs the insertion Finally, `'⌊=$⌊æ∧;` uniquifies the result and keeps only those invariant under conversion to int and which are also prime. [Answer] # [JavaScript (Node.js)](https://nodejs.org), n = 351 Reached \$n=351\$ in 5 minutes on my laptop. Reaches \$n\approx 250\$ in 1 minute on TIO. Uses a Miller-Rabin primality test with 10 rounds. **NB**: Because the challenge allows a probability of false positive as high as 1/1000, we could actually perform fewer rounds -- at least until \$n\$ becomes really large. This would however not improve the performance drastically, as most of the computation is used for processing non-primes for which the test is most likely to fail on the first round anyway. ``` const ROUNDS = 10; function modpow(k, e, m) { let r = 1n; while(e) { if(e & 1n) { r = (r * k) % m; } e >>= 1n; k = (k * k) % m; } return r; } function millerRabin(sz, n, k) { let d = n - 1n, s = 0n; do { s++; d >>= 1n; } while(!(d & 1n)); while(k--) { let a; do { a = BigInt([...Array(sz)].map(_ => Math.random() * 10 | 0).join('')); } while(a < 2n || a > n - 1n); if(millerRabinIteration(n, d, s, a)) { return false; } } return true; } function millerRabinIteration(n, d, s, a) { let x = modpow(a, d, n); if(x == 1n || x == n - 1n) { return false; } for(let i = 0n; i < s - 1n; i++) { x = modpow(x, 2n, n); if(x == n - 1n) { return false; } } return true; } let ts = Date.now(), time; for(let sz = 2; (time = Math.round((Date.now() - ts) / 1000)) < 300; sz++) { console.log(time + 's', 'n=' + sz, search(sz)); } function search(sz) { for(let i = 1; i <= 9; i++) { let a = Array(sz).fill(i); for(let j = 0; j <= 9; j++) { for(let k = j ? 0 : 1; i !=j && k < sz; k++) { a[k] = j; let n = BigInt(a.join('')); if( n % 2n && n % 3n && n % 5n && n % 7n && millerRabin(sz, n, ROUNDS) ) { return n; } a[k] = i; } } } return false; } ``` [Try it online!](https://tio.run/##lVRNb9swDL3nV7CHxtLieE6LYdicZNjQSw/bgA47FcWgxUrjL7mQlbXL4t@ekbZsK0F22CVhRPKR75FMKn6JaqWTJzNVZSwPh1WpKgN3X79/ufkGC5iF0Wi03qqVSUoFRRk/lc8s80H6UHD4MwLIpQFNkQojAZ43SS6ZbH0AyZpJGKOze4AmmGl4BRmHSyii5rluPiUsly0S/cooMDsKpDAtzVYr0NGodltL8lzqO/EzUaza@aB8SusajBFKwRShfajQDpsScWmbqiaTtmTsNFBbLhcsbhlwh2A2nXaMCF80LgcRQGCZT8njrTLsPgiCj1qL39gZfwgK8cR@wGIJn4XZBFqouCwYR56zEPYQ8iAtkYTnUcFGG1tTwByuFOz3iL20dLgtjDo7CtwaqQXJwpBvjJR9ENyZQKvgWuSVHOR3tDV6K/8p71nwXukXpG3XRDRu2yI2iC7Slgg0pmVg2zptqqasdakZoSbtzPB7jvOjNLQnky7XKfrio0ZtVavLmVr/IwGVN7QzN8LIQGEJ7oNJCkmHYdurdui/ioDRO5rtYMutihkb0rAFU3F4jXMOQxzHHK7DMMLkjgjdXpnLIC8fW6QJeJXng6cWHtq01pUUerWhPeLHAxocDZQr3KzRbQHvjjRr1ha9/WIGa5wxS7qN6hBSkj7CrxYhHRCGGLrUFD5ACO/baheLFMZjfMdx7SLI3CQ8jfvsgTKi/oVA1HAw4vQE7Ch7GzD6ko4Bi5B13VtveustWU7GmX@I9m@O90Fuk/0mqKGF@pRC0vnqcztkt6s@HP4C "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3 (PyPy)](http://pypy.org/), n = 808 ~432 digits on TIO in one minute (no multiprocessing) ~808 digits on my computer in 5 minutes ~697 digits on my computer in 5 minutes on 1 core Uses [Baillie-PSW primality testing](https://en.wikipedia.org/wiki/Baillie%E2%80%93PSW_primality_test). Avoids testing any multiple of 2, 3 or 5. ``` # aab -- a in [1,2,3,4,5,6,7,8,9] # -- b in [1,3,7,9] # aba -- a in [1,3,7,9] # -- b in [0,1,2,3,4,5,6,7,8,9] # baa -- a in [1,3,7,9] # -- b in [1,2,3,4,5,6,7,8,9] # b + a*(n-1) != 0 mod 3 aab = [[(a,b) for a in [1,2,3,4,5,6,7,8,9] for b in [1,3,7,9] if (b + a*(n-1))%3] for n in range(3)] aba = [[(a,b) for a in [1,3,7,9] for b in [0,1,2,3,4,5,6,7,8,9] if (b + a*(n-1))%3] for n in range(3)] baa = [[(a,b) for a in [1,3,7,9] for b in [1,2,3,4,5,6,7,8,9] if (b + a*(n-1))%3] for n in range(3)] def f(n): A = (10**n-1)//9 # aab for a,b in aab[n%3]: if baillie_psw(a*A + (b-a)): return (n,a,b,0) # baa B = 10**(n-1) for a,b in baa[n%3]: if baillie_psw(a*A + (b-a)*B): return (n,a,b,n-1) # aba for k in range(1, n-1): B = 10**k for a,b in aba[n%3]: if baillie_psw(a*A + (b-a)*B): return (n,a,b,k) sike def main(): import multiprocessing import time t = time.time() for i in range(3, 2500, 2): if baillie_psw(i): small_primes.append(i) with multiprocessing.Pool(multiprocessing.cpu_count()-1 or 1) as pool: for i in pool.imap(f, range(2, 10000)): print(i, time.time() - t) def baillie_psw(n): for p in small_primes: if n == p: return True if n%p == 0: return False return strong_pseudoprime(n) and lucas_prime(n) small_primes = [2] # calculated out to 3000 in main def ds(d): s = 0 while d%2 == 0: s += 1 d //= 2 return d,s def strong_pseudoprime(n): n1 = n-1 d,s = ds(n1) x = pow(2,d,n) if x == 1 or x == n1: return True for _ in range(s): x = (x*x)%n if x == n1: return True return False # code from https://en.wikipedia.org/wiki/Jacobi_symbol def jacobi(D, n): D %= n t = 1 while D: while D%2 == 0: D //= 2 r = n%8 if r == 3 or r == 5: t = -t n,D = D,n if D%4 == 3 == n%4: t = -t D %= n if n == 1: return t return 0 def sign(n): if n > 0: return 1 if n < 0: return -1 return 0 def isqrt(n): if n < 2: return n k = n//2 k1 = n while k < k1: k1 = k k = (k+n//k)//2 return k def is_square(n): np = isqrt(n) return np*np == n def UVQ(P, Q, D, k, m): u,v,q = 0,0,-1 B = f'{k:b}' B1 = B.rstrip('0') for i in B1: u,v,q = (u*v)%m,(v*v-2*q)%m,(q*q)%m if i == '1': a = P*u + v b = D*u + P*v if a%2: a += m if b%2: b += m u,v,q = (a//2)%m, (b//2)%m, (Q*q)%m if u == 0 or v == 0: return True for _ in range(len(B)-len(B1)-1): u,v,q = (u*v)%m,(v*v-2*q)%m,(q*q)%m if v == 0: return True return False def lucas_prime(n): for D in [5, -7, 9, -11, 13, -15, 17, -19, 21, -23, 25, -27, 29, -31, 33, -35, 37, -39, 41, -43]: J = jacobi(D, n) if J == -1: break if J == 0 and D%n: return False else: if is_square(n): return False else: while J != -1: D = -D - 2*sign(D) J = jacobi(D, n) if J == 0 and D%n: return False P = 1 Q = (1-D)//4 if Q == -1: P = Q = 5 return UVQ(P, Q, D, n+1, n) if __name__ == '__main__': main() ``` [Try it online!](https://tio.run/##nVZZb@M2EH73r2BRCKYUKtZhNxtjXSCBsEWDLpD0egkCgYrkrCqJVnQ4CYr97ekMdVGRDST1g0WOZr755iKVv1TfdsI185f85fU1zvJdUZEyfhA8nc2a52nzoO3uj19/ufjt96@MpDwLQk4Mfx09xxXV9U6fp7zI6Gqlz2Y/Es4DYpqEk1iQW5s5zGVLtmI/sTP2iZ3fgQb@QCNoNVx4I@U84KplLx/pW@wgZsDfYXvYkpwQblBh2jr5YUMsku1C4s5mGMeG3N5SzgKdbHfF0ZDky3E0JN4SqiDrmtuoCVQruHiIqKvfzTDkw05anAH6UODvdYPZeaeb/@9kFkZbsqVCX88w6xfgkdqWYaDNYnEuhbI95EqSYNIniG4FgDZ2@AOPAY/TNI78vHyi3LgA9zQwua6vSRFVdSEIFQzsmaW3wBCjXF2CX3Qrub51BUrvdmVcTpz1kLJZe/BkSITNCCoN@B2dpJeokQdv6XyYUtIQKuMkaiqQ8VjQlkA73lWcRXJfARncnOIfHbITK5VkxFlZFvzrR5MUA4sy42nq5wUAlac8zyMRgvwQosMgAfBT8MBMVHQLBkzlQ0xS6U0UqruuoxA3R1zV94ikIJsNyfsU/VnU0ei1lqOC1St84WnZaLSCsip24gG8RnW4kw7AO@EiJGl9z0u/E8FRqXDA2XLuoCnueXpfp7yKQrKrIe874kLgSBmr0kQWljRsA0JDS66evsVpRELNafj1pEtyAu3Tb0OyWGyIozIOWdngHqTeIAkbHEFbyg0YwA5YiLaXn2Gb756gTiETjQhy9YxMbAIplythT7OK9fCHOpdKgRGTPhvPuibUAhyFGtVDhvMPv98FMfVgnlpcj2hg3PexrSTOGzy3gkkmG4Qhfd2vwNRon94OYIHmLoYvV6u19GlWvV7BBPPQlnlsFKOnLRtbDFVbTgyVMLqOHRJSqdmw2sLCJduXUpr8rLSwPYg/K@K22GOkuHwsqjHUZ@L0Ng2pBINaLJosJbJzlEwnYJHYQ1qlwnC2oTFNTsA@0TuMFj3pOPjlY80LpTthKHtqqoXIDSEHtp2cv/6@odeM3DACXZEwkrUANduzRxwlZrE2bjx1t/N/k3Xwfd4IkOflaQFTEud0bs3fHFWXSkwdHq2Nva5ljO6NvekYj3L9KJ9qwWOkOLfn417DC/faqOHk3o/k@FHhSfm1sX/bdVyDanCc@WxyI@CrYPqqJ8sh38gQbop@dTOQBYhajgT29H58DB6b6DQS9FI35cPWR9faB3N0zOF07sfn7HDwe/LrZMWIecbIOTxsuGptFxcgtM9wAWIHpKYjLzFcgNhBZRfELiq7IHZR2QXxEpWX6vV7BSGpJ48awxXGYMKsBkXEk8kbS14TniYO3C4RLEYX1WgKpvpTm2ECr/Ar1bTHr5qDBeQe3KGOIY8MT5@oHA3vI8Fc94fvjfzEMz0Y9WXXZDddllANFVZqoUcjLE5sSWIGZr4veBb5vpwl38fr0vfbkWq@aF5f/wM "Python 3 (PyPy) – Try It Online") In profiling I found that about 97% of the time was spent in `strong_pseudoprime`, specifically the line `x = pow(2,d,n)`. I wanted to avoid using external libraries in my answer, but it is possible to improve the speed significantly by using gmpy2 (or gmpy\_cffi with pypy), and replacing the line with `x = pow(mpz(2),d,n)`. This achieved ~1050 digits in 5 minutes. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), n=770 ``` (n = #; r = RandomChoice[{1,3,7,9}]; While[! PrimeQ[p = FromDigits@ RandomSample[ Join[Table[r, n - 2], {r1 = RandomChoice@Complement[Range[0, 9], {r}]}, {r}]]] || r1 == r]; i = IntegerDigits@p; f = First /@ Reverse@SortBy[Tally@i, Last]; Flatten[{n, f, Position[i, f[[2]]]}]) & ``` [Try it online!](https://tio.run/##TZBRS8MwEMff9ylOBFGI2FVEhhSKk4Liw9wEH448xJm2YU1S0kMYXT97vbZTl5ccv@R@@V@solJbRWar@iLpLx0kcP4wAwhcrJX78nZZerPV2M7FrbgXi04Oxx@lqTSeAZe8VsFY/YY190wAIAvePpnCUJP@oqNvo2zNvX8UXrxx@K4@GQYB/xzAwTXEUkAb5ifqE9eULV36QWm1I2ReaIwELMa@TnbTJiUcDpNikCUQxjkMe58d6UKHY9p6wDnjzISG4CaFtf7WodHpxgd63HPSqtqnRsCramiUZJUi0g5bJyAXsPKNIeMd8p0cMea3O3kFF/00I3@WI8ACd1KKdidicRdFnZz1Pw "Wolfram Language (Mathematica) – Try It Online") n=500 in 1min n=770 in 5min [Answer] # [Kotlin](https://kotlinlang.org), n = 575 ``` fun main() { var n = 2 while (true) { println(primesForN(n)) n++ } } fun primesForN(n: Int): String { for (major in '1'..'9') { // Java's String.repeat is much faster than Kotlin's @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") val digits = (major.toString() as java.lang.String).repeat(n - 1) for (minor in '0'..'9') { if (major == minor) continue if (major.isEven()) { if (minor.isEven()) continue val number = digits + minor if (number.toBigInteger().isProbablePrime(10)) { return number } } else { for (i in 0 until n - 1) { if ((i == n - 1 && minor.isEven()) || (i == 0 && minor == '0')) continue val number = digits.substring(0, i) + minor + digits.substring(i) if (number.toBigInteger().isProbablePrime(10)) { return number } } } } } return "No near-repdigit primes found for n = $n" } fun Char.isEven() = this == '0' || this == '2' || this == '4' || this == '6' || this == '8' ``` [Try it online!](https://tio.run/##pZRNb9pAEIbv/hUjFMU2NMZEVdRGQiqliZSGACrc0ZIs9qb2GO0HPTT8djrrNV/BtIfugfV435195xmzPwudCdxsFgYhZwKDEH57QGPFJCB04bqMfqUi4xBoafhWYMdSCtQZBjTnXN0XchhgGO6WsdUqn9fe2vPazaYHTegX@dJoroBlGSBn8kry5YtIhAaXBRaFBAaJWHGEjGOiU8CItrY9a/LwqFt4QB3ewkSTj6TyZbcHOXulSSD4HT@K/M/@oet2G76zFfNVtTEiB5xpEApy85zCginNJeiUITyWfHy12/xlYpZLyZUKGuNBb3o/@vE06w96k8nsqTce332bTUezx9F08DBs7EGsWAZljYqIOnORLtzpRJwpeCVDUcbIjHsbVqYChCvo7DO56gRW1cWn1dkhFlsE3S6U6hCeC9QCDa8XRkLdEfAgfJ9qp7JZDlS16ba1osnnRLC7LbrlTNQmdlrC8VUk1E6ecBmEdNBYFnM2z/jYNjzoxLXO7JBcG4nVmSeK9dGbNfBM8ZpEJVdhmcZgqDKqoQR/5kxrnOREt5TB5SW8B/T2Bk4R71ZtRC37G70zBCNl5sp9LvEHEOGWKM0nAhGetfzfrP/N@5R5TRe84yf3W@VtDItz94LBl7JR9l66wIa9VeyV0E/ZHjwt6ZT@yQ617cIuvD4OPx6HN8fhJ3@z@QM "Kotlin – Try It Online") Gotta love Kotlin's `CharRange`. The `isProbablePrime` test is a Miller-Rabin test that has a \$\frac{1}{2^{10}}\$ chance of failing. For ease, [here](https://drive.google.com/file/d/1-3rczmlzqyqlrN5eYSoR66JTAmukwih2/view?usp=sharing) is the jar file. [Answer] # [C++ (clang)](http://clang.llvm.org/) with [GMP](https://gmplib.org/) n = 1164 To be compiled with the following flags: -O3 -lgmp -lpthread. ``` #include <atomic> #include <chrono> #include <cstring> #include <iostream> #include <mutex> #include <thread> #include <map> #include <vector> #include <gmp.h> struct result { char major; char minor; int pos; }; std::atomic<int> digits{ 2 }; std::atomic<bool> timeOut{ false }; std::mutex mtx; std::map<int, result> results; result calcPrimes(int n) { mpz_t x; char buf[10000] = { 0 }; for (char i = '1'; i <= '9'; i+=2) { std::memset(buf, i, n); for (char j = '0'; j <= '9'; j++) { if (j != i) { for (int k = 0; k < n; k++) { if (k > 0 || j > '0') { buf[k] = j; mpz_init_set_str(x, buf, 10); if (mpz_probab_prime_p(x, 10)) { return { i, j, k }; } buf[k] = i; } } } } } return {}; } void threadJob() { while (!timeOut) { int n = digits.fetch_add(1); auto result = calcPrimes(n); mtx.lock(); results[n] = result; mtx.unlock(); } } int main() { int count = 0; int maxTime = 5 * 60; const auto start = std::chrono::steady_clock::now(); const auto tc = std::thread::hardware_concurrency(); std::vector<std::thread> threads; for (int j = 0; j < tc; j++) threads.emplace_back(threadJob); for (;;) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); mtx.lock(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - start); if (seconds.count() >= maxTime) { timeOut = true; mtx.unlock(); break; } for (const auto& result : results) { std::cout << result.first << ": " << "major: " << result.second.major << ", minor: " << result.second.minor << ", pos: " << result.second.pos; std::cout << ", time: " << seconds.count() << " sec, count: " << ++count << "\n"; } results.clear(); mtx.unlock(); } for (int j = 0; j < tc; j++) threads[j].join(); std::cout << "Time: " << maxTime << " seconds\n"; std::cout << "Count: " << count << "\n"; } ``` [Try it online!](https://tio.run/##lVbBcpswEL3zFWo600LtME476UzB4dJbL@mht7TDyEK2hUFiJJE4Tf3rdVdIYOHYyZSDkVbvrd6udoVJ01ySCvPVfv@WcVK1BUVzrEXNSBYcLGQtBRcji9KS8ZVvYgJsFNe@rW413foGvQZIMYLgxp/eU6KF9C2ruonXWRCA95ZoJKlqKx08BQgessYS1bgUMvXmjPdzxjVqhEqDXWocFElig5vDQoYKtmJaPaGPCJb91YUQVYY0q@ltq5/QEleKDpguJlTrbT/HjXE3dcoy94ZNAztCBFfkuwRvKjSCeOTU183vXKOtJ33RLu@uZvD8QjfoCc3MpmZxKSQKOwSDhfdX71MYzGH0xYwmNx@jDmbdmscqo7WiOgSnU8SmsG86rB8clsbhDNyUg8NyMokG5MFnl9AlCkv05gaxaGQfo4YdTLgb2GCWwmuOOLx83@fZ/V4blEEW/vwBdZmRGZ1EnuabxyR0Y5JZpmcx5hgYZzqHZOVQZeF2irqcXc2i8yyjzjAbKRZ4AS8437wxXKBFZ2nnpZpHUt1KDicPx1VOIWe78wJ2rwfNTrOfM8eWw8yO7G@vDSTtguBesALZbv4mFmFf0g9rVlEUvnG9c1yWXfmDMNt58ZJqss5xUYRXXqZxq4VrIoB6zeMXMPRfXAmyCT2ba7w7bmK3kzGh5T5lZ@IwimrMeBg5mcZARMt1V7aDqcbbHyACjNfoA/rsVojgSlvBSmNpOF3n2QszSZSG/DzmxGybJFw89Ht7RE16lk1nkkBbFg9Y0hxQpJWScvLYEzugvSTnHilzZ6G8@8LILm3zQW/DPked7RgxrZsKE5ovMORmONLI85SmJ@8XvWYq70WritImB3g4ykDNqoopCpEUKryGznj5CG0qLfw4mUUrsWaC5wQrPR/n2TKy8LXso0t7UN6WppEdP@4OHlDZTX/g5y5CV@CgET5LdNxnz0tt6EzI1SYNnjeavY@HonjX13/SF3V0tL8NVICC@dxh4iWTqptfJOiie3efRjdxIBtq3K10mKn9YJ5GmRWHgu/oSUz3fT0rDYgmVY55nGcDMMapbTmHmkxsA5rVn/ziVL5cVmJSUSzD6OU2/9@OuCt/xaUwd4LXc0NAPw7h9JdCH4aJbRA8Zn314juKbrff/yXLCq/U/rKCfzv7y9tPMGqsmn8 "C++ (clang) – Try It Online") [Answer] # Python 3, computed till `n`=8 > > "Takes 51 seconds for 8 digits" > > > Not a very interesting answer, I fear, and it's very slow. ``` from itertools import product as pt def isprime(n): # This was borrowed from https://en.wikipedia.org/wiki/Primality_test # Modified to save bytes unnecessarily if n <= 3:return n > 1 if not n%2 or not n%3:return False for i in range(5, int(n**.5)+1, 6): if not n%i or not n%(i+2):return False return True def isnrep(n): if (not isprime(n)) or not (len(set(str(n)))==2):return False return list(str(n)).count(list(set(str(n)))[0])in[len(str(n))-1, 1] def getnrepfor(n): x=[list(i)for i in eval("list(pt((1,2,3,4,5,6,7,8,9),"+("(0,1,2,3,4,5,6,7,8,9), "*(n-2))+"(1,3,7,9)))")] for i in range(len(x)): for j in range(len(x[i])): x[i][j]=str(x[i][j]) x=[int("".join(i)) if isnrep(int("".join(i))) else '' for i in x] for i in x: if i!='':return i return 'It has been proven that for %d, there does not exist a near-repdigit' % n ``` Back to the bounty... I've found out that the amount of near-repdigit primes actually *increases* when the number of digits is increased. So I guess nobody will get that bounty. Uses the 6k+-1 computation of primes. I've updated this with an approach similar to lyxal's answer, but it hasn't produced much of a speedup. Oh well, guess esoteric languages are faster than those around 1991. [Answer] # [C (gcc)](https://gcc.gnu.org/) + [GMP](https://gmplib.org/), n = 1015 (w/ -j2) * Compile with same flags as in [TIO](https://tio.run/##jVb7b5tIEP6dv2LUqinYkOL0Xg1JpFPrO0WK4lPanCrlLMRjwWvjXQ6WPHrKv36@2QcY25waS@Yxr29m@GYg8fIk2WxepySjjED4dfbH9Dr8PLu9@TiFn33fek1ZUjQpgbOI8uPFRU@Qr8tdQSkWFYnSXWEt0kjwNU0OxPvxUFTQeFfWMIpiKbPEU0kwTahF1SQCbkj5ieZUwD8W4K9hNc0ZSaHgLId1tAyGxJQNiUteB9ZzFzGwrFpEgiZbjCQqkrCs6JrU9q5vKvW1E7Qu95ymQBkVIWdovC6/hQIqXrrwAr/Rkse2vkKN1cJb34W3dBMMGkE0pXCBNeuhiqkLSxdWiNG6yZRru@96fXt15WjnbT1bg9roWuewJsJGOFfi93RRmmqv9uAY1IxXYFM4h0kAFM7O4UPQOag4XTAX9eNzOGkKGIE9wdNYeZ7De8dxDAFaPEwjbKhtipj4JpUOcaURV3Bm6tCo66bouZmTdHdhPF71QTqgJjZOKlHjQnt4HeYSMVcyX40InsxgaWoej5f74VXPM@V3jhEPdPKXcCYoa0hwoDVNHEhu6QSDONKjrHgcxZplYandfnSGsXMuOBCWDmMPN2Yf@9l6Wc79hmqfZ8tC7NOOYUlBomqXuypAj8AVEU3FwG4nChuuR6B7IKtnXAGWJYfPevn49uauoWHJH2T2ynziD8wJdqYz0FY9ZUrvyWOUiF2LD06XF4ys7X6IqrxF77ZUOTTqZuMli6iCuMnuTvwffpnfTX6aa7nZprjck1gfa23iwog3wsyqWVJ6kYdNrwXI7BNjpDJzADMLtgOOMdDkyET254EkPAr7lGdoYUJnRCQLyYSQPJYFTaiwjzQQNsuFNVnz6inkVUqqsCJF9EjSHj9KDNTflaynezdqM8aXA6@oeJKvA31R8ATr48yeeJSlRAaF0bvOFdP1LrCCMKNFSmTJn798mt1@CX@7vJpez4JDQ55luIfQ0B9Q4lNAjXwWsjme6fp8wJLFT0Lh1QwrYiKzD7xcqOk3wjMVz8fbV2@KBnr/v9grnAcXymOsW52ousOXnjMAWZG/EYr/T@pILHJPmDhWFyHjgmZPsh@Xv0//DK9n19Otk7R/wPYSyQED9ayZgs@iYfipgKSMC9K22gypHFvFeSzYWkeU2XghWZW4msWS@/d385b@UstLuWF4XGsY8yGCoyu0gDwKgqG1OxorjiqNdFJvBHX3sKCYj22jCQpzIvDC1tASFLu7PH2Fr5wL8PsErh8o0hakW1@cRDWBt8u3pzurziAi4amtU9nbjGrzSyOJcrBhY6xsteuA7cyiosCieZMv@szF76WoKcRuApnhEn5YkarCmpo6yskpvKnhzluq/OaKNarP/nwvPfKIQzn9eon0//Xy6vZmOrSge81UpXjeBS67Xm/aR5TgESlyZD44XDhC@53d3bdOiUDS2Ht0klvROHyfXr7k1maz8ZYn/yZZEeX1xpu933gGYuMV@F2Lx0r8Bw "C (gcc) – Try It Online"). * Specify number of threads as `-j jobs` depending on your hardware. This uses [`mpz_probab_prime_p()`](https://gmplib.org/manual/Number-Theoretic-Functions) from GMP which uses a combination of a Baille-PSW test, and then Miller-Rabin tests. Output: ***digits majority minority location(1-indexed)***. ``` #define _XOPEN_SOURCE 700 #include <aio.h> #include <gmp.h> #include <pthread.h> #include <stdatomic.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> typedef struct RepDigit { unsigned long maj; unsigned long min; unsigned long pos; } RepDigit; static RepDigit calc_primes(unsigned long digits); static void init_ones(mpz_t rop, unsigned long digits); static void *job(void *); RepDigit calc_primes(unsigned long digits) { mpz_t rep, digit, num; unsigned long i, j, k; mpz_inits(rep, digit, NULL); init_ones(rep, digits); mpz_init_set(num, rep); mpz_add(rep, rep, rep); for (i = 1; i <= 9; mpz_add(num, num, rep), i += 2ul * (1ul + (i == 3))) { mpz_set_ui(digit, 10); for (k = 1; k < digits; mpz_mul_ui(digit, digit, 10), ++k) { mpz_submul_ui(num, digit, i); for (j = k == digits - 1; j <= 9; ++j) { if (j == i) continue; mpz_addmul_ui(num, digit, j); if (mpz_probab_prime_p(num, 5)) goto end; mpz_submul_ui(num, digit, j); } mpz_addmul_ui(num, digit, i); } } end: mpz_clears(rep, digit, num, NULL); return (RepDigit) {i, j, digits - k}; } void init_ones(mpz_t rop, unsigned long digits) { mpz_ui_pow_ui(rop, 10, digits); mpz_sub_ui(rop, rop, 1); mpz_divexact_ui(rop, rop, 9); } void * job(void *arg) { RepDigit p; unsigned long n; char buf[2048][16]; struct aiocb aiocbs[2048], *out; static atomic_ulong digits = 2; (void) arg; for (out = &aiocbs[0];; ++out) { n = atomic_fetch_add_explicit(&digits, 1, memory_order_relaxed); p = calc_primes(n); /* digits majority minority location(1-indexed) */ out->aio_fildes = STDOUT_FILENO; out->aio_offset = 0; out->aio_buf = buf[out - aiocbs]; out->aio_nbytes = snprintf(buf[out - aiocbs], sizeof buf[0], "%lu %lu %lu %lu\n", n, p.maj, p.min, p.pos); out->aio_reqprio = 0; out->aio_sigevent.sigev_notify = SIGEV_NONE; aio_write(out); } /* unreachable */ return NULL; } int main(int argc, char *argv[]) { int opt, jobs; pthread_t t; extern char *optarg; jobs = 1; while ((opt = getopt(argc, argv, "j:")) > 0) { switch (opt) { case 'j': jobs = atoi(optarg); if (jobs > 0) break; /* fallthrough */ default: fprintf(stderr, "usage: %s [-j jobs]\n", argv[0]); exit(EXIT_FAILURE); } } while (jobs --> 1) { pthread_create(&t, NULL, &job, NULL); pthread_detach(t); } job(NULL); /* unreachable */ return 0; } ``` [Try it online!](https://tio.run/##jVb7b5tIEP6dv2LUqinYkOL0Xg1JpFPrO0WK4lPanCrlLMRjwWvjXQ6WPHrKv36@2QcY25waS@Yxr29m@GYg8fIk2WxepySjjED4dfbH9Dr8PLu9@TiFn33fek1ZUjQpgbOI8uPFRU@Qr8tdQSkWFYnSXWEt0kjwNU0OxPvxUFTQeFfWMIpiKbPEU0kwTahF1SQCbkj5ieZUwD8W4K9hNc0ZSaHgLId1tAyGxJQNiUteB9ZzFzGwrFpEgiZbjCQqkrCs6JrU9q5vKvW1E7Qu95ymQBkVIWdovC6/hQIqXrrwAr/Rkse2vkKN1cJb34W3dBMMGkE0pXCBNeuhiqkLSxdWiNG6yZRru@96fXt15WjnbT1bg9roWuewJsJGOFfi93RRmmqv9uAY1IxXYFM4h0kAFM7O4UPQOag4XTAX9eNzOGkKGIE9wdNYeZ7De8dxDAFaPEwjbKhtipj4JpUOcaURV3Bm6tCo66bouZmTdHdhPF71QTqgJjZOKlHjQnt4HeYSMVcyX40InsxgaWoej5f74VXPM@V3jhEPdPKXcCYoa0hwoDVNHEhu6QSDONKjrHgcxZplYandfnSGsXMuOBCWDmMPN2Yf@9l6Wc79hmqfZ8tC7NOOYUlBomqXuypAj8AVEU3FwG4nChuuR6B7IKtnXAGWJYfPevn49uauoWHJH2T2ynziD8wJdqYz0FY9ZUrvyWOUiF2LD06XF4ys7X6IqrxF77ZUOTTqZuMli6iCuMnuTvwffpnfTX6aa7nZprjck1gfa23iwog3wsyqWVJ6kYdNrwXI7BNjpDJzADMLtgOOMdDkyET254EkPAr7lGdoYUJnRCQLyYSQPJYFTaiwjzQQNsuFNVnz6inkVUqqsCJF9EjSHj9KDNTflaynezdqM8aXA6@oeJKvA31R8ATr48yeeJSlRAaF0bvOFdP1LrCCMKNFSmTJn798mt1@CX@7vJpez4JDQ55luIfQ0B9Q4lNAjXwWsjme6fp8wJLFT0Lh1QwrYiKzD7xcqOk3wjMVz8fbV2@KBnr/v9grnAcXymOsW52ousOXnjMAWZG/EYr/T@pILHJPmDhWFyHjgmZPsh@Xv0//DK9n19Otk7R/wPYSyQED9ayZgs@iYfipgKSMC9K22gypHFvFeSzYWkeU2XghWZW4msWS@/d385b@UstLuWF4XGsY8yGCoyu0gDwKgqG1OxorjiqNdFJvBHX3sKCYj22jCQpzIvDC1tASFLu7PH2Fr5wL8PsErh8o0hakW1@cRDWBt8u3pzurziAi4amtU9nbjGrzSyOJcrBhY6xsteuA7cyiosCieZMv@szF76WoKcRuApnhEn5YkarCmpo6yskpvKnhzluq/OaKNarP/nwvPfKIQzn9eon0//Xy6vZmOrSge81UpXjeBS67Xm/aR5TgESlyZD44XDhC@53d3bdOiUDS2Ht0klvROHyfXr7k1maz8ZYn/yZZEeX1xpu933gGYuMV@F2Lx0r8Bw "C (gcc) – Try It Online") n ~ 700 (w/ `-j2`). [Answer] # [Python](https://docs.python.org/3/), with [gmpy2](https://gmpy2.readthedocs.io/en/latest/), n=920 ~920 digits in 5 minutes on my Windows machine ``` import gmpy2 import time def nrdprime(n): for j in range(1,10): for k in range(n, 0, -1): for l in range(10): if j == l: continue if l == 0 and k == 1: continue a = [j] * n a[k-1] = l if a[n-1] % 2 == 0: continue x = int(''.join(map(str, a))) if gmpy2.is_prime(x): print(n, j, l, k) return x print(n, "has no answer") start_time = time.time() i = 2 while time.time() - start_time < 300: # Run for 300 seconds (5 minutes) nrdprime(i) i += 1 print(f"Processed up to n = {i-1} in 5 minutes.") ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 164 bytes, n = 839 ``` f(n)=d=(10^n-1)/9;for(i=1,9,for(j=0,n-1,for(k=0,9,if(i!=k&&(k>0||j<n-1)&&((i*n+k-i)%3)&&ispseudoprime(p=d*i+(k-i)*10^j),return(p))))) for(n=2,oo,print(n" -> "f(n))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5NDoIwEIX3ngJJJFOYRtCNRMtRNCZQM21smwI7buKGhcYzeRtbf2b1Xl7em-_2dGdPp4ub58c4SL573SUYJloBVXk0vGLrei-tBxIV1hiVEiWG4KN10DWSBFoKnWWgm3Ka1CH2ggPKTaE5sdU2WOpd342tdZ6uHTjR5lRATPPwSTH03TB6A47FW8R1IzZoLYaCGcCkCW-SNNIx9mX9If_R3w) The [`ispseudoprime`](https://pari.math.u-bordeaux.fr/dochtml/html/Arithmetic_functions.html#se:ispseudoprime) function uses [the BPSW primality test](https://en.wikipedia.org/wiki/Baillie%E2%80%93PSW_primality_test). Currently no counterexample is known. The package name for PARI/GP is `pari-gp` on Ubuntu, Debian, Arch Linux and some other distros. Runs as `gp -qf ./file_name.gp`. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), n = 595 * Compile with `-O3 -pthread -lfmt` ``` #include <atomic> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/miller_rabin.hpp> #include <fmt/core.h> #include <thread> namespace mp = boost::multiprecision; struct RepDigit { int pos; char maj, min; }; static std::atomic<int> digits{2}; static RepDigit calcPrimes(int digits) { static const mp::cpp_int ten{10}; char buf[2048] = {}; for (char i = '1'; i <= '9'; i += 2) { std::memset(buf, i, digits); mp::cpp_int num{buf}; mp::cpp_int n{ten}; for (int k = 1; k < digits; n *= ten, ++k) { for (char j = '9'; j >= '0'; --j) { if (j == i) continue; num += n * (j - i); if (mp::miller_rabin_test(num, 10)) return {digits - k, i, j}; num -= n * (j - i); } } } return {}; } static void job() { for (;;) { auto n = digits.fetch_add(1); auto p = calcPrimes(n); /* digits majority minority location(1-indexed) */ fmt::print("{} {} {} {}\n", n, p.maj, p.min, p.pos); } } int main() { for (auto hc = std::thread::hardware_concurrency(); hc > 1; --hc) std::thread{job}.detach(); job(); } ``` No TIO link because it doesn't have [{fmt}](https://fmt.dev/latest/index.html). ]
[Question] [ In November 2019, Alon Ran published a particularly lovely sequence in the OEIS, [A329126](https://oeis.org/A329126): > > \$a(n)\$ is the lexicographically earliest string of digits which yields a multiple of \$n\$ when read in any numeric base. > `1, 110, 101010, 111100, 100010001000100010, 1111110, 10000010000010000010000010000010000010, 11111111000, 1010101010101010100, ...` > > > For example, \$a(3) = 101010\$ because this is the smallest number that is a multiple of \$3\$ in every integer base $$ \begin{alignat}{2} 101010\_1 &= 1^5 + 1^3 + 1^1 = 3 &&= 3\cdot1 \\ 101010\_2 &= 2^5 + 2^3 + 2^1 = 42 &&= 3\cdot14 \\ 101010\_3 &= 3^5 + 3^3 + 3^1 = 273 &&= 3\cdot91 \\ 101010\_4 &= 4^5 + 4^3 + 4^1 = 1092 &&= 3\cdot364 \\ 101010\_5 &= 5^5 + 5^3 + 5^1 = 3255 &&= 3\cdot1085 \\ &\hspace{0.4em}\vdots \end{alignat} $$ Another way of conceptualizing this is that the polynomial \$f(n) = n^5 + n^3 + n\$ is divisible by \$3\$ for every integer \$n\$, which you can check manually with modular arithmetic. --- We can generalize this idea further by looking at polynomials with restricted coefficients. For example, if we allow the coefficients of the polynomial to be \$\{-1,0,1\}\$, then \$g(n) = n^4-n^2\$ is divisible by \$4\$ for all integers \$n\$. --- ## The challenge! In any reasonable format of your choosing, you will be given a list of allowed integer coefficients, `coefficients` (which always contains both \$0\$ and \$1\$), and a positive integer, `k`. Your job is to find the degree, `d`, of the smallest [monic polynomial](https://en.wikipedia.org/wiki/Monic_polynomial) as measured by degree, $$ p(n) = n^d + c\_{d-1}n^{d-1} + \dots + c\_2n^2 + c\_1n + c\_0, $$ such that each \$c\_i\$ is in `coefficients` and \$p(n)\$ is a multiple of \$k\$ for all integers \$n \in \mathbb{Z}\$. In order to avoid the simplest form of brute-forcing, your program must be able to compute each individual test case from the test data on [TIO](https://tio.run/#) (or, if TIO does not support your language, on my machine within 60 seconds). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. ## Test data ``` coefficients | k | d | example -------------+---+----+-------------------------------------------- [0,1] | 1 | 0 | 1 [0,1] | 2 | 2 | x^2 + x [0,1] | 3 | 5 | x^5 + x^3 + x [0,1] | 4 | 5 | x^5 + x^4 + x^3 + x^2 [0,1] | 5 | 17 | x^17 + x^13 + x^9 + x^5 + x [0,1] | 6 | 6 | x^6 + x^5 + x^4 + x^3 + x^2 + x [0,1] | 7 | 37 | x^37 + x^31 + x^25 + x^19 + x^13 + x^7 + x [-1,0,1] | 4 | 4 | x^4 - x^2 [-1,0,1] | 5 | 5 | x^5 - x [-1,0,1] | 6 | 3 | x^3 - x [-1,0,1] | 7 | 7 | x^7 - x [-1,0,1] | 8 | 5 | x^5 - x^3 [-1,0,1] | 9 | 8 | x^8 - x^6 - x^4 + x^2 [ 0,1,2] | 4 | 4 | x^4 + x^2 + 2x [ 0,1,3] | 5 | 9 | x^9 + x^5 + 3x [ 0,1,2,3] | 6 | 3 | x^3 + 3x^2 + 2x ``` [Answer] # [Python 3.8+](https://docs.python.org/3.8/), ~~385~~ 372 bytes ``` from itertools import* E=enumerate def f(c,k): p=[range(k)] while(n:=[a*b%k for a,b in E(p[-1])])not in p:p+=n,;S=[{0}];M=[D:=0]*len(p) for d in range(k*k): if[]==p[D:]:D=p.index(n) if any(all(sum(s)%k<1for s in zip(*T))for T in product(*[[[P*(C+(i==D))for P in p[i]]for C in S[r]]for i,r in E(M)])):return(k!=1)+d S+=[{a+b for b in S[-1]for a in c}];M[D]+=1;D+=1 ``` [Try it online!](https://tio.run/##dVJha9swEP3uX3EzFCRbHfHSrK0zDUrTwWCFgPtNiOHY8irsyEJWWLvS355JcrY1JjOy5Xv39O6dJP1sH3s1v9Jmv29MvwVphbF93w0gt7o3NonuqFC7rTClFVEtGmhQRVqcR6ApM6X6IVCLeQQ/H2UnkMopK5PNWQtNb6AkG5AK7pBm5xnHHKveekDnOqWKLAvKXmavfHlP2SqnM550QiGNo7C49sxDgSQUBNkwTql2ZJ6vqH4vVS2ekMIhBaV6RmXXoWG3RQM@az9lXmbwMr@kRskDxh54CA5MX@8qixLG2DpBtymSlK5GwjoQmOTcR7c@KpgZI0nM2NG96wbnRtidUah9RzOc1s5GkbqWynQTOtiMS13rYTN8VPlu2YqnNFuu3GdvxWAHoMDcYgDGZgQy7l4CM06OsQ9uTLE5gcUUuziBLdx0OQU/ujHFLp3mP@K59/FX9eIUvnhb7Q3uxOencFfgpP7Vf3SuXerIZNiFYzsjPB/dXE/ZY@bgh0eRP4yqF00zEPDb/709zOHGhQPJg0Kp/Mm4@35ExiGnjVQWhV//TPVi@jkmXsD9rm@KIh4vqNOjf2qJbhDQxF9uvn4jIJ60qKyo4WXMvsZBGu9/Aw "Python 3.8 (pre-release) – Try It Online") This code is surprisingly fast and runs in only about 1.5s on TIO. *-12 bytes thanks to @ovs* Python 3.8+ is used for the walrus operator (`:=`), but it costs three bytes because Python 3 doesn't allow mixed tabs and spaces. ## How A naive way to go about the challenge is to test all possible coefficient combinations at a given degree, then proceed to the next degree. This is viable for all of the test cases except for `[0,1] | 7`, which requires degree `d=37`. This would require brute-forcing more than `2^37` combinations, even if the order is chosen intelligently. My next approach was to work out what possible sums could be obtained for each `n` then work backwards on sets of coefficients which work for those sums, but that ran into much of a similar problem. Since only that one test case fails, it would be possible to optimize for coeffs=`[0,1]` specifically, but that seems too cheaty / against the spirit of the challenge. The method used in this answer relies on the property that the powers of `n` (mod `k`) are periodic, at least after a certain point. As an example for `k=4`: ``` Table of n^i mod k for k=4 i=0 corresponds to the constant term n\i 0 1 2 3 4 5 6 7 8 9 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 2 1 2 0 0 0 0 0 0 0 0 3 1 3 1 3 1 3 1 3 1 3 ``` Thus the powers mod `4` overall have a period of length `2` starting from `i=1`. (Note that `i=0` is never a solution unless `k=1`, and the constant term should always be divisible by `k`, so it should normally be zero). We use this periodicity to our advantage. For example, in the `[0,1] | 7 | 37` case, we don't need to consider `37` exponents. The powers have a period of length `6` starting from `i=0`, so there are only `6` distinct tuples of residues of of powers. ``` Table of n^i mod k for k=7 i=0 corresponds to the constant term n\i 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 4 1 2 4 1 2 4 1 3 3 2 6 4 5 1 3 2 6 4 4 2 1 4 2 1 4 2 1 5 5 4 6 2 3 1 5 4 6 6 6 1 6 1 6 1 6 1 6 ``` We only need to consider the coefficients with which to weight the six columns `i∊[1...6]`. Now we have to be careful. The coefficients are not just chosen from `[0,1]`. As we proceed to higher degrees, we can reuse the coefficients, so for example the `n` term is the same as the `n^7` term is the same as the `n^13` term; these all have powers in the `1` column. Thus we can use `7` copies of the `1` column to obtain the desired polynomial. ## Ungolfed Code ``` import itertools def min_degree(coeffs, k): if k == 1: return 0 # powers[n-1] will be the tuple of [1...k]^m mod k # e.g. for k=4, powers=[(1,2,3),(1,0,1),(1,0,3)]; next power will be (1,0,1) which repeats powers = [tuple(range(1, k))] # keep computing more powers until two are the same, # (we know the sequence of powers must be periodic eventually) while ( next_power := tuple([a * b % k for a, b in enumerate(powers[-1], 1)]) ) not in powers: powers.append(next_power) # period_start_index is 0-indexed # for k=4, period_start_index=1 and period_length=2 period_start_index = powers.index(next_power) period_length = len(powers) - period_start_index # summed_coeffs[i] is all possibilities of sums of i coeffs with replacement. # for example for i=2 and coeffs=[0,1,3], summed_coeffs[i]={0,1,2,3,4,6}={0+0,0+1,1+1,0+3,1+3,3+3} summed_coeffs = [{0}] for i in range(k * k): # mod by k here is unnecessary but can theoretically improve speed summed_coeffs.append({(a + b) % k for b in summed_coeffs[-1] for a in coeffs}) max_repeats = [0 for _ in powers] # A simple upper bound for d is d ≤ k*φ(k) # because Σ_{m=1}^{k}(n^(mφ(k)) always works # Since φ(k) ≤ k-1, we know d ≤ k*φ(k) ≤ k*(k-1) < k*k for d in range(1, k * k): # degree_index is the index of [1...n]^(d-1) mod k in the list `powers` # we use d-1 because the `d`-th coefficient must be 1 ∵ monic polynomial degree_index = ( d - 1 if d - 1 < period_start_index else period_start_index + (d - 1 - period_start_index) % period_length ) possible_column_totals = [ [ tuple( [p * (coeff + (1 if i == degree_index else 0)) for p in powers[i]] ) for coeff in summed_coeffs[r] ] for i, r in enumerate(max_repeats) ] max_repeats[degree_index] += 1 for column_totals in itertools.product(*possible_column_totals): if all(sum(s) % k == 0 for s in zip(*column_totals)): return d ``` [Answer] # Haskell, 221 bytes ``` import Data.Set k%g|w<-fromList.fmap(\q->(`mod`k).sum.zipWith(*)q.(<$>[1..]).(^)<$>[1..k]).mapM id=[n|n<-[0..],t<-[div n 2],n>(k-1)^2||size(intersection(w$(0-)<$>g<$[1..t])$w$([0]<$[1..t])++(g<$[1..n-t-1])++[[1]])>0]!!0 ``` Use compiler flags `-O2` (I didn't test if `-O` is enough. It might be) To get the result, evaluate `k%digits`, e.g, `6%[0,1]`. Here's a link to TIO with a `main` function that runs all the tests, except `7%[0,1]`: [Try it online!](https://tio.run/##bc5Bb4IwFAfwO5/imWDSzrYBnG5LkNOOW3bYYQeskQhigxSk3UwMn32soDFuay/t@/X1/btLVJHt910nyrpqNDwnOmHvmXaKcd4eQ7ptqvJFKM22ZVKj5YFGaF1W6brATH2W7CTqD6F36A4fGArdKPYZ45ihFb4UhanMy1cQ6SKWrQxp7JkWos0hFV8gIeBERqigPl4FbavEKUNC6qxR2UaLSqKjizzaj8tDt5@oOXaNxR6/1pMJulxKqqnfQxz7nOPI46OR1zllIiQsYPgIWqJU5EIrAgUGGkHdmDxAxfjMGIPOlFaOM2zmWeyAWSaR@Lw/AQEfk/8Y2HBqw3sbzmw4vyClv/jh2kt9cvbbqTc4s@HchtaZjzZ8uiIYIsGf9AGnf9LPnYb79MF4973Z7pNcdfQt@AE "Haskell – Try It Online") The code works by generating all the negations of the possible first halves of the polynomial, and all the possible second halves of the polynomial. Then it evaluates all of them `mod k` at all possible inputs, puts the results in two sets, and checks if they have any intersection. It also has two spot optimizations: the constant coefficient is always zero, and a polynomial of degree `k^2-2k+2` is always possible. The code doesn't run to completion on the TIO site. however, it reached 30s on my computer. So I'm waiting for the OP to decide if this program is ok. Also, there is a slightly shorter but less performant version that also might make the cut: ``` import Data.Set k%g|w<-fromList.fmap(\q->(`mod`k).sum.zipWith(*)q.(<$>[1..]).(^)<$>[1..k]).mapM id=[n|n<-[0..],t<-[div n 2],size(intersection(w$(0-)<$>g<$[1..t])$w$([0]<$[1..t])++(g<$[1..n-t-1])++[[1]])>0]!!0 ``` that removes the `k^2-2k+2` optimization. [Answer] # JavaScript (ES6), ~~297 290 286~~ 284 bytes Expects `(coefficients)(k)`. ``` c=>k=>(g=(i,q,d,A,m,h)=>i<n?c.map(c=>c*q&&i>=r|!m&&g(i,q-1,(D=m-~i)>d?D:d,A.map((v,j)=>v+B[i][j]*c),m+n-r,D>d?c:h),g(i+1,q,d,A,0,h)):M=h^!A.some(x=>x%k)|M<d?M:d)(0,k,0,(M=A=>(r=M[A+A])?A.fill(!r--):M(A.map((v,i)=>v*i%k),M[A+A]=n=B.push(A)))([...Array(k)].map((_,i)=>i),B=[]),0)&&M^k<2 ``` [Try it online!](https://tio.run/##dZJRbptAFEX/vYrnSMYz9gOBHccJ8YCwnE9WgEiFBmzGGHAgtVIpygoi9aef7T6ynmygS3CfidM2CQFpNMy5990rDetoF9WyUttbvSjjZL8UeymcTDhsJZjCG4zRwxxTLhw1K1xp5NGWkUIObjRNOaK67@aatjpIdQvZQuT6g@JO7C5scjZqtsM12XfDeaDCYB0OJMd8WOgVLkgn7ZQj@YfWMcykMG77Ir3uekZd5gm7E85dL@P3/ix2fTvmzMSMZMwXHvWshB94Qy/krmcs1WbDupWu0wD2N10d0geKRuCLVBRibmy/1inzOOcsMAzDq6roG8t4@GL60pgUx7kIQo4m1zT/OpuN9pdBByCg10QrRDg8FoIJEOIHMEIYtYIxwqQVnH4GJgjWtA2cIZy1OqYI438OuptXRBmn0AYmb8L/A5QxbgWUMW0F55@NukA4f1sXRy2tGjB@bXXx3tGgY6tO2DGWZXUVyZSxACRChhAnKwg5CAdkWdTlJjE25YqdSBAQ9GoyZ7Tr1fDg0HqCR1eV1HS8ZJLTj3D8FM0sF/q/n74///xBax9s6D//euxzvv8D "JavaScript (Node.js) – Try It Online") ## Commented I think this is very close to @fireflame241's solution, although I came up with this independently. The first part was working fine from the beginning. But for some reason, I got the second part poorly written and very slow on my early attempts. ### Step 1 We store in \$B[\:]\$ all the distinct tuples \$(0,1,\dots,k-1)\$ raised to increasing powers, modulo \$k\$. At the end of the process, \$n\$ is the number of entries in \$B[\:]\$ and \$r\$ is the 0-based index at which the sequence restarts. ``` ( M = A => // M is a recursive function taking a vector A[] (r = M[A + A]) ? // if A[] was already encountered at index r: A.fill(!r--) // stop the recursion, clear all values in A[] // and decrement r : // else: M( // do a recursive call: A.map((v, i) => // update each value in A[] ... v * i % k // ... to the next power modulo k ), // end of map() M[A + A] = n = // store A[] in M, set n = length of B[] ... B.push(A) // ... once A[] has been appended to B[] ) // end of recursive call )( // initial call to M with: [...Array(k)] // an array filled with all values from 0 to k - 1 .map((_, i) => i), // B = [] // initialize B[] to an empty array ) // ``` ### Step 2 We now use a recursive function \$g\$ to find a combination of tuples from \$B[\:]\$ multiplied by some coefficients from \$c[\:]\$ that sum up to \$0\$'s modulo \$k\$. We eventually return the lowest degree \$M\$ of the corresponding polynomials, ignoring those that are not monic. By using any tuple that repeats, it's always possible to build a solution with exactly \$k\$ terms that lead to the same result modulo \$k\$. That's why we use \$k\$ as an upper bound for the number of terms in the polynomial. The initial call to \$g\$ is `g(0, k, 0, A, 0)` and the returned value is `M ^ k < 2` to support the edge case \$k=1\$. ``` g = ( // g is a recursive function taking: i, // i = pointer in B[] q, // q = max. number of terms in the polynomial d, // d = degree A, // A[] = current vector, initialized to the // array of k 0's, returned by step 1 m, // m = number of times B[i] has been used h // h = coefficient of the leading term ) => // i < n ? // if i is less than n: c.map(c => // for each coefficient c in c[]: c * q && // if both c and q are not 0 i >= r | !m && // and B[i] can be repeated or m = 0, g( // do a recursive call: i, // leave i unchanged q - 1, // decrement q (D = m - ~i) // D is the degree of the new term > d ? D : d, // update d to D if D > d A.map((v, j) => // update A[]: v + B[i][j] * c), // add B[i][j] * c to each A[i] m + n - r, // add the period to m D > d ? c : h // update the coeff. of the leading term ), // end of recursive call g( // do another recursive call with: i + 1, q, d, A, 0, h // i + 1, m = 0 ) // all other parameters unchanged ) // end of map() : // else (i = n): M = h ^ // if the leading coeff. is not equal to 1 !A.some(x => x % k) // or some value in A[] is not 0 modulo k | M < d ? M // or M is less than d, leave M unchanged : d // else update it do d ``` ]
[Question] [ This challenge is about creating these neat "green spray paint" patterns: (more pictures below) [![example 1](https://i.stack.imgur.com/yV9Cp.png)](https://i.stack.imgur.com/yV9Cp.png) [![example 2](https://i.stack.imgur.com/U1avD.png)](https://i.stack.imgur.com/U1avD.png) [![example 3](https://i.stack.imgur.com/hl92r.png)](https://i.stack.imgur.com/hl92r.png) [![example 7](https://i.stack.imgur.com/fNWS3.png)](https://i.stack.imgur.com/fNWS3.png) Loosely explained, they are generated by starting with a black image and a point in the center. That point is successively moved by a randomly chosen offset or delta in x and y. Every pixel the point visits has 1 added to its green color channel. This process is then repeated with many many more points, all starting from the center, generating an entire green pattern. Your task is to write the shortest program possible that takes in the necessary parameters and displays or outputs the resulting green spray paint image. **This is code golf so the shortest code in bytes wins!** # Specifics The images require the following parameters, which must be inputs to your program in any order you choose: * Positive integer **S** is the width and height (**S**ize) of the output image in pixels. * Non-negative integer **N** is the number of points to move over the image one by one, each adding a trail of green. * Non-negative integer **M** is the maximum number of moves that each point can take. (Without this they'd never stop.) * **D** is a list of pairs of integers `[(dx1, dy1), (dx2, dy2), ...]` that are deltas each point may be offset by each move. + You may also take this flattened `[dx1, dy1, dx2, dy2, ...]` or as two lists `[dx1, dx2, ...]` and `[dy1, dy2, ...]`. Generate the patterns by starting with a pure black **S**×**S** pixel image. Then repeat the following process **N** times, after which your image will be ready to be output: 1. Start a point in the center of the image. (This means `(floor(S/2), floor(S/2))` for most image coordinate systems.) 2. Add 1 to the green color channel of the pixel currently below the point (up to a max of 255). 3. Consider moving the point by each of the deltas in **D** so it becomes like `(x + dx, y + dy)`. Keep track of the valid moves. * A valid move is one that keeps the point inside the bounds of the image, i.e. over a pixel. 4. If there are no valid moves or the current point has taken **M** moves then stop and restart at step 1 with a new point. 5. Otherwise, have the current point take a random *valid* move. Every valid move should have an equal chance. 6. Go to step 2 to move the current point again. Your implementation does not need to follow these precise steps as long as the results produced are the same. Of course they won't be *exactly* the same due to randomness, but it's easy to visually tell when things are working as expected. Be sure to keep these corner cases in mind: * When **N** is 0 there are no points so the output should always be a totally black **S**×**S** image. * When **M** is 0 or **D** is empty it means no moves can be made, so only the starting pixel will have color. ([See example 5.](https://i.stack.imgur.com/lyuzN.png)) * **D** may contain duplicate values that are valid moves, effectively meaning that move is more likely. ([See example 7.](https://i.stack.imgur.com/fNWS3.png)) # Reference Program Ungolfed reference code in Python 3. Not strictly a solution since it is hardcoded to output the [first example from above](https://i.stack.imgur.com/yV9Cp.png). ``` S = 250 N = 800 M = 7000 D = [(1, 2), (-1, 2), (1, -2), (-1, -2), (2, 1), (-2, 1), (2, -1), (-2, -1)] # chess knight moves import random from PIL import Image img = Image.new('RGB', (S, S), 'black') pix = img.load() for i in range(N): if (i + 1) % 10 == 0: print(f'{(i + 1)/N:.1%}') # progress tracker, not required output x, y, = S//2, S//2 m = 0 while True: pix[x, y] = 0, pix[x, y][1] + 1, 0 valid = [(x + dx, y + dy) for dx, dy in D if 0 <= x + dx < S and 0 <= y + dy < S] if m >= M or not valid: break x, y = random.choice(valid) m += 1 #img.save('spraypaint.png') # uncomment to save image img.show() ``` # Examples 1. ``` S = 250 N = 800 M = 7000 D = [(1, 2), (-1, 2), (1, -2), (-1, -2), (2, 1), (-2, 1), (2, -1), (-2, -1)] ``` [![example 1](https://i.stack.imgur.com/yV9Cp.png)](https://i.stack.imgur.com/yV9Cp.png) (from above) 2. ``` S = 250 N = 1000 M = 3000 D = [(2, -1), (-2, -1), (-3, 0), (4, 0), (0, 2), (0, -1)] ``` [![example 2](https://i.stack.imgur.com/U1avD.png)](https://i.stack.imgur.com/U1avD.png) (from above) 3. ``` S = 250 N = 400 M = 10000 D = [(60, 59), (60, -59), (-59, 60), (-59, -60)] ``` [![example 3](https://i.stack.imgur.com/hl92r.png)](https://i.stack.imgur.com/hl92r.png) (from above) 4. ``` S = 400 N = 600 M = 10000 D = [(0, 1), (-1, 0), (0, -1), (1, 0)] ``` [![example 4](https://i.stack.imgur.com/wiTxF.png)](https://i.stack.imgur.com/wiTxF.png) 5. ``` S = 51 N = 1000 M = 1000 D = [] ``` [![example 5](https://i.stack.imgur.com/lyuzN.png)](https://i.stack.imgur.com/lyuzN.png) 6. ``` S = 51 N = 1000 M = 1 D = [(-5, 5), (9, 9), (-15, 1), (20, -25)] ``` [![example 6](https://i.stack.imgur.com/uopqp.png)](https://i.stack.imgur.com/uopqp.png) 7. ``` S = 300 N = 1000 M = 1000 D = [(1, 0), (1, 0), (1, 0), (1, 0), (-3, 0), (0, 3), (0, -3)] ``` [![example 7](https://i.stack.imgur.com/fNWS3.png)](https://i.stack.imgur.com/fNWS3.png) (from above) 8. ``` S = 345 N = 123 M = 21212 D = [(1, -4), (2, -3), (3, -2), (4, -1), (-9, 9)] ``` [![example 8](https://i.stack.imgur.com/pgN32.png)](https://i.stack.imgur.com/pgN32.png) 9. ``` S = 200 N = 1 M = 1500000 D = [(1, 1), (1, -1), (-1, 1), (-1, -1)] ``` [![example 9](https://i.stack.imgur.com/ibwl7.png)](https://i.stack.imgur.com/ibwl7.png) 10. ``` S = 300 N = 4000 M = 1000 D = [(7, 1), (-4, 3), (-4, -3)] ``` [![example 10](https://i.stack.imgur.com/3gTTU.png)](https://i.stack.imgur.com/3gTTU.png) 11. ``` S = 300 N = 1500 M = 1000 D = [(10, -10), (-10, 10), (5, 5), (-5, -5), (1, 0), (-1, 0)] ``` [![example 11](https://i.stack.imgur.com/aeGPu.png)](https://i.stack.imgur.com/aeGPu.png) 12. ``` S = 240 N = 1000 M = 10000 D = [(80, 81), (80, -81), (-81, 80), (-81, -80)] ``` [![example 12](https://i.stack.imgur.com/l3I6S.png)](https://i.stack.imgur.com/l3I6S.png) [All example inputs together.](https://pastebin.com/raw/GyXkkzyN) # Bonus This isn't required but I would love to see what other neat patterns are possible. Put any cool images you make in your answer! [Answer] # [Ruby](https://www.ruby-lang.org/), ~~263...150~~ 147 bytes ``` ->s,n,m,d{c=[0]*3*s*s;n.times{x=y=s/2;0.upto(m){c[3.*x+y*s]+=1;d.shuffle.find{|p,q|(g=x+p,y+q)-[*0...s]==[]&&(x,y=g)}||break}};puts:P3,s,s,255,0,c} ``` [Try it online!](https://tio.run/##dZPRjtowEEXf@QpXSCsIdmrHMUuL3G/ou5UHFpIt6iaw60QiAr6dztixF7KqInmuJs6dMzPKR/fS3yp9Y78sbWhNd@etNrxIZGITu27Sdl@X9nzSvbbfszVPu2N7mNXz89bINDkt@sQWCy3Wu9T@6arqrUyrfbM7X470/TJ71afFkfaL9zkzCU/T1BZam@LpaXaivX6dXy@Xl49y8/d6XR@71v78LamFJ1OKcrq93qaka7aHui6blhyakrzt4di0ZEOQ6tukLW1L9GRqMsUpISuOJyHPHIUxgpKsAMGCgMhixquMEuEyQUBkMQOqKMjUlbPk0LUTX0rwoZQcSo2/QiUp4SjyIfKBgg@@kTv3ZmjqzJZwqh94FRXzEgIlSx4lAz1imxrvtBz58dCj@CTxjC7xxYUocdeiF8bxPr7Bl@jPFPCiHWB5VqHCNLFUpu66HfuaAPW/GOcIt2Wgl95R5lCIiEyiYybgGRxZHnbpPpFh3XncjmP1WAEI4BTnn1hhRCxOL4qwQImX83FLz@FmPiCjiMx4Bws9TsHtxDcs3JhQhsHihJl6mMqwOuTP78Yal76Cc@UoUDEvIUCWR8lWX9Y/qUyC/1Vx@wc "Ruby – Try It Online") (Times out on four of the test cases and truncates output for all but two of the others.) ### Explanation Takes `d` as an array of arrays and outputs in [PPM format](https://en.wikipedia.org/wiki/Netpbm) to STDOUT. Two features of PPM are exploited: 1. No attempt is made to avoid G values greater than 255: PPM treats any such values as if they were equal to 255. 2. Extraneous bytes at the end of the file (i.e. beyond the specified pixel count) are ignored. This allows a byte to be saved by working internally with the *red* channel rather than green, then shifting all the RGB values by one place on output. ``` ->s,n,m,d{ c=[0]*3*s*s; # initialise all pixels to black n.times{ x=y=s/2; # set initial position 0.upto(m){ c[3.*x+y*s]+=1; # add 1 to red channel at current position (x+y*s is single-digit pixel index, starting from 0 at top left) d.shuffle # randomise moves .find{|p,q| # if there is a move such that (g=x+p,y+q) # the new co-ordinates -[*0...s]==[] # are both in [0, s) (i.e. within the image) &&(x,y=g) # take that move } ||break # otherwise restart with a new point } }; puts:P3,s,s,255,0,c # print PPM file to STDOUT, inserting 0 to get green output } ``` ### Sample outputs for test cases Composite image including all test cases, ordered as follows: ``` 1, 2, 3 4, 8 5, 6, 7, 9 10, 11, 12 ``` [![enter image description here](https://i.stack.imgur.com/0fSbU.jpg)](https://i.stack.imgur.com/0fSbU.jpg) ### Bonus ``` 'Excalibur' S = 400, N = 5000, M = 5000, D = [[1, -1], [1, -1], [-2, 10], [-10, 2]] 'Aurora' S = 400, N = 2500, M = 2500, D = [[11, 13], [13, -11], [-29, 31], [31, 29], [41, 43], [43, -41], [-59, 61], [-59, -61]] ``` [![enter image description here](https://i.stack.imgur.com/2FKN5.jpg)](https://i.stack.imgur.com/2FKN5.jpg) [Answer] # Java 10, ~~516~~ ~~513~~ ~~508~~ 504 bytes ``` import java.awt.*;(S,N,M,D)->new Frame(){{add(new Panel(){public void paint(Graphics g){var G=(Graphics2D)g;G.setPaint(Color.BLACK);G.fillRect(0,0,S,S);int c[][]=new int[S][S],x,y,d[],r,n=N,m;for(;n-->0;)for(x=y=S/2,m=M;m-->0;){c[x][y]++;var L=new java.util.Stack<int[]>();for(var q:D)if(q[0]>~x&x+q[0]<S&q[1]>~y&y+q[1]<S)L.add(q);r=L.size();if(r<1)break;d=L.get(r*=Math.random());x+=d[0];y+=d[1];}for(x=S*S;x-->0;G.drawLine(x,y,x,y))G.setPaint(new Color(0,Math.min(c[r=x/S][y=x%S],255),0));}});show();}} ``` -4 bytes thanks to *@ceilingcat*. Some example outputs: Input: `S=250; N=800; M=7000; D=[[1,2],[-1,2],[1,-2],[-1,-2],[2,1],[-2,1],[2,-1],[-2,-1]]` Output: [![enter image description here](https://i.stack.imgur.com/htg49.png)](https://i.stack.imgur.com/htg49.png) Input: `S=200; N=10000; M=5000; D=[[1,1],[2,2],[30,30],[1,-1],[2,-2],[30,-30],[-1,1],[-2,2],[-30,30]]` Output: [![enter image description here](https://i.stack.imgur.com/lDpsv.png)](https://i.stack.imgur.com/lDpsv.png) Input: `S=200, N=5000, M=5000, D=[[10,11],[11,10],[25,26],[26,25],[50,51],[51,50],[-75,-75]]` Output: [![enter image description here](https://i.stack.imgur.com/VFzWc.png)](https://i.stack.imgur.com/VFzWc.png) **Explanation:** ``` import java.awt.*; // Required import for almost everything (S,N,M,D)-> // Method with the 4 parameters and Frame return-type new Frame(){ // Create the Frame { // In an inner code-block: add(new Panel(){ // Add a Panel we can draw on: public void paint(Graphics g){ // Overwrite its paint method: var G=(Graphics2D)g; // Cast interface to object so we can use it to draw G.setPaint(Color.BLACK); // Set the color to black G.fillRect(0,0,S,S); // Create the square of size `S` by `S` int c[][]=new int[S][S], // Create an integer-matrix of the same size, // filled with 0s by default x,y, // Temp integers for the current coordinates d[], // Temp integer-array for the randomly selected delta r, // Temp integer for the random index n=N, // Copy of the input `N` (since we are in a // code-block, it has to be effectively final..) m; // Temp integer for(;n-->0;) // Loop `n` amount of times: for(x=y=S/2, // Start `x,y` at the center m=M;m-->0;){ // Inner loop `M` amount of times: c[x][y]++; // Increase the value at the current `x,y` by 1 var L=new java.util.Stack<int[]>(); // Create an empty list for(var q:D) // Loop over the deltas: if(q[0]>~x&x+q[0]<S&q[1]>~y&y+q[1]<S) // If `x,y` + this delta is within bounds: L.add(q); // Add the current delta to the list r=L.size(); // Set `r` to the amount of valid deltas left if(r<1) // If there are no valid deltas: break; // Stop the inner loop d=L.get(r*=Math.random()); // Pick a random delta from the list x+=d[0];y+=d[1];}// And update the `x,y` coordinate with it for(x=S*S;x-->0 // Then loop over all coordinates: ; // After every iteration: G.drawLine(r,y,r,y)) // Draw the current pixel G.setPaint(new Color(0,Math.min(c[r=x/S][y=x%S],255),0));}}); // Set the green color based on the value in `c`, // or 255 if it's exceeding that show();}} // And finally show the Frame ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 216 bytes ``` (s=Table[{0,0,0}~Table~S,S=#];t=1;Do[s[[##&@@(d=Floor[{S/2,S/2}])]]={0,t++,0};Do[s[[##&@@(c=RandomChoice[If[(z=Select[d+#&/@If[#4=={},{0,0},#4],Max@#<S-1&&Min@#>1&])=={},d,z]])]]+={0,1,0};d=c,#3],#2];s~Image~"Byte")& ``` > > > > > > [400, 600, 10000, {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}] > > > > > > > > > [![enter image description here](https://i.stack.imgur.com/opkk9.png)](https://i.stack.imgur.com/opkk9.png) > > > > > > [1000, 2000, 2000, {{5, 5}, {2, 3}, {1, -1}, {-3, -4}, {4, > > 5}, {-5, -5}}] > > > > > > > > > [![enter image description here](https://i.stack.imgur.com/tuxMF.png)](https://i.stack.imgur.com/tuxMF.png) [Answer] ## JavaScript (ES6), ~~279~~ 269 bytes ``` f= (c,s,n,m,d)=>{c.width=c.height=s c=c.getContext('2d',{alpha:0}) i=c.getImageData(0,0,s,s) for(;x=y=s/2|0,n--;)for(o=m;i.data[(x+y*s)*4+1]++,l=o--&&(e=d.map(([a,b])=>[x+a,y+b]).filter(([a,b])=>a>=0&b>=0&a<s&b<s)).length;)[x,y]=e[l*Math.random()|0] c.putImageData(i,0,0)} ``` ``` Size: <input id=s type=number min=1 value=250><br>Pixels: <input id=n type=number min=0 value=800><br>Moves: <input id=m type=number min=0 value=7000><br>Deltas: <input id=d value=[[1,2],[-1,2],[1,-2],[-1,-2],[2,1],[-2,1],[2,-1],[-2,-1]]><br><input type=button value=Go! onclick=f(c,+s.value,+n.value,+m.value,JSON.parse(d.value))><br><canvas id=c> ``` Takes a fifth parameter which is the canvas element on which to draw the resulting image. Byte count does not include the test driver, which comprises the `f=` line of JavaScript and all of the HTML. Edit: Saved 10 bytes thanks to @Kaiido. Ungolfed version with incremental rendering: ``` b.onclick = async function() { b.disabled = true; try { await f(c, +s.value, +n.value, +m.value, JSON.parse(d.value)); } catch (ex) { console.error(ex); } b.disabled = false; } async function f(canvas, size, number, moves, deltas) { canvas.width = canvas.height = size; let context = canvas.getContext('2d', { alpha: false }); context.fillRect(0, 0, size, size); let image = context.getImageData(0, 0, size, size); for (let i = 0; i < number; i++) { let x = size / 2 | 0, y = x, j = moves; for (;;) { image.data[(x + y * size) * 4 + 1]++; if (!j--) break; let valid = deltas.map(([dx, dy]) => [x + dx, y + dy]).filter(([x, y]) => x >= 0 && y >= 0 && x < size && y < size); if (!valid.length) break; [x, y] = valid[valid.length * Math.random() | 0]; } context.putImageData(image, 0, 0); await new Promise(requestAnimationFrame); } } ``` ``` <div>Size: <input id=s type=number min=1 value=250></div> <div>Pixels: <input id=n type=number min=0 value=800></div> <div>Moves: <input id=m type=number min=0 value=7000></div> <div>Deltas: <input id=d value=[[1,2],[-1,2],[1,-2],[-1,-2],[2,1],[-2,1],[2,-1],[-2,-1]]></div> <div><input id=b type=button value=Go!></div> <canvas id=c> ``` [Answer] # [Python 2](https://docs.python.org/2/) + PIL, ~~217~~ ~~214~~ 211 bytes A golf of the reference implementation, but a lot less efficient. Instead of using loops, this generates many many lines of code (`N*(M+2)`) that will run once. ``` import random,PIL.Image as I S,N,M,D=input() i=I.new('RGB',(S,S)) p=i.load() exec('v=[[S//2]*2]\n'+'if v:x,y=random.choice(v);p[x,y]=0,p[x,y][1]+1,0;v=[(x+a,y+b)for a,b in D if-1<x+a<S>y+b>=0]\n'*-~M)*N i.show() ``` Output for `S=51, N=1000, M=1, D=[(-5, 5), (9, 9), (-15, 1), (20, -25)]`: [![enter image description here](https://i.stack.imgur.com/769Fp.png)](https://i.stack.imgur.com/769Fp.png) Output of an older version for `S=300, N=1500, M=1000, D=[(10, -10), (-10, 10), (5, 5), (-5, -5), (1, 0), (-1, 0)]`, don't try such a large example with the current version: [![enter image description here](https://i.stack.imgur.com/lQ0fQ.png)](https://i.stack.imgur.com/lQ0fQ.png) ]
[Question] [ Given a positive integer \$n\$ you can always find a tuple \$(k\_1,k\_2,...,k\_m)\$ of integers \$k\_i \geqslant 2\$ such that \$k\_1 \cdot k\_2 \cdot ... \cdot k\_m = n\$ and $$k\_1 | k\_2 \text{ , } k\_2 | k\_3 \text{ , } \ldots \text{ , }k\_{m-1}|k\_m.$$ Here \$a|b\$ means \$b\$ is a multiple of \$a\$, say "a divides b". If \$n>1\$ all entries \$k\_i\$ must be at least \$2\$. For \$n=1\$ we have no such factor and therefore we get an empty tuple. In case you're curious where this comes from: This decomposition is known as *invariant factor decomposition* in number theory and it is used in the [classification of finitely generated Abelian groups.](https://en.wikipedia.org/wiki/Abelian_group#Classification) ### Challenge Given \$n\$ output *all* such tuples \$(k\_1,k\_2,...,k\_m)\$ for the given \$n\$ exactly once, in whatever order you like. The standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") output formats are allowed. ### Examples ``` 1: () (empty tuple) 2: (2) 3: (3) 4: (2,2), (4) 5: (5) 6: (6) 7: (7) 8: (2,2,2), (2,4), (8) 9: (3,3), (9) 10: (10) 11: (11) 12: (2,6), (12) 108: (2,54), (3,3,12), (3,6,6), (3,36), (6,18), (108) ``` Related: <http://oeis.org/A000688>, [List all multiplicative partitions of n](https://codegolf.stackexchange.com/questions/104707/list-all-multiplicative-partitions-of-n) [Answer] ## Haskell, ~~66~~ ~~62~~ 60 bytes ``` f n=[n|n>1]:[k:l:m|k<-[2..n],l:m<-f$div n k,mod(gcd n l)k<1] ``` [Try it online!](https://tio.run/##DcdBDsIgEAXQq/xFF23aTqQrQ6g38ASEGCKiZGDaqHHVuyO7917@w4@ca42Q1cohF@W0ZZ11OdjMdiESN7WZOXYh/SDgqWyhf95Dcx7YKFeLT4IVxe/XG/r9neQLigM6WEWkFodxbDydXf0D "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` Òœ€.œP€`êʒüÖP ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8KSjkx81rdE7OjkASCUcXnVq0uE9h6cF/P9vaGABAA "05AB1E – Try It Online") ``` Ò # prime factorization of the input œ€.œ # all partitions P # product of each sublist €` # flatten ê # sorted uniquified ʒ # filter by: üÖ # pairwise divisible-by (yields list of 0s or 1s) P # product (will be 1 iff the list is all 1s) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` ÆfŒ!Œb€ẎP€€QḍƝẠ$Ƈ ``` [Try it online!](https://tio.run/##y0rNyan8//9wW9rRSYpHJyU9alrzcFdfAJACosCHO3qPzX24a4HKsfb/h9uPTnq4c8b//4YGFgA "Jelly – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), ~~73~~ 70 bytes Prints the tuples in descending order \$(k\_m,k\_{m-1},...,k\_1)\$. ``` f=(n,d=2,a=[])=>n>1?d>n||f(n,d+1,a,d%a[0]||f(n/d,d,[d,...a])):print(a) ``` [Try it online!](https://tio.run/##JY2/DoIwHIR3nuK3GGg8K8V/KGmdXH2BpkNDQ8ShEiQs4rPXCtN9@S6Xe9rRvuu@7YbNWIbQyMzDyQJWasOk8kpcnfLT1Pz9WsDCrazOzWy2Dg7agXNuDWOXrm/9kFkWKi1QYIc9DjjihBJniBxCQBQRSpPw5tXfbP3IPElFn4RoGad3kpTSmjyroowncy5lxC8LPw "JavaScript (V8) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input d = 2, // d = current divisor a = [] // a[] = list of divisors ) => // n > 1 ? // if n is greater than 1: d > n || // unless d is greater than n, f( // do a recursive call with: n, // -> n unchanged d + 1, // -> d + 1 a, // -> a[] unchanged d % a[0] || // unless the previous divisor does not divide the current one, f( // do another recursive call with: n / d, // -> n / d d, // -> d unchanged [d, ...a] // -> d preprended to a[] ) // end of inner recursive call ) // end of outer recursive call : // else: print(a) // this is a valid list of divisors: print it ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ѦIиæʒPQ}êʒüÖP ``` Very slow for larger test cases. -1 byte thanks to *@Grimy*. [Try it online.](https://tio.run/##ASIA3f9vc2FiaWX//8ORwqZJ0LjDpsqSUFF9w6rKksO8w5ZQ//80) **Explanation:** ``` Ñ # Get all divisors of the (implicit) input-integer ¦ # Remove the first value (the 1) Iи # Repeat this list (flattened) the input amount of times # i.e. with input 4 we now have [2,4,2,4,2,4,2,4] æ # Take the powerset of this list ʒ } # Filter it by: PQ # Where the product is equal to the (implicit) input ê # Then sort and uniquify the filtered lists ʒ # And filter it further by: ü # Loop over each overlapping pair of values Ö # And check if the first value is divisible by the second value P # Check if this is truthy for all pairs # (after which the result is output implicitly) ``` [Answer] # JavaScript, 115 bytes ``` f=(n,a=[],i=1)=>{for(;i++<n;)n%i||(a=a.concat(f(n/i).filter(e=>!(e[0]%i)).map(e=>[i].concat(e))));return n>1?a:[a]} ``` I will write an explanation later [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~78~~ ~~76~~ ... ~~61~~ 51 bytes ``` Do[i∣##&&##~#0~i,{i,2,-#/-##2/. 1:>Print@{##2}}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yU/OvNRx2JlZTU1ZeU6ZYO6TJ3qTB0jHV1lfV1lZSN9PQVDK7uAosy8EodqIL@2Nlbtf5qDlmtyRn5dcHJiXl01l6EOl5EOl7EOl4kOl6kOl5kOl7kOl4UOl6UOl6EBEAPlDY1AbAuuWn39wNLM1JL/AA "Wolfram Language (Mathematica) – Try It Online") Recursive search tree. Prints the list of decompositions. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~18~~ 15 bytes ``` fΛ¦ufo=¹ΠṖmΠtṖp ``` [Try it online!](https://tio.run/##yygtzv7/P@3c7EPLStPybQ/tPLfg4c5puecWlACpgv///1sAAA "Husk – Try It Online") Similar to Grimmy's 05AB1E answer. -3 bytes from Zgarb. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~22~~ 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÆâÃcÅà â f@¶XcXäv)× ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xuLDY8XgIOIgZkC2WGNY5HYp1w&footer=8SBxUg&input=NA) ``` ÆâÃcÅà â f@¶XcXäv)× :Implicit input of integer U Æ :Map the range [0,U) â : Divisors of U à :End map c :Flatten after Å : Slicing the first element off each à :Combinations â :Deduplicate f :Filter by @ :Passing each X through the following function ¶ : Test U for equality with Xc : Concatenate to X Xä : Consecutive pairs of X v : Reduced by testing divisibility ) : End concat × : Reduce by multiplication ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ḊœċRẎḍƝẠ×P=¥ʋƇ ``` [Try it online!](https://tio.run/##ATYAyf9qZWxsef//4biKxZPEi1Lhuo7huI3GneG6oMOXUD3CpcqLxof/MTDDh@KCrMWS4bmY4oKsWf8 "Jelly – Try It Online") ## How it works ``` ḊœċRẎḍƝẠ×P=¥ʋƇ - Main link. Takes n on the left Ḋ - Dequeue; Yield [2, 3, ..., n] R - Range, Yield [1, 2, ..., n] œċ - For each integer, 1 ≤ i ≤ n, yield combinations with replacement of length i from the dequeued range Ẏ - Tighten into a single list of lists ʋƇ - Keep those for which the following is true: × ¥ - Both of the following are true: Ɲ - Over overlapping pairs: ḍ - Is the left divisible by the right? Ạ - Is all true? × - And: P - The product = - Equals n? ``` ]
[Question] [ I recently had a problem to solve at work where I had two lists: a master list, and a smaller list that contains a subset of the items in the master list potentially in a different order. I needed to reorder the master list in such a way that the items in the subset would appear in the same order without changing the order of the items not found in the list and keeping items in the same location whenever possible. Okay, that probably sounds confusing, so I'll break it down: * The master list defines the default order of items. * The subset list defines relative order of certain items. * Where the master list has two elements out of order according to the subset list, the item that is earlier in the master list should be moved to the earliest index where it is in the correct location relative to other items within the subset list. (i.e. immediately after the later item) Your task is to implement this reordering algorithm. ## Example Test Cases ``` Master: [1, 2, 3] Subset: [] Result: [1, 2, 3] ``` --- ``` Master: [9001, 42, 69, 1337, 420] Subset: [69] Result: [9001, 42, 69, 1337, 420] ``` --- ``` Master: [9001, 42, 69, 1337, 420, 99, 255] Subset: [69, 9001, 1337] Result: [42, 69, 9001, 1337, 420, 99, 255] ``` --- ``` Master: [1, 2, 3, 4, 5] Subset: [2, 5] Result: [1, 2, 3, 4, 5] ``` --- ``` Master: [apple, banana, carrot, duck, elephant] Subset: [duck, apple] Result: [banana, carrot, duck, apple, elephant] ``` --- ``` Master: [Alice, Betty, Carol, Debbie, Elaine, Felicia, Georgia, Helen, Ilene, Julia] Subset: [Betty, Felicia, Carol, Julia] Result: [Alice, Betty, Debbie, Elaine, Felicia, Carol, Georgia, Helen, Ilene, Julia] ``` --- ``` Master: [snake, lizard, frog, werewolf, vulture, dog, human] Subset: [snake, werewolf, lizard, human, dog] Result: [snake, frog, werewolf, lizard, vulture, human, dog] ``` --- ``` Master: [Pete, Rob, Jeff, Stan, Chris, Doug, Reggie, Paul, Alex] Subset: [Jeff, Stan, Pete, Paul] Result: [Rob, Jeff, Stan, Pete, Chris, Doug, Reggie, Paul, Alex] ``` --- ``` Master: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] Subset: [8, 1, 2, 12, 11, 10] Result: [3, 4, 5, 6, 7, 8, 1, 2, 9, 12, 11, 10] ``` --- ``` Master: [lol, rofl, lmao, roflmao, lqtm, smh, jk, wat] Subset: [wat, lmao, rofl] Result: [lol, roflmao, lqtm, smh, jk, wat, lmao, rofl] ``` ## Rules * Standard loopholes, yadda yadda, convenient I/O, blah blah. * Even though the examples use numbers and strings, you only need to support one element type, whether that's integers, strings, or anything else with well-defined equality semantics, including heterogeneous lists if that's convenient in your language. * You may assume both the master list and the subset list contain no duplicates * You may assume that all items found in the subset list are found in the master list * Either list may be empty * You must, at minimum, support arrays up to 100 elements long. * Reordering may be implemented in-place or through the creation of a new list/array. Happy Golfing! [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 51 bytes ``` +`(\b(\w+),(\w+)\b.*¶.*\b)\3,(.*\b\2\b) $1$4,$3 1A` ``` [Try it online!](https://tio.run/##K0otycxL/P9fO0EjJkkjplxbUwdMxiTpaR3apqcVk6QZY6yjAWLEGAE5XCqGKiY6KsZcho4J//8X5yVmp@qUpxallufnpOnkZFYlFqXoZJTmJubppOSnc0HkocJpRfnpCLVlpTklpUWpIGUQDQA "Retina 0.8.2 – Try It Online") Takes input as a comma-separated list of subwords on the first line and a comma-separated master list of words on the second line. Explanation: ``` (\b(\w+),(\w+)\b.*¶.*\b)\3,(.*\b\2\b) ``` Find two adjacent subwords where the second word precedes the first on the master list. ``` $1$4,$3 ``` Move the second word to appear after the first word in the master list. ``` +` ``` Repeat until no words appear out of order. ``` 1A` ``` Delete the subwords. [Answer] # JavaScript (ES6), ~~96 89 74~~ 71 bytes This started as a bulky mess and was eventually shrunk to a rather concise and elegant form. I'd like to thank the *.splice()* method for its fruitful collaboration on that one. ;) Takes input as `(master)(subset)`. Outputs by updating the master list. ``` m=>s=>s.map(p=x=>m.splice(p,0,...m.splice(i=m.indexOf(x),p>i||!(p=i)))) ``` [Try it online!](https://tio.run/##hVJNb5tAEL37V2xPBmmLMG7SWhGW0jT9ujRKj4jDGhZYZz/oArHbpr/dndklGEWqaizNm5n3ZoZh9uyRdYUVbf9am5KfqvSk0m0H/0ixNmjTY7pVUddKUfCgpTGNomjyRaoioUt@/FYFx5C2W/H09Ao0IoTf6SpbEJKRbEVJQsk6pyTLSU59cBPHEH8DicsNJav1@i16MZIuN/@lUbIBN7m48HxwHQ/zZ@3YFwSUOGKCdkovWdtKvqRkuWMaHkQFs9b0iMqheEDLJW8bpvslFpiiXjqrdY37wMx73vc/EdwwaySCD3y3Ey53K5nQDn3kwBeu5SdubO3hZ2imEXwB63hfBwkp13oqPNNOPUbeeZ5OswdXQYpfzJaIKmtqtAdu@cHICvHjIPvBOmLps82gmPYdpxpzxbmeZ47KWes73jvVvdm50XjlhN97z75prOjcXszgOt7zuvb7uWODe5tryY9@hJfi59qO@Y8vDadCCZzJO7gKOAm4lRWeRoIFIea5q2QMx7PJpV@mNZWzUjHz7I9Q/ugV2k41aPbuGA5svA4EL3Q45CJfRJWxt6xogiBTlHR5SNIt@U2qQIVBF16RwujOSB5JUwcq2huhA6wQhuRPePoL "JavaScript (Node.js) – Try It Online") ### How? We are using two nested *[.splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)* methods on the same array to conditionally move an element from position \$i\$ to position \$p\$: ``` m.splice(p, 0, ...m.splice(i, condition)) ``` If the condition is truthy (coerced to \$1\$): * the inner *.splice()* removes and returns the element at position \$i\$ as a singleton array \$[element]\$ * thanks to the [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), this element is expanded as a 3rd argument for the outer *.splice()*, which causes it to be inserted back at position \$p\$ If the condition is falsy (coerced to \$0\$): * the inner *.splice()* removes nothing and returns an empty array * as a result, the outer *.splice()* receives *undefined* as its 3rd argument and nothing is inserted either ### Commented ``` m => s => // m[] = master list, s[] = subset list s.map( // p = // p = position in the master list of the last element from // the subset list (initialized to a non-numeric value) x => // for each element x in the subset list: m.splice( // insert in the master list: p, // at position p 0, // without removing any element ...m.splice( // remove from the master list and flatten: i = m.indexOf(x), // i = position of x in the master list p > i // if p is greater than i, remove x from its current // position and insert it at position p || !(p = i) // otherwise, set p to i and don't remove/insert anything ) // end of inner splice() ) // end of outer splice() ) // end of map() ``` [Answer] ## Haskell, 79 bytes ``` (m:n)#u@(s:t)|m==s=m:n#t|all(/=m)u=m:n#u|(x,_:z)<-span(/=s)n=(x++s:m:z)#u m#_=m ``` [Try it online!](https://tio.run/##jVLbbtNAEH3vV1g2D7Y6FbbTpnVUS5QCBZ6q8lhF1SbZxCZ7MXshocq/h5l1Am1TJGRpz@zMOWfWs9swu@RCbLepHKks8e9SO3LZRta1rTGTuA0TIn1by8yHvd@ka3gYPWaXJ7ZjCis2U3W6Pj62I4npxB/J5KGWW8laFdXRTB9FUWda5aI3UZpk0X0BJQzG0f34ZaHK8wJOSxhWUAwG5xjmSBtW/0OEqoLy7CzwIdSpMn61N5wCEUtcX9Zj1nWCxxBPmMIPgykzRjsMZn66ROCCdw1TLkaHfa4XHZpdiXZKZu@5c78Qr5nRAvEDn0xaKnwUOCQKPnGkttTvhmuzCNFnbKUQvyAQ56sXmKe2e7@/qr3zjnNwEqvYkjxE@8jMDIO50QuEFTd8pcUcw59eOG@INAulxkumQru9@An5j0/P6jWHbW@5I@GdntDZ@Jyk31wQXDemtTQL7anbHV8swkhumacfuRJ8HZo/V@0MA@nflwtDOIcLwNeRQ4EvoUSjC6ByUYZEfnhUEeZn9JxASKZ3uz4SP5xEsLLB9Tvd@Yr1T4DwmSAeb38D "Haskell – Try It Online") ``` (m:n)#u@(s:t) -- m: head of master list -- n: tail of master list -- s: head of subset -- t: tail of subset -- u: whole subset |m==s -- if m==s =m:n#t -- return 'm' and append a recursive call with 'n' and 't' |all(/=m)u -- if 'm' is not in 'u' =m:n#u -- return 'm' and append a recursive call with 'n' and 'u' | -- else (note: 's' is element of 'n') (x,_:z)<-span(/=s)n -- split 'n' into a list 'x' before element 's' and -- a list 'z' after element 's' and = (x++s:m:z)#u -- make a recursive call with -- x++s:m:z as the new master list (i.e. 'm' inserted into 'n' after 's') -- and 'u' m # _ = m -- if either list is emtpy, return the master list ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~73~~ 68 bytes ``` ->a,b{0while b.zip(a&b).find{|m,n|m!=n&&a=a[0..a.index(m)]-[n]|a};a} ``` [Try it online!](https://tio.run/##ZY2xTsMwEIZ3nsJkiFrpatkxASIUJAQTUwWj5cEWdmopcavSiELTZw93KZmYft9/33fe9@57DPW4erTgTuJrE1vPHP@Ju4XN3ZKHmD5OQwdp6K7rlOe2tlpwbjn2/rjolmalkxns@cGexx0LWisoQBrQElMZczWVlRAS2E0B7LYCJpW6o0kAq3AsytIA07S5cLSfTRzRUogDK1EHhuo9koihLwkvSMfuwsrirxbzjWztDz4Dlr1tHcWrD4Hy/WAT5fNmHz/p8bLtm4nzTRMnY237lvKp9ceMvvknz7cn0pjxFw "Ruby – Try It Online") ### How? * The intersection between `a` and `b` contains all elements of `b`, but in the same order as we would find them in `a` * So, if we iterate on `b` and on the intersection in parallel, as soon as we find a difference, we can relocate a single element. * Relocation is done by cutting `a` on the position of the element we found in `b`, then removing the element we found in the intersection, and then adding the remainder of a. * Repeat from the beginning, until all elements of `b` are in the right order in `a` [Answer] # [Python 2](https://docs.python.org/2/), ~~124~~ ~~109~~ ~~106~~ ~~99~~ 96 bytes ``` def f(a,b,i=0): while b[i+1:]:x,y=map(a.index,b)[i:i+2];i+=1;x>y>a.insert(x,a.pop(y)) return a ``` [Try it online!](https://tio.run/##ZZBBT4NAEIXv/RUTLkA6adjFqqVpE6MnT40eCYclLLCRLmQLFvzzuANqSTy92Xnve5NsM7Rlrfk4ZjKH3BOYojoEfrSCa6kqCWms1ixKoh6Hw1k0ntgonckeUz9WkVrzZK/WB7bvj8ORrIs0rdej2DR14w2@vwIj285oEGNjlG7tiThEjizBmFkNE3/1Z@yCgCHccYT7HQILwwd6BQg7@@TbbYIQkzPnyF/SdmXJ0CIIW1uBYPFHm7ZR28EI4VRhd3OW8Z91sOxxTrKVDoLzVqckrzLPSd9boUmfS6MuNLzUXTHlZFGoiTiJriJ9qmTv0Kl/8G/3lFxedS9afEgXwa3UlzAZTbmpC9KrNPJaVznNn11l/3MKZrNbdmehXbp261gSt745@UMm/vgN "Python 2 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 40 bytes ``` {*.permutations.first(*.grep(.any)eq$_)} ``` [Try it online!](https://tio.run/##fYvdCoIwFMfve4pzEbGJiGUakvkiEnGqmdXm5pyERM9umwXSTZyL8//6KaZ5MogeFiXshqcXKKZFZ9BcZd0G5VW3hnjBRTNFAqx7ypr5gb6GFnsoSbGnpFj6sPIh2tPt7JsmqcvTMLTV2nZJ6sMyijbOhT87Hz4r1/5h7MzaVRxPcHbuTndApTjLKclGAUes7cEJtZYGxgXjTFVYm3wiH2iAC5SgZckdzCUf9ZS6zxsjoBUV3O5gkZwObw "Perl 6 – Try It Online") Anonymous code block that takes the input curried (like `f(subList)(masterList)`, and finds the first lexographical permutation of the indexes of the master list where the elements from the sub list are in the correct order. Intuitively, the first satisfying permutation will leave the correctly ordered elements in the original order, while moving the incorrectly placed ones the minimum needed distance forward in order to have them in the correct order, which places them directly after the previous element in the subset. ### Explanation: ``` {* } # Anonymous code block that returns a lambda .permutations # In all permutations of the master list .first( ) # Find the first permutation (*.grep(.any) # Where the order of the subset eq$_ # Is the same as the given order ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Œ!iⱮṢƑ¥ƇḢ ``` [Try it online!](https://tio.run/##y0rNyan8///oJMXMRxvXPdy56NjEQ0uPtT/csej/4eWR//8r5eTnKOkoFeWngaic3MR8KA/CyiksyQVSxbkZQDIrG0iUJ5Yo/QeTKMqVAA "Jelly – Try It Online") or [Test suite](https://tio.run/##fZC/ToNQFMZ3ngKZb2ILtoZZJ6emToYw3JbLv164eAGJTo1LZ511aWJcjImbXW3se5QXwXO4YOxiSO75zjm/7zsJMeP8tmm@H4@i@uN9v1nvHr5edqv957rZvh7H9fKJ6PXyWduu6vu3q6ZxnCHRTaJbLtEcV3OJozn2YADDE5iObaIPLesUuwESY/t/hug2tOZopGBoWw73nbE7BzTRW8rEqnYGzTLODGLMaAofiDmVUhQgvHK@gMI4y0KaFgY6@6Fy9Rl5SheYwaM7Kj0QvhQBlIpJVgnug7wpeVFKhLx2FZYJTVVk7/5D/wYpTJn6axNWID4VM3gvmI@Gy6LFzkIZ5VDPRYlHpiwIImQntOTq2CHfRal1F88Fh5EUPhaeUNF1SvHrIoGSJyG8Mf6Kina/BsWBAyN/AA) Inefficient, particularly with large master lists. Generates all possible permutations, filters out those where the subset is in the wrong order, and then returns the first. ### Explanation ``` Œ! | Generate all permutations of the master list ¥Ƈ | Filter including only those where... iⱮ | the index of each sublist item in this permutation... Ƒ | is... Ṣ | in order. Ḣ | Finally take the first item ``` [Answer] # [J](http://jsoftware.com/), 49 bytes ``` [:(<@({:+i.@>:@-/)@i.~C.])^:(>/@i.~)&.>/]|.@;2<\[ ``` [Try it online!](https://tio.run/##bU67DoIwFN35ihMHaaOUUl5SkTQhcXJyRVyMRFz8AI2/jqVF0IShyT3Pnnu3YG6DnYSLNTikfh5DeTzsu0qSXJGnXLVMFVJ5PlUte5espmdJCr8HdMkKv34xtRX5qeqo41wvtwdIHkAgpPB0r4sGBo5ixnmASCDJEIRhqk9urBo3mBHHoKWN46shyyDi2OTJr0jnuwb//1BEGBpEfwx7exaj0cIEKTZG1pUCgf7LbieWnbgGZGqxMR3hRhbU6T4 "J – Try It Online") ## explanation We take the subset as the left arg and the full input as the right. We'll work through the code with a specific example for clarity: ``` 5 2 4 f 1 2 3 4 5 ``` Take the boxed infixes of size two of the subset: ``` 2 <\ [ ``` producing: ``` ┌───┬───┐ │5 2│2 4│ └───┴───┘ ``` append them to the original input, and reverse the whole thing: ``` ] |.@; ``` We get: ``` ┌───┬───┬─────────┐ │2 4│5 2│1 2 3 4 5│ └───┴───┴─────────┘ ``` Solving the problem becomes a right to left reduction on the above. We need only find the right verb to insert `/` between the items. Each iteration of the reduction will update the rightmost box (the full input, which we're transforming) so it conforms to the ordering constraint represented by the pair to its left. When the reduction is finished, the input will respect the complete subset ordering. If the ordering of the pair is the same as ordering in the input, the following will evaluate to 0 and we'll do nothing: ``` ^:(>/@i.~) ``` Otherwise it will evaluate to 1 and we'll apply the verb to the left of `^:` ``` {: + i.@>:@-/)@i.~ C. ] ``` which moves the left item to the right of the right item. This movement is simply a *cyclic permutation* of all the items between (and including) the two elements in question. J has primitive to apply such a cyclic permutation: ``` <cyclic permutation definition> C. ] ``` and the remainder of the verb does nothing but pick out the indexes we need to cycle: ``` {: + i.@>:@-/)@i.~ ``` which seems longer than it should be, but I wasn't able to golf that phrase further. Finally we rebox the result `<@` and we're done. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` i@€MƤFṬœṗƲḊ;JḟF}W€ʋ@¥ṢFị ``` [Try it online!](https://tio.run/##y0rNyan8/z/T4VHTGt9jS9we7lxzdPLDndOPbXq4o8va6@GO@W614UC5U90Oh5Y@3LnI7eHu7v@Hl0f@/69UnliipKOUk5uYD6SK8tNylP4r5eTnwDgoUhBWTmFJLpAqzs0AklnZQAJkBgA "Jelly – Try It Online") or [Test suite](https://tio.run/##fVFNS8NAEL33V4SeB0xSWw1e6lf9AEH0IBJ62LbbNnWbrdvEqiCIF0GPHrwogiheevLU4k3Rg/8i/SNxZpP4cZGQvDc7781MdjpciKM49sqTs@HGx0MlGg/fr6Lx9cdzNLqYW49Gd5WTHcx9XpZfH6PxfSV6uYzfnspTncnpDRiT09vc2znmd@PYdS0wbDAKVci51VwV3JzrmCYeTuNpyQHDKhRmKDJJUXL@14DhYGgXi4kYQ62jfGpM26EaDK2yCZNcnvV6guchX2M@PkjqTCkZIGmE9T0ELnivzfwgT87sMHFlNeaFV6caCzwIjhAXmZICcYnXah4llgXzfCIVjlKP2qxwqVqarWIHH3ENgTTrocBz3S0r@GPLSqeidIC@z/bIKrxjphpImkq2EAZc8YEUTaQHoQhCRaKGTrXDLvOTLpn7l/q7UCJLTFm3TR6QfEvWaBDeJMN2oGWLbeX16c9lSE22eKulL2CThTT1vOCHSc@/trSiVn0vzYYCTEMRSjADs@CAZYJlgWWTfxYXrLdq0UvrNrPphL4fJZsEostkGiVM7AddhH63jd8OrXLA0tUS@eOgUb4A "Jelly – Try It Online") ### Explanation A dyadic link that takes the subset as the left and master list as right arguments. The below example uses 9001, 42, 69, 1337, 420, 99, 255 as master and 69, 9001, 1337 as subset. ``` i@€ | Find the index of each subset item in the master list [3, 1, 4] Ʋ | Previous 4 links as a monad MƤ | Find the index of the maximum for each prefix of this list [1, 1, 3] F | Flatten (because the previous result are actually each length one lists) Ṭ | Convert to a boolean list [1,0,1] œṗ | Partition the [3, 1, 4] list before each 1 [[], [3, 1], [4]] Ḋ | Remove the empty first list [[3, 1], [4]] ¥ | Previous two links as a dyad ʋ@ | Previous 4 links as a dyad with reversed arguments J | Sequence along the master list [1, 2, 3, 4, 5, 6, 7] ḟF} | Filter out items in the flattened [3, 1, 4] list W€ | Wrap each item as a list [[2], [5], [6], [7]] ; | Concatenate rhis to the [[3, 1], [4]] list Ṣ | Sort (effectively by first item in each list) [[2], [3, 1], [4], [5], [6], [7]] F | Flatten ị | Look up in original master list (and implicitly output) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 118 bytes ``` a=>b=>{for(int j;b.Any();)foreach(var e in b.Intersect(a.Take(j=a.IndexOf(b.Dequeue())))){a.Remove(e);a.Insert(j,e);}} ``` [Try it online!](https://tio.run/##jVJNS8NAEL3nVyw9bWANSWrVkG6gIIJQ8APBQ@lhs04wFbeYbKtS9rfH2SSapK1oLpl5782bSWZkeSLLvLraKDmd56We5konbCZ1vlbTuw1soEaSJOOV4EnKk122LihiZBWn3kx9Ujd2EQIhn@lWFARIrkjqXSsNRQlSU@E9iBegKy4QfIKPm4ym3iW8WXPq2mcnvHt4XW@BghtbVQmFpiuGmTFV7FhbDaUuCScK3hfLndO@SJsHjISMjA1rEBxBL/wlO@AdVOyVRr6P7CnSZxEjwXh8bjPfdMVnUS/5Tf5/Z0YiTMPJZNAC0VpuZT3iu7oj9zyO9G0/FoWM9JuEw3Qo@8sHx2AEm19gaxwEJwjsQGHPEKmmJAhbtv8XD30acTTQO8bETv@c7N7tRdX7d4mdzsKC2zX/XCy1NG7cjVs@rfnugBtB0AnkMYOw4TMqXJrW4W2BLKZdLOv4scg1zHMFdMQ5HyFmqi8 "C# (Visual C# Interactive Compiler) – Try It Online") Leveraging some classes in the `System.Collections.Generic` namespace. The master is a `List<T>` and the subset is a `Queue<T>`. ``` // a: master // b: subset a=>b=>{ // continue until b is empty for(int j;b.Any();) // iterate over values that are out of order in a // per the head of b using loop variable e foreach(var e in // the out of order values are determined by // intersecting remaining values in b with b.Intersect( // values in a occurring before the current head of b // save the position in a to variable j and remove the head of b a.Take(j=a.IndexOf(b.Dequeue())) ) ){ // push back the out of order element in a a.Remove(e); a.Insert(j,e); } } ``` ]
[Question] [ [Abbreviate that US state!](https://codegolf.stackexchange.com/questions/122896/abbreviate-that-us-state/122925?noredirect=1#comment304738_122925) was fun, but we learnt that efficiently abbreviating US state names is hard with the current system. Let's come up with an alternative state code scheme for efficient golfing. Your task: > > Write a function (or program) which, given a valid US state name (only the 50 normal states required), returns a unique two-letter code in uppercase identifying it. The code must meet these requirements: > > > * The first letter must be the same as the first letter of the state. > * The second letter must be one of the other letters of the state (not a space). > * It must always give the same output for the same input, and must never give the same output for two different valid inputs. > > > For instance, given "Alabama", your function could return "AL", "AA", "AB" or "AM" - as long as it doesn't return that value for any of Alaska, Arkansas, etc. ("AA" is only possible because "A" appears more than once in the state name.) Standard loopholes forbidden. Standard input/output are ok. This is code golf, so shortest solution, in bytes, wins. The complete list of possible inputs is here: ``` Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi Missouri Montana Nebraska Nevada New Hampshire New Jersey New Mexico New York North Carolina North Dakota Ohio Oklahoma Oregon Pennsylvania Rhode Island South Carolina South Dakota Tennessee Texas Utah Vermont Virginia Washington West Virginia Wisconsin Wyoming ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 907ị;⁸Qḣ2ṢŒu ``` A monadic link taking and returning lists of characters. **[Try it online!](https://tio.run/##y0rNyan8/9/SwPzh7m7rR407Ah/uWGz0cOeio5NK////75tZXAxCBQWZAA)** or see a [test suite](https://tio.run/##XZG9TuNAEIBfxV2aKxDN6XQVCgIMJOHvQCdEMdhDPHizE@2sCaaDhoLuHgFaHgAE3YkHSV7E7I8NAmml/eb/7xyVqpvm19LP@cvd78X10@786WF5/nz/9q9q3l7/3y5uHteb5ri3ouAUJtD7kXiUMpKhK9YtlqAFxHMfFJ2x0RQsfVZsIOfIWmNmKausF1dRwQwMel5zXpSHiHVkM47BG85O5CnNoQg5UqVIM4VKqc4JYgMpz8K/9dHGFmpbZWXteZsrks51AKQxgqkV6DyyCGRFJWhtCB9QVtAYdGTXt7CN4STi33RKnciViczatkWGeGq6PQ3xAvKWZskGTKZSUBzbKzbRCNadNMBLyriT/rIpA7OxRdIHw256@NSsQtm2NSooRI1K5TYVTzUyOOYwwQ5qLbW6gPYqewXnmKTSjb/P1bf8UfOZ/wD9DgQxCpdxyX8sFP4/RDNxwwckd722zBG4SfXYxiaOUGzyxUySsRaK1ponzrd38g4) ### How? ``` 907ị;⁸Qḣ2ṢŒu - Monadic link: list of characters, state e.g. Alabama or Kansas 907 - literal 907 ị - index into state b K ⁸ - link's left argument, state ; - concatenate bAlabama KKansas Q - de-duplicate (unique by 1st appearance) bAlam Kans ḣ2 - head to index 2 bA Ka Ṣ - sort Ab Ka Œu - convert to uppercase AB KA ``` Indexing in Jelly is 1-indexed and modular, so the 907th index of something of length L is the (907-modulo-L)th item. For example for "Alabama" the length is 7 so the item at index 907 is the (907-modulo-7)th, and 907-modulo-7 is 4 (907 = 129 \* 7 + **4**), so the item at index 907 is 'b'. 907 is the first positive index at which the state abbreviations using index 1 and that index over all of the 50 states become unique. State names, including their spaces, are of length 4 through 14 inclusive, and 907-modulo-6 is 1 (whereas for all other lengths the value is not 1). This means that if we were to use the 1st and 907th characters for the abbreviations that Alaska, Hawaii, Kansas, Nevada, and Oregon would be AA, HH, KK, NN, and OO respectively - this is not acceptable for Hawaii, Kansas, or Nevada; so an adjustment needs to be made; this is the reason for the concatenation, de-duplication, head to index 2 and sort, this makes Alaska, Hawaii, Kansas, Nevada, and Oregon become AL, HA, KA, NA and OR respectively and does not collide with existing state abbreviations. [Answer] # Ruby, 34 bytes ``` ->s{s[0]+(s[1,8]*999)[445].upcase} ``` I started off with `s[0]+s*99999[x].upcase` and found many values of x up to x=100000 which returned unique codes for all 50 states. Unfortunately they all had cases where the second letter of the abbreviation was the first letter of the state duplicated, which is not allowed (unless the letter appears twice in the state name.) So I decided to use the expression `s[0]+s[1,8]*999[x]` and found the smallest value of x that worked was 445. **Commented in test program, and output** ``` f=->s{s[0]+ #Return character 0 of the input. Then.. (s[1,8]*999)[ #Concatenate 999 copies of the 8 characters starting at character 1 (or till end of name if state has less than 9 characters) 445].upcase #Return character 445 of the result, converted to uppercase. } "Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi Missouri Montana Nebraska Nevada New Hampshire New Jersey New Mexico New York North Carolina North Dakota Ohio Oklahoma Oregon Pennsylvania Rhode Island South Carolina South Dakota Tennessee Texas Utah Vermont Virginia Washington West Virginia Wisconsin Wyoming".split($/).map{|i|p [f[i],i]} ["AA", "Alabama"] ["AL", "Alaska"] ["AI", "Arizona"] ["AS", "Arkansas"] ["CR", "California"] ["CA", "Colorado"] ["CT", "Connecticut"] ["DA", "Delaware"] ["FO", "Florida"] ["GO", "Georgia"] ["HA", "Hawaii"] ["IA", "Idaho"] ["IO", "Illinois"] ["ID", "Indiana"] ["IW", "Iowa"] ["KA", "Kansas"] ["KC", "Kentucky"] ["LA", "Louisiana"] ["MI", "Maine"] ["MA", "Maryland"] ["MH", "Massachusetts"] ["MG", "Michigan"] ["MO", "Minnesota"] ["MS", "Mississippi"] ["MU", "Missouri"] ["MN", "Montana"] ["NS", "Nebraska"] ["NE", "Nevada"] ["NM", "New Hampshire"] ["NR", "New Jersey"] ["NX", "New Mexico"] ["NO", "New York"] ["NC", "North Carolina"] ["ND", "North Dakota"] ["OI", "Ohio"] ["OO", "Oklahoma"] ["OR", "Oregon"] ["PL", "Pennsylvania"] ["RI", "Rhode Island"] ["SC", "South Carolina"] ["SD", "South Dakota"] ["TS", "Tennessee"] ["TX", "Texas"] ["UA", "Utah"] ["VR", "Vermont"] ["VN", "Virginia"] ["WG", "Washington"] ["WI", "West Virginia"] ["WS", "Wisconsin"] ["WO", "Wyoming"] ``` [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda s:s[0]+s[906%len(s)or 1].upper() ``` [Try it online!](https://tio.run/##bZJtaxNBEIC/51fsF0mCtbQigoEKkqKNNY3YapGYD5O7SW64vZ1jZ6/pNeS3x325sygeB/vM687MTt26gs3r4@bi11FDtc5ByUSWZ6uXsnx39vaFRjOSMVt1vjpt6hrtaHwUBw5FXajl8IOGNVQwPFEBpUxk6YlNhyUYAQk8BU0btoaiZcqaLeSc2BjMHGWNC@IlatiBxcAfvRflMeITst2m4CtvJwo0y6GIOWZak2GKN81MTpAKmPEuntd/yrhG45qsbAN/4Yakd50DGUxgWw0mTywCWdEIOhfD55QVtAWT2Nct7FI4iYS/rqkXubGJ2bjukhtc235ON/gAeUc7dQVVLQWltoPiM1rBtpfm@EgZ99JPtmVktq5QU7Dsu4dnzSWUXVmLgmLUotR@UumpFha3HDv4isZIqx@ge5VvBeeoZtK3f8vNP/mT5jn/HYYZCGISHtOQvzsowvkDbeWbj0j@9bpr7sF3arYuFXGP4tRfZpKMjVCytlx53@FqMKgtGafCSu43o7iFY@U3SkVUZBLIYTwY/Ec9GSj/pRzD/eT8zeHVe7U/DE@9bwUuJTxRfebx8Tc "Python 2 – Try It Online") ## [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda s:s[0]+s[306%len(s)or-3].upper() ``` [Try it online!](https://tio.run/##bZLdb9NADMDf@1fcC2ortmkwxEOlIaFOsDK6IgZMqPTBTdzGyuUcnS/rQtW/vbuPhAlEFOl@/jzb57p1BZvXx83lr6OGap2Dkoksz1cvZXlx/vaFRjOSMdvTi9VZU9doR@OjOHAo6lIth@81rKGC4YkKKGUiS7/ZdFiCEZDAU9C0YWsoWqas2ULOiY3BzFHWuCBeoYYdWAz8wXtRHiM@ItttCr72dqJAsxyKmGOmNRmmeNPM5ASpgBnv4nnzp4wbNK7JyjbwZ25Ietc5kMEEttVg8sQikBWNoHMxfE5ZQVswiX3dwi6Fk0j465p6kRubmI3rLrnFte3ndIsPkHe0U9dQ1VJQajsoPqEVbHtpjo@UcS/9ZFtGZusKNQXLvnt41lxB2ZW1KChGLUrtJ5WeamFxy7GDL2iMtPoBulf5WnCOaiZ9@3fc/JM/aZ7zf8MwA0FMwmMa8ncHRTh/oK188xHJv153zT34Ts3WpSLuUZz6y0ySsRFK1pYr7ztcDQa1JeNUWMn9ZhS3cKz8RqmIikwCOYwHg/@oJwPlv5RjuJ@8enM4faf2h@GZ963ApYQnqs88Pj4B "Python 2 – Try It Online") [Answer] ## JavaScript (ES6), 46 bytes ``` s=>s[0]+s[(s>'M')+1153%s.length].toUpperCase() ``` ### Demo ``` let f = s=>s[0]+s[(s>'M')+1153%s.length].toUpperCase() ;[ 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California','Colorado','Connecticut','Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts','Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire','New Jersey', 'New Mexico', 'New York', 'North Carolina','North Dakota','Ohio', 'Oklahoma','Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee','Texas', 'Utah', 'Vermont', 'Virginia','Washington', 'West Virginia','Wisconsin', 'Wyoming' ] .map( s => console.log(f(s), s) ) ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~49~~ 46 bytes ``` \B.*(?=[A-Zflmpxz])|\B.*(?=[hru]) T`l`L !`^.. ``` [Try it online!](https://tio.run/##TVDbThtBDH33V6QPlaBS8wcI0aDCAklQS0G9UMXsmoy1s3Y0niVZxL@nnoWqlUbj44uOfU6izIL79wdnq/2vT9MPB8dHP08@/niM3Wb3fH/48rcWUn9/CHCziqsreLf6PZ3u9ycRH7BD8Gith8TPKiW2KIYGM4z8qEkYYaZREzbqQITqzHWf4ZQibjERfPYmNwhnpGnt0@deZoaqwaBQxciibFBJw@j8lW4RLl9XXJLkvm4HuNKebWzPkYX8T0NEaRyYYR16o5wN5lwHXqM48DtMs8@zWXmbDY9Y@@RAJReyBT2kUdyCnrApYTs5x25jgf3ukl1QMhpGOKcd1zrC75paWGjKYTLDpK4A39JTbMvWZWCFZRtdoTu4TLRWgWsSsSE@YbHsS9CGJpWNKr5q/z/Va/pGdUNFihE52rkn3zIGuKXUuQa4ZXe00N2h3yzr7GvuyPLkX4OtVjH2@qCdj/wB "Retina – Try It Online") If the state contains a second uppercase letter, or one of the letters `flmpxz`, then that becomes the second letter of the code. Otherwise, if it contains one of the letters `hru`, then that becomes the second letter of the code, otherwise just use the first two letters of the state. [Answer] # JavaScript (ES6), 52 bytes ``` s=>s[0]+(s=s.slice(2,9))[146%s.length].toUpperCase() ``` ``` f= s=>s[0]+(s=s.slice(2,9))[146%s.length].toUpperCase() states = `Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi Missouri Montana Nebraska Nevada New Hampshire New Jersey New Mexico New York North Carolina North Dakota Ohio Oklahoma Oregon Pennsylvania Rhode Island South Carolina South Dakota Tennessee Texas Utah Vermont Virginia Washington West Virginia Wisconsin Wyoming`.split('\n') states.forEach(state => console.log(f(state), state)) ``` --- # JavaScript (ES6), 52 bytes ``` s=>s[0]+(s[8]||s[s[1]=='o'?5:4]||s[2]).toUpperCase() ``` ``` f= s=>s[0]+(s[8]||s[s[1]=='o'?5:4]||s[2]).toUpperCase() states = `Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi Missouri Montana Nebraska Nevada New Hampshire New Jersey New Mexico New York North Carolina North Dakota Ohio Oklahoma Oregon Pennsylvania Rhode Island South Carolina South Dakota Tennessee Texas Utah Vermont Virginia Washington West Virginia Wisconsin Wyoming`.split('\n') states.forEach(state => console.log(f(state), state)) ``` ]
[Question] [ **Background** The [Schläfli Symbol](https://en.wikipedia.org/wiki/Schl%C3%A4fli_symbol) is a notation of the form {p,q,r,...} that defines regular polytopes and tessellations. The Schläfli symbol is a recursive description, starting with a p-sided regular polygon as {p}. For example, {3} is an equilateral triangle, {4} is a square and so on. A regular polyhedron that has q regular p-sided polygon faces around each vertex is represented by {p,q}. For example, the cube has 3 squares around each vertex and is represented by {4,3}. A regular 4-dimensional polytope, with r {p,q} regular polyhedral cells around each edge is represented by {p,q,r}. For example a tesseract, {4,3,3}, has 3 cubes, {4,3}, around an edge. In general a regular polytope {p,q,r,...,y,z} has z {p,q,r,...,y} facets around every peak, where a peak is a vertex in a polyhedron, an edge in a 4-polytope, a face in a 5-polytope, a cell in a 6-polytope, and an (n-3)-face in an n-polytope. A regular polytope has a regular vertex figure. The vertex figure of a regular polytope {p,q,r,...y,z} is {q,r,...y,z}. Regular polytopes can have star polygon elements, like the pentagram, with symbol {5/2}, represented by the vertices of a pentagon but connected alternately. The Schläfli symbol can represent a finite convex polyhedron, an infinite tessellation of Euclidean space, or an infinite tessellation of hyperbolic space, depending on the angle defect of the construction. A positive angle defect allows the vertex figure to fold into a higher dimension and loops back into itself as a polytope. A zero angle defect tessellates space of the same dimension as the facets. A negative angle defect cannot exist in ordinary space, but can be constructed in hyperbolic space. **Competition** Your goal is to create a program which when passed a Schläfli Symbol will return a complete description of a convex polytope. This is only a subset of the Schläfli Symbols, but it is the simplest one, I believe even without the other possibilities this will be a very difficult task, and polytopes are the starting point for tessellations. The rules of this question were designed with the idea of this result being an API, and I have not been able to locate any such program on the internet. Your program must accomplish all of the following. * The program must be able to generate any finite dimensional regular convex polytope. In 2 dimensions this includes n-gons. In 3 dimensions these are the platonic solids, in 4 dimensions this includes the tesseract, the orthoplex and a few others) * The program must either (a) place a point on the origin, or (b) ensure that the average of all points is the origin. Orientation does not matter. Overall size does not matter. * The program must provide a **complete** description meaning that for a 4-dimensional object, the program will return/print the vertices, edges, faces, and polyhedra. The order these are reported does not matter. For polyhedra, this is the information you would need in order to render the object. You do *not* need to handle: * Tesselations * Hyperbolic Geometry * Fractional Schläfli symbols (non-convex) * Embedded Schläfli Symbols (non-uniform tilings) If asked to do any of these things you can return an error. Example: Cube Input: ``` 4 3 ``` Output: ``` Vertices 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 Edges (These are the vertex pairs that make up the edges) 0 1 0 2 0 4 1 3 1 5 2 3 2 6 3 7 4 5 4 6 5 7 6 7 Faces (These are the squares which are the faces of the cube) 0 1 3 2 0 1 5 4 0 2 6 4 6 7 5 4 7 6 2 3 7 5 1 3 ``` I had some ideas for how this algorithm could work and be very recursive, but thus far I've failed, but if you are looking for inspiration check out: <https://en.wikipedia.org/wiki/Euler_characteristic> As an example of working out the number of vertices, edges and faces, Consider the cube which is {4,3}. If we look at the initial 4, then it has 4 edges and 4 vertices. Now if we look at the next 3, we know that 3 edges meet at each vertex, each edge connects to 2 vertices, 2 faces meet at each edge, each face connects to 4 edges(because of the square sides), and we have the Euler Characteristic formula. E = 3/2 V E = 4/2 F V - E + F = 2 Which gives E=12, V=8, F=6. # Scoring In order to keep the question on topic, this has been revised to Code Golf. Shortest code wins. [A github has been created for this question](https://github.com/aruth2/schlafli) [Answer] # Ruby **Background** There are three families of regular polytope extending into infinite dimensions: * the simplexes, of which the tetrahedron is a member (I will often refer to them here as hypertetrahedra, though the term simplex is more correct.) Their schlafi symbols are of the form `{3,3,...,3,3}` * the n-cubes, of which the cube is a member. Their schlafi symbols are of the form `{4,3,...,3,3}` * the orthoplexes, of which the octahedron is a member (I will often refer to them here as hyperoctahedra) Their schlafi symbols are of the form `{3,3,...,3,4}` There is one further infinite family of regular polytopes, symbol `{m}`, that of the 2 dimensional polygons, which may have any number of edges m. In addition to this, there are just five other special cases of regular polytope: the 3-dimensional icosahedron `{3,5}` and dodecahedron `{5,3}`; their 4-dimensional analogues the 600-cell `{3,3,5}` and 120-cell `{5,3,3}`; and one other 4 dimensional polytope, the 24-cell `{3,4,3}` (whose closest analogues in 3 dimensions are the cuboctahedron and its dual the rhombic dodecahedron.) # Main function Below is the main `polytope` function that interprets the schlafi symbol. It expects an array of numbers, and returns an array containing a bunch of arrays as follows: * An array of all vertices, each expressed as an n-element array of coordinates (where n is the number of dimensions) * An array of all edges, each expressed as a 2-element of vertex indices * An array of all faces, each expressed as an m-element of vertex indices (where m is the number of vertices per face) and so on as appropriate for the number of dimensions. It calculates 2d polytopes itself, calls functions for the 3 infinite dimensional families, and uses lookup tables for the five special cases. It expects to find the functions and tables declared above it. ``` include Math #code in subsequent sections of this answer should be inserted here polytope=->schl{ if schl.size==1 #if a single digit calculate and return a polygon return [(1..schl[0]).map{|i|[sin(PI*2*i/schl[0]),cos(PI*2*i/schl[0])]},(1..schl[0]).map{|i|[i%schl[0],(i+1)%schl[0]]}] elsif i=[[3,5],[5,3]].index(schl) #if a 3d special, lookup from tables return [[vv,ee,ff],[uu,aa,bb]][i] elsif i=[[3,3,5],[5,3,3],[3,4,3]].index(schl) #if a 4d special. lookup fromm tables return [[v,e,f,g],[u,x,y,z],[o,p,q,r]][i] elsif schl.size==schl.count(3) #if all threes, call tetr for a hypertetrahedron return tetr[schl.size+1] elsif schl.size-1==schl.count(3) #if all except one number 3 return cube[schl.size+1] if schl[0]==4 #and the 1st digit is 4, call cube for a hypercube return octa[schl.size+1] if schl[-1]==4 #and the last digit is 4, call octa for a hyperoctahedron end return "error" #in any other case return an error } ``` # Functions for the tetrahedron, cube and octahedron families <https://en.wikipedia.org/wiki/Simplex> <https://en.wikipedia.org/wiki/5-cell> (4d simplex) <http://mathworld.wolfram.com/Simplex.html> **Tetrahedron family explanation - coordinates** an n-dimensional simplex/hypertetrahedron has n+1 points. It is very easy to give the vertices of the n-dimensional simplex in n+1 dimensions. Thus `(1,0,0),(0,1,0),(0,0,1)` describes a 2d triangle embedded in 3 dimensions and `(1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1)` describes a 3d tetrahedron embedded in 4 dimensions. This is easily verified by confirming that all distances between vertices are sqrt(2). Various complicated algorithms are given on the internet for finding the vertices for the n-dimensional simplex in n-dimensional space. I found a remarkably simple one in Will Jagy's comments on this answer <https://mathoverflow.net/a/38725> . The last point lies on the line `p=q=...=x=y=z` at a distance of sqrt(2) from the others. Thus the triangle above can be converted to a tetrahedron by addition of a point at either `(-1/3,-1/3,-1/3)` or `(1,1,1)`. These 2 possible values of the coordinates for the last point are given by `(1-(1+n)**0.5)/n` and `(1+(1+n)**0.5)/n` As the question says the size of the n-tope does not matter, I prefer to multiply through by n and use the coordinates `(n,0,0..0)` up to `(0..0,0,n)` with the final point at `(t,t,..,t,t)` where t = `1-(1+n)**0.5` for simplicity. As the centre of this tetrahedron is not at the origin, a correction to all coordinates must be done by the line `s.map!{|j|j-((1-(1+n)**0.5)+n)/(1+n)}` which finds how far the centre is from the origin and subtracts it. I have kept this as a separate operation. However I have used `s[i]+=n` where `s[i]=n` would do, to allude to the fact that when the array is initialised by `s=[0]*n` we could put the correct offset in here instead and do the centring correction at the outset rather than the end. **Tetrahedron family explanation - graph topology** The graph of the simplex is the complete graph: every vertex is connected exactly once to every other vertex. If we have an n simplex, we can remove any vertex to give an n-1 simplex, down to the point where we have a triangle or even an edge. Therefore we have a total of 2\*\*(n+1) items to catalogue, each represented by a binary number. This ranges from all `0`s for nothingness, through one `1` for a vertex and two `1`s for an edge, up to all `1`s for the complete polytope. We set up an array of empty arrays to store the elements of each size. Then we loop from zero to (2\*\*n+1) to generate each of the possible subsets of vertices, and store them in the array according to the size of each subset. We are not interested in anything smaller than an edge (a vertex or a zero) nor in the complete polytope (as the complete cube is not given in the example in the question), so we return `tg[2..n]` to remove these unwanted elements. Before returning, we tack [tv] containing the vertex coordinates onto the beginning. **code** ``` tetr=->n{ #Tetrahedron Family Vertices tv=(0..n).map{|i| s=[0]*n if i==n s.map!{(1-(1+n)**0.5)} else s[i]+=n end s.map!{|j|j-((1-(1+n)**0.5)+n)/(1+n)} s} #Tetrahedron Family Graph tg=(0..n+1).map{[]} (2**(n+1)).times{|i| s=[] (n+1).times{|j|s<<j if i>>j&1==1} tg[s.size]<<s } return [tv]+tg[2..n]} cube=->n{ #Cube Family Vertices cv=(0..2**n-1).map{|i|s=[];n.times{|j|s<<(i>>j&1)*2-1};s} #Cube Family Graph cg=(0..n+1).map{[]} (3**n).times{|i| #for each point s=[] cv.size.times{|j| #and each vertex t=true #assume vertex goes with point n.times{|k| #and each pair of opposite sides t&&= (i/(3**k)%3-1)*cv[j][k]!=-1 #if the vertex has kingsmove distance >1 from point it does not belong } s<<j if t #add the vertex if it belongs } cg[log2(s.size)+1]<<s if s.size > 0 } return [cv]+cg[2..n]} octa=->n{ #Octahedron Family Vertices ov=(0..n*2-1).map{|i|s=[0]*n;s[i/2]=(-1)**i;s} #Octahedron Family Graph og=(0..n).map{[]} (3**n).times{|i| #for each point s=[] ov.size.times{|j| #and each vertex n.times{|k| #and each pair of opposite sides s<<j if (i/(3**k)%3-1)*ov[j][k]==1 #if the vertex is located in the side corresponding to the point, add the vertex to the list } } og[s.size]<<s } return [ov]+og[2..n]} ``` **cube and octahedron families explanation - coordinates** The n-cube has `2**n` vertices, each represented by an array of n `1`s and `-1`s (all possibilities are allowed.) We iterate through indexes `0` to `2**n-1` of the list of all vertices, and build an array for each vertex by iterating through the bits of the index and adding `-1`or `1` to the array (least significant bit to most significant bit.) Thus Binary `1101` becomes the 4d point `[1,-1,1,1]`. The n-octahedron or n-orthoplex has `2n` vertices, with all coordinates zero except one, which an be `1` or `-1`. The order of the vertices in the array generated is `[[1,0,0..],[-1,0,0..],[0,1,0..],[0,-1,0..],[0,0,1..],[0,0,-1..]...]`. Note that as the octahedron is the dual of the cube, the vertices of the octahedron are defined by the centres of the faces of the cube that surrounds it. **cube and octahedron families explanation - graph topology** Some inspiration was taken from [Hypercube sides](https://codegolf.stackexchange.com/q/69674/15599) and the fact that the hyperoctahedron is the dual of the hypercube. For the n-cube, there are `3**n` items to catalogue. For example, the 3 cube has `3**3` = 27 elements. This can be seen by studying a rubik's cube, which has 1 centre, 6 faces, 12 edges and 8 vertices for a total of 27. We iterate through -1,0 and -1 in all dimensions defining an n-cube of sidelength 2x2x2.. and return all vertices that are NOT on the opposite side of the cube. Thus the centrepoint of the cube returns all 2\*\*n vertices, and moving one unit away from the centre along any axis reduces the number of vertices by half. As with the tetrahedron family, we start by generating an empty array of arrays and populate it according to the number of vertices per element. Note that because the number of vertices varies as 2\*\*n as we go up through edges, faces, cubes, etc, we use `log2(s.size)+1` instead of simply `s.size`. Again, we have to remove the hypercube itself and all elements with less than 2 vertices before returning from the function. The octahedron/orthoplex family are the duals of the cube family, therefore again there are `3**n` items to catalogue. Here we iterate through `-1,0,1` for all the dimensions and if the nonzero coordinate of a vertex is equal to the corresponding coordinate of the point, the vertex is added to the list corresponding to that point. Thus an edge corresponds to a point with two nonzero coordinates, a triangle to a point with 3 nonzero coordinates and a tetrahedron to a point with 4 nonzero contacts (in 4d space.) The resulting arrays of vertex for each point are stored in a large array as for the other cases, and we have to remove any elements with less than 2 vertices before returning. But in this case we do not have to remove the complete parent n-tope because the algorithm does not record it. The implementations of the code for the cube were designed to be as similar as possible. While this has a certain elegance, it is likely that more efficient algorithms based on the same principles could be devised. <https://en.wikipedia.org/wiki/Hypercube> <http://mathworld.wolfram.com/Hypercube.html> <https://en.wikipedia.org/wiki/Cross-polytope> <http://mathworld.wolfram.com/CrossPolytope.html> # Code for generating tables for the 3d special cases An orientation with the icosahedron / dodecahedron oriented with the fivefold symmetry axis parallel to the last dimension was used, as it made for the most consistent labelling of the parts. The numbering of vertices and faces for the icosahedron is per the diagram in the code comments, and reversed for the dodecahedron. According to <https://en.wikipedia.org/wiki/Regular_icosahedron> the latitude of the 10 non-polar vertices of the icosahedron is +/-arctan(1/2) The coordinates of the first 10 vertices of the icosahedron are calculated from this, on two circles of radius 2 at distance +/-2 from the xy plane. This makes the overall radius of the circumsphere sqrt(5) so the last 2 vertices are at (0,0,+/-sqrt(2)). The coordinates of the vertices of the dodecahedron are calculated by summing the coordinates of the three icosahedron vertices that surround them. ``` =begin TABLE NAMES vertices edges faces icosahedron vv ee ff dodecahedron uu aa bb 10 / \ / \ / \ / \ / \ /10 \ /12 \ /14 \ /16 \ /18 \ -----1-----3-----5-----7-----9 \ 0 / \ 2 / \ 4 / \ 6 / \ 8 / \ \ / 1 \ / 3 \ / 5 \ / 7 \ / 9 \ 0-----2-----4-----6-----8----- \11 / \13 / \15 / \17 / \19 / \ / \ / \ / \ / \ / 11 =end vv=[];ee=[];ff=[] 10.times{|i| vv[i]=[2*sin(PI/5*i),2*cos(PI/5*i),(-1)**i] ee[i]=[i,(i+1)%10];ee[i+10]=[i,(i+2)%10];ee[i+20]=[i,11-i%2] ff[i]=[(i-1)%10,i,(i+1)%10];ff[i+10]=[(i-1)%10,10+i%2,(i+1)%10] } vv+=[[0,0,-5**0.5],[0,0,5**0.5]] uu=[];aa=[];bb=[] 10.times{|i| uu[i]=(0..2).map{|j|vv[ff[i][0]][j]+vv[ff[i][1]][j]+vv[ff[i][2]][j]} uu[i+10]=(0..2).map{|j|vv[ff[i+10][0]][j]+vv[ff[i+10][1]][j]+vv[ff[i+10][2]][j]} aa[i]=[i,(i+1)%10];aa[i+10]=[i,(i+10)%10];aa[i+20]=[(i-1)%10+10,(i+1)%10+10] bb[i]=[(i-1)%10+10,(i-1)%10,i,(i+1)%10,(i+1)%10+10] } bb+=[[10,12,14,16,18],[11,13,15,17,19]] ``` # Code for generating the tables for the 4d special cases This is a bit of a hack. This code takes a few seconds to run. It would be better to store the output in a file and load it in as required. The list of 120 vertex coordinates for the 600cell is from <http://mathworld.wolfram.com/600-Cell.html> . The 24 vertex coordinates which do not feature a golden ratio form the vertices of a 24-cell. Wikipedia has the same scheme but has an error in the relative scale of these 24 coordinates and the other 96. ``` #TABLE NAMES vertices edges faces cells #600 cell (analogue of icosahedron) v e f g #120 cell (analogue of dodecahedron) u x y z #24 cell o p q r #600-CELL # 120 vertices of 600cell. First 24 are also vertices of 24-cell v=[[2,0,0,0],[0,2,0,0],[0,0,2,0],[0,0,0,2],[-2,0,0,0],[0,-2,0,0],[0,0,-2,0],[0,0,0,-2]]+ (0..15).map{|j|[(-1)**(j/8),(-1)**(j/4),(-1)**(j/2),(-1)**j]}+ (0..95).map{|i|j=i/12 a,b,c,d=1.618*(-1)**(j/4),(-1)**(j/2),0.618*(-1)**j,0 h=[[a,b,c,d],[b,a,d,c],[c,d,a,b],[d,c,b,a]][i%12/3] (i%3).times{h[0],h[1],h[2]=h[1],h[2],h[0]} h} #720 edges of 600cell. Identified by minimum distance of 2/phi between them e=[] 120.times{|i|120.times{|j| e<<[i,j] if i<j && ((v[i][0]-v[j][0])**2+(v[i][1]-v[j][1])**2+(v[i][2]-v[j][2])**2+(v[i][3]-v[j][3])**2)**0.5<1.3 }} #1200 faces of 600cell. #If 2 edges share a common vertex and the other 2 vertices form an edge in the list, it is a valid triangle. f=[] 720.times{|i|720.times{|j| f<< [e[i][0],e[i][1],e[j][1]] if i<j && e[i][0]==e[j][0] && e.index([e[i][1],e[j][1]]) }} #600 cells of 600cell. #If 2 triangles share a common edge and the other 2 vertices form an edge in the list, it is a valid tetrahedron. g=[] 1200.times{|i|1200.times{|j| g<< [f[i][0],f[i][1],f[i][2],f[j][2]] if i<j && f[i][0]==f[j][0] && f[i][1]==f[j][1] && e.index([f[i][2],f[j][2]]) }} #120 CELL (dual of 600 cell) #600 vertices of 120cell, correspond to the centres of the cells of the 600cell u=g.map{|i|s=[0,0,0,0];i.each{|j|4.times{|k|s[k]+=v[j][k]/4.0}};s} #1200 edges of 120cell at centres of faces of 600-cell. Search for pairs of tetrahedra with common face x=f.map{|i|s=[];600.times{|j|s<<j if i==(i & g[j])};s} #720 pentagonal faces, surrounding edges of 600-cell. Search for sets of 5 tetrahedra with common edge y=e.map{|i|s=[];600.times{|j|s<<j if i==(i & g[j])};s} #120 dodecahedral cells surrounding vertices of 600-cell. Search for sets of 20 tetrahedra with common vertex z=(0..119).map{|i|s=[];600.times{|j|s<<j if [i]==([i] & g[j])};s} #24-CELL #24 vertices, a subset of the 600cell o=v[0..23] #96 edges, length 2, found by minimum distances between vertices p=[] 24.times{|i|24.times{|j| p<<[i,j] if i<j && ((v[i][0]-v[j][0])**2+(v[i][1]-v[j][1])**2+(v[i][2]-v[j][2])**2+(v[i][3]-v[j][3])**2)**0.5<2.1 }} #96 triangles #If 2 edges share a common vertex and the other 2 vertices form an edge in the list, it is a valid triangle. q=[] 96.times{|i|96.times{|j| q<< [p[i][0],p[i][1],p[j][1]] if i<j && p[i][0]==p[j][0] && p.index([p[i][1],p[j][1]]) }} #24 cells. Calculates the centre of the cell and the 6 vertices nearest it r=(0..23).map{|i|a,b=(-1)**i,(-1)**(i/2) c=[[a,b,0,0],[a,0,b,0],[a,0,0,b],[0,a,b,0],[0,a,0,b],[0,0,a,b]][i/4] s=[] 24.times{|j|t=v[j] s<<j if (c[0]-t[0])**2+(c[1]-t[1])**2+(c[2]-t[2])**2+(c[3]-t[3])**2<=2 } s} ``` <https://en.wikipedia.org/wiki/600-cell> <http://mathworld.wolfram.com/600-Cell.html> <https://en.wikipedia.org/wiki/120-cell> <http://mathworld.wolfram.com/120-Cell.html> <https://en.wikipedia.org/wiki/24-cell> <http://mathworld.wolfram.com/24-Cell.html> # Example of use and output ``` cell24 = polytope[[3,4,3]] puts "vertices" cell24[0].each{|i|p i} puts "edges" cell24[1].each{|i|p i} puts "faces" cell24[2].each{|i|p i} puts "cells" cell24[3].each{|i|p i} vertices [2, 0, 0, 0] [0, 2, 0, 0] [0, 0, 2, 0] [0, 0, 0, 2] [-2, 0, 0, 0] [0, -2, 0, 0] [0, 0, -2, 0] [0, 0, 0, -2] [1, 1, 1, 1] [1, 1, 1, -1] [1, 1, -1, 1] [1, 1, -1, -1] [1, -1, 1, 1] [1, -1, 1, -1] [1, -1, -1, 1] [1, -1, -1, -1] [-1, 1, 1, 1] [-1, 1, 1, -1] [-1, 1, -1, 1] [-1, 1, -1, -1] [-1, -1, 1, 1] [-1, -1, 1, -1] [-1, -1, -1, 1] [-1, -1, -1, -1] edges [0, 8] [0, 9] [0, 10] [0, 11] [0, 12] [0, 13] [0, 14] [0, 15] [1, 8] [1, 9] [1, 10] [1, 11] [1, 16] [1, 17] [1, 18] [1, 19] [2, 8] [2, 9] [2, 12] [2, 13] [2, 16] [2, 17] [2, 20] [2, 21] [3, 8] [3, 10] [3, 12] [3, 14] [3, 16] [3, 18] [3, 20] [3, 22] [4, 16] [4, 17] [4, 18] [4, 19] [4, 20] [4, 21] [4, 22] [4, 23] [5, 12] [5, 13] [5, 14] [5, 15] [5, 20] [5, 21] [5, 22] [5, 23] [6, 10] [6, 11] [6, 14] [6, 15] [6, 18] [6, 19] [6, 22] [6, 23] [7, 9] [7, 11] [7, 13] [7, 15] [7, 17] [7, 19] [7, 21] [7, 23] [8, 9] [8, 10] [8, 12] [8, 16] [9, 11] [9, 13] [9, 17] [10, 11] [10, 14] [10, 18] [11, 15] [11, 19] [12, 13] [12, 14] [12, 20] [13, 15] [13, 21] [14, 15] [14, 22] [15, 23] [16, 17] [16, 18] [16, 20] [17, 19] [17, 21] [18, 19] [18, 22] [19, 23] [20, 21] [20, 22] [21, 23] [22, 23] faces [0, 8, 9] [0, 8, 10] [0, 8, 12] [0, 9, 11] [0, 9, 13] [0, 10, 11] [0, 10, 14] [0, 11, 15] [0, 12, 13] [0, 12, 14] [0, 13, 15] [0, 14, 15] [1, 8, 9] [1, 8, 10] [1, 8, 16] [1, 9, 11] [1, 9, 17] [1, 10, 11] [1, 10, 18] [1, 11, 19] [1, 16, 17] [1, 16, 18] [1, 17, 19] [1, 18, 19] [2, 8, 9] [2, 8, 12] [2, 8, 16] [2, 9, 13] [2, 9, 17] [2, 12, 13] [2, 12, 20] [2, 13, 21] [2, 16, 17] [2, 16, 20] [2, 17, 21] [2, 20, 21] [3, 8, 10] [3, 8, 12] [3, 8, 16] [3, 10, 14] [3, 10, 18] [3, 12, 14] [3, 12, 20] [3, 14, 22] [3, 16, 18] [3, 16, 20] [3, 18, 22] [3, 20, 22] [4, 16, 17] [4, 16, 18] [4, 16, 20] [4, 17, 19] [4, 17, 21] [4, 18, 19] [4, 18, 22] [4, 19, 23] [4, 20, 21] [4, 20, 22] [4, 21, 23] [4, 22, 23] [5, 12, 13] [5, 12, 14] [5, 12, 20] [5, 13, 15] [5, 13, 21] [5, 14, 15] [5, 14, 22] [5, 15, 23] [5, 20, 21] [5, 20, 22] [5, 21, 23] [5, 22, 23] [6, 10, 11] [6, 10, 14] [6, 10, 18] [6, 11, 15] [6, 11, 19] [6, 14, 15] [6, 14, 22] [6, 15, 23] [6, 18, 19] [6, 18, 22] [6, 19, 23] [6, 22, 23] [7, 9, 11] [7, 9, 13] [7, 9, 17] [7, 11, 15] [7, 11, 19] [7, 13, 15] [7, 13, 21] [7, 15, 23] [7, 17, 19] [7, 17, 21] [7, 19, 23] [7, 21, 23] cells [0, 1, 8, 9, 10, 11] [1, 4, 16, 17, 18, 19] [0, 5, 12, 13, 14, 15] [4, 5, 20, 21, 22, 23] [0, 2, 8, 9, 12, 13] [2, 4, 16, 17, 20, 21] [0, 6, 10, 11, 14, 15] [4, 6, 18, 19, 22, 23] [0, 3, 8, 10, 12, 14] [3, 4, 16, 18, 20, 22] [0, 7, 9, 11, 13, 15] [4, 7, 17, 19, 21, 23] [1, 2, 8, 9, 16, 17] [2, 5, 12, 13, 20, 21] [1, 6, 10, 11, 18, 19] [5, 6, 14, 15, 22, 23] [1, 3, 8, 10, 16, 18] [3, 5, 12, 14, 20, 22] [1, 7, 9, 11, 17, 19] [5, 7, 13, 15, 21, 23] [2, 3, 8, 12, 16, 20] [3, 6, 10, 14, 18, 22] [2, 7, 9, 13, 17, 21] [6, 7, 11, 15, 19, 23] ``` [Answer] # Python Here's a recursive program without any special cases. Ignoring blank lines and comments, it's less than ~~100~~ 90 lines, including a gratuitous check of Euler's formula at the end. Excluding the definitions of ad-hoc math functions (which could probably be provided by a library) and i/o, the polytope generation is 50 lines of code. And it even does the star polytopes! The output polytope will have edge length 1 and will be in canonical position and orientation, in the following sense: * the first vertex is the origin, * the first edge lies along the +x axis, * the first face is in the +y half-plane of the xy plane, * the first 3-cell is in the +z half-space of the xyz space, etc. Other than that, the output lists are in no particular order. (Well, actually, that's not *entirely* true-- they'll actually come out roughly in order starting from the first element and expanding outwards.) There's no checking for invalid schlafli symbol; if you give it one, the program will probably go off the rails (endless loop, stack overflow, or just garbage out). If you ask for an infinite planar tiling such as {4,4} or {3,6} or {6,3}, the program will actually start generating the tiling, but it will go forever until it runs out of space, never finishing nor producing output. This would not be too hard to fix (just put a limit on the number of elements to generate; the result should be a fairly coherent region of the infinite picture, since elements are generated in roughly breadth-first-search order). ## The code ``` #!/usr/bin/python3 # (works with python2 or python3) # # schlafli_interpreter.py # Author: Don Hatch # For: https://codegolf.stackexchange.com/questions/114280/schl%C3%A4fli-convex-regular-polytope-interpreter # # Print the vertex coords and per-element (edges, faces, etc.) vertex index # lists of a regular polytope, given by its schlafli symbol {p,q,r,...}. # The output polytope will have edge length 1 and will be in canonical position # and orientation, in the following sense: # - the first vertex is the origin, # - the first edge lies along the +x axis, # - the first face is in the +y half-plane of the xy plane, # - the first 3-cell is in the +z half-space of the xyz space, etc. # Other than that, the output lists are in no particular order. # import sys from math import * # vector minus vector. def vmv(a,b): return [x-y for x,y in zip(a,b)] # matrix minus matrix. def mmm(m0,m1): return [vmv(row0,row1) for row0,row1 in zip(m0,m1)] # scalar times vector. def sxv(s,v): return [s*x for x in v] # scalar times matrix. def sxm(s,m): return [sxv(s,row) for row in m] # vector dot product. def dot(a,b): return sum(x*y for x,y in zip(a,b)) # matrix outer product of two vectors; that is, if a,b are column vectors: a*b^T def outer(a,b): return [sxv(x,b) for x in a] # vector length squared. def length2(v): return dot(v,v) # distance between two vectors, squared. def dist2(a,b): return length2(vmv(a,b)) # matrix times vector, homogeneous (i.e. input vector ends with an implicit 1). def mxvhomo(m,v): return [dot(row,v+[1]) for row in m] # Pad a square matrix (rotation/reflection) with an extra column of 0's on the # right (translation). def makehomo(m): return [row+[0] for row in m] # Expand dimensionality of homogeneous transform matrix by 1. def expandhomo(m): return ([row[:-1]+[0,row[-1]] for row in m] + [[0]*len(m)+[1,0]]) # identity matrix def identity(dim): return [[(1 if i==j else 0) for j in range(dim)] for i in range(dim)] # https://en.wikipedia.org/wiki/Householder_transformation. v must be unit. # Not homogeneous (makehomo the result if you want that). def householderReflection(v): return mmm(identity(len(v)), sxm(2, outer(v,v))) def sinAndCosHalfDihedralAngle(schlafli): # note, cos(pi/q)**2 generally has a nicer expression with no trig and often # no radicals, see http://www.maths.manchester.ac.uk/~cds/articles/trig.pdf ss = 0 for q in schlafli: ss = cos(pi/q)**2 / (1 - ss) if abs(1-ss) < 1e-9: ss = 1 # prevent glitch in planar tiling cases return sqrt(ss), sqrt(1 - ss) # Calculate a set of generators of the symmetry group of a {p,q,r,...} with # edge length 1. # Each generator is a dim x (dim+1) matrix where the square part is the initial # orthogonal rotation/reflection and the final column is the final translation. def calcSymmetryGenerators(schlafli): dim = len(schlafli) + 1 if dim == 1: return [[[-1,1]]] # one generator: reflect about x=.5 facetGenerators = calcSymmetryGenerators(schlafli[:-1]) # Start with facet generators, expanding each homogeneous matrix to full # dimensionality (i.e. from its previous size dim-1 x dim to dim x dim+1). generators = [expandhomo(gen) for gen in facetGenerators] # Final generator will reflect the first facet across the hyperplane # spanned by the first ridge and the entire polytope's center, # taking the first facet to a second facet also containing that ridge. # v = unit vector normal to that bisecting hyperplane # = [0,...,0,-sin(dihedralAngle/2),cos(dihedralAngle/2)] s,c = sinAndCosHalfDihedralAngle(schlafli) v = [0]*(dim-2) + [-s,c] generators.append(makehomo(householderReflection(v))) return generators # Key for comparing coords with roundoff error. Makes sure the formatted # numbers are not very close to 0, to avoid them coming out as "-0" or "1e-16". # This isn't reliable in general, but it suffices for this application # (except for very large {p}, no doubt). def vert2key(vert): return ' '.join(['%.9g'%(x+.123) for x in vert]) # Returns a pair verts,edgesEtc where edgesEtc is [edges,faces,...] def regular_polytope(schlafli): dim = len(schlafli) + 1 if dim == 1: return [[0],[1]],[] gens = calcSymmetryGenerators(schlafli) facetVerts,facetEdgesEtc = regular_polytope(schlafli[:-1]) # First get all the verts, and make a multiplication table. # Start with the verts of the first facet (padded to full dimensionality), # so indices will match up. verts = [facetVert+[0] for facetVert in facetVerts] vert2index = dict([[vert2key(vert),i] for i,vert in enumerate(verts)]) multiplicationTable = [] iVert = 0 while iVert < len(verts): # while verts is growing multiplicationTable.append([None] * len(gens)) for iGen in range(len(gens)): newVert = mxvhomo(gens[iGen], verts[iVert]) newVertKey = vert2key(newVert) if newVertKey not in vert2index: vert2index[newVertKey] = len(verts) verts.append(newVert) multiplicationTable[iVert][iGen] = vert2index[newVertKey] iVert += 1 # The higher-level elements of each dimension are found by transforming # the facet's elements of that dimension. Start by augmenting facetEdgesEtc # by adding one more list representing the entire facet. facetEdgesEtc.append([tuple(range(len(facetVerts)))]) edgesEtc = [] for facetElementsOfSomeDimension in facetEdgesEtc: elts = facetElementsOfSomeDimension[:] elt2index = dict([[elt,i] for i,elt in enumerate(elts)]) iElt = 0 while iElt < len(elts): # while elts is growing for iGen in range(len(gens)): newElt = tuple(sorted([multiplicationTable[iVert][iGen] for iVert in elts[iElt]])) if newElt not in elt2index: elt2index[newElt] = len(elts) elts.append(newElt) iElt += 1 edgesEtc.append(elts) return verts,edgesEtc # So input numbers can be like any of "8", "2.5", "7/3" def parseNumberOrFraction(s): tokens = s.split('/') return float(tokens[0])/float(tokens[1]) if len(tokens)==2 else float(s) if __name__ == '__main__': if sys.stdin.isatty(): sys.stderr.write("Enter schlafli symbol (space-separated numbers or fractions): ") sys.stderr.flush() schlafli = [parseNumberOrFraction(token) for token in sys.stdin.readline().split()] verts,edgesEtc = regular_polytope(schlafli) # Hacky polishing of any integers or half-integers give or take rounding error. def fudge(x): return round(2*x)/2 if abs(2*x-round(2*x))<1e-9 else x print(repr(len(verts))+' Vertices:') for v in verts: print(' '.join([repr(fudge(x)) for x in v])) for eltDim in range(1,len(edgesEtc)+1): print("") elts = edgesEtc[eltDim-1] print(repr(len(elts))+' '+('Edges' if eltDim==1 else 'Faces' if eltDim==2 else repr(eltDim)+'-cells')+" ("+repr(len(elts[0]))+" vertices each):") for elt in elts: print(' '.join([repr(i) for i in elt])) # Assert the generalization of Euler's formula: N0-N1+N2-... = 1+(-1)**(dim-1). N = [len(elts) for elts in [verts]+edgesEtc] eulerCharacteristic = sum((-1)**i * N[i] for i in range(len(N))) print("Euler characteristic: "+repr(eulerCharacteristic)) if 2.5 not in schlafli: assert eulerCharacteristic == 1 + (-1)**len(schlafli) ``` ## Trying it out on some cases Input ([cube](https://en.wikipedia.org/wiki/Cube)): ``` 4 3 ``` Output: ``` 8 Vertices: 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 1.0 1.0 0.0 0.0 0.0 1.0 1.0 0.0 1.0 0.0 1.0 1.0 1.0 1.0 1.0 12 Edges (2 vertices each): 0 1 0 2 1 3 2 3 0 4 1 5 4 5 2 6 4 6 3 7 5 7 6 7 6 Faces (4 vertices each): 0 1 2 3 0 1 4 5 0 2 4 6 1 3 5 7 2 3 6 7 4 5 6 7 ``` Input from a unix command shell ([120-cell polychoron](https://en.wikipedia.org/wiki/120-cell)): ``` $ echo "5 3 3" | ./schlafli_interpreter.py | grep ":" ``` Output: ``` 600 Vertices: 1200 Edges (2 vertices each): 720 Faces (5 vertices each): 120 3-cells (20 vertices each): ``` Input (10-dimensional [cross polytope](https://en.wikipedia.org/wiki/Cross-polytope)): ``` $ echo "3 3 3 3 3 3 3 3 4" | ./schlafli_interpreter.py | grep ":" ``` Output: ``` 20 Vertices: 180 Edges (2 vertices each): 960 Faces (3 vertices each): 3360 3-cells (4 vertices each): 8064 4-cells (5 vertices each): 13440 5-cells (6 vertices each): 15360 6-cells (7 vertices each): 11520 7-cells (8 vertices each): 5120 8-cells (9 vertices each): 1024 9-cells (10 vertices each): ``` Input (15-dimensional [simplex](https://en.wikipedia.org/wiki/Simplex)): ``` $ echo "3 3 3 3 3 3 3 3 3 3 3 3 3 3" | ./schlafli_interpreter.py | grep ":" 16 Vertices: 120 Edges (2 vertices each): 560 Faces (3 vertices each): 1820 3-cells (4 vertices each): 4368 4-cells (5 vertices each): 8008 5-cells (6 vertices each): 11440 6-cells (7 vertices each): 12870 7-cells (8 vertices each): 11440 8-cells (9 vertices each): 8008 9-cells (10 vertices each): 4368 10-cells (11 vertices each): 1820 11-cells (12 vertices each): 560 12-cells (13 vertices each): 120 13-cells (14 vertices each): 16 14-cells (15 vertices each): ``` ## Star polytopes Ha, and it just naturally does star polytopes too! I didn't even need to try :-) Except that the bit about Euler's formula at the end fails, since that formula isn't valid for star polytopes. Input ([small stellated dodecahedron](https://en.wikipedia.org/wiki/Small_stellated_dodecahedron)): ``` 5/2 5 ``` Output: ``` 12 Vertices: 0.0 0.0 0.0 1.0 0.0 0.0 0.8090169943749473 0.5877852522924732 0.0 0.19098300562505266 0.5877852522924732 0.0 0.5 -0.36327126400268034 0.0 0.8090169943749473 -0.2628655560595667 0.5257311121191336 0.19098300562505266 -0.2628655560595667 0.5257311121191336 0.5 0.162459848116453 -0.3249196962329062 0.5 0.6881909602355867 0.5257311121191336 0.0 0.32491969623290623 0.5257311121191336 0.5 0.1624598481164533 0.8506508083520398 1.0 0.32491969623290623 0.5257311121191336 30 Edges (2 vertices each): 0 1 0 2 1 3 2 4 3 4 0 5 1 6 5 7 6 7 0 8 2 9 7 8 7 9 1 8 0 10 3 11 5 9 4 10 7 11 4 9 2 5 1 10 4 11 6 11 6 8 3 10 3 6 2 10 9 11 5 8 12 Faces (5 vertices each): 0 1 2 3 4 0 1 5 6 7 0 2 7 8 9 1 3 7 8 11 0 4 5 9 10 2 4 5 7 11 1 4 6 10 11 0 3 6 8 10 3 4 6 7 9 2 3 9 10 11 1 2 5 8 10 5 6 8 9 11 Traceback (most recent call last): File "./schlafli_interpreter.py", line 185, in <module> assert sum((-1)**i * N[i] for i in range(len(N))) == 1 + (-1)**len(schlafli) AssertionError ``` Input ([great stellated 120-cell](https://en.wikipedia.org/wiki/Great_stellated_120-cell)): ``` $ echo "5/2 3 5" | ./schlafli_interpreter.py | grep ":" ``` Output: ``` 120 Vertices: 720 Edges (2 vertices each): 720 Faces (5 vertices each): 120 3-cells (20 vertices each): ``` ]
[Question] [ The [VIC cipher](https://en.wikipedia.org/wiki/VIC_cipher) is one of the most complicated pencil and paper ciphers ever devised. Used in the 1950s by Soviet spy Reino Häyhänen, codenamed "VICTOR", its main principle is security through obfuscation; a *lot* of obfuscation. Your task is to write a program or function that will take a message and encode it using the VIC cipher. I have also [posted a VIC cipher decoder challenge here](https://codegolf.stackexchange.com/questions/89063/write-a-vic-cipher-decoder). If any of the following instructions are unclear, don't hesitate to ask about them in the comments. The instructions are [adapted from this site](http://everything2.com/user/raincomplex/writeups/VIC+cipher). # Encoding the VIC cipher **Preparation** You will need five inputs: * the plaintext message * a short keyword or phrase containing the most common letters in your language * a key phrase, such as a quote or a line from a song (at least 20 characters) * a date (or another number that is six digits or more) * a personal agent number In practice, these last four should be agreed upon beforehand by the sender and the recipient, including whether the agent number of the sender or the recipient is used in encoding. My example message will be: `We are discovered. Take what you can. Burn everything else. Move to Safehouse Foxtrot 3.` We'll be encoding in English (though you may use whatever language and alphabet you prefer) and the most common letters in the English alphabet are `A, E, I, N, O, R, S, T`. I'll use the keyword `SENATORI`. My key phrase is a quote by Richard Feynman: "The first principle is that you must not fool yourself — and you are the easiest person to fool." As a date, I'll use July 31, 2016 (in the format `3172016`), which is the day it was when I wrote this description. The personal number I have chosen for myself is `9`. **Summary of steps** 1. Derive the intermediate keys for use in the following steps. 2. Construct and apply the straddling checkerboard. 3. Construct and apply the first transposition table. 4. Construct and apply the second (disrupted) transposition table. 5. Finalize the message by inserting the message indicator group. **Submechanisms** Two more things to explain before we get into the meat of the matter: the processes of chain addition and sequentializing. Chain addition, also known as a lagged Fibonacci generator, works by taking a starting digit sequence, adding the first two digits without carrying (add them together then `mod 10`) and appending the result to the end. For example: ``` 79081 7 + 9 = 6 790816 9 + 0 = 9 7908169 0 + 8 = 8 79081698 8 + 1 = 9 790816989 1 + 6 = 7 7908169897 ... and so on ``` Sequentializing is essentially taking a sequence of letters or digits and labeling them by their alphabetical/numerical order. Duplicates are labelled left to right. For example: ``` E X A M P L E 0 # A 1 0 2 # Es 1 0 3 2 # L 1 0 4 3 2 # M 1 0 4 5 3 2 # P 1 6 0 4 5 3 2 # X 3 3 0 5 8 4 2 0 4 7 5 4 8 1 0 1 # 0s 0 1 2 # 1 0 3 1 2 # 2 4 5 0 3 1 2 # 3s 4 5 0 6 3 1 7 8 2 # 4s 4 5 0 9 6 3 1 7 10 8 2 # 5s 4 5 0 9 6 3 1 7 11 10 8 2 # 7 4 5 0 9 12 6 3 1 7 11 10 8 13 2 # 8s ``` I use zero-indexing here, but index however you like. **1. Intermediate Keys** Split the first 20 letters of the key phrase into two groups of 10 and sequentialize each individually, which we will call `S1` and `S2`. ``` THEFIRSTPR S1: 8201357946 INCIPLEIST S2: 2603751489 ``` Choose a random 5-digit message identifier, `M` (this can be one of the inputs if you prefer): ``` M = 47921 ``` Subtract, without borrowing (subtract `mod 10`), the first five digits of the key date `3172016` from `M`: ``` M 47921 date - 31720 = 16201 ``` Chain add the result until you have ten digits: ``` 1620178218 ``` Add these digits to `S1`, without carrying or `mod 10`, to obtain `G`: ``` 1620178218 S1 + 8201357946 G = 9821425154 ``` Above `S2`, write the sequence 0123456789. Locate each digit of `G` in the sequence 0123456789 and replace it with the digit directly below it in `S2`. The result is `T`. ``` 0123456789 S2 2603751489 G 9821425154 T 9806705657 ``` Use chain addition to expand `T` to 60 digits. ``` 9806705657 becomes 980670565778637511245490262369939288595822106344304316978734 ``` These last 50 digits, in five rows of ten digits each, form the `U` block. ``` T 9806705657 U 7863751124 5490262369 9392885958 2210634430 4316978734 ``` The last two non-equal digits of the `U` block are individually added to the agent's personal number to give the widths of the two transpositions, `p` and `q`. 9 + 3 = 12 (p, first transposition width) 9 + 4 = 13 (q, second transposition width) Sequentialize `T` and use this sequence to copy off the columns of the `U` block, from top to bottom, into a new row of digits, `V`. ``` T 9806705657 seqT 9804612537 U 7863751124 5490262369 9392885958 2210634430 4316978734 V 69911 56837 12548 26533 30206 13947 72869 49804 84323 75924 ``` Sequentialize the first `p` digits to get the key for the first transposition `K1`, and the following `q` digits for the key for the second `K2`. ``` First 12 6 9 9 1 1 5 6 8 3 7 1 2 K1 6 10 11 0 1 5 7 9 4 8 2 3 Next 13 5 4 8 2 6 5 3 3 3 0 2 0 6 K2 8 7 12 2 10 9 4 5 6 0 3 1 11 ``` Finally, sequentialize the final row of the `U` block to get `C`, the column headers for the straddling checkerboard: ``` U5 4316978734 C 3105968724 ``` **2. Straddling Checkerboard** First, I will give my example checkerboard then explain the principles in creating it in that way: ``` 3 1 0 5 9 6 8 7 2 4 S E N A T O R I 2 B D G J L P U W Y . 4 C F H K M Q V X Z # ``` The first line of letters is our short keyword `SENATORI`. Your keyword can be any string without duplicates, but since it defines the top row of your checkerboard, choose wisely. Above the keyword is `C`, and the other rows are the rest of your alphabet in whatever order you choose. In my case, I filled the checkerboard with the rest of the Latin alphabet, a punctuation mark `.` and a mark for demarcating numbers `#`. Essentially, the checkerboard is a fancy substitution cipher. For example, "E" will be substituted with `1`, and "W" will be substituted with `27`. Once we have encoded our plaintext message with this checkerboard, but first, we need to make the beginning of our message less obvious by splitting it at a random position, and making it all uppercase. To denote the other original beginning, we use two full stops `..` ``` We are discovered. Take what you can. Burn everything else. Move to Safehouse Foxtrot 3. ``` becomes ``` HING ELSE. MOVE TO SAFEHOUSE FOXTROT#3#.. WE ARE DISCOVERED. TAKE WHAT YOU CAN. BURN EVERYT ``` We encode with the checkerboard, giving us: ``` 407020 1293124 496481 96 354114062831 416479869443442424 271 581 2173436481812124 95451 274059 22628 435024 232880 14818229 ``` If the length of the message isn't divisible by 5, we add some null characters to pad out the message. Our message is 109 digits long, so I will add one null: "4". ``` 40702 01293 12449 64819 63541 14062 83141 64798 69443 44242 42715 81217 34364 81812 12495 45127 40592 26284 35024 23288 01481 82294 ``` Note: Since my example message does not contain numbers, I'll say here that you might designate, say, as `#3#`, which is encoded as `44344` here. **3. First Transposition** Create the transposition table by writing `K1` (from the Intermediate Keys section) followed by the encoded message from the previous step, in rows of the same length, below the key: ``` K1 6 10 11 0 1 5 7 9 4 8 2 3 4 0 7 0 2 0 1 2 9 3 1 2 4 4 9 6 4 8 1 9 6 3 5 4 1 1 4 0 6 2 8 3 1 4 1 6 4 7 9 8 6 9 4 4 3 4 4 2 4 2 4 2 7 1 5 8 1 2 1 7 3 4 3 6 4 8 1 8 1 2 1 2 4 9 5 4 5 1 2 7 4 0 5 9 2 2 6 2 8 4 3 5 0 2 4 2 3 2 8 8 0 1 4 8 1 8 2 2 9 4 ``` Taking the numbered columns in order of their numbers we get: ``` 060826428 246674580 151411542 246272922 961311401 082918141 4414434239 118451234 334422028 293488758 0417249224 794943568 ``` **4. Second Transposition** The first transposition was relatively simple. This one, however, is a disrupted transposition. The disruption pattern is determined by the width of the table and the key. In our example, we have 110 digits and 13 columns, meaning we'll have 8 full rows and 6 leftovers. We start filling in the first row, but stop at column 0, and continue as follows: ``` K2 8 7 12 2 10 9 4 5 6 0 3 1 11 0 6 0 8 2 6 4 2 8 stop at 0 2 4 6 6 7 4 5 8 0 1 continue in a triangle pattern 5 1 4 1 1 5 4 2 2 4 6 2 7 2 9 2 2 9 6 1 3 1 1 4 0 1 0 8 2 9 1 8 1 4 1 4 until the end 4 1 4 4 3 4 2 3 9 1 1 restart and stop at 1 8 4 5 1 2 3 4 3 3 4 4 2 2 0 2 8 2 9 3 4 8 8 7 5 8 0 4 1 restart and stop at 2 ``` Then we fill the last few spaces with the remaining digits. ``` K2 8 7 12 2 10 9 4 5 6 0 3 1 11 0 6 0 8 2 6 4 2 8 7 2 4 9 2 4 6 6 7 4 5 8 0 1 2 2 4 5 1 4 1 1 5 4 2 2 4 6 7 9 2 7 2 9 2 2 9 6 1 3 1 1 4 4 0 1 0 8 2 9 1 8 1 4 1 4 4 1 4 4 3 4 2 3 9 1 1 9 4 8 4 5 1 2 3 4 3 3 4 4 2 3 2 0 2 8 2 9 3 4 8 8 7 5 8 0 4 1 5 6 8 ``` Now, we read off the columns in the exactly the same way we did for in the first transposition. ``` 71431148 42711925 861904185 22614147 45499243 28261334 80218938 641701404 025244820 645224398 271283226 94944438 064214521 ``` And split everything up into 5-digit groups: ``` 71431 14842 71192 58619 04185 22614 14745 49924 32826 13348 02189 38641 70140 40252 44820 64522 43982 71283 22694 94443 80642 14521 ``` **5. Finalize the Message** The final step is to insert our random message identifier, `47921`, into the message itself. The final digit of the key date `6` indicates the distance the group should be from the end. ``` 71431 14842 71192 58619 04185 22614 14745 49924 32826 13348 02189 38641 70140 40252 44820 64522 43982 47921 71283 22694 94443 80642 14521 ``` **Notes for this challenge** * You are given a minimum of five inputs: the message, the letter keyword, the key phrase, the date, and a personal number. You may include two additional inputs: the random message identifier and the nulls needed to pad out the message, or your function may generate some random numbers on its own. * You may assume all inputs are valid, with the correct number of digits and letters (5-digit message identifier, at least 20 digits for the key phrase, and so on). You may assume that your strings (the message and keywords) have already had all punctuation and spaces removed except for those that you allow in your version, and that numbers are already demarcated with number signs. * The first keyword should not have duplicate letters in it, and in your code, you may assume that it never has duplicate letters. * The language you use to encode in does not matter, as long as the language is preexisting, the alphabet is preexisting, and you specify which language you use in your answer. * Whichever alphabet you employ for your straddling checkerboard, you may add or remove symbols to pad the checkerboard out. Specify what you use those symbols for (for example, punctuation, a separate "message begin" symbol, symbols for common words). You may forego the number sign entirely and spell out the numbers or include each digit in the checkerboard, using the slot where the number sign was for something else. Please specify which checkerboard you used in your answer. * The output should be either a string of space-separated five-digit groups, a list of five-digit integers, or something similar. * I used zero-indexing and `0123456789` in my example. You may use 1-indexing and `1234567890`, or some other system in your answer, as long as you specify what you used. Here is an [example implementation on Ideone](http://ideone.com/8qRtw7). This is a long post and I wrote most of it by hand, so if there are any confusing parts in this post or errors in my counting and transposing, please let me know. Good luck and good golfing! [Answer] # [Python 3](https://docs.python.org/3/), ~~1423~~ ~~1348~~ ~~1324~~ ~~1316~~ ~~1300~~ ~~1286~~ ~~1250~~ ~~1249~~ ~~1209~~ ~~1206~~ 1204 bytes This is definitely the longest golf I've ever done, and the only golf where I was seriously worried about running out of one-character variable names. Golfing suggestions welcome. [Try it online!](https://tio.run/nexus/python3#bVRtU@I6FP7Or@jgMCS0RVrFvZtsdqa65VIFqm0VdzL54Epxg1KZthTonetf9560qLs790tzcl6e57ylrx6TSU5H7ElmOXXZU5zQgKV3yUNMT1mWp/SctdvdxbNM6JRZvcYsnmtDlBkxJg1t/pxqUpOJFqDYdFGGMcl0dv8zRcd/6dl6iZZ3K/SczoyMSyJ1W2DcOrJbU9zQ0jhfp4mWVYBXEApwKeM90VE4NGMjOGqGsmao8X@wrCuTWbxFS5koDU35D8FKmqmj@dJ8h04r6AhtjUdjxnqKYM1ctMW0gOMR0wcWoALTC/ZYI9KErQ8PC92iG8YFjVnKdqxHJbtAO0zvQdfQ5FybAZC2@SmfYi39kqiL0qZfE9MikqmspIHWrUKD1AuMlX2jQzlbHpNYlwIbNNaZpFJnFk3hs0eQXwuyY@bLrlXsOcHwlkJh7hW/E294Kn7D3kObf0B/schO0QFnjfRm3XDTAgTebosOKmCGlaLKWrV@oVr/QO51do5KvhDv49hgo6HFT1lMoC9bmC4pxPs2PECjsmqWRT3BeQ2T8Uc@F4Ldw/d9TOdqzmpSZ2hpZMbGSNSkcvZPs9uECNMmwmgeVKIlOva/dMFK1qtxt/Vm2CcqRCuqzdvqJ32VPpRdVJmSnBeCZXyz35sCA3md@95SmrbQMyiPLnTYpBKGULZstY/nSHZlNpMPMkf4LplBfUCbc/lR7PJjmVM94QR6mOJWX1Q13UBNG@PSmBmOMVaV3TLL9NCsajLNAf8UXaFLPiV2T2DuIaVAHhq@CWOgwlWEVI9nin95cn2MjSlWBt2rUMhU4P/xm@JKK/7Q0TUbotw46WGgF3TFHIBZQ8OFeiERWhtXKAe3EuQIqemonOQHyhV4H/cI8FVTA/eCk5W6KmlFVvoe0VLkhgXLyXjJ@x1J@h3z5ZceBshE0LcSHx5CUYLW/Wxr9Y8HxZzcCp2PhR7zW@B7XaXw00I3qDn0Jn@7o9Dtjv0bN/JDZ@AO/evQHfi3UeBHB0cH3e7UdQL3mxeegQsI3ci5cKdDJ/ruX585k@7pdTBxwfI9ahqNZuhOnMgPPCVHQ3fgBWF0GXiTM@9y5HphVMeNr8No4kcD3x/BLQjd0cCZfAMRmCDKdULPhTg3CP1J5Cs3hXdkfbJ71gmIn@F2/OmzbSn1cRPj1/8A) I'm encoding with the uppercase Latin alphabet with additional characters `.` and `#`, using 0-indexing and `0123456789` when converting `g` to `t`. My checkerboard is in a format similar to the following example: ``` 2 9 7 4 5 8 3 1 0 6 # C S E N A T O R I # keyword 0 B D G J L P U W Y . # remaining alphabet arranged in columns 6 C F H K M Q V X Z # # . and # at the end ``` **Edit:** -63 bytes thanks to TuukkaX's suggestion to shorten some of the frequently used functions with one-letter variables. -12 bytes from making `a, g, t` more compact. **Edit:** -24 bytes from making by removing variable names for intermediate keys that are only used once, namely `a, g, s, S, k, K`. **Edit:** -74 bytes from consolidating `H(), T() and C()`. **Edit:** -1 byte thanks to Nick A for their suggestion of changing `ord(s[i])+ord(s[i+1])` to `sum(map(ord,s[i:i+2]))`. -2 bytes from changing 2 `+=[a]` calls to `+=a,`. -13 bytes from changing how `G()` found the index of the minimum of `s`. -2 bytes from changing `y=(y+1)%v` to `y=-~y%v`. -15 bytes from assigning `k.index()` to `K`. -4 bytes from assigning `10` to `W`. -5 bytes from assigning `1-I(d[-1])` to `X` inside `V`. -3 bytes from rewriting `C()`'s main loop. -2 bytes from reorganizing `T()`. ``` I=int;L=list;E=len;R=range;B=str;J=''.join;W=10 def H(s,e): for i in R(e-E(s)):s+=chr(48+sum(map(ord,s[i:i+2]))%32%W) return s def Q(s): r=[0]*E(s);s=L(s) for z in R(E(s)):b=s.index(min(s));r[b]=z;s[b]="~" return r def T(x,k,d=0): u=E(x);v=E(k);g=R(v);K=k.index;n=u//v+1;w=[];e=r=y=0;i=K(y);c=[] if d: while r<n: if r>n-1:i=min(i,(u%v or v)) w+=L(x[e:e+i]),;e+=i;i+=1;r+=1 if i>v:y=-~y%v;i=K(y) r=y=0;i=v-K(y) while r<n: w[r]+=L(x[e:e+i]);e+=i;i-=1;r+=1 if i<1:y+=1;i+=v-K(y);r+=1 w[-1]+=['']*(v-E(w[-1])) for j in g:c+=J(z[j]for z in w), else:c=[x[i::v]for i in g] s=[0]*v for f in g:s[k[f]]=c[f] return J(s) def C(m,s,w,n): t={".":s[-2:],"#":s[-1]*2};j=z=0 for x in R(26): v=chr(x+65) if v in w:t[v]=s[w.index(v)] else:t[v]=s[z-2]+s[j];j+=z;z=-~z%2 r=J(i.isdigit()and i or t[i]for i in m) return r+n[:-E(r)%5] def V(m,w,P,d,A,M,n):X=1-I(d[-1]);t=J(B(Q(P[W:20])[I(J(B((I(H(J(B((I(M[i])-I(d[i]))%W)for i in R(5)),W)[i])+I(Q(P[:W])[i]))%W)for i in R(W))[i])])for i in R(W));u=H(t,60)[W:];p=A+I(u[-2]);v=T(u,Q(t));z=T(T(C(m,J(B(i)for i in Q(u[40:])),w,n),Q(v[:p])),Q(v[p:p+A+I(u[-1])]),1);e=[z[5*i:5*-~i]for i in R(-(-E(z)//5))];return' '.join(e[:X]+[M]+e[X:]) ``` **Ungolfing:** ``` def chain_add(seq, end): for i in range(end - len(seq)): seq += chr(48+sum(map(ord,seq[i:i+2]))%32%10) return seq def sequent(seq): res = [0]*len(seq) seq = list(seq) for z in range(len(seq)): b = seq.index(min(seq)) res[b] = z seq[b] = "~" return res def transpose(text, keys, disrupt=False): if disrupt: num_rows = len(text) // len(keys) + 1 len_last = len(text) % len(keys) if len_last == 0: len_last = len(keys) d_rows = [] text_index = 0 current_row = 0 stop_key = 0 stop_index = keys.index(stop_key) while current_row < num_rows: if current_row > num_rows-1: stop_index = min(stop_index, len_last) d_rows += [list(text[text_index:text_index+stop_index])] text_index += stop_index stop_index += 1 if stop_index>len(keys): stop_key = (stop_key+1) % len(keys) stop_index = keys.index(stop_key) current_row += 1 current_row = 0 stop_key = 0 stop_len = len(keys) - keys.index(stop_key) while current_row < num_rows: d_rows[current_row] += list(text[text_index:text_index+stop_len]) text_index += stop_len stop_len -= 1 if stop_len < 1: stop_key += 1 stop_len = len(keys) - keys.index(stop_key) current_row += 1 current_row += 1 d_rows[-1] += ['']*(len(keys)-len(d_rows[-1])) columns = [] for j in range(len(keys)): columns += [''.join(i[j]for i in d_rows)] else: columns = ['']*len(keys) for t in range(len(text)): columns[t%len(keys)] += text[t] res = [0]*len(keys) for index in range(len(keys)): res[keys[index]] = columns[index] return''.join(res) def checkerboard(message, seq, word, null): trans = {".":seq[-2:], "#":seq[-1]*2};res='';j=z=0 for x in range(26): v = chr(x + 65) if v in word: trans[v] = seq[word.index(v)] else: trans[v] = seq[z-2] + seq[j] j += z z = (z+1) % 2 for i in message: if i.isdigit(): res += i else: res += trans[i] return res + null[:-len(res)%5] def vic_cipher(message, keyword, phrase, date, agent, m_id, null): s1 = sequent(phrase[:10]) s2 = sequent(phrase[10:20]) a = ''.join(str((int(m_id[i])-int(date[i]))%10) for i in range(5)) g = ''.join(str((int(a[i])+int(s1[i]))%10) for i in range(10)) t = ''.join(str(s2[int(g[i])]) for i in range(10)) u = chain_add(t,60)[10:] p = agent+int(u[-2]) q = agent+int(u[-1]) seqT = sequent(t) v = transpose(u,seqT) k1 = sequent(v[:p]) k2 = sequent(v[p:p+q]) c = ''.join(str(i)for i in sequent(u[40:])) x = checkerboard(message,c,keyword,null) y = transpose(x,k1) z = transpose(y,k2,1) e = [z[5*i:5*(i+1)] for i in range(-(-len(z)//5))] X = 1-int(date[-1]) return ' '.join(e[:X] + [m_id] + e[X:]) ``` [Answer] # C, ~~2880~~ ~~2769~~ ~~2766~~ ~~2762~~ ~~2743~~ ~~2741~~ ~~2739~~ ~~2699~~ 2458 bytes ``` #include<stdio.h> #define m(x)malloc(x) #define Y(x)strlen(x) typedef int i;typedef char*c;c _(c A,i B,i D){if(D>=B){return A;}c C=m(Y(A)+2);sprintf(C,"%s%c",A,48+(A[D]+A[D+1]-96)%10);return _(C,B,D+1);}c l(c A){i J=Y(A);c P=m(J+2);for(i m=0;m<J;m++){P[m]=32;}for(i v=0;v<J;v++){char G;i R;for(i u=0;u<J;u++){R=u<1|A[u]<G?u:R;G=u<1|A[u]<G?A[u]:G;}P[R]=48+v;c V=m(J);for(i t=0;t<J;t++){V[t]=t!=R?A[t]:97;}A=V;}return P;}c S(c C,c N,c I,char U){srand(time(NULL));i M=Y(I);i O=Y(N);i R=rand()%M;c Q=m(M+1);for(i u=R;u<M;u++){Q[u-R]=I[u];}Q[M-R]=46;for(i H=0;H<R;H++){Q[H+M-R+1]=I[H];}c g=m(28);c V=m(28);strcat(V,C);sprintf(g,"%s%s",N,"BCDFGHJKLMPQUVWXYZ.#");i B=Y(N);for(i q=B;q<10;q++){for(i x=0;x<10;x++){char J[2]={C[q],C[x]};V[B]=48+atoi(J);B++;}}c w=m(M*2+4);for(i J=0;J<=M;J++){i K=0;for(i X=0;X<28;X++){if(Q[J]==g[X]){char F[3];sprintf(F,"%d",V[X]-48);strcat(w,F);K=1;}}if(K<1){w[Y(w)]=Q[J];}}i f=Y(w);if(f%5>0){c P=m(5-f%5);for(i E=0;E<5-f%5;E++){P[E]=U;}strcat(w,P);}return w;}c a(c I,c U){i M=Y(I),K=Y(U);c T=m(M);i F=0;for(i b=0;b<K;b++){for(i y=0;y<K;y++){if(U[y]==48+b){for(i u=y;u<M;u+=K){T[F]=I[u];F++;}}}}return T;}c da(c I,c K){i e=Y(I),k=Y(K);c T=m(e);for(i y=0;y<e;y++){T[y]=32;}i F,P;F=P=0;for(i u=0;u<k;u++){for(i v=0;v<k;v++){T[F]=I[P];P++;F++;if(K[v+1]-48==u){for(i C=1;C<k-v;C++){F+=k-v-C;for(i E=0;E<=v+C;E++){if(F<e&P<e){T[F]=I[P];}F++;P++;}}break;}}if(F>e){break;}}i U=0;for(i g=0;g<e;g++){U=T[g]-48<10&-1<T[g]-48?U+1:U;}for(i j=U;j<e;j++){for(i x=0;x<e;x++){if(T[x]==32){T[x]=I[j];break;}}}return a(T,K);}En(c n,c m,c k,i d,c v,c s,char u){c S1,S2;S1=m(10);S2=m(10);for(i i=0;i<20;i++){if(i<10){S1[i]=k[i];}else{S2[i-10]=k[i];}}S1=l(S1);S2=l(S2);c M=m(5);for(i i=4;i>-1;i--){M[i]=48+(s[i]-v[i])%10;}c G=_(M,5,0);for(i y=0;y<10;y++){G[y]=48+(S1[y]+G[y]-96)%10;}c N="0123456789";c T=m(10);for(i q=0;q<10;q++){for(i t=0;t<10;t++){if(N[t]==G[q]){T[q]=S2[t];}}}c Z=_(T,50,0);c U=m(50);for(i h=0;h<50;h++){U[h]=Z[h+10];}i p,q;for(i b=49;b>10;b++){if(U[b]!=U[b-1]){q=d+U[b]-48;p=d+U[b-1]-48;break;}}c V=m(50);i Ct=0;for(i j=0;j<10;j++){for(i o=0;o<10;o++){if(l(T)[o]==48+j){for(i x=o;x<o+41;x+=10){V[Ct]=U[x];Ct+=1;}}}}c K1=m(p);c K2=m(q);for(i D=0;D<p+q;D++){if(D<p){K1[D]=V[D];}else{K2[D-p]=V[D];}}K1=l(K1);K2=l(K2);c C=m(10);for(i b=40;b<50;b++){C[b-40]=U[b];}C=l(C);c t=da(a(S(C,m,n,u),K1),K2);i O=0;for(i B=0;B<Y(t)/5+1;B++){if(B==Y(t)/5-v[Y(v)-1]+49){printf("%s ",s);}else{for(i J=O;J<O+5;J++){printf("%c",t[J]);}printf(" ");O+=5;}}} ``` My gosh. This is the longest program I have *ever* had to golf. This is also the first on which I actually ran out of single-character variable names for the global scope and so had to move on to using a few 2 character ones (the fact that I apparently cannot redeclare variables doesn't help). Golfing tips are therefore very much appreciated. ## Ungolfed Compiles without any warnings, unlike the golfed version. Minor changes made to the golfed version will not be reflected in this ungolfed version. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> char*Chain_Add(char*String,int End,int Start){ if(Start>=End){return String;} char*C=malloc(strlen(String)+2); sprintf(C,"%s%c",String,'0'+(((String[Start]-'0')+(String[Start+1]-'0'))%10)); return Chain_Add(C,End,Start+1); } char*Sequent(char*String){ int J=strlen(String); char*P=malloc(J+2); for(int m=0;m<J;m++){ P[m]=' '; } for(int v=0;v<J;v++){ char G; int R; for(int u=0;u<J;u++){ R=(u<1||String[u]<G)?u:R; G=(u<1||String[u]<G)?String[u]:G; } P[R]='0'+v; char*V=malloc(J); for(int t=0;t<J;t++){ if(t!=R){ V[t]=String[t]; } else{ V[t]='a'; } } String=V; } return P; } char*Straddling_Checkerboard(char*C,char*Key,char*Message,char null){ srand(time(NULL)); int Msg_Len=strlen(Message); int Key_Len=strlen(Key); int R=rand()%Msg_Len; char*Q=malloc(Msg_Len+1); for(int u=R;u<Msg_Len;u++){ Q[u-R]=Message[u]; } Q[Msg_Len-R]='.'; for(int H=0;H<R;H++){ Q[H+Msg_Len-R+1]=Message[H]; } char*Alphabet=malloc(26); for(int W=0;W<26;W++){ Alphabet[W]='A'+W; } int q=0; char*e=malloc(Key_Len); for(int z=0;z<Key_Len;z++){ if(strchr(e,Key[z])!=NULL){ q++; } else{ e[z-q]=Key[z]; } } int r=0; for(int h=0;h<26;h++){ if(strchr(e,Alphabet[h-r])!=NULL){ for(int X=h-r;X<26;X++){ Alphabet[X]=Alphabet[X+1]; } r++; } } char*Checkerboard=malloc(28); for(int i=0;i<26;i++){ if(i<strlen(e)){ Checkerboard[i]=e[i]; } else{ Checkerboard[i]=Alphabet[i-strlen(e)]; } } Checkerboard[26]='.'; Checkerboard[27]='#'; char*Values=malloc(28); strcat(Values,C); int B=strlen(e); for(int q=B;q<10;q++){ for(int x=0;x<10;x++){ char J[2]={C[q],C[x]}; Values[B]='0'+atoi(J); B++; } } char*Encoded=malloc(Msg_Len*2+4); for(int J=0;J<=Msg_Len;J++){ int K=0; for(int X=0;X<28;X++){ if(Q[J]==Checkerboard[X]){ char F[3]; sprintf(F,"%d",Values[X]-'0'); strcat(Encoded,F); //printf("F = %s while Q[J] = %c and Checkerboard[X] = %c and Encoded = %s\n",F,Q[J],Checkerboard[X],Encoded); K=1; } } if(K<1){ Encoded[strlen(Encoded)]=Q[J]; } } int Encded_Len=strlen(Encoded); if(Encded_Len%5>0){ char*P=malloc(5-Encded_Len%5); for(int E=0;E<5-Encded_Len%5;E++){ P[E]=null; } strcat(Encoded,P); } return Encoded; } char*Transpose(char*Message,char*K1){ int Msg_Len=strlen(Message),K1_Len=strlen(K1); char*T=malloc(Msg_Len); int F=0; for(int i=0;i<K1_Len;i++){ for(int y=0;y<K1_Len;y++){ if(K1[y]=='0'+i){ for(int u=y;u<Msg_Len;u+=K1_Len){ T[F]=Message[u]; F++; } } } } return T; } char*Disrupted_Transpose(char*Message,char*K2){ int Msg_Len=strlen(Message),K2_Len=strlen(K2); char*T=malloc(Msg_Len); for(int y=0;y<Msg_Len;y++){ T[y]=' '; } int F=0; int P=0; for(int u=0;u<K2_Len;u++){ for(int v=0;v<K2_Len;v++){ T[F]=Message[P]; P++;F++; if(K2[v+1]-'0'==u){ for(int C=1;C<K2_Len-v;C++){ F+=K2_Len-v-C; for(int E=0;E<=v+C;E++){ if(F<Msg_Len&P<Msg_Len){ T[F]=Message[P]; } F++;P++; } } break; } } if(F>Msg_Len){ break; } } int U=0; for(int g=0;g<Msg_Len;g++){ U=(T[g]-'0'<10&-1<T[g]-'0')?U+1:U; } for(int j=U;j<Msg_Len;j++){ for(int x=0;x<Msg_Len;x++){ if(T[x]==' '){ T[x]=Message[j]; break; } } } return Transpose(T,K2); } void VIC_Encoder(char*Message,char*Phrase,char*Key,int a_id,char*date,char*m_id,char null){ char*S1=malloc(10); char*S2=malloc(10); for(int i=0;i<20;i++){ if(i<10){ S1[i]=Key[i]; } else{ S2[i-10]=Key[i]; } } S1=Sequent(S1); S2=Sequent(S2); char*M=malloc(5); for(int i=4;i>-1;i--){ M[i]='0'+(((m_id[i]-'0')-(date[i]-'0'))%10); } char*G=Chain_Add(M,5,0); for(int y=0;y<10;y++){ G[y]='0'+(((S1[y]-'0')+(G[y]-'0'))%10); } char*N="0123456789"; char*T=malloc(10); for(int q=0;q<10;q++){ for(int t=0;t<10;t++){ if(N[t]==G[q]){ T[q]=S2[t]; } } } char*Z=Chain_Add(T,50,0); char*U=malloc(50); for(int h=0;h<50;h++){ U[h]=Z[h+10]; } int p,q; for(int b=49;b>10;b++){ if(U[b]!=U[b-1]){ q=a_id+(U[b]-'0'); p=a_id+(U[b-1]-'0'); break; } } char*seqT=Sequent(T); char*V=malloc(50); int Count=0; for(int j=0;j<10;j++){ for(int o=0;o<10;o++){ if(seqT[o]=='0'+j){ for(int x=o;x<o+41;x+=10){ V[Count]=U[x]; Count+=1; } } } } char*K1=malloc(p); char*K2=malloc(q); for(int D=0;D<p+q;D++){ if(D<p){ K1[D]=V[D]; } else{ K2[D-p]=V[D]; } } K1=Sequent(K1); K2=Sequent(K2); char*C=malloc(10); for(int b=40;b<50;b++){ C[b-40]=U[b]; } C=Sequent(C); char*Transposed_2=Disrupted_Transpose(Transpose(Straddling_Checkerboard(C,Phrase,Message,null),K1),K2); int O=0; for(int B=0;B<strlen(Transposed_2)/5+1;B++){ if(B==strlen(Transposed_2)/5-date[strlen(date)-1]+'1'){ printf("%s ",m_id); } else{ for(int J=O;J<O+5;J++){ printf("%c",Transposed_2[J]); } printf(" "); O+=5; } } } ``` ## Notes * This uses a checkerboard similar to the following to encode the message: ``` 3 4 5 6 2 3 4 5 6 7 S E N A T O R I 6 B C D F G H J K L M 7 P Q U V W X Y Z . # ``` * This assumes that all applicable strings are given in uppercase. The message should also have all punctuation *except periods* removed and all numbers demarcated by `#`s, while the key phrase should have *all* punctuation removed. * The resulting encoded message is output to STDOUT as a string of space-separated five-digit groups. * The input message should be in English. * I would have combined a few of the functions I used, but then I would have to resort to using more two-letter variable names, making the final program longer than it would be with a few more functions. * ~~This currently does *not* assume that the keyword (at least in English) is always going to contain the same set of letters, and so makes up for that by removing duplicates, manipulating the checkerboard, etc. This capability is apparently not required by OP, so I am currently golfing off the extra, unnecessary bytes that is taking up.~~ Updated for golfed version. [Answer] # JavaScript (ES6), ~~946~~ ~~938~~ 953 bytes ``` V=(c,d,f,g,j,k,m)=>{S=a=>a.split``,J=a=>a.join``,A=(a,b)=>{for(i=0;a[L="length"]<b;a+=(a[i++]- -a[i])%h);return a},Q=b=>(a=S(b).sort(),S(b).map(b=>a[i=a[X="indexOf"](b)]=i)),u=A(t=J(S(A(J(S(k).map((a,b)=>Math.abs(a-g[b]))),h=10)).map((a,b)=>Q(f[C="slice"](h,20))[(Q(f[C](0,h))[b]- -a)%h])),60)[C](h),T=((a,b,c)=>{if(r=Array(l=b[L]).fill(""),c){for(e=a[L]/l,i=0,w=[],u=R=b[X](x=0);i<e;)w[i++]=a[P](0,R++),u?u=0:R>l||(R=b[X](u=++x));for(i=0;i<e;)w[i]=J(w[i].concat(a[P](0,l-w[i++][L])));a=J(w)}for(i in a)r[+b[i%l]]+=a[i];return r}),v=J(T(u,Q(t))),q=J(Q(u[C](-h))),t="ABCDEFGHIJKLMNOPQRSTUVWXYZ#".match(new RegExp("[^"+d+"]","g")),t[P="splice"](9,0,"."),M=[];for(i in t)M[t[i]]=q[8^i/h]+(M[d[i]]=q[i%h]);for(n=c[L],b=J((c[C](n-=new Date%n)+"."+c[C](0,n)).split(/ |/).map(a=>M[a]||a)),b+=m.repeat(5-b[L]%5),i=f=q=49;f==q;)f=+u[i-1]+j,q=+u[i++]+j;return t=J(T(S(J(T(b,Q(v[C](0,f))))),Q(v.substr(f,q)),1)).match(/.{5}/g),g=-g[C](-1),g++&&t[P](g||t[L],0,k),t} ``` I saw over the weekend there was no JS entry for this yet, so here's my (last minute) attempt. Implementing and golfing this was as crazy as it was fun! ### Demo Snippet ``` V=(c,d,f,g,j,k,m)=>{S=a=>a.split``,J=a=>a.join``,A=(a,b)=>{for(i=0;a[L="length"]<b;a+=(a[i++]- -a[i])%h);return a},Q=b=>(a=S(b).sort(),S(b).map(b=>a[i=a[X="indexOf"](b)]=i)),u=A(t=J(S(A(J(S(k).map((a,b)=>Math.abs(a-g[b]))),h=10)).map((a,b)=>Q(f[C="slice"](h,20))[(Q(f[C](0,h))[b]- -a)%h])),60)[C](h),T=((a,b,c)=>{if(r=Array(l=b[L]).fill(""),c){for(e=a[L]/l,i=0,w=[],u=R=b[X](x=0);i<e;)w[i++]=a[P](0,R++),u?u=0:R>l||(R=b[X](u=++x));for(i=0;i<e;)w[i]=J(w[i].concat(a[P](0,l-w[i++][L])));a=J(w)}for(i in a)r[+b[i%l]]+=a[i];return r}),v=J(T(u,Q(t))),q=J(Q(u[C](-h))),t="ABCDEFGHIJKLMNOPQRSTUVWXYZ#".match(new RegExp("[^"+d+"]","g")),t[P="splice"](9,0,"."),M=[];for(i in t)M[t[i]]=q[8^i/h]+(M[d[i]]=q[i%h]);for(n=c[L],b=J((c[C](n-=new Date%n)+"."+c[C](0,n)).split(/ |/).map(a=>M[a]||a)),b+=m.repeat(5-b[L]%5),i=f=q=49;f==q;)f=+u[i-1]+j,q=+u[i++]+j;return t=J(T(S(J(T(b,Q(v[C](0,f))))),Q(v.substr(f,q)),1)).match(/.{5}/g),g=-g[C](-1),g++&&t[P](g||t[L],0,k),t} ``` ``` <div id="demo"> <h2>Test</h1> <p><strong>Message: </strong><input id="message" type="text" value="WE ARE DISCOVERED. TAKE WHAT YOU CAN. BURN EVERYTHING ELSE. MOVE TO SAFEHOUSE FOXTROT #3#."/></p> <p><strong>Keyword: </strong><input id="keyword" type="text" value="SENATORI"/></p> <p><strong>Phrase: </strong><input id="phrase" type="text" value="THEFIRSTPRINCIPLEISTHATYOUMUSTNOTFOOLYOURSELFANDYOUARETHEEASIESTPERSONTOFOOL"/></p> <p><strong>Date: </strong><input id="date" type="text" value="3172016"/></p> <p><strong>Agent Id: </strong><input id="agent" type="text" value="9"/></p> <p><strong>Message Id: </strong><input id="mid" type="text" value="47921"/></p> <p><strong>Null: </strong><input id="null" type="text" value="4"/></p> </div> <input type="button" value="Run" onclick="alert(V( document.getElementById('message').value, document.getElementById('keyword').value, document.getElementById('phrase').value, document.getElementById('date').value, document.getElementById('agent').value, document.getElementById('mid').value, document.getElementById('null').value).join(', '))"/> ``` ### Edit: -8 bytes Realized there were extra parenthesis around function `S,J,A,Q` ### Edit: +15 bytes Updated the logic for how the `message id` is placed in the final message (now 1-indexed and 0 does not include it in the output). ## Ungolfed ``` chainAdd = (s,l)=>{for(i=0;s.length<l;s+=(s[i++]- -s[i])%10);return s;} sequentialize = (s)=> { a=s.split('').sort(); return s.split('').map(c=>(i=a.indexOf(c),a[i]='',i)); } transpose = (s,k,disruptive)=>{ var result=Array(k.length).fill('') if(disruptive){ rows=[] k_index=0; rowLength=k.indexOf(k_index); triangling=!rowLength; expectedRows = s.length/k.length for(row=0;row<expectedRows;row++){ rows[row]=s.splice(0,rowLength++) if(triangling){ if(rowLength>k.length){ triangling=false; rowLength=k.indexOf(++k_index) } } else{ triangling=true; } } for(row=0;row<expectedRows;row++){ rows[row]= rows[row].concat(s.splice(0,k.length-rows[row].length)).join('') } s=rows.join('') } for(i in s) result[+k[i%k.length]]+=s[i]; return result; } checkerboard =(message,seq, keyword, nulls)=>{ t='ABCDEFGHIJKLMNOPQRSTUVWXYZ#'.match(new RegExp('[^'+keyword+']','g')); t.splice(9,0,'.') map=[] for(i in t) map[t[i]]=(seq[8^(i/10)])+(map[keyword[i]]=seq[i%10]) r = new Date%message.length; rotateMessage=message.substr(message.length-r)+'.'+message.substr(0,message.length-r) result =rotateMessage.split(/ |/).map(x=>map[x]||x).join(''); result+=nulls.repeat(5-result.length%5) return result; } vic = (message, keyword, phrase, date, agent, m_id, nulls)=>{ s1=sequentialize(phrase.substr(0,10))//.join('') s2=sequentialize(phrase.substr(10,10))//.join('') r = m_id.split('').map((x,i)=>Math.abs(x-date[i])).join('') g = chainAdd(r,10).split('').map((x,i)=>(s1[i]- -x)%10); t = g.map(i=>s2[+i]).join(''); u=chainAdd(t,60).substr(10) var p,q; for(i=49;p==q;i++){ p=agent + +u[i-1]; q=agent + +u[i]; } seqT = sequentialize(t); v=transpose(u,seqT).join(''); k1 = sequentialize(v.substr(0,p)); k2 = sequentialize(v.substr(p,q)); c = sequentialize(u.substr(-10)).join('') CB =checkerboard(message,c, keyword, nulls); t1=transpose(CB,k1).join('') t2=transpose(t1.split(''),k2,1).join('').match(/.{5}/g); (d=-date.substr(-1))&&t2.splice((d+1)||t2.length,0,m_id); return t2; } ``` ## Notes * This uses a checkerboard similar to the following to encode the message: ``` 3 1 0 5 9 6 8 7 2 4 S E N A T O R I 2 B C D F G H J K L . 4 M P Q U V W X Y Z # ``` * All strings are given in uppercase. The message is alphanumeric Latin (plus `.` and `#`) and should have all punctuation (except periods) removed. All numbers should already be marked with `#`s. The key phrase should have all punctuation/spaces removed. * The resulting message is returned as an array of 5 digit strings. ## Enhancements * I feel like there's a way to abuse the "All languages" to save some bytes. If I had more time I'd refigure this to assume the language was something like Hawaiian which has only 12 letters. * Any golfing suggestions are always welcome. [Answer] ## Clojure, ~~1197~~ 1212 bytes Ough, I'm exhausted. Update: Added the required random splitting location of the message, ungolfed version uses the same location as the given example so that algorithm can be easily verified. ``` (defn enc[I K E D Y M](let[P split-at A concat Z zipmap R partition W mapcat % count X repeat O vector / map x(fn[C](apply / O C))G range t 10 r(G t)m(fn[i](mod i t))F(fn[[n & N]](/ last(iterate(fn[[[b & N]a]][(A N[(m(+ a b))])b])[N n])))Q(fn[S](for[i(G(% S))a[(nth S i)]](apply +(%(filter #{a}(take i S)))(for[b S :when(pos?(compare a b))]1))))[S J](/ Q(P t(take 20 E)))T(/(Z r J)(/ m(/ + S(F(/ - M D)))))U(take 50(drop t(F T)))l(last U)p(+ Y(last(remove #{l}U)))V(W(Z(Q T)(x(R t U)))r)[k j](/ Q(P p(take(+ p Y l)V)))B(into(Z(/ char(G 48 58))(G))(/(fn[i c][c(+(*(quot i 10)20)(nth(Q(reverse(take t(reverse U))))(m i)))])(G)(A(str K",,")(remove(set K)(/ char(A(G 65 91)".#"))))))?(% k)T(vec(filter some?(W(Z k(x(R ?(A(flatten(R 5(A(W str(/ B(let[[b e](P(rand-int(count I))I)](apply str(A e".. "b)))))(X 4(B\,)))))(X(dec ?)nil)))))(G ?))))w (% j)NR(+(quot(% T)w)1)L(flatten(for[k r](for[i(G(.indexOf j k)(inc w))](G i))))C(for[[r c](/ O(rest(reductions + -1(/(fn[i](get{0 1}i 0))L)))L):when(< r NR)][r c])H(R 5(filter some?(W(Z j(x(R w (A(vals(into(sorted-map)(/ O(A C(for[i(G NR)j(G w)c[[i j]]:when(not((set C)c))]c))T)))(X(dec w)nil)))))(G w))))](/(fn[p](apply str p))(let[[b e](P(-(% H)(D 6)-1)H)](A b[M]e))))) ``` Sample inputs and test case: ``` (def mymsg (clojure.string/upper-case "We are discovered. Take what you can. Burn everything else. Move to Safehouse Foxtrot#3#")) (def mykey "SENATORI") (def mypharase (clojure.string/upper-case (apply str (remove #{\space} "The first principle is that you must not fool yourself — and you are the easiest person to fool.")))) (def mydate [3 1 7 2 0 1 6]) (def mynum 9) (def M [4 7 9 2 1]) ;("61231" "12824" "71192" "58609" "92185" "48612" "14927" "22944" "34046" "13348" "04159" "38645" "70546" "20254" "22026" "64584" "21904" "47921" "90253" "42694" "42221" "56644" "14541") (enc mymsg mykey mypharase mydate mynum M) ``` Ungolfed: ``` (defn enc[mymsg mykey mypharase mydate mynum M] (let[t 10 r (range t) m (fn[i](mod i t)) lagfib (fn[[n & N]](map last(iterate(fn[[[b & N]a]][(concat N[(m(+ a b))])b])[N n]))) toseq (fn[S](for[i(range(count S))a[(nth S i)]](apply +(count(filter #{a}(take i S)))(for[b S :when(pos?(compare a b))]1)))) [S1 S2] (map toseq(split-at t(take 20 mypharase))) M2 (take t(lagfib(map - M mydate))) G (map m(map + S1 M2)) Gmap (zipmap r S2) T (map Gmap G) U (take 50(drop t(lagfib T))) L2 (last U) L1 (last(remove #{L2}U)) p (+ mynum L1) q (+ mynum L2) seqT (toseq T) V (mapcat(zipmap seqT(apply map vector(partition t U)))r) [K1 K2] (map toseq(split-at p(take(+ p q)V))) C (toseq(reverse(take t(reverse U)))) B (into(zipmap(map char(range 48 58))(range))(map(fn[i c][c(+(*(quot i 10)20)(nth C(m i)))])(range)(concat(str mykey",,")(remove(set mykey)(map char(concat(range 65 91)".#")))))) ;B (into(zipmap(map char(range 48 58))(range))(map(fn[i c][c(+(nth C(quot i 3))(*(mod i 3)20))])(range)(flatten(apply map vector(partition 10(apply concat mykey",,"(apply map vector (partition 2(remove(set mykey)(map char(concat(range 65 91)".#"))))))))))) N1 (count K1) mymsg (flatten(partition 5(concat(mapcat str(map B(let[[b e](split-at 49 mymsg)](apply str(concat e".. "b)))))(repeat 4(B\,))))) T1 (vec(filter some?(mapcat(zipmap K1(apply map vector(partition N1(concat mymsg(repeat(dec N1)nil)))))(range N1)))) N2 (count K2) NR (+(quot(count T1)N2)1) cols (flatten(for[k r](for[i(range(.indexOf K2 k)(+(count K2)1))](range i)))) rows (rest(reductions + -1(map(fn[i](get{0 1}i 0))cols))) coords (for[[r c](map vector rows cols):when(< r NR)][r c]) coords (concat coords(for[i(range NR)j(range N2)c[[i j]]:when(not((set coords)c))]c)) T2 (partition 5(filter some?(mapcat(zipmap K2(apply map vector(partition N2(concat(vals(into(sorted-map)(map vector coords T1)))(repeat(dec N2)nil)))))(range N2))))] (map(fn[p](apply str p))(let[[b e](split-at(-(count T2)(mydate 6)-1)T2)](concat b[M]e))))) ``` It has an alternative implementation on the checkerboard `B` which is the same as on the task definition. But the submission uses an other one in which unused alphabets first fill the 2nd row and then the 3rd instead of filling column-by-column. ]
[Question] [ **Problem** One day, you boss walks up to you and tells you he needs to know the time. He still insists after you pointing at the clock directly above your head, and confesses he has a severe case of [dyscalculia](https://en.wikipedia.org/wiki/Dyscalculia), which causes him to not even be able to see numbers on a clock. While you're still left wondering how someone unable to see numbers can run a company, he tells you to "do something about it", whatever that is. Your task is now to create a program or function that, given an input time with hours and minutes (seconds are optional)(hours are 24-based), outputs a readable english sentence, that doesn't contain numbers. It is not necessary to ouput the seconds. For example, `08:45:15` should output `quarter to nine o'clock AM` **Test cases** ``` 00:00:00 > twelve night 12:00:00 > twelve noon 06:00:00 > six o'clock AM 18:00:00 > six o'clock PM 06:15:00 > quarter past six o'clock AM 18:45:00 > quarter to seven o'clock PM 11:30:00 > half past eleven o'clock AM 13:22:00 > twentytwo minutes past one o'clock PM 17:43:00 > seventeen minutes to six o'clock PM 00:09:00 > nine minutes past twelve o'clock AM ``` **Rules** Outputting numbers can be both in the form of fortytwo or forty-two, whichever you like best. Standard loopholes are not allowed. Trailing newlines are allowed, but the sentence should be on 1 line. Input can be in any format you want, for example `HH:MM:SS`, `HH,MM,SS`, `HHMMSS`, `HH/MM/SS`, or any variant without seconds, but you should make the input format clear in your answer. It's not needed to output `one minute` instead of `one minutes` for minutes ranging from 0 trough 30 (0 and 30 included) you should use `past`, and for the others you should use `to` Because time is relative, shortest code in bytes wins. [Answer] # LaTeX, 466 bytes ``` \usepackage{fmtcount,etoolbox}\def\x{\the\numexpr}\def\n[#1]{\numberstringnum{#1}}\def\h[#1]{\ifnumequal{#1}{0}{twelve night}{\ifnumequal{#1}{12}{twelve noon}{\ifnumless{#1}{13}{\n[#1] o'clock AM}{\n[\x#1-12\relax] o'clock PM}}}}\def\m[#1]{\ifnumequal{#1}{15}{quarter}{\ifnumequal{#1}{30}{half}{\n[#1] minutes}}}\newcounter{c}\def\f[#1]#2{\ifnumequal{#2}{0}{\h[#1]}{\ifnumless{#2}{31}{\m[#2] past \h[#1]}{\setcounter{c}{\x60-#2\relax}\m[\thec] to \h[\x#1+1\relax]}}} ``` Just call the macro `\f` as `\f[hour]{minutes}`, here some tests: ``` \begin{document} \noindent \textbf{Test cases:} \\ \\ 00:00 = \f[00]{00} \\ 12:00 = \f[12]{00} \\ 06:00 = \f[6]{00} \\ 18:00 = \f[18]{00} \\ 06:15 = \f[6]{15} \\ 18:45 = \f[18]{45} \\ 11:30 = \f[11]{30} \\ 13:22 = \f[13]{22} \\ 17:43 = \f[17]{43} \\ \noindent \textbf{More test cases:} \\ \\ 00:13 = \f[00]{13} \\ 12:12 = \f[12]{12} \\ 12:15 = \f[12]{15} \\ 11:45 = \f[11]{45} \\ 11:41 = \f[11]{41} \\ \end{document} ``` [Answer] # Python 2, 498 bytes Input comes as function argument. First hour and then minute, both as integer. Result gets printed to the screen. ``` def g(h,m): a=lambda x:"twelve one two three four five six seven eigth nine ten eleven".split()[x%12];b=lambda x:a(x)+" o'clock "+["AM","PM"][x>=12] if m: z=m if m<30else 60-m;print(a(z)if z<13else("twenty"+(a(z-20)if z-20else"")if z>19else"thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()[z-13])if m%15else"quarter"if m-30else"half")+(" minutes"if m-30and m%15else"")+[" past "+b(h)," to "+b(h+1)][m>30] else:print"twelve "+("noon"if h else "night")if h in[0,12]else b(h) ``` [Try it online!](https://repl.it/BkMv/43) *(with slightly extended testcases)* That was a pretty fun golf. Although all those nested ternaries drove me a little bit crazy ^^ I was planning on doing this in Pyth after this, but I don't think that I am mentally able to do this at the moment (or ever). **Ungolfed:** ``` def ungolfed(h,m): toStr=lambda x:"twelve one two three four five six seven eigth nine ten eleven".split()[x%12] hour=lambda x:toStr(x)+" o'clock "+["AM","PM"][x>=12] minute=lambda x:"twenty"+(toStr(x-20)if x-20else"")if x>19else"thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()[x-13] if m: s="" if m==30: s+="half" else: if m%15==0: s+="quarter" else: z=m if m<30 else 60-m if z<13: s+=toStr(z) else: s+=minute(z) print s+(" minutes"if m-30and m%15else "")+[" past "+hour(h)," to "+hour(h+1)][m>30] else: if h in[0,12]: print"twelve "+("noon"if h else "night") else: print hour(h) ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 376 bytes ``` lambda h,m,N='one two three four five six seven eight nine ten eleven twelve thir four _ six seven eigh nine'.split()+['']:m+h%12and((m%15<1and['half','quarter'][m%2]or(lambda T:T<20and N[T-1]+T//13*'teen'or'twenty'+N[T%10-1])([m,60-m][m//31])+' minutes')+[' past ',' to '][m//31])*(m>0)+N[(h-1+m//31)%12]+" o'clock "+'APA'[(h+m//31)//12]+'M'or'twelve n'+['ight','oon'][h//12] ``` [Try it online!](https://tio.run/##ZZDdTuMwEIXveYoRUjUOcWkct92CAIkHWMRF77IRCtRZR8R2cFx@nr47Cd1V3L3z8fnOzLG7r6CdlZvOH@rbX4e2Ms@7CjQ3/OEWnVUQPhwE7ZWC2u091M27gr75hF69Kwuq@a0D2GYAB9mOt@FDtYQF3fjv1NNJZEzgZd@1TWBJWiCW1ybVM5FXdseYmYnVjaBjgbpqa@T4tq98UB7Lwszy0nl2LLq93t7kGZHwUGznoky3i4WQFxiUsug8UhMbvjAldyYyAhJWGL7O5oYmLRaSLlIE09h9UD0OTaCr@gC0EoID/EddMHOXJTSH6blIx8uE6pbpOTh8ad3LK5yneP94j0QcfapCAP48Fhm@xCKtGP6MFjhnab4eqUPnGxtYzSDjkCXJ2V8t8ljD@sTf/OeLVewvIy24jPKS5/lU/@BLOZ1Hfa6m/oqLKQ8bnmdxXkT6NE99xcn7RNxHRn04wCbm5TJ@z2rq53LUhz8 "Python 3.8 (pre-release) – Try It Online") Stumbled on this challenge by accident and decided to give it a go. # Explanation Handles the edge cases of midnight and noon by using a standard `... and ... or ...` that has become ubiquitous for any Python code-golfer. For these edge cases return `twelve` , followed by night or noon depending on the hour. In the general case, we build a string representing the minutes. If the minutes is 15 or 45, we start with `quarter`; if it is 30, we start with `half`; otherwise, we determine whether to use itself or 60 minus itself (think of it this way: 5:21 is 21 past 5, but 6:37 is 23 to 7, not 37 to 7). Let `M` denote this number. We build the appropriate number: * if `M` is less than 20, start with the conversion of itself to letters, minus `teen`. * if `M` is 20 or more, start with `twenty`. Then: * if `M` is less than 20 but more than 12, add `teen`. * if `M` is 20 or more, add the conversion to letters of its units digit, with nothing being added if its units digit is zero. If the minutes count was not divisible by 15, we also have to add `minutes`. Next, we have to deal with `past` and `to`. This is determined by indexing a list. If the minutes count is zero, the above string goes to waste. Because `zero` or something similar does not appear in `N`, one might assume that building the string for zero would cause the program to error with an IndexError. But because Python allows negative indices, it doesn't error. When the minutes count is zero, we just don't use the above string. Next we have to deal with `o' clock`, which is simply done using `%` and our list of text numbers again. Finally we append `AM` or `PM` depending on the hour. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 155 bytes ``` 1→m?\:/⌊:£t¬[¥h12ḋ:→d÷¬[0→m12←d h¬[‛⟇Ẏ|‛₄⟨]|¥h12%]|¥t15ḋ:→d÷¬[←d h∷[‛ɽ¢|‛»⌈]|¥t:30>[60ε]‛«¦]¥t30≤[‛×Ṡ¥h12Ḋ[12|¥h12%]|‛to¥h12%›]]←m[`o'∵₅`¥h12<‛PAi\M+]WḢ∆ċṄ ``` Takes input as HH:MM. [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIx4oaSbT9cXDov4oyKOsKjdMKsW8KlaDEy4biLOuKGkmTDt8KsWzDihpJtMTLihpBkIGjCrFvigJvin4fhuo584oCb4oKE4p+oXXzCpWgxMiVdfMKldDE14biLOuKGkmTDt8KsW+KGkGQgaOKIt1vigJvJvcKifOKAm8K74oyIXXzCpXQ6MzA+WzYwzrVd4oCbwqvCpl3CpXQzMOKJpFvigJvDl+G5oMKlaDEy4biKWzEyfMKlaDEyJV184oCbdG/CpWgxMiXigLpdXeKGkG1bYG8n4oi14oKFYMKlaDEyPOKAm1BBaVxcTStdV+G4ouKIhsSL4bmEIiwiIyAwMDowMDowMCA+IHR3ZWx2ZSBuaWdodFxuIyAxMjowMDowMCA+IHR3ZWx2ZSBub29uXG4jIDA2OjAwOjAwID4gc2l4IG8nY2xvY2sgQU1cbiMgMTg6MDA6MDAgPiBzaXggbydjbG9jayBQTVxuIyAwNjoxNTowMCA+IHF1YXJ0ZXIgcGFzdCBzaXggbydjbG9jayBBTVxuIyAxODo0NTowMCA+IHF1YXJ0ZXIgdG8gc2V2ZW4gbydjbG9jayBQTVxuIyAxMTozMDowMCA+IGhhbGYgcGFzdCBlbGV2ZW4gbydjbG9jayBBTVxuIyAxMzoyMjowMCA+IHR3ZW50eXR3byBtaW51dGVzIHBhc3Qgb25lIG8nY2xvY2sgUE1cbiMgMTc6NDM6MDAgPiBzZXZlbnRlZW4gbWludXRlcyB0byBzaXggbydjbG9jayBQTVxuIyAwMDowOTowMCA+IG5pbmUgbWludXRlcyBwYXN0IHR3ZWx2ZSBvJ2Nsb2NrIEFNXG5cbiMgSW5wdXQgaXMgSEg6TU0iLCIxMzoyMiJd) [Answer] # Javascript, ~~384~~ 381 bytes ``` (h,m)=>(o='one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,'.split`,`,o=o.map((x,i)=>i>11?(x||o[i-10])+'teen':x),(a=m>30,t=12,m?(m-30?m%15?((m=a?59-m:m)>=(b=a?19:20)?'twenty'+((m%=b)?o[a?m:m-1]:''):o[a?m:m-1])+' minutes':'quarter':'half')+(a?' to ':' past '):'')+(h%t|m?o[(a?h:(h?h-1:11))%t]+` o'clock ${h>t?'P':'A'}M`:o[11]+(h-t?' night':' noon'))) ``` ``` f= (h,m)=>( o='one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,'.split`,`, o=o.map((x,i)=>i>11?(x||o[i-10])+'teen':x), (a=m>30,t=12, m? (m-30? m%15? ((m=a?59-m:m)>=(b=a?19:20)? 'twenty'+((m%=b)?o[a?m:m-1]:'') :o[a?m:m-1])+' minutes' :'quarter' :'half')+(a?' to ':' past ') :'') +(h%t|m? o[(a?h:(h?h-1:11))%t]+` o'clock ${h>t?'P':'A'}M` :o[11]+(h-t?' night':' noon')) ) document.body.innerHTML = '<pre>' + 'f(00,00) = ' + f(00,00) + '\n' + 'f(12,00) = ' + f(12,00) + '\n' + 'f(06,00) = ' + f(06,00) + '\n' + 'f(18,00) = ' + f(18,00) + '\n' + 'f(06,15) = ' + f(06,15) + '\n' + 'f(18,45) = ' + f(18,45) + '\n' + 'f(11,30) = ' + f(11,30) + '\n' + 'f(13,22) = ' + f(13,22) + '\n' + 'f(17,43) = ' + f(17,43) + '\n' + 'f(00,09) = ' + f(00,09) + '\n' + 'f(23,59) = ' + f(23,59) + '\n' + '</pre>' ``` [Answer] # Perl 5, ~~367 361~~ 385 Bytes Garbled ``` use integer;$_=<>;~/(\d+):(\d+)/;@b=(one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve); @x=(@b,thirteen,(map{/fi/?quarter:$_.teen}@b[3..8]),(map{twenty.$_}'',@b[0..8]),half);@y=map{/^q|h/?$_:$_.' minutes'}@x;$s=1-$2/31;$y=abs((-29,0)[$s]+$2%31)-1;$h=$1-$s;print((+-$2?@y[$y].' '.(to,past)[$s].' ':'').@b[$h++%12]." o' clock ".($h%12?(AM,PM)[$h/12]:(night,noon)[$h/12%2])) ``` Formatted and test cases: ``` use integer; map{ # capture (implicit $_) ~/(\d+):(\d+)/; # bare words @b=(one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve); # construct up to 30 @x=(@b,thirteen, (map{/fi/?quarter:$_.teen}@b[3..8]), (map{twenty.$_}'',@b[0..8]),half); # quarter/half business @y=map{/^q|h/?$_:$_.' minutes'}@x; # whether we are to/past $s=1-$2/31; # num minutes wrapped around $y=abs((-29,0)[$s]+$2%31)-1; # num hours $h=$1-$s; #print('$s='.$s."\th=".$h."\th%12=".($h%12)."\n"); print($_.' > '); #minute component print((+-$2 ?@y[$y].' '.(to,past)[$s].' ' :'') # hours .@b[$h++%12] ." o' clock " # Night/Noon .($h%12 ?(AM,PM)[$h/12] :(night,noon)[$h/12%2])); print "\n" } ('00:00:00', '00:01:00', '11:59:00', '12:00:00', '12:01:00', '06:00:00', '18:00:00', '06:15:00', '18:45:00', '11:30:00', '13:22:00', '17:43:00', '23:59:59') ``` [Answer] # C, 478 bytes ``` *w(i){char*p,*n[]={"","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};return i>19?asprintf(&p,"twenty%s",n[i%20]),p:n[i];}main(m,h){scanf("%d%d",&h,&m);m>30?h++:0;printf("%s%s%s%s%s %s\n",m%15?m>30?w(60-m):w(m):m^30?m?"quarter":"":"half",m%15?" minutes":"",m?m>30?" to ":" past ":"",w((h+11)%12+1),h%12||m?" o'clock":"",h%12||m?h>11?"PM":"AM":h?"noon":"night");} ``` ## Test Cases ``` $ echo "0 0" | ./a.out twelve night $ echo "12 0" | ./a.out twelve noon $ echo "6 0" | ./a.out six o'clock AM $ echo "18 0" | ./a.out six o'clock PM $ echo "6 15" | ./a.out quarter past six o'clock AM $ echo "18 45" | ./a.out quarter to seven o'clock PM $ echo "11 30" | ./a.out half past eleven o'clock AM $ echo "13 22" | ./a.out twentytwo minutes past one o'clock PM $ echo "17 43" | ./a.out seventeen minutes to six o'clock PM $ echo "0 9" | ./a.out nine minutes past twelve o'clock AM ``` Try it [here](http://ideone.com/O17u5E). [Answer] ## Batch, ~~779~~ ~~774~~ ~~752~~ 749 bytes ``` @echo off set t=%1 set/ah=%t:~0,2%,m=%t:~3,2% set p=past if %m% gtr 30 set p=to&set/am=60-m,h+=1 for %%a in ("one minute.1" quarter.15 half.30)do if %%~xa==.%m% set o=%%~na&goto g set o= if %m% gtr 20 set o=twenty-&set/am-=20 for %%a in (one.1 two.2 three.3 four.4 five.5 six.6 seven.7 eight.8 nine.9 ten.10 eleven.11 twelve.12 thirten.13 fourteen.14 sixteen.16 seventeen.17 eighteen.18 nineteen.19 twenty.20)do if %%~xa==.%m% set o=%o%%%~na minutes :g if not %m%==0 set o=%o% %p% set a= AM if %h% gtr 12 set a= PM&set/ah%%=12 if %h%==0 (echo %o%twelve night)else if %h%==12 (echo %o%twelve noon)else for %%a in (one.1 two.2 three.3 four.4 five.5 six.6 seven.7 eight.8 nine.9 ten.10 eleven.11)do if %%~xa==.%h% echo %o%%%~na o'clock%a% ``` Change the second line to `set t=%1%time%` to default to saying the current time if no time is provided. Edit: Saved 22 bytes by optimising my `set/a` statements. Saved 3 bytes thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ. When I wrote my original version I made the mistake of saying the time as I would actually say it, i.e. o'clock only on exact hours, and midnight and midday instead of twelve night and twelve noon: ``` @echo off set t=%1 set/a h=%t:~0,2% set/a m=%t:~3,2% set p=past if %m% gtr 30 set p=to&set/a m=60-m&set/a h=h+1 for %%a in ("one minute.1" quarter.15 half.30) do if %%~xa==.%m% set o=%%~na&goto g set o= if %m% gtr 20 set o=twenty-&set/a m=%m%-20 for %%a in (one.1 two.2 three.3 four.4 five.5 six.6 seven.7 eight.8 nine.9 ten.10 eleven.11 twelve.12 thirten.13 fourteen.14 sixteen.16 seventeen.17 eighteen.18 nineteen.19 twenty.20) do if %%~xa==.%m% set o=%o%%%~na minutes :g set o=%o% %p% set a= AM if %h% gtr 12 set a= PM&set/a h=h%%12 if %m%==0 set a= o'clock%a%&set o= if %h%==0 (echo %o%midnight)else if %h%==12 (echo %o%midday)else for %%a in (one.1 two.2 three.3 four.4 five.5 six.6 seven.7 eight.8 nine.9 ten.10 eleven.11) do if %%~xa==.%h% echo %o%%%~na%a% ``` ]
[Question] [ Given a string with a multiple people's investment data, find out how much profit/loss they recorded. The string only contains capital and lowercase letters, like this: ``` AABaBbba ``` Each letter represents a person - a capital letter means buy, a lowercase letter means sell. The price of the stock they are investing in (CGLF) starts at $50. After someone buys, the price goes up 5%. After someone sells the price goes down 5%. You need to figure out how much money each person who participated made/lost. ## Notes: * The string will always be valid, no selling without first buying. Also, everyone who buys a stock will sell it eventually. * Your calculations should be accurate to at least 6 decimal places. However, final answers should be rounded to two decimals. ## Test Cases: **Input:** `AABaBbba` > > * A: Buy - $50 > * A: Buy - $52.50 > * B: Buy - $55.125 > * a: Sell - $57.88125 > * B: Buy - $54.9871875 > * b: Sell - $57.736546875 > * b: Sell - $54.8497195313 > * a: Sell - $52.1072335547 > > > * Person A profit: `57.88125+52.1072335547-50-52.50=`7.4884835547 * Person B profit: `57.736546875+54.8497195313-55.125-54.9871875=`2.4740789063 **Output:** `A:7.49,B:2.47` (order doesn't matter, separators not required) --- **Input:** `DGdg` > > * D: Buy - $50 > * G: Buy - $52.50 > * d: Sell - $55.125 > * g: Sell - $52.36875 > > > * Person D profit: `55.125-50=`5.125 * Person G profit: `52.36875-52.50=`-0.13125 **Output:** `D:5.13,G:-.13` --- **Input:** `ADJdja` > > * A: Buy - $50 > * D: Buy - $52.50 > * J: Buy - $55.125 > * d: Sell - $57.88125 > * j: Sell - $54.9871875 > * a: Sell - $52.237828125 > > > * Person A profit: `52.237828125-50=`2.237828125 * Person D profit: `57.88125-52.50=`5.38125 * Person J profit: `54.9871875-55.125=`-0.1378125 **Output:** `A:2.24,D:5.38,J:-.14` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~34~~ 32 bytes ``` ⌊{⍺,2⍕+/-⍵}⌸××50ׯ1×\⍤↓1,1+.05×× ``` ``` Monadic × in Dyalog extended for letters corresponds to the casing ¯1 1 ≡ ×'aA' 1+.05×× - 1 + 0.05 times the sign (either 1.05 or 0.95) 1, - concat 1 to the front ¯1×\⍤↓ - cumulative product and drop the last element 50× - multiply by 50 ××50... - the sign times that ⌊{⍺,2⍕+/-⍵}⌸ - group (dyadic ⌸) by the lowercased input (⌊) {⍺,2⍕+/-⍵} - return the left item (the person) concat their rounded total ``` -2 thanks to Adám [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FPV/Wj3l06Ro96p2rr6z7q3Vr7qGfH4emHp5saHJ5@aL3h4ekxj3qXPGqbbKhjqK1nYAqS@u/2qG3Co96@R13Nj3rXPOrdcmi98aO2iY/6pgYHOQPJEA/PYIVH3S0KaUB11UABIOWmADQbLAjhq6vXAkXmKhSnFiQWJZakKpRkpOYq5OYXpSrkJ5Vl5pcW51T@T1NQd3R0SnRKSkpU5wJyXNxT0sEMRxevlKxEdQA "APL (Dyalog Extended) – Try It Online") [Answer] ## Java, 277 bytes ``` class c{public static void main(String[]a){double[]m=new double[26];double s=50;for(byte b:a[0].getBytes()){if(b>=97){m[b-97]+=s;s*=.95;}else{m[b-65]-=s;s*=1.05;}}char g=65;for(double k:m){if(k!=0){System.out.println(g+String.format(java.util.Locale.ENGLISH,"%.2f",k));}g++;}}} ``` Ungolfed: ``` class c { public static void main(String[]a) { double[] m = new double[26]; double s = 50; for(byte b : a[0].getBytes()) { if(b>=97) { m[b-97]+=s; s*=.95; } else { m[b-65]-=s; s*=1.05; } } char g=65; for(double k:m) { if(k!=0) { System.out.println(g+String.format(java.util.Locale.ENGLISH,"%.2f",k)); } g++; } } } ``` [Answer] # JavaScript (ES7), ~~145~~ 142 bytes I can't find a shorter way to round out the results... ``` x=>[for(c of(i=50,a={},x))(a[d=c.toUpperCase()]=a[d]||0,c<"["?(a[d]-=i,i*=1.05):(a[d]+=i,i*=.95))]&&Object.keys(a).map(k=>[k,a[k].toFixed(2)]) ``` Fun fact: this would only be 101 bytes if not for the rounding requirement: ``` x=>[for(c of(i=50,a={},x))(a[d=c.toUpperCase()]=a[d]||0,c<"["?(a[d]-=i,i*=1.05):(a[d]+=i,i*=.95))]&&a ``` [Answer] # Python 3, 116 bytes ``` P=50 M={} for c in input():C=c.upper();u=c>C;u+=~-u;M[C]=M.get(C,0)+P*u;P*=1-u*.05 for k in M:print(k,round(M[k],2)) ``` ### Ungolfed ``` price = 50 profits = {} for char in input(): upper = char.upper() direction = 2 * (char > upper) - 1 profits[upper] = profits.get(upper, 0) + price * direction price *= 1 - direction * .05 for key in profits: print(key, round(profits[key], 2)) ``` [Answer] # ARM Thumb-2 (VFP + `printf`, softfp ABI), ~~109~~ 104 bytes Uses the softfp ABI (default on Android). It won't work on `armhf` Linux. `f7ff fffe` is a 4 byte linker placeholder for `printf`. Both of these examples must be placed at an address that is **not** a multiple of 4 (but even), and must be in a W+X section because we modify an inline `printf` string in place. ``` b5f8 2100 2234 3a01 b402 d8fc f2c4 0249 ec42 1b10 ed9f 1b11 f810 2b01 b192 3a61 bf48 3220 eb0d 02c2 ed92 5b00 bf47 ee35 5b40 ee00 0b01 ee35 5b00 ee00 0b41 ed82 5b00 e7e9 2641 bc0c b11b a005 7006 f7ff fffe 3601 2e5a ddf6 bdf8 999a 9999 9999 3fa9 2558 322e 0066 ``` Assembly: ``` .syntax unified .arch armv6t2 // We need VFPv2 for this. .fpu vfpv2 // We modify an inline string in place, so we need W+X. .section ".writeable_text","awx",%progbits .thumb .globl silly_stocks .thumb_func // Must NOT be 4 byte aligned. // .align 4 // nop // void silly_stocks(const char *input); // Follows AAPCS convention. // input is a null-terminated string in r0. silly_stocks: push {r3-r7, lr} // double buf[26] = {0} movs r1, #0 movs r2, #26*2 .Lclear_loop: subs r2, #1 push {r1} bhi .Lclear_loop .Lclear_loop_end: // note: r1 and r2 are zero at this point // r1:r2 = 0x4049000000000000 = 50.0 double movt r2, #0x4049 vmov d0, r1, r2 vldr d1, .Lfloat_pool .Lprocess_loop: // Loop until the null terminator. // while (r2 = *input++) ldrb r2, [r0], #1 cbz r2, .Lprocess_loop_end // tolower(r2) - 'a' // // Specifically, we subtract 'a', and if the char was uppercase, // it would be negative, triggering the N flag, which is why we // check the mi condition in the following IT blocks. subs r2, #'a' it mi // if (isupper(r2)) addmi r2, #'a' - 'A' // Yucky. We can't use proper offsetting with VFP and we need to // keep the flags for the IT block. add.w r2, sp, r2, lsl #3 // Behold, the beautiful syntax of VFP/NEON. // Combine it with a an IT block and you get a 10 letter mnemonic. OwO vldr.64 d5, [r2] ittee mi // if (isupper(r2)) { // Buy vsubmi.f64 d5, d5, d0 // profit[i] -= d0 vmlami.f64 d0, d0, d1 // stock_price += stock_price * 0.05 // } else { // Sell vaddpl.f64 d5, d5, d0 // profit[i] += stock_price vmlspl.f64 d0, d0, d1 // stock_price -= stock_price * 0.05 // } endif vstr.64 d5, [r2] b .Lprocess_loop .Lprocess_loop_end: movs r6, #'A' .Lprint_loop: // Pop the double into r2 and r3. We are using the softfp abi, so // doubles are passed in integer registers. pop {r2, r3} // Only check if the most signicant half of the double is zero. // Any non-zero double that is 0x00000000xxxxxxxx is denormal. cbz r3, .Lprint_loop_skip // Set up an AEABI call to printf. adr r0, .Lprintf_str // Instead of %c, store the char directly (that's why we need W+X) strb r6, [r0] bl printf .Lprint_loop_skip: // Loop from A-Z. adds r6, #1 cmp r6, #'Z' ble .Lprint_loop pop {r3-r7, pc} // At least for the softfp ABI, doubles are smaller than floats. // This is because printf takes doubles, not floats, and we need // to pass them in a register pair. // So we would need something like this, which is 12 bytes. // vpop {d0} // vcvt.f64.f32 d0, s0 // vmov r2, r3, d0 .align 2 .Lfloat_pool: .double 0.05 .Lprintf_str: // Our printf string. We modify X directly. .asciz "X%.2f" .section ".testsuite_unscored","ax",%progbits .macro $TEST str adr r0, 1f bl puts adr r0, 1f bl silly_stocks movs r0, #'\n' bl putchar b 2f .align 2 1: .asciz "\str" .align 2 2: .endm .align 2 .globl main .thumb_func main: push {r4, lr} $TEST "AABaBbba" $TEST "DGdg" $TEST "ADJdja" pop {r4, pc} ``` Decided to take a shot at VFP code in ARM assembly instead of doing something easy (and basically identical to the Java entry) like C or C++. One of the things I realized the hard way was that ARM actually needs the stack to be 8 byte aligned, or else subtle bugs will occur. Two hours of debugging I am NEVER getting back. 😫 Oddly enough, using doubles is smaller than floats, despite the larger literal pool. This is because the C calling convention mandates that `float`s be promoted to `double` in variadic functions, so we would have to convert to `double` anyways, and that is larger than the 8 bytes for the larger pool. Output isn't pretty. But the question says "**separators not required**" so I took that in the most literal sense. 😏 ``` AABaBbba A7.49B2.47 DGdg D5.12G-0.13 ADJdja A2.24D5.38J-0.14 ``` But aside from the `5.12` which is the same rounding error that was mentioned in Python, the results are correct. # ARM Thumb-2 (VFP + `printf`, softfp ABI, very imprecise), ~~99~~ 96 bytes This version uses 32-bit x 16-bit fixed point arithmetic. It lacks the required 6 digits of precision, but for the test cases it products the same results. Interpret it as you wish. Must be loaded at an address that is not a multiple of 4 for constant pool alignment. Machine code: ``` b5f8 2100 2534 3d01 b402 d8fc f2c0 0132 4d11 f810 2b01 b172 3a61 bf48 3220 f85d 3032 fb51 f605 bf47 1a5b 4431 440b 1b89 f84d 3032 e7ed 2641 ecbd 0b02 eeba 0bc8 ec53 2b10 b11b a004 7006 f7ff fffe 3601 2e5a ddf1 bdf8 cccc 0ccc 2558 322e 0066 ``` Assembly: ``` .syntax unified .arch armv6t2 // We need VFPv2 for this. .fpu vfpv2 // We modify an inline string in place, so we need W+X. .section ".writeable_text_fixed","awx",%progbits .thumb .globl silly_stocks_fixed .thumb_func // Must not be 4 byte aligned. // .align 4 // nop // void silly_stocks_fixed(const char *input); // Follows AAPCS convention. // input is a null-terminated string in r0. silly_stocks_fixed: push {r3-r7, lr} // We use double the width because we need to keep alignment. // int64_t buf[26] = {0} movs r1, #0 movs r5, #26*2 .Lclear_loop_fixed: subs r5, #1 push {r1} bhi .Lclear_loop_fixed .Lclear_loop_end_fixed: // Load our float constants from the pool. movt r1, #0x32 // 0x00320000 = 50.0 in 16-bit fixed point ldr r5, .L.05.fix32 // 0x0ccccccc = 0.05 in 32-bit fixed point .Lprocess_loop_fixed: // Loop until the null terminator. // while (r2 = *input++) ldrb r2, [r0], #1 cbz r2, .Lprocess_loop_end_fixed // tolower(r2) - 'a' // // Specifically, we subtract 'a', and if the char was uppercase, // it would be negative, triggering the N flag, which is why we // check the mi condition in the following IT blocks. subs r2, #'a' it mi // if (isupper(r2)) addmi r2, #'a' - 'A' ldr r3, [sp, r2, lsl #3] // fixed point multiply: // x<fixA> = (y<fixB> * z<fixC>) >> (B + C - A) // tmp<fix16> = (stock_price<fix16> * 0.05<fix32>) >> 32 smmul r6, r1, r5 // r6 = stock_price * 0.05 ittee mi // if (isupper(r2)) { // Buy submi r3, r1 // profit[i] -= stock_price addmi r1, r6 // stock_price += stock_price * 0.05 // } else { // Sell addpl r3, r1 // profit[i] += stock_price subpl r1, r6 // stock_price -= stock_price * 0.05 // } endif str r3, [sp, r2, lsl #3] b .Lprocess_loop_fixed .Lprocess_loop_end_fixed: movs r6, #'A' .Lprint_loop_fixed: // Pop the result into d0 (also cleaning the stack) vpop {d0} // Convert from fix16 to double vcvt.f64.s32 d0, d0, #16 // Move the double result into r2 and r3. This is for the softfp ABI // which passes floating point values in registers. vmov r2, r3, d0 // Only check if the most signicant half of the double is zero. // Any non-zero double that is 0x00000000xxxxxxxx is denormal. cbz r3, .Lprint_loop_skip_fixed // Set up an AEABI call to printf. adr r0, .Lprintf_str_fixed // Instead of %c, store the char directly (that's why we need W+X) strb r6, [r0] bl printf .Lprint_loop_skip_fixed: // Loop from A-Z. adds r6, #1 cmp r6, #'Z' ble .Lprint_loop_fixed pop {r3-r7, pc} // 0.05 in fix32. .L.05.fix32: .word 0x0ccccccc // Our printf string. We replace the X when we use it. .Lprintf_str_fixed: .asciz "X%.2f" .section ".testsuite_unscored","ax",%progbits .macro $TEST str adr r0, 1f bl puts adr r0, 1f bl silly_stocks_fixed movs r0, #'\n' bl putchar b 2f .align 2 1: .asciz "\str" .align 2 2: .endm .align 2 .globl main .thumb_func main: push {r4, lr} $TEST "AABaBbba" $TEST "DGdg" $TEST "ADJdja" pop {r4, pc} ``` For the reference, here is the results for float vs fixed point at 6 digits of precision. ``` AABaBbba float: A:7.488484,B:2.474079, fixed: A:7.488434,B:2.474060, DGdg float: D:5.125000,G:-0.131250, fixed: D:5.124969,G:-0.131256, ADJdja float: A:2.237828,D:5.381250,J:-0.137812, fixed: A:2.237808,D:5.381226,J:-0.137817, ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=pairmap -F`, 80 bytes ``` $p=50;map{$k{uc$_}+=$q=95>ord?-$p:$p;$p-=$q/20}@F;pairmap{printf"$a:%.2f ",$b}%k ``` [Try it online!](https://tio.run/##LY1BC4IwGEDv/oqITyxKW8IObaxSxCDq2DlmZixNv@Y6iX@9ZdHpwePBw6uuqLWAghL@kNhB2b0ucO5nAp5iRdeNzjc@IAPkgP4gFyHptylHqfS3R61qU4xBMjcIi9F4Dlnvlpb/vOdxtxSTKbdRFMs4y6ST7PKbEyX7/C7fDRrV1K31jzQgSzLwoFrD2MmoSvwH1q/SDw "Perl 5 – Try It Online") [Answer] # Javascript (ES6, Node.js), 136 bytes ## Source ``` s=>(m=50,a={},[...s].map(p=>(u=p.toUpperCase(),n=p==u?1:-1,a[u]=(a[u]||0)-m*n,m*=1+n/20)),Object.keys(a).map(k=>a[k]=a[k].toFixed(2)),a) ``` ## Explanation ``` f=s=>( // (s)tring m=50, // stock value (m)oney a={}, // (a)ll people [...s].map( p=>( u=p.toUpperCase(), // (u)ppercase: used to group buys and sells for each person n=p==u?1:-1, // sig(n): 1 for buy, -1 for sell a[u]=(a[u]||0)-m*n, // adjust balance with stock value and sign m*=1+n/20 // adjust stock value ) ), Object.keys(a).map(k=>a[k]=a[k].toFixed(2)), // round profits a // return profits ) ``` ## Proof ``` f=s=>(m=50,a={},[...s].map(p=>(u=p.toUpperCase(),n=p==u?1:-1,a[u]=(a[u]||0)-m*n,m*=1+n/20)),Object.keys(a).map(k=>a[k]=a[k].toFixed(2)),a) const TESTS = [ ['AABaBbba',{A:'7.49',B:'2.47'}], ['DGdg',{D:'5.13',G:'-0.13'}], ['ADJdja',{A:'2.24',D:'5.38',J:'-0.14'}] ] TESTS.forEach(([input,expected])=>{ console.log(input); console.log(expected); console.log(f(input)) }); ``` [Answer] # Japt, ~~91~~ 84 bytes ``` A=[]J=50¡AhD=Xc %H(X<'_?[AgD ª0 -JJ*=1.05]:[AgD +JJ*=.95] g};A£X©[Y+I d X*L r /L]} f ``` Based on my JS answer. [Try it online!](http://ethproductions.github.io/japt?v=master&code=QT1bXUo9NTChQWhEPVhjICVIKFg8J18/W0FnRCCqMCAtSkoqPTEuMDVdOltBZ0QgK0pKKj0uOTVdIGd9O0GjWKlbWStJIGQgWCpMIHIgL0xdfSBm&input=IkFBQmFCYmJhIg==) [Answer] # [J](http://jsoftware.com/), 64 bytes ``` tolower(~.@[,.(0j2":_50*+/)/.)](]*1*/\@}:@,1+0.05*])_1+2*91>3&u: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/S/Jz8stTizTq9ByidfQ0DLKMlKziTQ20tPU19fU0YzVitQy19GMcaq0cdAy1DfQMTLViNeMNtY20LA3tjNVKrf5rcqUmZ@QrpCmoOzo6JTolJSWqg0XU1eESLu4p6RiCji5eKVlAtVz/AQ "J – Try It Online") ]
[Question] [ The cofactor matrix is the transpose of the [Adjugate Matrix](https://en.wikipedia.org/wiki/Adjugate_matrix). The elements of this matrix are the [cofactors](https://en.wikipedia.org/wiki/Minor_%28linear_algebra%29) of the original matrix. The cofactor [![enter image description here](https://i.stack.imgur.com/3QQ4e.png)](https://i.stack.imgur.com/3QQ4e.png) (i.e. the element of the cofactor matrix at row i and column j) is the determinant of the submatrix formed by deleting the ith row and jth column from the original matrix, multiplied by (-1)^(i+j). For example, for the matrix [![enter image description here](https://i.stack.imgur.com/BDLIM.png)](https://i.stack.imgur.com/BDLIM.png) The element of the cofactor matrix at row 1 and column 2 is: [![enter image description here](https://i.stack.imgur.com/t40WC.png)](https://i.stack.imgur.com/t40WC.png) You can find info on what the determinant of a matrix is and how to calculate them [here](https://en.wikipedia.org/wiki/Determinant). ### Challenge Your goal is to output the cofactor matrix of an input matrix. **Note**: Built-ins that evaluate cofactor matrices, or adjugate matrices, or determinants or anything similar are **allowed**. ### Input The matrix may be inputed as a command line argument, as a function parameter, in `STDIN` or in any way that is most appropriate for the language you use. The matrix will be formatted as a list of lists, each sublist corresponding to one row, which contains factors ordered from left to right. Rows are ordered from top to bottom in the list. For example, the matrix ``` a b c d ``` will be represented by `[[a,b],[c,d]]`. You may replace the square brackets and commas with something else if it fits your language and is sensible (e.g. `((a;b);(c;d))`) Matrices will **only contain integers (which can be negative)**. Matrices will **always be square** (i.e. same number of rows and columns). You may assume that the input will always be correct (i.e. no formatting problem, nothing other than integers, no empty matrix). ### Output The resulting cofactor matrix may be outputed to `STDOUT`, returned from a function, written to a file, or anything similar that naturally suits the language you use. The cofactor matrix must be formatted in the exact same way the input matrices are given, e.g. `[[d,-c],[-b,a]]`. If you read a string, then you must return/output a string in which the matrix is formatted exactly like in the input. If you use something like e.g. a list of lists as input, then you must return a list of lists too. ### Test cases * Input: `[[1]]` Output: `[[1]]` * Input: `[[1,2],[3,4]]` Output: `[[4,-3],[-2,1]]` * Input: `[[-3,2,-5],[-1,0,-2],[3,-4,1]]` Output: `[[-8,-5,4],[18,12,-6],[-4,-1,2]]` * Input: `[[3,-2,7,5,0],[1,-1,42,12,-10],[7,7,7,7,7],[1,2,3,4,5],[-3,14,-1,5,-9]]` Output: ``` [[9044,-13580,-9709,23982,-9737],[-1981,1330,3689,-3444,406],[14727,7113,2715,-9792,414],[-28448,-2674,-707,16989,14840],[-2149,2569,-2380,5649,-3689]] ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins. [Answer] # Matlab, ~~42~~ 33 bytes Using an anonymous function: ``` @(A)round(inv(A+eps)'*det(A+eps)) ``` Input and output are matrices (2D numeric arrays). `eps` is added in case the matrix is singular. It is "removed" using `round` (the true result is guaranteed to be an integer). Example: ``` >> @(A)round(inv(A+eps)'*det(A+eps)) ans = @(A)round(inv(A+eps)'*det(A+eps)) >> ans([-3,2,-5; -1,0,-2; 3,-4,1]) ans = -8 -5 4 18 12 -6 -4 -1 2 ``` Example with singular matrix: ``` >> @(A)round(inv(A+eps)'*det(A+eps)) ans = @(A)round(inv(A+eps)*det(A+eps)') >> ans([1,0 ; 0,0]) ans = 0 0 0 1 ``` Or [try it online](http://ideone.com/NoIUmO) in Octave. [Answer] # Mathematica, ~~27~~ 35 bytes ``` Thread[Det[#+x]Inverse[#+x]]/.x->0& ``` [Answer] # R, ~~121~~ 94 bytes ``` function(A)t(outer(1:(n=NROW(A)),1:n,Vectorize(function(i,j)(-1)^(i+j)*det(A[-i,-j,drop=F])))) ``` This is an absurdly long function that accepts an object of class `matrix` and returns another such object. To call it, assign it to a variable. Ungolfed: ``` cofactor <- function(A) { # Get the number of rows (and columns, since A is guaranteed to # be square) of the input matrix A n <- NROW(A) # Define a function that accepts two indices i,j and returns the # i,j cofactor C <- function(i, j) { # Since R loves to drop things into lower dimensions whenever # possible, ensure that the minor obtained by column deletion # is still a matrix object by adding the drop = FALSE option a <- A[-i, -j, drop = FALSE] (-1)^(i+j) * det(a) } # Obtain the adjugate matrix by vectorizing the function C over # the indices of A adj <- outer(1:n, 1:n, Vectorize(C)) # Transpose to obtain the cofactor matrix t(adj) } ``` [Answer] # [GAP](http://www.gap-system.org), 246 Bytes You can tell this is good coding by the triple nested for-loops. It's pretty straightforward. GAP doesn't really have the same tools to deal with matrices that other math oriented languages do. The only thing really used here is the built in determinant operator. ``` f:=function(M)local A,B,i,j,v;A:=StructuralCopy(M);if not Size(M)=1 then for i in [1..Size(M)] do for j in [1..Size(M)] do B:=StructuralCopy(M);for v in B do Remove(v,j);od;Remove(B,i);A[i][j]:= (-1)^(i+j)*DeterminantMat(B);od;od;fi;Print(A);end; ``` ungolfed: ``` f:=function(M) local A,B,i,j,v; A:=StructuralCopy(M); if not Size(M)=1 then for i in [1..Size(M)] do for j in [1..Size(M)] do B:=StructuralCopy(M); for v in B do Remove(v,j); od; Remove(B,i); A[i][j]:= (-1)^(i+j)*DeterminantMat(B); od; od; fi; Print(A); end; ``` [Answer] # J, 29 bytes ``` 3 :'<.0.5+|:(-/ .**%.)1e_9+y' ``` Same epsilon/inverse/determinant trick. From right to left: * `1e_9+` adds an epsilon, * `(-/ .**%.)` is *determinant* (`-/ .*`) times *inverse* (`%.`), * `|:` transposes, * `<.0.5+` rounds. [Answer] # [Verbosity v2](https://github.com/cairdcoinheringaahing/Verbosity-v2), 196 bytes ``` IncludeTypePackage<Matrix> IncludeTypePackage<OutputSystem> print=OutputSystem:NewOutput<DEFAULT> input=Matrix:Adjugate<ARGV0> input=Matrix:Transpose<input> OutputSystem:DisplayAsText<print;input> ``` [Try it online!](https://tio.run/##bY3LDoIwFET3/QqWsFN0haVJE9SY@IpW9xVuSBVL04fSr68GNmpcnpnJmQfoS2uE9WkIK1k2rgLmFex5eeM14A23WnQE/al2zipnj95YuBOktJA2/8yyLTwHxsV8QU9rRpCQb8wHaUarq6u5BUwPy/Pop2SaS6NaA7iPCfpSF8KohntqGHQW99@zYRdCiONxlCZRPImmSfIC "Verbosity v2 – Try It Online") NB: Doesn't currently work on TIO, awaiting a pull. Should work offline Takes input in the form `((a b)(c d))` to represent $$ \bigg[ \begin{matrix} a \: b \\ c \: d \end{matrix} \bigg] $$ Despite having a builtin for the adjugate, Verbosity's verbosity still cripples it. Fairly basic how it works, just transposes the adjugate of the input. ]
[Question] [ ### Definition A positive integer `n` is a [practical number](http://en.wikipedia.org/wiki/Practical_number) (OEIS sequence [A005153](http://oeis.org/A005153)) iff all smaller positive integers can be represented as sums of distinct divisors of `n`. For example, `18` is a practical number: its divisors are 1, 2, 3, 6, 9, and 18, and the other positive integers smaller than 18 can be formed as follows: ``` 4 = 1 + 3 5 = 2 + 3 7 = 1 + 6 8 = 2 + 6 10 = 1 + 9 11 = 2 + 9 12 = 3 + 9 = 1 + 2 + 9 = 1 + 2 + 3 + 6 13 = 1 + 3 + 9 14 = 2 + 3 + 9 15 = 6 + 9 16 = 1 + 6 + 9 17 = 2 + 6 + 9 ``` But `14` is not a practical number: its divisors are 1, 2, 7, and 14, and there's no subset of these which adds to 4, 5, 6, 11, 12, or 13. ### Challenge Write a program, function, or verb which takes as input a positive integer `x` and either returns or prints the xth practical number, indexed from 1 for consistency with OEIS. Your code must be sufficiently efficient that it can handle inputs up to 250000 in less than two minutes on a reasonable desktop computer. (NB my reference implementation in Java manages 250000 in less than 0.5 seconds, and my reference implementation in Python manages it in 12 seconds). ### Test cases ``` Input Expected output 1 1 8 18 1000 6500 250000 2764000 1000000 12214770 3000000 39258256 ``` [Answer] # Mathematica, ~~126~~ 121 chars Thanks to belisarius. Using the formula on wikipedia. ``` f=(i=j=1;While[j<#,If[And@@Thread[#[[;;,1]]<2+Most@DivisorSum[FoldList[#Power@@#2&,1,#],#&]&@FactorInteger@++i],j++]];i)& ``` Examples: ``` f[1] ``` > > 1 > > > ``` f[8] ``` > > 18 > > > ``` f[250000] ``` > > 2764000 > > > It took 70s to compute `f[250000]` on my computer. [Answer] # J (99 chars) ``` f=:3 :0 'n c'=.0 1 while.c<y do. 'p e'=.__ q:n=.n+2 c=.c+*/(}.p)<:}:1+*/\(<:p^e+1)%<:p end. n+n=0 ) ``` Since the problem statement asks for a "program, function *or verb*", someone had to make a J submission. J people will notice I didn't really golf (!) or optimize this. Like the other entries, I used Stewart's theorem, mentioned at the OEIS link, to test whether each even number is practical or not. I don't have ready access to a "reasonable desktop computer" with J installed. On my six year old netbook `f 250000` computes in 120.6 seconds, which is not quite under two minutes, but presumably on any slightly more reasonable computer this finishes in time. [Answer] # Haskell - 329 ``` s 1=[] s n=p:(s$div n p)where d=dropWhile((/=0).mod n)[2..ceiling$sqrt$fromIntegral n];p=if null d then n else head d u=foldr(\v l@((n,c):q)->if v==n then(n,c+1):q else(v,1):l)[(0,1)] i z=(z<2)||(head w==2)&&(and$zipWith(\(n,_)p->n-1<=p)(tail n)$scanl1(*)$map(\(n,c)->(n*n^c-1)`div`(n-1))n)where w=s z;n=u w f=((filter i[0..])!!) ``` Examples: ``` > f 1 1 > f 13 32 > f 1000 6500 ``` Here's a small testing suite (prepend to the above): ``` import Data.Time.Clock import System.IO test x = do start <- getCurrentTime putStr $ (show x) ++ " -> " ++ (show $ f x) finish <- getCurrentTime putStrLn $ " [" ++ (show $ diffUTCTime finish start) ++ "]" main = do hSetBuffering stdout NoBuffering mapM_ test [1, 8, 1000, 250000, 1000000, 3000000] ``` Test results after being compiled with `ghc -O3`: ``` 1 -> 1 [0.000071s] 8 -> 18 [0.000047s] 1000 -> 6500 [0.010045s] 250000 -> 2764000 [29.084049s] 1000000 -> 12214770 [201.374324s] 3000000 -> 39258256 [986.885397s] ``` [Answer] # Javascript, ~~306 307~~ 282B ``` function y(r){for(n=r-1,k=1;n;k++)if(p=[],e=[],c=0,P=s=1,!((x=k)%2|1==x)){while(x>1){for(f=x,j=2;j<=Math.sqrt(f);j++)if(f%j==0){f=j;break}f!=p[c-1]?(p.push(f),e.push(2),c++):e[c-1]++,x/=f}for(i=0;c>i;i++){if(p[i]>P+1){s=0;break}P*=(Math.pow(p[i],e[i])-1)/(p[i]-1)}s&&n--}return k-1} ``` 250k in approx. 6s on my laptop. Commented un-golfed code: <http://jsfiddle.net/82xb9/3/> now with better sigma-testing and a better if condition (thank you comments) Pre-edit versions: <http://jsfiddle.net/82xb9/> <http://jsfiddle.net/82xb9/1/> ]
[Question] [ The book Green Eggs and Ham by Dr. Seuss is famous for only having 50 different words in the entire story of the book. Your task is to create a sequence of keystrokes that will result in the entire text of Green Eggs and Ham when applied to an empty file in the [vim](http://www.vim.org/) text editor, starting in normal mode with all default settings. Your keystrokes must not load any other files as part of their operation - all text must be generated within the editor itself. Your final buffer must look exactly like [this file](http://pastebin.com/MRRpGXYx), although it can remain in whichever mode it ends up being in (you don't have to have a final `<Esc>` to return it to normal mode). Chorded keystrokes like `<C-o>` or using Shift to type a capital letter count as a single keystroke. The sequence of the fewest keystrokes to achieve this goal wins. [Answer] ## 1864 keystrokes Somebody could probably write some code that produces a more optimal solution, but this beats the reference case for now. This is a damn mess, and I am ashamed I did it by hand. First, we enter insert mode. ``` i ``` Then all this ``` That ]! That ]! IDNlike that ]! Do Y like$? |;]. IDNlike$. WPY LTB or tB? IZ LTB or tB. IZ LTanywB. IDNlike$. |;]. WPY LTin a h@? WPY LT=a m@? |in a h@. |=a m@. |B or tB. |. IDNlike$. |;]. WPY ETin a box? WPY ET=a fox? Not_a box. Not =a fox. Not_a h@. Not =a m@. IZ ETB or tB. IZ ETanywB. IZ eat$. |;]. WPY? CPY? In a car? Eat them! Eat them! B they are. IZ,X,_a car. You may LT. You will see. You may LTin a tree! IZ,X_a tree. Not_a car! You let me be. |in a box. |=a fox. |in a h@. |=a m@. |B or tB. |. IDNlike$. |;]. AQ! AQ! AQ! AQ! CPY;wPY;on aQ? Not_aQ! Not_a tree! Not_a car! Sam! Let me be! IZ,X,_a box. IX,Z;=a fox. :=a m@. :in a h@. :B or tB. :anywB. IDNlike$. |;]. Say! In +? B_+! WPY;cPY,_+? IZ,X,_+. WPY;cPY,_the rain? IZ,X,_the rain. Not_+. Not on aQ. Not_a car. Not_a tree. |;Sam;Y see. Not_a h@. Not_a box. Not =a m@. Not =a fox. :B or tB. |! You do not like$? |;]. CPY;wPY;=a g^? IZ,X;=a g^! WPY;cPY;on a b^? IX,Z;on a b^. IWN,WN;=a g^. :in the rain. :on aQ. Not_+! Not_a tree! Not_a car! You let me be! |in a box. |=a fox. :in a h@. |=a m@. |B or tB. |! IDNlike$! |;]. You do not LT. So Y say. Try them! Try them! & Y may. Try them and Y may;I say. Sam! If Y will let me be, I will try them. You will see. Say! I like$! I do! I LT;]! & I wPETin a b^. & I wPET=a g^. !ETin the rain. &_+. & on aQ. &_a car. &_a tree. They are so good;so good;Y see! So I will ETin a box. !ET=a fox. !ETin a h@. !ET=a m@. !ETB and tB. Say! I will ETanywB! I do so like$! Thank Y! Thank Y;]! ``` Hit escape to enter command mode. And unravel the compressed stuff. Order matters, as I've compressed some compressed text. ``` <Esc> %s/|/|anywB/g %s/:/IWNET/g %s/|/IDNLT/g %s/Z/ wPnot/g %s/X/ cPnot/g %s/&/And/g %s/+/the dark/g %s/@/ouse/g %s/^/oat/g %s/Y/you/g %s/IDN/I do not /g %s/LT/like them /g %s/]/Sam-I-am/g %s/ET/eat them /g %s/WN/ will not/g %s/$/ green eggs and ham/g %s/P/ould /g %s/!/And I will /g %s/Q/ train/g %s/B/here/g %s/_/ in /g %s/=/with /g %s/;/, /g ``` [Answer] # 3,470 keystrokes ``` i<entire text of file> ``` The text file is 3,469 characters long, so typing "i" to put it in insert mode and typing out each character individually will take 3,470 keystrokes. ]
[Question] [ There is a well-known theorem that [any permutation can be decomposed into a set of cycles](http://en.wikipedia.org/wiki/Permutation#Notation). Your job is to write the shortest possible program to do so. ## Input: Two lines. The first contains a number `N`, the second contains `N` distinct integers in the range `[0,N-1]` separated by spaces. These integers represent a permutation of `N` elements. ## Output: One line for each cycle in the permutation. Each line should be a space-separated list of integers in cycle order. Cycles can be output in any order, and each cycle can be output starting at any position. ## Example 1: ``` 8 2 3 4 5 6 7 0 1 ``` This input encodes the permutation 0->2, 1->3, 2->4, 3->5, 4->6, 5->7, 6->0, 7->1. This decomposes into cycles like this: ``` 0 2 4 6 1 3 5 7 ``` An equally valid output would be ``` 5 7 1 3 2 4 6 0 ``` ## Example 2: ``` 8 0 1 3 4 5 6 7 2 ``` valid output: ``` 0 1 4 5 6 7 2 3 ``` [Answer] **C ~~145~~ 134 Characters** ``` N,A[999],i,j,f;main(){gets(&i);for(;~scanf("%d",A+N);)N++;for(;j<N;j++,f=f&&!puts(""))while(i=A[j]+1)f=printf("%d ",j),A[j]=-1,j=--i;} ``` <http://www.ideone.com/BrWJT> [Answer] # Python 131 chars ``` input();d=dict((i,int(x))for i,x in enumerate(raw_input().split())) while d: x=list(d)[0] while x in d:print x,;x=d.pop(x) print ``` the ending newline is not needed [Answer] # J (between 2 and 32) I'm not quite clear on i/o format, but I think `C.` would do, if the following output would be accepted: ``` C. 0 1 3 4 5 6 7 2 ┌─┬─┬───────────┐ │0│1│7 2 3 4 5 6│ └─┴─┴───────────┘ ``` (It looks better in the J terminal.) If it needs to be a named function that complies to my best understanding of the i/o format, that'd be 32 characters, of which 30 are for output format conversion... ``` g=:>@(":L:0)@(C.@".@}.~>:@i.&LF) ``` In action: ``` g=:>@(":L:0)@(C.@".@}.~>:@i.&LF) g >@(":L:0)@(C.@".@}.~ >:@i.&(10{a.)) t 8 0 1 3 4 5 6 7 2 g t 0 1 7 2 3 4 5 6 ``` ## Explanation: J is executed from right to left (practically). `@` is a 'function' (not technically a function, but that's close enough) to combine functions. * `i.&LF` - find the first index of `LF`, a predefined variable containing ASCII character number 10, the line feed. * `>:` - find the first `LF`, and increment it's index by one. We don't actually want the linefeed, we want the array that follows it. * `}.~` - Selects the part of the input that we want. * `".` - Since the input format is valid J (*\*\õ/\**) we can just use the `eval` verb (I know it's not actually called `eval`.) to turn it into an array * `C.` - Pure magic. I really have no idea what this does, but it seems to work! * `":L:0` - Representation. Turns the output of `C.` into a boxed sequence of strings * `>` - Unbox. The actual output is actually a string array (there are spaces behind the first to numbers of the example). [Answer] ## Haskell, 131 characters ``` n%l|all(>n)l=(n:l>>=(++" ").show)++"\n"|1<3="" c(_:a)=a>>=(\n->n%(takeWhile(/=n)$iterate(a!!)$a!!n)) main=interact$c.map read.words ``` * Edit: (135 -> 131) `>=` became `>`, eliminated two `tail` calls though pattern matching & pre-application of `a!!`. [Answer] # C (sort of), 139 chars ``` n,j,t,a[999];main(){scanf("%*i");for(;scanf("%i",a+n)>0;)n++;while(n--)if(a[j=n]+1){for(;t=a[j]+1;a[j]=-1,j=t)printf("%i ",--t);puts("");}} ``` The final newline is not included. I said "sort-of" because AFAIK for example 1. it's not legal to omit declaration for variadic functions (ANSI C89: 3.3.2.2) 2. `int` cannot be omitted for variable declaration (I didn't find where it's said it can be omitted and implicit type declaration is only described for functions. The grammar specification in the standard is basically useless as accepts much more than valid C declarations, for example `double double void volatile x;`) 3. a newline at the end of a non-empty source file is mandatory (ANSI C89: A.6.2) but the above code compiled with `gcc -ocycles cycles.c` apparently works anyway. [Answer] # Clojure, 145 ``` (let[v(vec(repeatedly(read)read))](loop[a(set v)b 0](cond(a(v b))(do(print" "b)(recur(disj a(v b))(v b)))(seq a)(do(prn)(recur a(first a)))1""))) ``` Somewhat ungolfed, and broken out into a function (input must be a vector, which is what (vec(repeatedly(read)read)) from above produces): ``` (defn p [v] (loop [a (set v) b 0] (cond (a (v b)) (do (print" "b) (recur (disj a (v b)) (v b))) (seq a) (do (prn) (recur a (first a))) 1 ""))) ``` (Wow, just noticed this challenge is over 3 year old. Oh well, had fun doing it anyways!) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` ḲVJ’,Ɗy¥Ƭ`ZṢ€Q€QG ``` [Try it online!](https://tio.run/##y0rNyan8///hjk1hXo8aZuoc66o8tPTYmoSohzsXPWpaEwjC7v//W/w3UjBWMFEwVTBTMFcwUDAEAA "Jelly – Try It Online") or with modern I/O standards, [14 bytes](https://tio.run/##y0rNyan8/9/rUcNMnWNdlYeWHluTEPVw56JHTWsCQfj/4fajkx7unKEZ@f9/tJGOgrGOgomOgqmOgpmOgrmOgoGOgmGsjkI0iMaQNIoFAA). Takes `N` on STDIN and the list of numbers as the first command line argument The last 5 bytes feel far too long for such a simple task ## How it works ``` ḲVJ’,Ɗy¥Ƭ`ZṢ€Q€QG - Main link. Takes a string S on the left Ḳ - Split S on spaces V - Evaluate each element. Call this list of integer L ¥ - Group the previous 2 links into a dyad f(A, L): Ɗ - Group the previous 3 links into a monad g(A): J - Length range of A ’ - Decrement to use 0 indexing , - Pair with A y - Transliterate L using the mapping from g(A) Ƭ - While results are unique, repeatedly apply f(A, L), ` - starting with f(L, L) Z - Transpose Ṣ€ - Sort each subarray Q€ - Deduplicate each subarray Q - Deduplicate the whole array G - Join each subarray with spaces and the subarrays by newlines ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 110 bytes ``` (n,N=[])=>n.flatMap(e=>~N.indexOf(e)?[]:[(U=(T,P=T[T.length-1])=>N.push(P)&&(e==n[P]?T:U([...T,n[P]])))([e])]) ``` [Try it online!](https://tio.run/##dYy9CoMwFEb3PojcC9fQ2j8Qok9Q6xCnkEE0UUtIpNrSqa@e6lYKHb/DOd@tftZTcx/GOXa@1cHwAI4KLhXyzDFj6/lSj6B59i7Y4Fr9uhrQmEuVSqg4CCq5kIJZ7bq5j3drVrDxMfVQYhQtIXeyVLlIK5CMMUHrVIgIUitUGBrvJm81s74DAzKhPR3oSCc605aWP9z8GAv9cpI/xsrDBw "JavaScript (Node.js) – Try It Online") This is the version which takes in a list of integers and outputs a 2d list, where each sublist is a cycle. [This version](https://tio.run/##jc2/CsIwEMfx3adwkjs4D/8rQvQJrB3iFIINNdVKSIqt4uSr16qDdXO7H3w/3NncTJle8qLq@3CwdSZq2JMhLwyXhcurpJtQJJRGsfKcOVNtTAFWrB4R5/5g79sMLK6VXirYCZAUC6kkO@uP1ak/fLGIi2t5ghh7vQYKr2K9lssdKGaW9JoaEUFZjZrPIffNS/wcnaROgy@Ds@zCETJYkBrRmCY0pRnNaUDDL8FOu/1db9nULTv6V44/st3XTw) takes in the number of numbers (not used). The numbers are taken as a space-separated string, and the function returns a string formatted as described in the question. It is 141 bytes long. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 59 bytes ``` x=>x.flatMap(g=a=>1/x[a]?[[a,...g(x[a],x[a]=g)[0]||[]]]:[]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q5CLy0nscQ3sUAj3TbR1s5QvyI6MdY@OjpRR09PL10DxNMBEbbpmtEGsTU10bGxsVbRsZr/k/PzivNzUvVy8tM10jSijXSMdUx0THXMdMx1DHQMYzU1udBUAEWR1BjhUAES/w8A "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 60 bytes ``` x=>x.flatMap(g=a=>[1/x[a]?[a,...g(x[a],delete x[a])[0]]:[]]) ``` [Try it online!](https://tio.run/##dcpNCsIwEIbhvadwmcAY2/pTEFJP4AmGWQztJCihKTZIbh/NTgR33/fyPPjF6/i8L2k3x0mKsyXbIRsXON14Ud6yHbDdZ2S6IoMxxqt6YJIgSbZ1a2yILkikyxjnNQYxIXrlFHZwgCOc4Aw9NNCS1psf8alfpvsjai9v "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes ``` Needs["Combinatorica`"];Combinatorica`ToCycles ``` Complete code with test cases is: ``` Needs["Combinatorica`"]; Combinatorica`ToCycles /@ { {3, 4, 5, 6, 7, 8, 1, 2}, {1, 2, 4, 5, 6, 7, 8, 3}, {1, 2, 3}, {1 , 2 , 4 , 5 , 6, 7 , 8, 3} } // Grid ``` $$ \left( \begin{array}{ccc} \{3,5,7,1\} & \{4,6,8,2\} & \text{Null} \\ \{1\} & \{2\} & \{4,5,6,7,8,3\} \\ \{1\} & \{2\} & \{3\} \\ \{1\} & \{2\} & \{4,5,6,7,8,3\} \\ \end{array} \right) $$ [Answer] Python3.8, 129 chars ``` def v(i):_=a[i];a[i]=-1;return~_ and[i]+v(_)or[] input() for i in range(len(a:=[*map(int,input().split())])):~a[i]and print(v(i)) ``` [Answer] # MATL, 20 bytes ``` :wQy"yy)]v"@quS!]Xhu ``` [Try it out!](https://matl.suever.net/?code=%3AwQy%22yy%29%5Dv%22%40quS%21%5DXhu&inputs=8%0A%5B2+3+4+5+6+7+0+1%5D&version=22.4.0) Takes the liberty of assuming the second input is inside a pair of square brackets, but otherwise sticks to the requirements (spending 2 bytes on the 0-indexing for example). Works pretty similar to caird coinheringaahing's Jelly answer. ]
[Question] [ There is a game called *Get Home* that is played on the a chess board. In this game there is a single piece that is moved by both players in turns. There are some rules to how the piece can be moved. On a turn a player must make one of the following moves for positive **n**. * **n** spaces up * **n** spaces to the left * **n** spaces up and to the left (a diagonal) The player who moves the piece into the top left corner of the board wins the game. Now we will define the concept of a losing square. In [this video](https://www.youtube.com/watch?v=pzlpi7lJi4k) (from where I got the idea) a losing square is defined as a square on which, any player starting their turn will be forced to make a move allowing their opponent to force a win. The simplest example of a losing square would be the square at (1,2). A piece at (1,2) can move to any of the following places. [![Illustration](https://i.stack.imgur.com/M00pY.png)](https://i.stack.imgur.com/M00pY.png) All of which have a direct path to victory for the next player. It also follows that any square that has a one move path to a losing square allows the player starting on that square to force a win. This means that any square that is not one move away from a losing square is also a losing square. This brings us to this rather neat definition of a losing square: A losing square is a square from which no move can arrive on another losing square and (0,0) is a losing square. # Task Given the coordinates of a square on an arbitrarily sized chess board determine if it is a losing square. Output two values one for losing squares and one for others. 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 all the losing squares on a regular 8 by 8 chess board (marked with 0). ``` 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 ``` Here is an image of a 100 by 100 board with losing squares marked in black (each square is 2 pixels by 2 pixels). [![100 by 100 board](https://i.stack.imgur.com/9o8MP.png)](https://i.stack.imgur.com/9o8MP.png) [Answer] # [Python 3](https://docs.python.org/3/), 112 50 46 42 bytes -4 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)! -2 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)! ``` lambda r,c:abs(r-c)*(3+5**.5)//2==max(r,c) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFIJ9kqMalYo0g3WVNLw1jbVEtLz1RTX9/I1jY3sUIDKK35Py2/SKFCITNPoSgxLz1Vw9JM04pLASRYiS6oUFCUmVeioaTwaFqHUnSaRoVOpWasTmpeiq2SgpImF1Ra8z8A "Python 3 – Try It Online") Based on the formula for cold positions in Wythoff's game and making some modifications in order to produce an explicit formula. Explanation inbound once I actually finish a proper methodology for the derivation of the formula. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ạ/רpḞ⁼Ṃ ``` **[Try it online!](https://tio.run/##ASMA3P9qZWxsef//4bqhL8OXw5hw4bie4oG84bmC////WzMxLDE5XQ "Jelly – Try It Online")**, or see the top-left 60 by 60 as a [grid](https://tio.run/##ATYAyf9qZWxsef//4bqhL8OXw5hw4bie4oG84bmC/zYwO8O@NjDigJnDh@KCrOKCrOG7i@KBviouR/8 "Jelly – Try It Online"). ### How? A cold position in [Wythoff's game](https://en.wikipedia.org/wiki/Wythoff%27s_game) is a losing position. The coordinates `[n,m]` give a cold position when `n = floor(kφ) = floor(mφ) - m` or `m = floor(kφφ) = ceil(nφ) = n + k` for some natural number, `k`, and the golden ratio, `φ`. The former holds when `n` is less than `m`; the latter when `m` is less than `n` (both holding at `0,0`). `k` is thus the absolute difference between `n` and `m` and if `floor(abs(n-m)φ)=min(n,m)` the condition is met. ``` ạ/רpḞ⁼Ṃ - Link: list, c ([n,m]) / - reduce c by: ạ - absolute difference = abs(n-m) Øp - golden ratio yield × - multiply Ḟ - floor Ṃ - minimum of c = min(n,m) ⁼ - equal? ``` [Answer] ## JavaScript (ES6), 64 bytes ``` f=(x,y,p=5**.5/2+.5)=>x<y?f(y,x):y/p%p<1&(y/p%p-x*p%++p)**2<1e-9 ``` I see now that this is not the best technique, but I had to come up with it myself because I lost internet shortly after loading this page. (Would've posted a while ago if not for these internet issues...) In a perfect world, float precision wouldn't be an issue and I could save 9 bytes: ``` f=(x,y,p=5**.5/2+.5)=>x<y?f(y,x):y/p%p<1&y/p%p==x*p%++p ``` 6 more bytes could be saved if JS supported Python's comparison chaining: ``` f=(x,y,p=5**.5/2+.5)=>x<y?f(y,x):y/p%p==x*p%++p<1 ``` [Answer] # Pyth, 39 Bytes ``` =SQL?!b0-byytb;q@myd+0.fqyZytZ@Q1)-F_Qh ``` I wrote this with a named function (ew), and was extremely lazy with golfing. Planning to golf off quite a number of bytes later tonight [Try it online, with my own generated tests, meant to alternate True / False](https://pyth.herokuapp.com/?code=%3DSQL%3F%21b0-byytb%3Bq%40myd%2B0.fqyZytZ%40Q1%29-F_Qh&input=%5B1%2C3%5D&test_suite=1&test_suite_input=%5B0%2C0%5D%0A%5B1%2C0%5D%0A%5B1%2C2%5D%0A%5B2%2C2%5D%0A%5B2%2C1%5D%0A%5B3%2C1%5D%0A%5B3%2C5%5D%0A%5B4%2C5%5D%0A%5B4%2C7%5D%0A%5B5%2C7%5D%0A%5B5%2C3%5D%0A%5B6%2C3%5D%0A%5B6%2C10%5D%0A%5B7%2C10%5D%0A%5B7%2C4%5D&debug=1) Explanation: Diagonals of the solution matrix have a losing square according to the sequence of repeated numbers in [OEIS A005206](https://oeis.org/A005206). From `L` through `;` is pretty straightforward polish notation to define `y(b)=b-y(y(b-1))`. The rest of the explanation follows ``` =SQL?!b0-byytb;q@myd+0.fqyZytZ@Q1)-F_Qh Full program, take stdin as [x, y], output True or False to stdout =SQ Sort input L?!b0-byytb; Named lambda as explained above +0.f Make sequence of first max(x, y) numbers, starting with 0, qy y For which are equal Z tZ each element and the previous are equal myd Map this sequence to the y(index), not just index numbers q Check if are equal @ )-F_Q the x-yth element of sequence (x-y represents which diagonal) h(Q) and the lower of [x,y] (Q is added by the interpreter to fix arity issues ``` [Answer] ## Batch, 204 bytes ``` @if %1 lss %2 %0 %2 %1 @if %1==0 exit/b0 @set/au=l=i=0 :g @set/au+=2+i%%2,l+=1+i%%2 @if %1==%n% if %2==%m% exit/b0 @if %1 leq %n% exit/b1 :l @set/a"k=3*i^2*i^i,i+=1 @if %k%==0 goto g @goto l ``` Returns via exit code. Explanation: Since Batch only has integer arithmetic I had to devise a purely arithmetical solution. Excluding the `0,0` entry, the pairs of losing square coordinates follow the following rule: if the next `11`-free binary number is even then add `3,2` otherwise add `2,1`. A test for a `11`-free binary number is if there are no carries when it is multiplied by three, in other words that `(i*2)+i==(i*2)^i`. Here are the first few `11`-free binary numbers and their coordinates: ``` 0 2,1 + 3,2 = 5,3 1 5,3 + 2,1 = 7,4 10 7,4 + 3,2 = 10,6 100 10,6 + 3,2 = 13,8 101 13,8 + 2,1 = 15,9 1000 15,9 + 3,2 = 18,11 1001 18,11 + 2,1 = 20,12 1010 20,12 + 3,2 = 23,14 ``` etc. Mysteriously this rule suffices to make the sequences complementary. It then remains to compute the sequence until it reaches the larger coordinate, at which point we can determine whether the square is losing. ]
[Question] [ Given an input of a list of days of the week, output the shortest sorted representation of the list. The format of the input is a string consisting of one or more of the two-character substrings `Su` (Sunday), `Mo` (Monday), `Tu` (etc.), `We`, `Th`, `Fr`, and `Sa`. The input may not necessarily be given in sorted order. To convert the input to the output format, * Sort the input by day of week, starting from Sunday (ex. `ThMoSaSuFrTuWe` -> `SuMoTuWeThFrSa`). * Reduce the abbreviations down to one letter *if it leaves no ambiguity*. For example, `SuMoTuWe` should become `SMTW` because the first S couldn't possible be Saturday, as that would make the output unsorted (same for the T). However, `ThFrSa` should become `ThFS`, as both Tuesday and Thursday come before Friday and reducing it down to `TFS` would create ambiguity. * If the output is now `MTWTF`, output `D` instead (which stands for "week**day**s"). Similarly, `SS` should become `E` for week**end**. Finally, `SMTWTFS` should become `A` for **all** days. The input and output must both be a single string. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. Test cases: ``` In Out | In Out -----------------------|-------------------- SuTu STu | SuTuWe STW SuTuSa STuS | SuWeTh SWT TuThSa TTS | TuThSu STT Su Su | Sa Sa WeTh WT | FrTh ThF WeTu TW | FrTu TuF FrWeMo MWF | SaWeSu SWS ThTu TT | We W ThTuMoFrWe D | SaSu E SuMoWeTuThFr SMTWTF | ThMoSaSuFrTuWe A ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 152 88 Massively golfed with @Martin's and @randomra's help! Thanks both of you! ``` ^ SuMoTuWeThFrSa ([A-Z].)(?!.*\1) T`l``Su\B|\BSa|o|r|u?We.?.?|uTh ^MTWTF$ D SS E .{7} A ``` [Try it online.](http://retina.tryitonline.net/#code=bWBeClN1TW9UdVdlVGhGclNhCihbQS1aXS4pKD8hLipcMSkKClRgbGBgU3VcQnxcQlNhfG98cnx1P1dlLj8uP3x1VGgKbWBeTVRXVEYkCkQKU1MKRQouezd9CkE&input=U3VUdQpTdVR1U2EKVHVUaFNhClN1CldlVGgKV2VUdQpGcldlTW8KVGhUdQpUaFR1TW9GcldlClN1TW9XZVR1VGhGcgpTdVR1V2UKU3VXZVRoClR1VGhTdQpTYQpGclRoCkZyVHUKU2FXZVN1CldlClNhU3UKVGhNb1NhU3VGclR1V2U) A couple of the lines start with `m`` with this online interpreter link. This is so the program works with multiple input lines (to run all tests in one shot). However, multiple input lines is not a requirement, so these are not included above or in my score. [Answer] # JavaScript (ES7), ~~187~~ ~~178~~ ~~168~~ ~~157~~ 143 bytes ``` x=>({SMTWTFS:'A',SS:'E',MTWTF:'D'}[x=[for(a of'Su M Tu W Th F Sa'.split` `)if(x.match(a))x.match({S:/.../,T:/W|T.*T/}[b=a[0]])?b:a].join``]||x) ``` The regex tests helped make quick work of the special day rules, and while less than ideal, the object map does it's work. I'm certain I can squeeze a few more out of this though. [Answer] # Python 3, 321 Bytes ``` def w(n,a=lambda b,c,d:b.replace(c[0],d).replace(c[1],d)):d=''.join([[o[0],o][o[0]in'ST']for o in['Su','Mo','Tu','We','Th','Fr','Sa']if o in[n[i:i+2]for i in range(0,len(n),2)]]);d=[d,a(d,['Tu','Th'],'T')][('W'in d)+('TuT'in d)];l=len(d);d=[d,a(d,['Su','Sa'],'S')][l>2];return[[[d,'A'][l>8],'E'][d=='SS'],'D'][d=='MTWTF'] ``` [Test on ideone](http://ideone.com/fbkYWO) [Answer] # JavaScript (ES6), 197 bytes ``` s=>eval(`n=0;d="SuMoTuWeThFrSa";s.match(/../g).map(t=>n|=1<<d.search(t)/2);o="";for(i=0;i<7;i++)n&1<<i?o+=d.substr(i*2,n<2|n==64|(!(n&8|(n&20)>19)&&i==2|i==4)?2:1):0;n-127?n-62?n-65?o:"E":"D":"A"`) ``` ## Explanation Encodes each day as a bit and stores the input as a number `n`. Bit 0 = Sunday ... bit 6 = Saturday. This allows the ambiguity rule checking code to be a lot shorter due to the bit-wise operations and being able to compare the entire combination with a number that is always less than 128. ``` s=> eval(` // eval enables the for loop without {} or return n=0; // n = input encoded as a number d="SuMoTuWeThFrSa"; // d = day strings s.match(/../g).map(t=> // for each day string t in the input n|=1<<d.search(t)/2 // set the bit in n that corresponds to the day ); o=""; // o = output string for(i=0;i<7;i++) // for each day i from Sunday to Monday n&1<<i? // if the day was in the input o+=d.substr(i*2, // add the day string to the output n<2 // Sunday by itself is ambiguous |n==64 // Saturday by itself is ambiguous |(!(n&8 // Without Wednesday... |(n&20)>19 // ...or both Tuesday and Thursday, )&&i==2|i==4) // ...Tuesday or Thursday are ambiguous ?2:1 // 2 characters if ambiguous, else 1 ) :0; n-127? // n == 127 = All days (A) n-62? // n == 62 = All week days (D) n-65? // n == 65 = All weekend days (E) o // else output the constructed string :"E" :"D" :"A" `) ``` ## Test ``` var solution = s=>eval(`n=0;d="SuMoTuWeThFrSa";s.match(/../g).map(t=>n|=1<<d.search(t)/2);o="";for(i=0;i<7;i++)n&1<<i?o+=d.substr(i*2,n<2|n==64|(!(n&8|(n&20)>19)&&i==2|i==4)?2:1):0;n-127?n-62?n-65?o:"E":"D":"A"`) ``` ``` <input type="text" id="input" value="FrTh" /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` ]
[Question] [ You should write a program or function which receives the volume of a bowl and the volume of the water in it as input and outputs or returns an ASCII representation of a bowl with water in it with the desired volumes. A bowl has the following structure: ``` \ / \___/ ``` The bowl has at least one `_` character. The count of `\`'s and `/`'s are also positive and they are equal due to symmetry. The volume of the bowl is the total number of `_` and `space` characters between the `\`'s and `/`'s plus one for every pair of `\` and `/`. This means the above bowl has the volume of `10`: ``` \ / => xxxxx x (the last one is for the \/ pair) \___/ xxx x (the last one is for the \/ pair) ``` Note that two different bowl could have the same volume. E.g. both the following bowls have a volume of 18: ``` \ / \ / \ / \___/ \_______/ ``` We can pour some water into the bowl. The water is represented as a row of `~` characters instead of spaces inside the bowl. The bottom row has no spaces so it can not contain the `~`'s. This means our example can be filled with water in only one way: ``` \~~~~~/ \___/ ``` Other bowls could be filled in multiple ways: ``` \~~~~~/ \ / \ / \~~~/ \_/ \_/ ``` The volume of the water in a bowl is the volume of the bowl rows **below** the `~` characters. The above examples have water volumes of `4, 6 and 2` respectively. ## Input * Two positive integers, the volume of the bowl and the volume of the water. * You can choose the order of the two numbers. * The two integer can be inputted in any common list format (list, tuple, array, etc.) or as two separate integers. * At least one valid bowl-water configuration is guaranteed for the input values. ## Output * The ASCII representation of a bowl with water where the bowl and water volumes match the input. * If you choose to return the result instead of printing, it should be returned as single string (or your language's closest alternative). * Any trailing whitespace is allowed. * No unnecessary leading whitespace is allowed. * If there are multiple correct configurations you are free to choose which one you output but you can only output one of them. ## Examples Each input integer pair is followed by its one or more possible outputs. ``` 6 2 \~~~/ \_/ 10 4 \~~~~~/ \___/ 24 8 \ / \~~~~~~/ \ / \__/ 42 12 //either of the two output is correct \ / \ / \~~~~~~~/ \ / \ / \_/ \ / \~~~~~~~~~~~~~/ \___________/ 90 68 \~~~~~~~~~~~~~~~~~~~~~/ \ / \ / \ / \_____________/ 102 42 \ / \ / \~~~~~~~~~~~~~~~~~/ \ / \ / \___________/ ``` This is code golf so the shortest entry wins. [Answer] # CJam, ~~72~~ ~~70~~ 69 bytes ``` q~:QW=3m*{:,2ff*),)ff+}%{::)1fbQ=}=~W%ee_,S*W'_t@,~'~t.{S\+.*"\/".+N} ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%3AQW%3D3m*%7B%3A%2C2ff*)%2C)ff%2B%7D%25%7B%3A%3A)1fbQ%3D%7D%3D~W%25ee_%2CS*W'_t%40%2C~'~t.%7BS%5C%2B.*%22%5C%2F%22.%2BN%7D&input=%5B8%2024%5D). Run time and memory usage are **O(scary)**, so the last three test cases should be verified using the Java interpreter (and extra heap space). ### Example run ``` $ time java -Xmx4G -jar cjam-0.6.5.jar bowl.cjam <<< '[42 102]' \ / \ / \~~~~~~~~~~~~~~~~~/ \ / \ / \___________/ real 0m40.669s user 3m13.100s sys 0m11.690s ``` ### How it works ``` q~:Q e# Read from STIDN, evaluate and save the result in Q. W= e# Select the last element of Q (bowl volume B). 3m* e# Push all vectors of {0,...,B-1} × {0,...,B-1} x {0,...,B-1}. { e# For each vector [X Y Z]: :, e# Push [[0 1 ... X-1] [0 1 ... Y-1] [0 1 ... Z-1]]. 2ff* e# Multiply each coordinate by 2. ),) e# Pop the last vector, compute its length and increment. ff+ e# Add the result to each component of each vector. }% e# Result: [[Z Z+2 ... Z+2(X-1)] [Z Z+2 ... Z+2(Y-1)]] { e# Find: ::) e# Increment each coordinate (to account for the volume in "\/"). 1fb e# Sum the coordinate of both vectors. Q= e# Compare the result to Q (desired volumes). }= e# If they match, push the array and break. ~ e# Dump both vectors on the stack. W% e# Reverse the rightmost one (corresponds to the bowl volume). ee e# Enumerate its coordinates. e# [Z+2(Y-1) ... Z+2 Z] -> [[0 Z+2(Y-1)] ... [Y-2 Z+2] [Y-1 Z]]. _,S* e# Compute the length (Y) and push a string of Y spaces. W'_t e# Replace the last space with an underscore. @ e# Rotate the leftmost vector (corresponds to the water volume) on top. , e# Compute its length (X). ~'~t e# Replace the space at index X from the right with a tilde. .{ e# For each enumerates coordinate and the corresponding character: S\+ e# Append the character to the string " ". .* e# Vectorized repetition: [1 2] " ~" -> [" " "~~"] "\/".+ e# Append the first (second) solidus to the first (second) string. N e# Push a linefeed. } ``` [Answer] # C, 231 229 bytes Early submission :) There's lots more golfing to do here. ``` v,V,w,h,H,i,j;main(c,a)char**a;{V=atoi(a[1]);v=atoi(a[2]);for(;++H;)for(h=0;h++<H;){for(w=1;h*h+w*h-h<v;++w);if(H*H+w*H-H==V){for(;H--;){printf("%*s",++i,"\\");for(j=0;j++<w-1+2*H;)putchar(H?H==h?'~':32:95);puts("/");}exit(0);}}} ``` Ungolfed: ``` int v,V,w,h,H,i,j; int main(int c, char **a) { V=atoi(a[1]); /* Volume of bowl */ v=atoi(a[2]); /* Volume of water */ for(;++H;) /* Make the bowl taller */ { for(h=0;h++<H;) /* Make the water taller */ { for(w=1;h*h+w*h-h<v;++w); /* Make the bowl wider until the water volume matches */ if(H*H+w*H-H==V) /* if the bowl volume matches, then we're good */ { for(;H--;) /* Print out the bowl, one line at a time */ { printf("%*s",++i,"\\"); /* Print the left edge */ /* Print the inside (either with air/water, the top of the water, or the bottom of the bowl */ for(j=0;j++<w-1+2*H;) putchar(H?H==h?'~':32:95); /* Print the right edge of the bowl */ puts("/"); } exit(0); /* die, we're done */ } } } } ``` [Answer] # Javascript ES5, 364 bytes This is what i could come up with quickly during my lunch, help me golf it out while my shift ends! ## Source ``` function V(x,v) { // calculate volume of bowl/water for(i=v,j=x;i--;j+=2) { v+=j; } return v } function B(x,y,l) { // draw bowl/water for(s="",h=y,w = x+2*y;y--;s+="\n") for(i=w;i--;) { f= i>h-y-1 && w-i > h-y; s+=i==h-y-1?"/": w-i == h-y? "\\": y==l-1 && f? "~" : !y && f?"_":" " } return s; } n=prompt().split(" "); b=+n[0]; // bowl volume w=+n[1]; // water volume for(x=b;x;x--) // loop through possible widths for(y=b;y;y--) // loop through possible heights if(V(x,y)==b) // check if we found bowl volume for(y2=y;y2;y2--) { // check possible water heights v = V(x,y2-1); if(v==w){ // see if volume matches alert(B(x,y,y2)); x=1;break; } } ``` ## Golfed: *(ran through minifier to compress, lunch shift ended)* ``` function V(f,r){for(i=r,j=f;i--;j+=2)r+=j;return r}function B(r,y,n){for(s="",h=y,w=r+2*y;y--;s+="\n")for(i=w;i--;)f=i>h-y-1&&w-i>h-y,s+=i==h-y-1?"/":w-i==h-y?"\\":y==n-1&&f?"~":!y&&f?"_":" ";return s}for(n=prompt().split(" "),b=+n[0],w=+n[1],x=b;x;x--)for(y=b;y;y--)if(V(x,y)==b)for(y2=y;y2;y2--)if(v=V(x,y2-1),v==w){alert(B(x,y,y2)),x=1;break} ``` [Answer] # Perl, ~~227~~ 172 bytes Run with -n option: ``` / /;for$h(1..$`){for$w(1..$`){for$l(1..($h*($w+$h)==$`)*$h){if($l*($w+$l)==$'){for(0..$h-1){print$"x$_."\\".($_<$h-1?$_==$h-$l-1?"~":$":"_")x($w+($h-$_-1)*2)."/ "}exit}}}} ``` Thanks to Dennis for help golfing this down. Calculates bowl volume as height \* (width + height), where width is the number of `_` characters and height is the number of `\` characters. Each combination of height and width is tested in a pair of nested loops until the correct bowl volume is found, then another loop over possible water height levels is done to find if a the correct water volume is possible with that width. It is possible to remove the third loop by just calculating the water level using the quadratic formula with a as 1, b as the width and c as the negative of the desired water volume, and checking if it's an integer, but that takes more bytes than just doing a loop. Here it is anyway (183 bytes): ``` / /;for$h(1..$`){for$w(1..$`){if($h*($w+$h)==$`){$l=(sqrt($w*$w+4*$')-$w)/2;if(int$l==$l){for(0..$h-1){print$"x$_."\\".($_<$h-1?$_==$h-$l-1?"~":$":"_")x($w+($h-$_-1)*2)."/ "}exit}}}} ``` [Answer] # Python 2, 162 bytes ``` V,W=input() r=1 while r*r<V:a=V/r-r;k=1;exec"if(a+k)*k==W*(V%r<1):i=1;exec\"print' '*~-i+'\%s/'%(' _~'[(i==r)-(i==r-k)]*(a+2*(r-i)));i+=1;\"*r;r=V\nk+=1\n"*r;r+=1 ``` A little messy, but here's my first attempt. It tries all possible numbers of rows `r`, setting the number of base underscores to be `a = V/r-r`. Then it tries all possible water level heights `k` and checks if the bowl is valid, printing it if so. [Answer] ## Python 2.7, ~~284~~ ~~270~~ 260 Bytes ``` def f(b,w,i=1,e='while s<%s:j+=2;s+=j'): while 1: i+=1;j=s=i;exec e%w if s==w:p=j;exec e%b if s==b:break h=(j-i)/2+1;t=w=i+(h-1)*2+1 for j in range(h):r,s,t=((' '*(t-2),'_'*(i-1))[j==h-1],'~'*(t-2))[j==h-(p-i)/2-2],(w-t)/2,t-2;print" "*s+"\\"+r+"/"+" "*s ``` This basically calculates the height and width of the bucket and water and prints them. Tried hard to remove the ugly while loop part at the start(wherein I calculate the height of the bucket and the height from where water should be drawn. Right now, all lines in the code except for the last one are for calculating the width and height). Still trying :P Testing it for different cases - ``` >>> execfile("buckets.py") (6, 2) \~~~/ \_/ (10, 4) \~~~~~/ \___/ (24, 8) \ / \~~~~~~/ \ / \__/ (42, 12) \ / \ / \~~~~~~~/ \ / \ / \_/ (90, 68) \~~~~~~~~~~~~~~~~~~~~~/ \ / \ / \ / \_____________/ (102, 42) \ / \ / \~~~~~~~~~~~~~~~~~/ \ / \ / \___________/ ``` ]
[Question] [ ## Challenge Write a function or program which takes a positive decimal number, call it *A*, and output two positive numbers, *B* and *C*, such that: * *A* == *B* bitxor *C* * *B* and *C* must not contain any of the digits 0, 3 or 7 in its decimal representation. ## Examples ``` >>> decompose(3) 1, 2 >>> decompose(7) 1, 6 >>> decompose(718) 121, 695 >>> decompose(99997) 2, 99999 >>> decompose(4294967296) 4294968218, 922 >>> decompose(5296080632396965608312971217160142474083606142654386510789497504098664630388377556711796340247136376) 6291484486961499292662848846261496489294168969458648464915998254691295448225881546425551225669515922, 1191982455588299219648819556299554251659915414942295896926425126251962564256469862862114191986258666 ``` Since the decomposition is not unique, your function/program does not need to output the exact same results as these provided examples. ## Very detailed rules 1. Submissions should be in the form of a **complete function or program**. `import` statements *do* count towards the final score. 2. You may assume the input *A* always contains at least a digit of 0, 3 or 7. 3. You may assume a decomposition always exist. 4. You may use BigInt if they are part of the standard libraries of the language, or can be installed through the language's *de jure* package manager. 5. The function should be fast. It should take no more than **20 seconds** to run on reasonably modern computer when fed a 100-digit number, and no more than 2 seconds when fed a 10-digit number. 6. The function/program should support input up to at least **100 digits**. * If the function/program can only support integers up to N<100 digits, there will be a **penalty** of +10×(100/N - 1) bytes to the final score. This is to encourage golfers to support a wider range of numbers even if importing may be verbose. 7. There is **no restriction on the presentation** of input/outputs as long as they are clearly in decimal representation. * The function may input and output strings/BigInts if the built-in integer types are not sufficient. * The input may come from the function parameter, command line argument or STDIN. * The function may return the result, or just print the result directly to STDOUT. * However, signed overflow in the input/outputs are not allowed. * Approximate answers are not tolerated, the input/outputs must be exact. ## Scoring This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes win. There is a penalty if the program can only support numbers less than 100 digits: * 64-bit integers (19 digits) = +42 bytes * 63-bit integers (18 digits) = +45 bytes * 53-bit integers (15 digits) = +56 bytes * 31/32-bit integers (9 digits) = +101 bytes [Answer] # Common Lisp, 240 224 183 173 169 bytes Common Lisp is a bit verbose for golfing. However, this decomposes 100-digit numbers in under a second, and 200-digit integers in less than ten seconds, so no need for penalties. The algorithm is deterministic. ``` (defun s(z)(and #1=(some(lambda(q)(position q(format()"~a"z)))"037")(+ z(floor z(expt 10 #1#))))) (defun d(x)(do((y x(or(s y)(s #3=(logxor x y))(return`(,y,#3#)))))(()))) ``` The line feed between the functions is for typographic purposes only. Test run with the 100-digit reference input: ``` (time (d 5296080632396965608312971217160142474083606142654386510789497504098664630388377556711796340247136376)) took 677,000 microseconds (0.677000 seconds) to run. 20,989 microseconds (0.020989 seconds, 3.10%) of which was spent in GC. During that period, and with 8 available CPU cores, 671,875 microseconds (0.671875 seconds) were spent in user mode 0 microseconds (0.000000 seconds) were spent in system mode 54,221,104 bytes of memory allocated. (1864921261592819619661568919418981552559955289196969112566252282429216186594265918444566258544614425 5891958562486995519825158818455999516899524658151445485616155916296966645869599949958954491929662561) ``` As a bonus, I'm including a version of the code that incrementally builds the solution top-down. It can manage a 1000-digit number in less than ten seconds, but cannot compete in golf due to the additional code. ``` (defun decompose (x) (flet ((s (z) (mapcan #'(lambda (c) (and #1=(position c #2=(format () "~a" z)) (list (- (length #2#) #1# 1)))) '(#\0 #\3 #\7)))) (do ((y x (let ((p (nconc (s y) (s #3=(logxor x y))))) (or p (return`(,y,#3#))) (+ y (expt 10 (apply #'max p)))))) (nil)))) * (time (decompose (parse-integer (make-string 1000 :initial-element #\7)))) took 9,226,000 microseconds (9.226000 seconds) to run. 90,966 microseconds (0.090966 seconds, 0.99%) of which was spent in GC. During that period, and with 8 available CPU cores, 9,234,375 microseconds (9.234375 seconds) were spent in user mode 0 microseconds (0.000000 seconds) were spent in system mode 487,434,560 bytes of memory allocated. (8889898889152488921298888992819221914229899249999918899888899888888889999989141219898898888988988898888888888899142442899924898918898898988988895189988898888924192198992454114198911989191888889898888918888988988998888891421118891899122898888998989898888898988898888999988918888898889189918889888888899888989219188898998888988892119889198888988888894888912188898989952999888888888898899998988898889228918998949999998898898991141888898999988912121292118899889998989899999892889941898888911888898889118998898888911889889888891452888998889288921141888888942189888899988891918889118888888888989892198899199914111188988889421111188889118888918989988912989999998989891119888898888888892621229888988888999619888952462219889189899998899888889989898891118989218888888898962988891188899888888888999888888888888888888888891269188921288888888998898899214191188888888898992188998898889919888889989889899988892115549998888898889218899988998911898989199918898918988898888891889888989119899888889888998918889112189998 4184469818464841952189561886965821566229261221619858498284264289194458622668559698924621446851546256444641488616184155821914881485164244662156846141894655485889656891849662551896595944656451462198891289692696856414192264846811616261884188919426294584158925218559295881946496911489245664261126565546419851585441144861859822815144162828551969425529258169849412525611662488849586554989254181228254465226521648916188265491499166186964881248156451994924294646681548996645996894665198811511522424996844864211629888924642289925565591484541149414914699289441561496451494562955652129199261462268846144518142486845251946444998812988291119592418684842524648484689261441456645518518812265495165189812912919529151991611962525419626921619824496626511954895189658691229655648659252448158451924925658586522262194585891859285841914968868466462442488528641466655911199816288496111884591648442984864269495264612518852292965985888414945855422266658614684922884216851481646226111486498155591649619266595911992489425412191) * (apply #'logxor *) 7777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777 ``` [Answer] # CJam, 70 bytes ``` ri:Q{;Qmr_Q^`1$`+730`&}g_Q^p ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") Randomly selects integers until it finds a match. This barely complies with the 20 second limit for 64-bit integers (using the Java interpreter), so I've added 42 to the actual byte count. ### Example run ``` $ cjam t <<< 7777777777; echo 2695665494 6161166119 ``` [Answer] # Python 2, 103 + 42 = 145 bytes Python natively supports bigints, but this program far exceeds 20 seconds for a 100-digit number. However, it decomposes 64-bit integers in around 2 seconds. ``` from random import * def d(a): b=c=0 while set(`b`+`c`)&set('037'): b=randint(1,a);c=a^b return b,c ``` [Answer] # Python 3 (132 bytes) (This is just to stimulate better solutions. This is my solution when solving the original problem in ASCII movie.) ``` def d(a): l=len(str(a));s=int('1'*l);u=10**(l-1) while u: while set(str(s)+str((a^s)//u))&set('037'):s+=u u//=10 print(s,a^s) ``` Although the behavior of bitwise xor in decimal system is pretty complicated, there is one major observation: *modifying the low digits will not affect the high digits*. Therefore, we can work top-down: try to make the top digits free of 0, 3, 7, and then work on the next digit, until the whole number is worked out. This allows us to run in linear time, then processing a thousand-digit number can complete under 1 second. (The Common Lisp solution is also using the same technique I believe.) ]
[Question] [ As you may very well know python has lists. As you might not know these lists can contain themselves. ``` a = [] a.append(a) ``` [Python 2](https://tio.run/nexus/python2#@5@oYKsQHcuVqJdYUJCal6KRqPm/oCgzr0Qh8T8A "Python 2 – TIO Nexus") [Python 3](https://tio.run/nexus/python3#@5@oYKsQHcuVqJdYUJCal6KRqPm/oCgzrwTEAAA "Python 3 – TIO Nexus") These are cool and there are lots of interesting things you can do with them, however you cannot compare them. ``` a = [] a.append(a) b = [] b.append(b) a == b ``` [Python 2](https://tio.run/nexus/python2#@5@oYKsQHcuVqJdYUJCal6KRqMmVBBFKggklaXIl2tom/f8PAA "Python 2 – TIO Nexus") [Python 3](https://tio.run/nexus/python3#@5@oYKsQHcuVqJdYUJCal6KRqMmVBBFKggklaXIl2tom/f8PAA "Python 3 – TIO Nexus") ## Task Your job is to write a function in Python (or any language that can handle python objects directly) that will take two lists that may contain themselves and compare them. Two lists are equal if they are the same length and there does not exist sequence of numbers such that indexing both of the lists by that sequence results in two objects that are not equal under this definition of equal. All non-list objects contained in a list will be python integers for simplicity and should be compared with python's builtin equality for integers. Your program *should not* rely on the recursion depth of python to determine if a list is infinitely deep. That is: ``` def isInfinite(a,b): try: a==b return False except RunTimeError: return True ``` Is not a valid way of determining if two lists are self referential. ## Testcases Assumes you define a function `equal` ``` a = [] a.append(a) b = [] b.append(b) print(equal(a,b)) ``` --- ``` True ``` --- ``` a = [] b = [] a.append(b) b.append(a) print(equal(a,b)) ``` --- ``` True ``` --- ``` a = [] b = [] a.append(1) a.append(b) b.append(1) b.append(a) print(equal(a,b)) ``` --- ``` True ``` --- ``` a = [] a.append(a) b = [a] print(equal(a,b)) ``` --- ``` True ``` --- ``` a = [] b = [] c = [] a.append(b) b.append(c) c.append(a) equal(a,b) ``` --- ``` True ``` --- ``` a=[1,[2]] b=[1,[2,[1]]] a[1].append(a) b[1][1].append(b[1]) ``` --- ``` True ``` --- ``` a = [] a.append(a) b = [1] b.append(a) c = [1] c.append([c]) print(equal(b,c)) ``` --- ``` False ``` --- ``` a = [] b = [] a.append(1) a.append(b) b.append(a) b.append(1) print(equal(a,b)) ``` --- ``` False ``` --- ``` a = [] b = [] a.append(a) b.append(b) b.append(b) print f(a,b) ``` --- ``` False ``` [Answer] # [Python 2](https://docs.python.org/2/), 94 bytes ``` g=lambda c,*p:lambda a,b:c in p or all(map(g((id(a),id(b)),c,*p),a,b))if a>[]<b else a==b g(0) ``` [Try it online!](https://tio.run/##lVIxUsMwEOz1Ck0qCS4MsrskouQFdJor7hQ7eMZxREgKXm9kRzY2AYY0lvbGu7rb2/Bxej00WdvubE173pL0cBdW6U7AKy@rRgZ5OEqqa7WnoHZKVVtFGuKXtYaOoSH@q3VVSnpyuGFZ1O@FJGtZlHanHnVbvJ2ptqUQ4Vg1J1mqHHI9AofgUAtB0kqHgh4ohKLpXhF8KfFQ4sRSvaLq3xUvx3MxkPmbRiTwRO82stE/C5lbRK/GIfxfG/6PUbwWfqL7pZSErDPgMoxalxs4gxFRPKbtRDipdDAJpN0slsvlQvy@GYMzI3yqja05j3N7GHwc9pliQG41neYLuLYwqVqHa7q3jsDgmjvEETFkuB4C1xs1ps9gZ9UsjpNw5n02B2QgmzKh40bT2k8 "Python 2 – Try It Online") An improvement on [isaacg's very clever solution](https://codegolf.stackexchange.com/a/117153/20260) of storing the `id` pairs of lists being processed and declaring them equal if the same comparison comes up on a lower level. The recursive step `all(map(...,a,b))` says that `a` and `b` are equal if all corresponding pair of elements in them are equal. This works nicely to reject unequal-length because `map` pads the shortest list with `None`, unlike `zip` which truncates. Since none of the actual lists contain `None`, these padded lists will always be rejected. [Answer] # Python, ~~233~~ ~~218~~ ~~197~~ 217 bytes ``` d=id def q(a,b,w): w[(d(a),d(b))]=0 if d(a)==d(b):return 1 if(a>[]and[]<b)-1:return a==b if len(a)!=len(b):return 0 for x,y in zip(a,b): if((d(x),d(y))in w or q(x,y,w))-1:return 0 return 1 lambda a,b:q(a,b,{}) ``` The anonymous function on the last line performs the desired function. This is still in the process of being golfed, I just wanted to show that this is possible. Essentially, we put an entry in w if we're working on a given check. Two things are equal if they're the same object, if they're not lists, and they're equal, or if all their elements are either equal or being worked on. ]
[Question] [ We will be implementing division for arbitrarily large integers. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). **The task is to write a program or function that implements arbitrary precision integers and Division on them.** **Note that many things that might make this very easy are disallowed, please make sure to read through the spec**. **Input** You will be given 2 things as input: 1. a string of base 10 digits, call it \$n\$. 2. another string of base 10 digits, call it \$m\$ **Assume that \$n>m>0\$** meaning that **you will never be asked to divide by zero**. **Output** You will output two numbers, \$Q\$ and \$R\$ where \$m\times Q+R=n\$ and \$0 \leq R < m\$ **Specifications** * Your submission should work for arbitrarily large integers (limited by available memory). * You **may not** use external libraries. If you need an external library for i/o, you may treat it as a built-in. (looking at things like iostream, etc). * If your language has a built-in that trivializes this, you **may not** use it. This includes (but may not be limited to) built-in types that can handle arbitrary precision integers. * If a language for some reason uses arbitrary precision integers by default, this functionality cannot be used to represent integers that could not be typically stored in a 64 bits. * **Input and output MUST be in base 10**. It does not matter how you store the numbers in memory or how you perform arithmetic on them, but i/o will be base 10. * You have **15 Seconds** to output a result. This is to prohibit iterated subtraction. * The goal here is to actually implement arbitrary precision integers. If for some reason you are able to adhere to the challenge specs and successfully do this without implementing them, well I guess good for you, sounds valid. **Test Cases** 1. In this case, inputs are \$39!\$ and \$30!\$ Input ``` n = 20397882081197443358640281739902897356800000000 m = 265252859812191058636308480000000 ``` Output ``` Q = 76899763100160 R = 0 ``` 2. `n` is the sum of all factorials up to 50, plus 1. `m` is concatenated numbers up to 20. input ``` n = 31035053229546199656252032972759319953190362094566672920420940313 m = 1234567891011121314151617181920 ``` output ``` q = 25138393324103249083146424239449429 r = 62459510197626865203087816633 ``` 3. `n` is 205! + 200!. `m` is how many tears PeterTaylor has made me shed by tearing apart things I post in the sandbox. Input ``` n = 271841734957981007420619769446411009306983931324177095509044302452019682761900886307931759877838550251114468516268739270368160832305944024022562873534438165159941045492295721222833276717171713647977188671055774220331117951120982666270758190446133158400369433755555593913760141099290463039666313245735358982466993720002701605636609796997120000000000000000000000000000000000000000000000000 m = 247 ``` Output ``` q = 1100573825740813795225181252819477770473619155158611722708681386445423816849801159141424129060075102231232666057768175183676764503262931271346408394876267875141461722640873365274628650676808557279259873162169126398101692109801549256156915750794061370041981513180387019893765753438422927286098434193260562682052606153857091520795991080960000000000000000000000000000000000000000000000000 r = 0; ``` I'll probably add more test cases at some point. [Related](https://codegolf.stackexchange.com/questions/55807/golf-cpu-implement-arbitrary-precision-integer-division) [Sounds related, but really isn't](https://codegolf.stackexchange.com/questions/22146/implement-arbitrary-precision-division) [Answer] # Java 8, 485 bytes Could reduce by another 5 bytes naming the function `d` instead of `divide` or another 16 bytes if not counting class-definition. ``` public class G{int l(String a){return a.length();}String s(String n,String m){while(l(n)>l(m))m=0+m;String a="";for(int c=1,i=l(n);i>0;c=c/10){c=n.charAt(--i)+c-m.charAt(i)+9;a=c%10+a;}return e(a);}String e(String a){return a.replaceAll("^0+(?=[0-9])","");}String divide(String n,String m){String q="",p=q,y;for(int b=0,i=0;b<=l(n);i--){y=n.substring(0,b);if(l(y)==l(p)&&p.compareTo(y)<=0||l(y)>l(p)){y=s(y,p);n=y+n.substring(b);q+=i;b=l(y)+1;i=10;p=m+0;}p=s(p,m);}return e(q)+","+n;}} ``` Can be used like this: ``` public static void main(String[] args) { G devision = new G(); System.out.println(devision.divide("20397882081197443358640281739902897356800000000", "265252859812191058636308480000000")); System.out.println(devision.divide("31035053229546199656252032972759319953190362094566672920420940313", "1234567891011121314151617181920")); System.out.println(devision.divide( "271841734957981007420619769446411009306983931324177095509044302452019682761900886307931759877838550251114468516268739270368160832305944024022562873534438165159941045492295721222833276717171713647977188671055774220331117951120982666270758190446133158400369433755555593913760141099290463039666313245735358982466993720002701605636609796997120000000000000000000000000000000000000000000000000", "247")); } ``` yielding ``` 76899763100160,0 25138393324103249083146424239449429,62459510197626865203087816633 1100573825740813795225181252819477770473619155158611722708681386445423816849801159141424129060075102231232666057768175183676764503262931271346408394876267875141461722640873365274628650676808557279259873162169126398101692109801549256156915750794061370041981513180387019893765753438422927286098434193260562682052606153857091520795991080960000000000000000000000000000000000000000000000000,0 ``` Ungolfed: ``` public class ArbitraryPrecisionDivision { /** * Length of String */ int l(String a) { return a.length(); } /** * substract m of n; n >= m */ String s(String n, String m) { while (l(n) > l(m)) m = 0 + m; String a = ""; for (int c = 1, i = l(n); i > 0; c = c / 10) { c = n.charAt(--i) + c - m.charAt(i) + 9; a = c % 10 + a; } return e(a); } /** * trim all leading 0s */ String e(String a) { return a.replaceAll("^0+(?=[0-9])", ""); } /** * divide n by m returning n/m,n%m; m may not start with a 0! */ String divide(String n, String m) { // q stores the quotient, p stores m*i, y are the b leading digits of n String q = "", p = q, y; for (int b = 0, i = 0; b <= l(n); i--) { y = n.substring(0, b); if (l(y) == l(p) && p.compareTo(y) <= 0 || l(y) > l(p)) { y = s(y, p); n = y + n.substring(b); q += i; b = l(y) + 1; i = 10; p = m + 0; } p = s(p, m); } return e(q) + "," + n; } public static void main(String[] args) { ArbitraryPrecisionDivision division = new ArbitraryPrecisionDivision(); System.out.println(division.divide("20397882081197443358640281739902897356800000000", "265252859812191058636308480000000")); System.out.println(division.divide("31035053229546199656252032972759319953190362094566672920420940313", "1234567891011121314151617181920")); System.out.println(division.divide( "271841734957981007420619769446411009306983931324177095509044302452019682761900886307931759877838550251114468516268739270368160832305944024022562873534438165159941045492295721222833276717171713647977188671055774220331117951120982666270758190446133158400369433755555593913760141099290463039666313245735358982466993720002701605636609796997120000000000000000000000000000000000000000000000000", "247")); } } ``` I sacrificed a bit of speed by not precalculating an array with `m` times 1 through 9 and starting with `b=0` instead of `b=l(m)`, but saved lots of bytes doing so. If you are interested in arbitrary precision addition see [a previous version](https://codegolf.stackexchange.com/revisions/71764/3). I guess this will not be the shortest solution, but maybe it gives a good start. [Answer] # Python 2, 427 bytes ``` b=S=lambda l:sorted(l)[::-1] A=lambda a,b,o=0:A(a^b,{n+1for n in[b&a,b-a][o]},o)if b else a M=lambda a,*b:reduce(A,({n+m for n in a}for m in b)) def D(a,b): q=a-a while b<=S(a):n=max(a)-b[0];n-=S(M(b,n))>S(a);q|={n};a=A(a,M(b,n),1) return q,a exec"a=b;b=[]\nfor d in raw_input():b=A(M(b,3,1),{i for i in range(4)if int(d)>>i&1})\n"*2 for n in D(a,S(b)): s='' while n:n,d=D(n,[3,1]);s=`sum(2**i for i in d)`+s print s or 0 ``` Reads the input through STDIN, each number on a separate line, and prints the result to STDOUT. ## Explanation Instead of representing integers as arrays of digits, we represent each integer as the set of "on" bits in its binary representation. That is, an integer *n* is represented as the set of indices of the bits that equal 1 in the binary representation of *n*. For example, the number 10, 1010 in binary, is represented as the set {1, 3}. This representation allows us to express some of the arithmetic operations rather succinctly, using Python's set operations. To add two sets, we (recursively) take the sum of their symmetric difference, and the set of succeeding integers to their intersection (which corresponds to the collective carry, and hence eventually becomes the empty set, at which point we have the final sum.) Similarly, to subtract two sets, we (recursively) take the difference of their symmetric difference, and the set of succeeding integers to their (set) difference (which corresponds to the collective borrow, and hence eventually becomes the empty set, at which point we have the final difference.) The similarity of these two operations allows us to implement them as a single function (`A`). Multiplication (`M`) is simply distributed addition: given two sets *A* and *B*, we take the sum, as described above, of all the sets {*A*+*b* | *b*∈*B*} (where *A*+*b* is the set {*a*+*b* | *a*∈*A*}). Integer comparison becomes lexicographical comparison of the two sets, sorted in descending order. To divide (`D`) two sets, *A* and *B*, we start with the empty set as the quotient, and repeatedly find the largest integer *n*, such that *B*+n is less than or equal to *A* (which is simply the difference between the maxima of *A* and *B*, possibly minus-1), add *n* as an element to the quotient, and subtract *B*+n from *A*, as described above, until *A* becomes less than *B*, i.e., until it becomes the remainder. There is no free lunch, of course. We pay the tax by having to convert from-, and to-, decimal. In fact, the conversion to decimal is what takes most of the run time. We do the conversion "the usual way", only using the above operations, instead of ordinary arithmetic. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 131 bytes ``` ⌷∘⎕D⍤0{S←{⍵↓⍨(⊥⍨-∧/)⌽0=⍵}⋄L←<⍥≢∨=⍥≢∧{>/⍋⍵⍺}⋄⍺L⍵:0⍺⋄q a←(⍵∇⍨¯1↓⍺),¨0,⊢/⍺⋄S¨q(a{⍺L⍵:⍺⋄(⊃⌽q)+←1⋄(S(+⌿1 0⌽0 10⊤⊢)⍣≡⍺-⍵↑⍨-≢⍺)∇⍵}⍵)}⍥(⍎¨) ``` [Try it online!](https://tio.run/##lZPNalxHEIX38xSzGw3WoPrpru4KcTbJIgZDIMoLCCR5Y@IIskgQWSU4sqwRCcGQrR0La@eVCRiCQY9yX0T5emQZb32Hufd2V3WdU6fO3fvh4Wr/572Hjx6sDn768eD7/YP96@n82b1vpsd/yPV09u908jfrr6b1SzneZfN4Wr@ZHv81rS@3ptMLHqvp5NXOcjr7T@4S@mV6@tt90j6f1hfTkxfTyeXd27dXx1/sTOun4/z67cjjcZ/VZ8ILy6P5Hge3RvzkdwpfvdYN0Nvl9tWlbE@nL3ZuEnevLo@29o5vj99swuZXSBwt71BEx8bu1p3p7J3OZXCbq0ynL6mxnNb/TE@ec2i16eTPTQvwA2eDSwvrN0tuF1A5v7pcXh9SkVcArl77OHH@bPfbL7l/9/W93euF2uJw4aUuZqvVara1vZDF8qMN4k4CWR8vP0Rdi9a0qF57tiRkTbv18X@fYuLZejfpqtlKcVKjCDnNM3lm8xpd3l@jRFSr1mt2NU0V8j1cerlN@gAuXqW6WdYSmhk1OChu2azVdLYqN/EwyVIjolmalLES15vGaDVaB0YVuE1DGkoXSuptDywLfEvWBiuRRg0QW2QpUZSddInsDqgbqU2yVkmhX7ECKc3o1jgj0ulHGplw7K1176RaBZ9iHXSLjjbWIN41pLu5VJCoJGY0Sbg6pYlW9M@iUmrJIUQzNbPuDljTm59HadnoobMltTboI5OD2BJc9OiGOiC2St@wDiVcexE4JDNrdXOlp3oLQSXJNDJpxZOzm77r4IUTupWITG/GtKhKE5UZhuAR9puafOo1fFHaYjZbPjo8nPFFGDeZqcx9ZnP3mSqN2ZyZI61jmFmLzgJmMgiQjMY@RjQmhEtKIq0yPyvmyJvFch50gSYyhsscYvhJekPp2ICI0GS32gqGduRjIHhlGFazNC4pzZkzdBAwkNhQoDNJx/eMycbYesmO42qiJPiKlIGtADZzTDnGARIt4BLtHkwzSoV1GM7BkA5x@Gfpg2jrpFEqBtwINCSo1gpmiSoc7tKHQC1tuM5xmUaqhQ9D82pMFErDRjW0EqutYtOC0b2JFCURAbWLd0aanfkGOY4P8RN@BYoaxUmFJyNHQJPKKwVxOR@FoieiJd9bl4xPtsFc/gc "APL (Dyalog Extended) – Try It Online") An anonymous function that takes `n` (dividend) on the left and `m` (divisor) on the right, and returns a 2-row char matrix of digits where the first row is the quotient and the second is the remainder. This is an expansion of my ["shitty" solution](https://chat.stackexchange.com/transcript/message/55347207#55347207) to [ngn's CMC](https://chat.stackexchange.com/transcript/message/55346903#55346903). It was really hard to get this right *and* short at the same time. ### Ungolfed with comments ``` ⍝ Post-processing: Map each digit (numeric 0-9) to respective chars f←⌷∘⎕D⍤0{ ⍝ Inner function, m f n → (n/m)(n%m), I/O as numeric digit vectors ⍝ S x → trim leading zeros of x, leaving a single zero if x is entirely 0 S←{⍵↓⍨(⊥⍨-∧/)⌽0=⍵} ⍝ x L y → given two numbers as digit vectors, is x less than y? L←<⍥≢∨=⍥≢∧{>/⍋⍵⍺} ⍝ if ⍺<⍵, return quotient 0 and remainder ⍺ ⍺L⍵:0⍺ ⍝ get recursive result for (⍺/10) f ⍵, ⍝ multiply quotient by 10 (by appending 0), ⍝ and multiply remainder by 10 and add the last digit of ⍺ (by appending ⊢/⍺) q a←(⍵∇⍨¯1↓⍺),¨0,⊢/⍺ ⍝ fix the quotient and remainder by repeatedly subtracting the remainder ⍝ and adding 1 to the quotient until it is right, ⍝ then trim leading zeros from both S¨q(a{ ⍝ inner function with ⍺←remainder to fix, ⍵←divisor ⍝ done if ⍺ is less than ⍵ ⍺L⍵:⍺ ⍝ increment the last digit of q (⊃⌽q)+←1 ⍝ subtract and fix negative digits by borrowing (S(+⌿1 0⌽0 10⊤⊢)⍣≡⍺-⍵↑⍨-≢⍺)∇⍵ }⍵) ⍝ Pre-processing: convert the char vectors on both sides to numeric digit vectors }⍥(⍎¨) ``` A fun fact: Dyalog APL has a library operator, [`dfns.big`](http://dfns.dyalog.com/n_big.htm), designed to handle big integer arithmetic, but apparently [its modulo function is buggy](https://tio.run/##lZO9ql1VFIX7/RSn2wbuhfmz5l@dxlSCsbGMhBOEYAQrwU5IISRo4TvYWdrrm9wXuX7r5oe02Yezz95rjTXnmGOM8@zHl7fPf3728tWL@7u3fz756u7177KfHn97Pr/@8NN5/PfPd9@/uDkv580vPNy9@ev@Cubuzdu7337992@/e/0H6KdfP@b@zZdPnt5fj1PtvJ6@4jxub2@PL25OOR99ssC@AwD16evHXdelMZbh0VPDlpW29f6@h5j4VLdJq06t5UBzCZjyGX6nPLLl/bVLZFhYx7Sajgp4T5deH0Afm4uHhJtNrNSZjOSguE1ZxThLwU08TWZFZpaNydpv4vpuMEbNatqo0u5hIE1lCgX6YQZeF3zXRMFKpKhBx8pZK5eyMi457TR1A1oyETLCvGILUjrZVpwRaeaRAgnHrmpvoBb0p1jT3bLRxgrirSnt5hJ0opKYMSTb4ZRmN9B/lsqKNVuIMjWzdqdZ6buP56opZmiWJKKgj0xOxxr6okcb6tCxgrlhncp29BI4DJ5VPFzjo14pqCQzBpJRfDj7MHdsXiShbWXOeBluUZUhAg9TyAjrpSafe@1crDqP49Gr6/WQixo3OVQuftjF/VBlMLvgOdI6gTkqmxeYySYAGI19W7QdIiVrkFbxz5Y58s6yuSRToIlsc/Ehd56kC6XzoYkIQ7ZFLQLtyIchZGUHVmcVl6xyfIYOAiYSGwo0Tjq5xybbtvWaJnExKEl/RcokVjQ2c0K57aATI5ASbU/czBWwTiM5BNIhDv9ZvYlWA6NU7nZ7o5AgrBZhyRAOt/QWqMZ26pyUaY5a@g40j4ajUNoxitRgLyqI6SLoXiJLASKgtnhj6TT@Jhgnh@SJvNKKGsuBwhPLEdAkeKQgKedPoeiJaMP/rWXys2Nwkf8B) (returns the divisor when the remainder is zero), so it can't be used here anyway. [Answer] # Mathematica, 251 bytes ``` r=Reverse;f=FoldPairList;s={0}~Join~#&; p[a_,b_]:={First@#,#[[2,1,-1,2]]}/.{Longest[0..],x__}:>{x}&@Reap@f[Sow@{Length@#-1,Last@#}&@NestWhileList[r@f[{#~Mod~10,⌊#/10⌋}&[#+Subtract@@#2]&,0,r@Thread@{#,s@b}]&,Rest@#~Join~{#2},Order[#,s@b]<=0&]&,0s@b,s@a] ``` --- **Explanation** Arithmetics on decimal numbers can easily be implemented by `FoldPairList`. For example, ``` times[lint_,m_]:=Reverse@FoldPairList[{#~Mod~10,⌊#/10⌋}&[m #2+#]&,0,Reverse@lint] ``` just mimics the process of doing multiplications by hand. ``` times[{1,2,3,4,5},8] (* {9,8,7,6,0} *) ``` --- **Test case** ``` p[{1,2,3,4,5,6,7,8,9},{5,4,3,2,1}] (* {{2,2,7,2},{3,9,4,7,7}} *) ``` means `123456789 / 54321= 2272...39477`. ]