text
stringlengths
180
608k
[Question] [ ## The Challenge You are to write a complete program that takes seven numbers from STDIN, and prints the two dimensional history of the cellular automaton (CA) to STDOUT. This is code golf. **Input Formatting** The input will be seven integers/strings separated by commas. The first number is the number of the rule according to Wolfram code (the standard name for each rule). The second is the initial starting configuration. The third and fourth describe what pattern and how many times it should be appended to the left of the starting config. as padding. The fifth and sixth do the same for the right side. The last number is the number of generations to run the simulation. So, an example of input is `90,11,0,4,0,4,5`. This should tell your program that you are running [rule 90](http://en.wikipedia.org/wiki/Rule_90). It should also tell the program that you want the initial configuration to be `11` with the string `0` appended 4 times to both ends, so the actual starting pattern is `0000110000`. It also tells your program to run this simulation for 5 generations. **Output** Your program should print the entire array of cells each generation (separated by newlines), so that the output is the space-time diagram of the CA. For each generation, the state of each cell is determined by its state and the states of the cells to the immediate left and right, in accordance to the rule provided as input. The simulation should wrap around the edges. The first thing printed should be the starting array as gen. 0. The input `90,11,0,4,0,4,5` should result in the following output as exactly as possible. ``` 0000110000 0001111000 0011001100 0111111110 1100000011 0110000110 ``` Notice that the starting state is not included in the five generations. Also notice that the simulation wraps around the edges. **More Examples** input: ``` 184,1100,01,2,01,1,4 ``` output: ``` 0101110001 1011101000 0111010100 0110101010 0101010101 ``` input: ``` 0,1011,1,0,0,1,2 ``` output: ``` 10110 00000 00000 ``` [**More information on how 1D CA's work and how they are numbered**](http://mathworld.wolfram.com/ElementaryCellularAutomaton.html) [Answer] ## Golfscript, 77 73 70 chars ``` ','/)~\(~:?;~~*@@~*@+\+{1&}/]({[.,{.[3<?256+]{2base}/\~=\(+}*])n@)\+}* ``` Thanks to @Howard, who pointed out how to save 4 chars. [Answer] ## APL (153 characters) ``` ∇ cellularautomaton i ← ⍞ s ← (i=',') / ⍳ ⍴i (b a x c) ← {i[s[⍵]↓⍳s[⍵+1]-1]} ¨ ⍳4 (z x x l x r n) ← ⍎i y ← ⍎ ¨ ⊃ ,/ (l / ⊂a) , b , r / ⊂c (n+1) (⊃⍴,y) ⍴ '01'[1+⊃ ,/ y,{({(z ⊤⍨ 8/2)[8 - 2⊥¨ 3 ,/ (⊃⌽⍵),⍵,⊃⍵]}⍣⍵)y} ¨ ⍳n] ∇ ``` And in less readable, slightly shorter form: ``` i←⍞⋄s←(i=',')/⍳⍴i⋄b a x c←{i[s[⍵]↓⍳s[⍵+1]-1]}¨⍳4⋄z x x l x r n←⍎i⋄y←⍎¨⊃,/(l/⊂a),b,r/⊂c⋄'01'[1+⊃,/y,{({(z⊤⍨8/2)[8-2⊥¨3,/(⊃⌽⍵),⍵,⊃⍵]}⍣⍵)y}¨⍳n]⍴⍨(1+n),⊃⍴,y ``` Example: ``` cellularautomaton 26,00110,01,4,10,6,7 0101010100110101010101010 1000000011100000000000001 0100000110010000000000011 0010001101101000000000110 0101011001000100000001101 0000010110101010000011000 0000100100000001000110100 0001011010000010101100010 ``` I'm certain there is room for improvement (I even found a few changes while writing this post!), but some of it could involve fundamental changes, and I can't stand staring at APL any longer. The variant of APL used here is [Dyalog APL](http://www.dyalog.com). [Answer] ## Ruby, 165 159 characters ``` a=gets.split ?, b=a.map &:to_i c=(x=a[2]*b[3]+a[1]+a[4]*b[5]).chars.map &:hex (0..b[6]).map{puts c*'' c=(1..w=x.size).map{|i|b[0]>>c[i-1]*2+c[i%w]+c[i-2]*4&1}} ``` *Edit:* I found some places for small enhancements. Example run: ``` > 30,1,0,20,0,20,20 00000000000000000000100000000000000000000 00000000000000000001110000000000000000000 00000000000000000011001000000000000000000 00000000000000000110111100000000000000000 00000000000000001100100010000000000000000 00000000000000011011110111000000000000000 00000000000000110010000100100000000000000 00000000000001101111001111110000000000000 00000000000011001000111000001000000000000 00000000000110111101100100011100000000000 00000000001100100001011110110010000000000 00000000011011110011010000101111000000000 00000000110010001110011001101000100000000 00000001101111011001110111001101110000000 00000011001000010111000100111001001000000 00000110111100110100101111100111111100000 00001100100011100111101000011100000010000 00011011110110011100001100110010000111000 00110010000101110010011011101111001100100 01101111001101001111110010001000111011110 11001000111001111000001111011101100010001 ``` [Answer] ## C, ~~303 305 301 294~~ 292 305 Edit: oops. Forgot that `calloc()` takes two args. It was blowing up on larger input. 301 Edit: Ah HA! Used my `calloc()` boo-boo to save 2 more bytes by upping the block size of the requested memory. 294 Edit: Broke 300! Eliminated one of the `strcat()`s and tweaked a few loops. Got to use maximal munch, which is as much fun to say as use. 292 Edit: Didn't need the `+2` in memory allocation. I [used luser droog's answer](https://codegolf.stackexchange.com/a/9188/4777) as the base idea, but changed up the wrapping algorithm, as well as a lot of tweaking and factoring out of constants. ``` r,A,C,n,j;main(){char*s,*p,*t,a[9],b[9],c[9];scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);for(s=calloc(A+++C,9);A--;)strcat(s,A?a:b);for(;C--;)strcat(s,c);p=strdup(s);for(C=strlen(s);A++<n;puts(s),t=p,p=s,s=t)for(j=C;j--;)p[j]=(1<<(s[j?j-1:C-1]*4+s[j]*2+s[(j+1)%C])-336)&r?49:48;} r,A,C,n,j; main(){ char*s,*p,*t,a[9],b[9],c[9]; scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n); for(s=calloc(A+++C,9);A--;) strcat(s,A?a:b); for(;C--;) strcat(s,c); p=strdup(s); for(C=strlen(s);A++<n;puts(s),t=p,p=s,s=t) for(j=C;j--;) p[j]=(1<<(s[j?j-1:C-1]*4+s[j]*2+s[(j+1)%C])-336)&r?49:48; } ``` ![screenshot1](https://i.stack.imgur.com/JltOW.jpg) ![screenshot2](https://i.stack.imgur.com/5hpav.jpg) [Answer] # C (~~487~~ ~~484~~ 418 with spaces removed) \*Dropped *66* with help from JoeFish\* ``` C,A,r,n,j;main(){char*s,*p,*t,a[9],b[9],c[9]; scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n); s=malloc(strlen(a)*A+strlen(b)+strlen(c)*C+3);*s=0; strcat(s,"0"); for(;A--;)strcat(s,a); strcat(s,b); for(;C--;)strcat(s,c); strcat(s,"0"); p=malloc((C=strlen(s)-1)+2); for(;n--;){ *s=s[C-1]; s[C]=0; puts(s+1); s[C]=s[1]; for(j=1;s[j+1];j++) p[j]=(1<<(s[j-1]-48)*4+(s[j]-48)*2+s[j+1]-48)&r?49:48; t=p;p=s;s=t; } s[C]=0; puts(s+1); } ``` typescript ``` josh@Z1 ~ $ !m make ca cc ca.c -o ca ca.c:1:1: warning: data definition has no type or storage class ca.c: In function ‘main’: ca.c:2:5: warning: incompatible implicit declaration of built-in function ‘scanf’ ca.c:3:7: warning: incompatible implicit declaration of built-in function ‘malloc’ ca.c:3:14: warning: incompatible implicit declaration of built-in function ‘strlen’ ca.c:4:5: warning: incompatible implicit declaration of built-in function ‘strcat’ josh@Z1 ~ $ echo 90,11,0,4,0,4,5 | ca -bash: ca: command not found josh@Z1 ~ $ echo 90,11,0,4,0,4,5 | ./ca 0000110000 0001111000 0011001100 0111111110 1100000011 0110000110 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) ~~67~~ 59 ``` □÷bṅṅṘ‟:L∇∇~≤[$_⋏ð\0øV|$_Ẏ]$($₀Sf$~Ŀ,$_‟:₌ht∇++3lvB~İṅ$_^„) ``` There is extra feature: replacement "10" symbols to any Unicode characters. Many thanks to [@lyxal](https://codegolf.stackexchange.com/users/78850/lyxal) [Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLilqHDt2LhuYXhuYXhuZjigJ86TOKIh+KIh37iiaRbJF/ii4/DsFxcMMO4VnwkX+G6jl0kKCTigoBTZiR+xL8sJF/igJ864oKMaHTiiIcrKzNsdkJ+xLDhuYUkX17igJ4pIiwiIiwiW1wi4pagXCIsIFwiIFwiXVxuMTBcbjE1XG5cIjFcIlxuMzAiXQ==) Input: * List of replacement symbols * Width * Height (number of iterations) * Initial string * Wolfram CA-code [Explanations](https://github.com/lesobrod/StringUniverse/blob/main/Vyxal/CA-Readme.md) ]
[Question] [ Let's define a simple function \$f\$ which takes an integer and produces a list: \$ f(n) = [g(1),g(2),\dots,g(n)] \\ g(n) = [f(0),f(1),\dots,f(n-1)] \$ We can then calculate the first couple of values for \$f(n)\$: ``` 0 -> [] 1 -> [[[]]] 2 -> [[[]],[[],[[[]]]]] 3 -> [[[]],[[],[[[]]]],[[],[[[]]],[[[]],[[],[[[]]]]]]] 4 -> [[[]],[[],[[[]]]],[[],[[[]]],[[[]],[[],[[[]]]]]],[[],[[[]]],[[[]],[[],[[[]]]]],[[[]],[[],[[[]]]],[[],[[[]]],[[[]],[[],[[[]]]]]]]] ``` And we notice that each one is bigger than the last and has the last list as a prefix to itself. So we could say that \$f(\infty)\$ is the infinite sequence such that each \$f(n)\$ is the first \$n\$ entries of it. Now infinite lists of lists of lists ... are a little complicated so instead we will just treat \$f(\infty)\$ as an infinite sequence of opening and closing brackets. The `,`s are redundant so we just omit them. In fact we don't need to even deal with the brackets since there are only two values we can make a binary sequence! ``` 1110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000001... [[[]][[][[[]]]][[][[[]]][[[]][[][[[]]]]]][[][[[]]][[[]][[][[[]]]]][[[]][[][[[]]]][[][[[]]][[[]][[][[[]]]]]]][... ``` ## Task Your task is to output the binary sequence given by \$f(\infty)\$. You can choose any two distinct values for `1` and `0`. IO otherwise uses [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") defaults. Read [the tag wiki](https://codegolf.stackexchange.com/tags/sequence/info) for precise info. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with the goal being to minimize your source code size. ## Test cases Here's the first 10000 entries ``` 1110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000000011011100011100110111000001110011011100001101110001110011011100000001110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000011100110111000011011100011100110111000000110111000111001101110000011100110111000011011100011100110111000000001101110001110011011100000111001101110000110111000111001101110000000111001101110000110111000111001101110000001101110001110011011100000111001101110000110111000111001101110000000000110111000111001101110000011100110111000011011100011100110111000000011100110111000011011100011100110111000000110111000111001101110000011 ``` [Answer] # [Haskell](https://www.haskell.org/), 45 bytes The top line is a function that returns the nth digit (0-based). ``` (!!)=<<f 1 f d n=1:(f(1-d)=<<[d..n-1+d])++[0] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfYRvzX0NRUdPWxiZNwZArTSFFIc/W0EojTcNQNwUkGp2ip5ena6idEquprR1tEPs/NzEzT8FWoaC0JLikSEFFoTgjv1wvQwGoVCHaQE/P0MAAqMjQEEgDMZhGYqGJ45GB8f8lp@Ukphf/100uKAAA "Haskell – Try It Online") The function `f` generates both \$f(n)\$ with `d=1` and \$g(n)\$ with `d=0`. The top line is a point free version of ``` h n = f 1 n !! n ``` where `!!` is Haskells indexing operator. [Answer] # JavaScript (ES6), 71 bytes Returns the \$n\$-th term, 0-indexed. Very inefficient because it generates way more terms that needed. ``` n=>(F=n=>n?(g=(n,c=F,h=k=>k>n?0:c(k++)+h(k))=>1+h``)(n-1,g):'10')(n)[n] ``` [Try it online!](https://tio.run/##FYzNDoIwEITvPMXe2k2LoRcP4OKNlzAmkMqPlmwJoBfjs9flMl9mMjOv7tNtfn0ue87x0aeBElOtGxLlqx5Js/XU2IkC1UGiovQ6GINm0gGRamemtkXNubMjlsoVSgze@J6GuOr43oFAKQssLCrBBdxZKBfwzQCOhiEYZFRlv8xH3uLcn@Y4HmOs0h8 "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` ⊞υ10W¬›L⌈υ⊗θ⊞υ⪫10⭆υ⪫10⪫…υ⊕λω§⊟υN ``` [Try it online!](https://tio.run/##XY7LCsIwEEX3fkVwNYEKuhRXUkEqthT8gjQdmkIeNU5s/fqYFNx4V8Pcw@FKJbx0QsfYhpeCULDtYb/lp82sRo0MGkdw9SgIPdzRDqSgFstogoHAecEuLnQae3jyFPZz3NxoIYsK9iA/2qEW099/PcuP1Fgqt5aVlR4NWko6nd1zdqYpbTIQnKmyPS7QZppnfArUBNOlZRmL8ZgSd2/9BQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `n`th digit (0-indexed). Explanation: ``` ⊞υ10 ``` Start with the base case. ``` W¬›L⌈υ⊗θ ``` Repeat until the string is way long enough. ``` ⊞υ⪫10⭆υ⪫10⪫…υ⊕λω ``` Generate the next iteration. ``` §⊟υN ``` Output the `n`th value. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~59~~ 52 bytes ``` p(1).step &f=->n,a=0{p 1 n.times{|x|f[x+a,1-a]} p 0} ``` [Try it online!](https://tio.run/##KypNqvz/v0DDUFOvuCS1QEEtzVbXLk8n0dagukDBkCtPryQzN7W4uqaiJi26QjtRx1A3MbaWq0DBoPb/f0NDQwMDIAbTSCw0cQMA "Ruby – Try It Online") * Saved 7 Bytes thanks to @ovs Outputs terms indefinitely on new lines. Straightforward approach: > > actually saved many bytes by using ovs idea to use just one function behaving differently > > > ``` p 1 we first print a 1 because we call g(1..) note that we do not need to close an infinite stream. 1.step &$ again: we call g(1.. $f=->n,a=0 a=0->g() , a=1->f() {p 1 put a 1: open [ (a...n+a).map{|x|$f[x,1-a]} inner calls p 0 put a 0: close ] ``` ``` [Answer] # [Haskell](https://www.haskell.org/), 49 bytes Since it's [been beat](https://codegolf.stackexchange.com/a/240773/56656) here's my original Haskell solution. It takes a radically different approach. ``` x!y|q<-x++y++[0]=y++0:q!(y++q++[0]) 1:[1]![1,1,0] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0KxsqbQRrdCW7tSWzvaINYWSBlYFSpqAOlCsIgmV5qtoVW0YaxitKGOoY5B7P/cxMw8BVuF3MQCXwWNgtKS4JIiveKM/HJNBRWFksTsVAVzAwOFtP@GhoYGBkAMppFYaOJ4ZIg2gSpm0NW9Q9DFIyk@AQ "Haskell – Try It Online") Looking at this, you can start to see the relationship between the lengths of the terms and the Fibonacci sequence as pointed out by [Arnauld](https://codegolf.stackexchange.com/questions/240769/mutually-recursive-lists/240775#comment543331_240769). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` TλèληJ01ý11ì00«}I£ ``` Outputs the first \$n\$ bits. Could alternatively output the 0-based \$n^{th}\$ bit by replacing the trailing `£` with `è`. Becomes slower the larger \$n\$ becomes, because it will calculate all bits representing \$f(n)\$ first, before leaving just the first \$n\$. [Try it online.](https://tio.run/##ASYA2f9vc2FiaWX//1TOu8OozrvOt0owMcO9MTHDrDAwwqt9ScKj//8yMA) Could have been shorter if 05AB1E had a `to_string` function for lists somehow, since `¯¸λèλη` (7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) already outputs \$f(n)\$ including commas and spaces. [Try it online](https://tio.run/##ARcA6P9vc2FiaWX//8KvwrjOu8OozrvOt///NA). **Explanation:** ``` λ # Start a recursive environment è # to output the (implicit) input'th value T # Starting with a(0) = "10" # Where every following a(n) is calculated as follows: λ # Push all previous terms as list: [a(0),a(1),...,a(n-1)] η # Pop and push the prefixes of this list J # Join each inner prefix-list together to a string 01ý # Join this list of strings with "01"-delimiter 11ì # Prepend a leading "11" to the string 00« # Append a trailing "00" to the string } # After the recursive function: I£ # Leave just the first input amount of digits # (after which the result is output implicitly) ``` ]
[Question] [ Related Challenge: [Single Digit Representations of Natural Numbers](https://codegolf.stackexchange.com/questions/200185/single-digit-representations-of-natural-numbers) # Task Write a program/function that when given a non-negative integer \$n \le 100000\$ outputs an expression which uses all the digits from \$0\$ to \$9\$ exactly once and evaluates to \$n\$ The expression outputted by your program may only use the operations listed below: * addition * subtraction and unary minus (both must have the same symbol) * multiplication * division (fractional, i.e. 1/2 = 0.5) * exponentiation * parentheses **Note:** Concatenation is **not** allowed # Output Format * Output can be a string, list of operations and numbers or a list of lists in place of brackets. * You may choose the precedence of the operators but it must be consistent for all outputs produced by your program/function * Output may be in [polish](https://en.wikipedia.org/wiki/Polish_notation), [reverse polish](https://en.wikipedia.org/wiki/Reverse_Polish_notation) or [infix](https://en.wikipedia.org/wiki/Infix_notation) notation but it must be consistent for all outputs produced by your program/function. * You can use custom symbols for representing the digits and operations but the symbols used for representing the digits and operations should be distinct. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytes wins # Sample Testcases ``` 0 -> 0 ^ (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9) 4 -> (0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8) / 9 7 -> 0 * (1 + 2 + 3 + 4 + 5 + 6 + 8 + 9) + 7 45 -> 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0 29 -> 1 + 2 + 7 + 6 + 5 + 4 + 3 + 0 + (9 - 8) 29 -> (((9 + 8 + 7 + 6) * 0) + 5 + 4) * 3 + 2 * 1 100 -> (9 * 8) + 7 + 4 + 5 + 6 + 3 + 2 + 1 + 0 ``` --- A [proof by exhaustion](https://gist.github.com/Mukundan314/ee97fb46122a514fee5961e3bb3e949e) (also contains program used to generate the proof) that shows that all number less than or equal to \$100000\$ have an expression that uses all the digits. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 9Ýœ"+-*m"9ãðδšδ.ιJ˜.Δ.VQ ``` Brute-force approach, so obviously extremely slow. Outputs in reverse Polish notation, with the characters `+-*m` for addition, subtraction, multiplication, and exponentiation respectively. Division isn't necessary for the \$[0,100000]\$ range we have to support. [Try it online with additional (first) input to specify the digit-range \$[0,n]\$ instead of \$[0,9]\$](https://tio.run/##ATIAzf9vc2FiaWX//8K5w53FkyIrLSptIsK5w6PDsM60xaHOtC7OuUrLnC7OlC5WUf//NAoyNQ), for which I've used `4` right now as example. **Explanation:** ``` 9Ý # Push a list in the range [0,9] œ # Get all possible permutations of this list "+-*m" # Push string "+-*m" 9ã # Get all possible combinations of size 9 with the cartesian product δ # Map over each string of operations: ð š # Convert it to a list of characters, and prepend a space δ # Apply double-vectorized with both lists of lists: .ι # Interleave the lists J # Then join each inner list together to a string .Δ # Find the first string which is truthy for: .V # Evaluate/execute the string as 05AB1E code Q # And check if the result is equal to the (implicit) input-integer # (after which the found result is output implicitly) ``` If we are allowed to output all possible results instead of just one, the `.Δ` (find first) could be `ʒ` (filter) for -1 byte. Although in that case it would become even slower than it already is.. [Answer] # [R](https://www.r-project.org/), ~~249~~ ~~244~~ ~~234~~ ~~224~~ ~~220~~ 200 bytes Or [R](https://www.r-project.org/)+arrangements library, ~~237~~ ~~232~~ ~~222~~ ~~212~~ ~~208~~ 188 bytes (and somewhat faster) *Multiple edits: -15 bytes thanks to Mukundan314 (no division needed), -4 bytes thanks to 'my pronoun is monicareinstate', -10 bytes by outputting in Polish (prefix) notation, and (latest) -20 bytes by outputting as error message* ``` function(n){apply(gtools::permutations(10,10)-1,1,function(k)apply(expand.grid(rep(list(1:4),9)),1,function(l){for(m in 10:1)F=c(`+`,`-`,`*`,`^`)[[c(l,1)[m]]](F,k[11-m]) if(F==n)stop(letters[l],k)}))} ``` [Try it online!](https://tio.run/##TY/LCsIwEEX3foXLGU2lA25a6LY/EaKNbVpC8yJJQRG/vVYEcXFWl8PhxtXKWV3dYm8qNuu4uD5r78DhU4ZgHjBl702q66CiXbL8jAmoZFRiQYzYz5jxK6h7kG44TVEPEFUAo1MGqs/IKsR/weBz9BHsXrs9lTVh2/TQHTvWFRuHjUuHnPdgGCG3Qgho2cyJCitwp0dom8Zhyn5rqJxVTNwINuML8fX/CqoK1zc "R – Try It Online") Outputs **as error message**, in Polish notation using 'a' to denote plus, 'b' to denote minus, 'c' to denote multiply, and 'd' to denote exponentiation. Commented version before golfing (with more-readable output that can be copy-pasted to directly check): ``` make_number=function(n,with=0:9) { i=arrangements::permutations(with) # all the permutations of the digits 0..9 j=as.matrix(expand.grid(rep(list(1:5),length(with)-1))) # all the combinations of 1..5 (for the 5 operators) o=c("+"=`+`,"-"=`-`,"*"=`*`,"/"=`/`,"^"=`^`) # the 5 operators that we can use for(k in 1:nrow(i)){for(l in 1:nrow(j)){ # cycle through the permutations of digits & operators t=i[k,1] # total starts as first digit for(m in 2:length(with)-1){t=o[[j[l,m]]](t,i[k,m+1])} # apply all the operators using each next digit if(!is.na(t)&&(t==n)){ # if we get the answer we're looking for... # return a string with the calculation return( paste0( paste0(rep("(",ncol(j)),collapse=""),paste0(c("",names(o)[j[l,]]),i[k,],collapse=")"))) } }} } > make_number(1) [1] "(((((((((0)-1)-2)-3)*4)-5)+6)+7)+8)+9" > make_number(99) [1] "(((((((((0)+1)/2)+3)+4)+5)*6)+7)+8)+9" > make_number(1234) [1] "(((((((((0)*1)+2)+3)^4)/5)+6)+7)*9)-8" ``` Note that this algorithm will always find first (and stop at) a solution with the smallest rearrangment of the digits from the starting order of 0..9. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 84 bytes ``` Nθ≔”y⁰¹²³⁴⁵⁶⁷⁸⁹”ε≔VεηW¬ω«≔⭆◧Iηχ§εΣκζ≦⊕η¿⬤ε№ζκFX⁴¦⁹«≔⭆⁹§”y⁺×⁻X”÷κX⁴λδ¿⁼V⁺δ⪫ζ´¦θ≔δω»»ωζ ``` [Don't try it online!](https://tio.run/##ZZBNTsMwEIXXzSmsrMZSkEBiU3VVlS6CoIrUE5jGbaw6TpvYDSrqwqfgBqwRvy2wCjfxBThCmLQRXbCxLHvee9@bScLyScZkXYdqYfTIpDc8hyXtef2iEDMFvrOP1a56qp6dfXH21dk3Z9@d3Tq78wPCj5PDFZOGaQ6cBiTB9zIRkhMYZRpKSsmd12knxzoXanbNFhCx@IpPNQxYoSFB3dkpHn0dqpjfAg/I2KQwpxQf1@jYQU3rEapJzlOuNI8PaR0xJdCXslENMqM0rAPSSMk0ywlEWYnFzgPSPaD8Z@keg7H0x/e9s58/X1ssGSp9IVYi5jAPyJ@RpHuuuMnehw@XhsniuIdImgKQ7jITqoHxqwd/L1kiQhuP32VjsPE2XoQkzap67Q0b13V9spK/ "Charcoal – Try It Online") Link is to verbose version of code. Outputs prefix notation using Charcoal operators and digits (note that it's not valid Charcoal code due to the omission of `¦` separators between the digits, and it still wouldn't be useful without the `I` cast operator). Explantion: ``` Nθ ``` Input `n`. ``` ≔”y⁰¹²³⁴⁵⁶⁷⁸⁹”ε ``` Assign the list of Charcoal's digits. ``` ≔⁰η ``` Start checking starting at `0000000000` and working up. ``` W¬ω« ``` Repeat until we have an answer. ``` ≔⭆◧Iηχ§εΣκζ ``` Convert the current trial index to a 10-digit number in Charcoal digits. ``` ≦⊕η ``` Increment the trial index. ``` ¿⬤ε№ζκ ``` If this is a permutation of the 10 digits, then... ``` FX⁴¦⁹« ``` Loop over all operator combinations, ``` ≔⭆⁹§”y⁺×⁻X”÷κX⁴λδ ``` convert each into a string of operators, ``` ¿⁼V⁺δ⪫ζ´¦θ ``` compare the value with `n`, ``` ≔δω ``` and set the result if it matches. ``` »»ωζ ``` Output the resulting operator string and digits. 96-byte version that can actually finish in under a minute on very simple examples: ``` Nθ≔”y⁰¹²³⁴⁵⁶⁷⁸⁹”ε≔VεηW¬ω«≔⭆◧Iηχ§εΣκζ≦⊖ι≦⊕η¿⬤ε№ζκW∧¬ω‹ιX⁴¦⁹«≔⭆⁹§”y⁺×⁻X”÷ιX⁴λδ¿⁼V⁺δ⪫ζ´¦θ≔δω≦⊕ι»»ωζ ``` [Try it online!](https://tio.run/##dZBNbsIwEIXX5BRWVrbkSiB1g1ihwiIVRZE4gUsGYtU4EDukomLhU/QGXVf9hbar9Ca@QI@QOmkkiqpuLGvezJtv3jRm6TRhoiwDucz0OFtcQopXpOf1leJziX1r7ot98VA8WvNkzbM1L9a8WrOzZu9TBIfO4ZqJjGnAQCiKXT2PuQCEx4nGOSHoxms1nROdcjm/YEscsmgEM43PmNI4dnOdtnv6OpARXGOgaJIt8BUhrrhxji0303gMYJrCAqSGiCJ@rAXyl1aRtPgM4b4QleNZkkmNNxRVtqhh7Muo4aRoBEphTlGY5C6KU4q6hPzg/@XvHmBdUG@ft9a8f33sXDCB1AO@5hEcWQlS3xJVTDXUcJUxoQ7ZhSJT2FGfJ1xWkH5x59cjK4fQrHdyXhuAUID@ObuOZOttvdCxVof1mp/LsSw77XZ5shbf "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 26 bytes *+5 bytes for a fix based on Kevin Cruijssen* ``` “+×*_”ṗ9 ⁵ḶŒ!p¢ż/€Ẏ€V=¥ƇḢḢ ``` Brute force, like the 05AB1E answer, so it is also extremely slow. Outputs in infix notation with `+×*_` to represent addition, multiplication, exponentiation, and subtraction respectively. All operators have equal precedence. Similarly to my Python answer, this generates an expression and evals it to find what it evaluates to. [Try it online (in a version that allows you to enter the number of digits)](https://tio.run/##y0rNyan8//9Rwxztw9O14h81zH24c/qxyVzHJj/cse3oJMWCQ4uO7tF/1LTm4a4@IBlme2jpsfaHOxYB0f//plwm/40MAA "Jelly – Try It Online") The value for `n` should be provided as the first argument, while the input should consist of two lines: the first equal to the number of digits; the second less by one. ### Explanation (going to update soon, I should be able to golf a bit off): ``` “+×*_”ṗ9 # literal string "+×*_" (Jelly arithmetic symbols) Cartesian power 9 ⁵ḶŒ!p¢ż/€Ẏ€V=¥ƇḢḢ ⁵Ḷ # lowered_range(10): [0,1,2,3,...,9] Œ! # all permutations of these digits p # Cartesian product with ¢ # the list of all permutations of 9 arithmetic symbols ż/€Ẏ€ # zip and tighten each to squeeze together (golfportunity?) V=¥Ƈ # Filter for those that evaluate to Ḣ # n (surely there is a way around this) Ḣ # get the first one ``` If no string works (which could occur if `n` is too large or the number of digits is decreased), then it outputs `0`. [Answer] # [Python 3](https://docs.python.org/3/), ~~200~~ ~~194~~ ~~186~~ 178 bytes *-6, -2, -6, -8 bytes, and a test runner thanks to @Mukundan314.* ``` lambda n:next(s for o in product(*[[*"+-*","**"]]*9)for l in permutations("0123456789")if eval(s:="("*8+l[9]+')'.join(o[i]+str(l[i])for i in range(9)))==n) from itertools import* ``` [Try it online! (5 digits case)](https://tio.run/##JY5BTsQwDEX3OUWUzSQpjBiaSqhST1K6CDQtRqkdJR7EnL40xQv7y3p@cnrwF2H7lvK@Du979NvH7CX2GH5ZF7lQliQBZco03z9Z23G0qnm26klZq6bJOlOZeDIhb3f2DIRFq5fba@uUgUWGHx916QellW2bOLqpuZjL9ZsANY0wNYWzjkc4VVBV2eMatDPGDAMasWTaJHDITBSLhC1RZrv/T1keRYjzC8BQr4/FtfAM2At5VMqArFdde0UO694J14nu9gc "Python 2 – Try It Online") Outputs in infix notation with parentheses, using `+-*` respectively for addition, subtraction, and multiplication; uses `**` and exponentiation. The program generates Python code that gets eval'd to check for equivalence to `n`. Slightly more-readable version with a variable for the number of digits: ``` L=9 import itertools as i def g(n): for l in i.permutations(map(str,range(1,L+1))): for o in i.product("+-*m",repeat=L-1): s=l[L-1] for j in range(L-1): s='('+s+o[j]+l[j]+')' s=s.replace("m","**") if eval(s)==n: return s ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 23 bytes ``` hfqQ.vjdsT*^"+-*^"9.pUT ``` [Try it online! (5 digit case)](https://tio.run/##K6gsyfj/PyOtMFCvLCulOEQrTklbF0iY6BWEmv7/b2QMAA "Pyth – Try It Online") ### Explanation ``` hfqQ.vjdsT*^"+-*^"9.pUT h : first element of f : filter on * : cartesian product of ^"+-*^"9 : all 9 length string that can be formed with the chars +, -, * and ^ .pUT : and all permutations of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] qQ : for equality of input and .vjdsT : evaluated result of operators and permutation joined with spaces ``` ]
[Question] [ Most people are familiar with Pascal's triangle. ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ``` Pascal's triangle is an automaton where the value of a cell is the sum of the cells to the upper left and upper right. Now we are going to define a similar triangle. Instead of just taking the cells to the upper left and the upper right we are going to take all the cells along two infinite lines extending to the upper left and upper right. Just like Pascal's triangle we start with a single `1` padded infinitely by zeros and build downwards from there. For example to calculate the cell denoted with an `x` ``` 1 1 1 2 2 2 4 5 5 4 x ``` We would sum the following cells ``` . . . 2 . 2 . 5 5 . x ``` Making our new cell `14`. # Task Given a row number (**n**), and distance from the left (**r**) calculate and output the **r**th non-zero entry from the left on the **n**th row. (the equivalent on Pascal's triangle is **nCr**). You may assume that **r** is less than **n**. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the goal is to minimize the number of bytes in your solution. # Test cases ``` 0,0 -> 1 1,0 -> 1 2,0 -> 2 4,2 -> 14 6,3 -> 106 ``` Here's the first couple rows in triangle form: ``` 1 1 1 2 2 2 4 5 5 4 8 12 14 12 8 16 28 37 37 28 16 32 64 94 106 94 64 32 64 144 232 289 289 232 144 64 128 320 560 760 838 760 560 320 128 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 bytes ``` SṚ0;+Sṭ 1WWÇ⁸¡ṪṙḢ ``` Uses 0-based indexing. [Try it online!](https://tio.run/##y0rNyan8/z/44c5ZBtbaQGotl2F4@OH2R407Di18uHPVw50zH@5Y9P/onsPL9R81rfEGYiDKAlENcxQUHjXMjfz/PzraQEfBIFaHSyHaEMYwgjFMdBSMwAwzHQXj2FgA "Jelly – Try It Online") ### How it works ``` 1WWÇ⁸¡ṪṙḢ Main link. Arguments: n, r 1 Set the return value to 1. W Wrap; yield [1]. W Wrap; yield [[1]]. This is the triangle with one row. Ç⁸¡ Call the helper link n times. Each iteration adds one row to the triangle. Ṫ Tail; take the last array, i.e., the row n of the triangle. ṙ Rotate row n r units to the left. Ḣ Head; take the first element, i.e., entry r of row n. SṚ0;+Sṭ Helper link. Argument: T (triangle) S Take the column-wise sums, i.e., sum the ascending diagonals of the centered triangle, left to right. Ṛ Reverse the array of sums. The result is equal to the sums of the descending diagonals of the centered triangle, also left to right. 0; Prepend a 0. This is required because the first element of the next row doesn't have a descending diagonal. S Take the column-wise sum of T. + Add the ascending to the descending diagonals. ``` [Answer] # [Python 3](https://docs.python.org/3/), 72 bytes 1 byte thanks to Kritixi Lithos. ``` f=lambda n,r:n>=r>=0and(0**n or sum(f(i,r)+f(i,r+i-n)for i in range(n))) ``` [Try it online!](https://tio.run/##VczBCoMwEATQu1@xx6xuIVXxIMR/SbFpF@ooW3vo16ehUKin4THDbO/9vqLLOYVHXC5zJIiNmIJNwUfMztc1aDV6vhaXnIpx841GT@BUCiUFWcTt6sDMeTPFXqZePHP10/mg9qBe2j8N0pWXDw "Python 3 – Try It Online") [Answer] # ES6, 80 78 bytes ``` p=(n,r,c=0)=>n?(o=>{while(n&&r<n)c+=p(--n,r);while(o*r)c+=p(--o,--r)})(n)||c:1 ``` [In action!](https://jsfiddle.net/2ndAttmt/s6nojj9f/1/) Two bytes thanks to Arnauld. [Answer] # [PHP](https://php.net/), 94 bytes recursive way 0-indexed ``` function f($r,$c){for($s=$r|$c?$r<0?0:!$t=1:1;$t&&$r;)$s+=f($r-=1,$c)+f($r,$c-++$i);return$s;} ``` [Try it online!](https://tio.run/##LcxBCoAgFEXRrRQ8IrEgCRr0ExcjSU1Uvjaq1m4FTe7s3LjFspj41h3e5j34yrXgDlacLnCLpMEXrAEvgxnmGlmrWRFy04BJIEn9gV6rz8gf91JiF8RrPtgj0V1Wu4V3PXWjoPIA "PHP – Try It Online") # [PHP](https://php.net/), 125 bytes 0-indexed ``` for(;$r<=$argv[1];$r++)for($z++,$c=~0;++$c<$z;$v+=$l)$x[$c]+=$t[+$r][$c]=$l=($v=&$y[$r-$c])+$x[$c]?:1;echo$t[$r-1][$argv[2]]; ``` [Try it online!](https://tio.run/##JY1BC4JAEIXv/QwbwmUUsqBD6@IhPHSpS7dlkVhMhXCXYZHy4F@30Q4D8773wfOtn/PCt35TEzmqqPaOQtc38VRWt/vjeimF3MCTmkHpKI2S6MR3jIycX45iCZSrtdWZ4YAoFgwjYgJWTXuJCDaHUcKACt4CPhqs4TdoBDJLYKxiGNQOvhooZSLwrxXnTNa2dSxzkbG9Lh0Mr289dX2oeCsIOf8A "PHP – Try It Online") ## PHP>=7.1, 159 bytes 0-indexed for rows over 50 ``` for([,$m,$n]=$argv;$r<=$m;$r++)for($z++,$c=0;$c<$z;$v=bcadd($v,$l),$x[$c]=bcadd($x[$c],$l),$c++)$t[+$r][$c]=$l=bcadd(($v=&$y[$r-$c]),$x[$c])?:1;echo$t[$m][$n]; ``` [Answer] # [Python 3](https://docs.python.org/3/), 61 bytes ``` f=lambda n,r:sum(f(k,r)+f(k,r+k-n)for k in range(n))or~n<-r<1 ``` This returns *True* for base case **(0, 0)**, which is [allowed by default](https://codegolf.meta.stackexchange.com/a/9067/12012). [Try it online!](https://tio.run/##TY2xDoJAEERr@Irp2IXDBElMJPAlaoFyqEEWspyFjb9@giHRTDHFzJsZX@42SO59Wz3q/tzUEKPF9Oyppc4oJ19LulS4HRQd7gKt5WpJmAd9S5lqmfklk1@25yIMRr2LIysNKkSzYlC2Qzr3YmyZwzBYKP1bRIJsIVd0ckrzvxgo8@ZixVmlnA3WzaMgOihKyIn9Bw "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` !!¡ȯSż+oΘ↔mΣT;;1 ``` [Try it online!](https://tio.run/##ASMA3P9odXNr//8hIcKhyK9Txbwrb86Y4oaUbc6jVDs7Mf///zP/Mg "Husk – Try It Online") Same idea as Dennis' answer, but simpler indexing method. [Answer] # [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)), 145 bytes ``` function f(n,k:integer):integer;var i,r:integer;begin r:=1-Ord((k<0)or(k>n));if n>0 then r:=0;for i:=1 to n do r:=r+f(n-i,k-i)+f(n-i,k);f:=r;end; ``` [Try it online!](https://tio.run/##PY5BcsMgDEXX5hTaBVLTcTvNTAaaXKFncG1wFafCQ2l6fFcQk79g0Jf0vpb@Z@iv2i/Dui4xTLH/BhxdIGcFCP9LQ8JA4CW1s0FKbnJR1Y@99RGwjY/6001IEM3pRX/EUcr5vVMhyvlMSln0QOcO0pcrI531gbd5FlIAgjFkNz5xlMZ21qjqV1nPDetozDdxpgAWtnAxUJNFiRZNYYI5QZepR6aKJk9vbdj0FzE5uYOdkcf9QeP@oEa8wauyomkK5PKAYIGwNkbWfd/LfIQyb/e1ajNWlbpcXO0r1Uax@Xle138) Uses the `T(n, r) = T(n-1, r-1) + T(n-1, r)` recursion. ]
[Question] [ # Prelude: This challenge is different from "another cat program". There's literal tons of different twists, why can't I have my own, people? Unique things: * It isn't reading direct input to output. * It is manipulating the string in a way that for sure isn't a straight-up cat. # Challenge: Given 3 inputs (or one input, separated however you like) get three objects (words) that we're going to substitute for pens, pineapples and apples in the lyrics and output. ## Output format ([according to lyrics found on AZLyrics](http://www.azlyrics.com/lyrics/pikotaro/ppappenpineappleapplepen.html)): Assuming (replace values with brackets with these): * A, B, C with input words (ex. `apple`) * UA, UB, UC with input words with uppercase first letters (if not uppercase already) (ex. `Apple`) * FUA, FUB, FUC with respectively first uppercase letters: (ex. `A`) * a/an with article respective to first letter vowel/consonant (ex. `an`) ``` [FUA]-[FUB]-[FUC]-[FUA] I have [a/an] [A], I have [a/an] [C]. Uh! [UC]-[UA]! I have [a/an] [A], I have [a/an] [B]. Uh! [UB]-[UA]! [UC]-[UA], [UB]-[UA]. Uh! [UA]-[UB]-[UC]-[UA]. [UA]-[UB]-[UC]-[UA]! ``` # Test case: Test with `pen`, `pineapple` and `apple`: ``` P-P-A-P I have a pen, I have an apple. Uh! Apple-Pen! I have a pen, I have a pineapple. Uh! Pineapple-Pen! Apple-Pen, Pineapple-Pen. Uh! Pen-Pineapple-Apple-Pen. Pen-Pineapple-Apple-Pen! ``` # Rules: * If input doesn't start with a letter, assume consonant (`a`) and first uppercase the first character (ex. `123 -> 1`). * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest amount of characters wins! [Answer] ## JavaScript (ES6), ~~217~~ ... ~~187~~ 183 bytes Takes input as an array of 3 strings, such as `['pen', 'pineapple', 'apple']`. ``` a=>`0-1-2-0 6, 895-3! 6, 794-3! 5-3, 4-393-4-5-3. 3-4-5-3!`.replace(/\d/g,n=>[u=(w=a[n%3])[0].toUpperCase(),u+w.slice(1),`I have a${~'AEIOU'.search(u)?'n':''} `+w,`. Uh! `][n/3|0]) ``` ### Examples ``` let f = a=>`0-1-2-0 6, 895-3! 6, 794-3! 5-3, 4-393-4-5-3. 3-4-5-3!`.replace(/\d/g,n=>[u=(w=a[n%3])[0].toUpperCase(),u+w.slice(1),`I have a${~'AEIOU'.search(u)?'n':''} `+w,`. Uh! `][n/3|0]) console.log(f(['pen', 'pineapple', 'apple'])); console.log(f(['golf', 'puzzle', 'code'])); ``` [Answer] ## [Perl 6](http://perl6.org/), 165 bytes ``` {"0-3-6-0 2, 897-1! 2, 594-1! 7-1, 4-191-4-7-1. 1-4-7-1!".subst: /\d/,->$x {((.tc.comb[0],.tc,"I have a{'n' if /:i^<[aeiou]>/} $_" for $_),". Uh! ").flat[$x]},:g} ``` Uses the same approach as [Arnauld's JS answer](https://codegolf.stackexchange.com/a/103454/14880). [Answer] ## Batch, ~~494~~ 490 bytes ``` @echo off set s=%1 set t=%2 set u=%3 call:u %s:~,1%- %t:~,1%- %u:~,1%- %s:~,1% echo( call:h %1 %3 call:u Uh! %3- %1! echo( call:h %1 %2 call:u Uh! %2- %1! echo( call:u %3- %1, %2- %1. call:u Uh! %1- %2- %3- %1. call:u %1- %2- %3- %1! exit/b :h set s=I have a %1, I have a %2. for %%v in (a e i o u)do call set s=%%s:a %%v=an %%v%% echo %s% exit/b :u set s= %* for %%u in (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)do call set s=%%s: %%u= %%u%% echo%s:- =-% ``` Explanation: The `:h` subroutine handles the line `I have a %, I have a %.` The `%`s are substituted from the appropriate command-line arguments, and then the strings `a a`, `a e`, `a i`, `a o` and `a u` are replace with the equivalent `an` version. The `:u` subroutine handles the other lines; it takes the parameter words, and upper cases all the first letters. (An extra space is prefixed to allow the first word to be upper cased, but it is removed on output.) To handle words after `-`s, extra spaces are passed, but they are also deleted on output. The `:u` subroutine is also used for the first line, although extracting the initials is awkward. [Answer] # [Python 3.6](https://www.python.org/downloads/release/python-360a1/) - ~~351~~ ~~287~~ 286 bytes ``` def x(a,b,c):t=(a,b,c);p,q,r=('a'+'n'*(i[0]in'aeiouAEIOU')for i in t);A,B,C=map(str.title,t);print(f"""{A[0]}-{B[0]}-{C[0]}-{A[0]} I have {p} {a}, I have {r} {c}. Uh! {C}-{A}! I have {p} {a}, I have {q} {b}. Uh! {B}-{A}! {C}-{A}, {B}-{A}. Uh! {A}-{B}-{C}-{A}. {A}-{B}-{C}-{A}!""") ``` There is nothing fancy here except making use of the new feature of string literal formatting. ``` Input: s('golf','puzzle','code') ``` ``` Output: G-P-C-G I have a golf, I have a code. Uh! Code-Golf! I have a golf, I have a puzzle. Uh! Puzzle-Golf! Code-Golf, Puzzle-Golf. Uh! Golf-Puzzle-Code-Golf. Golf-Puzzle-Code-Golf! ``` **Note** - The version is `3.6` where string literal formatting was [introduced](https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep498). Hence, this won't work in earlier versions. [Answer] # Lua, ~~615~~ 607 bytes *Saved 8 bytes thanks to [an anonymous user]* *Whew, long one. [Try it here.](http://ideone.com/zkbzNK)* ``` w=io.read a,b,c=w(),w(),w()function d(u)if ("aeiouAEIOU"):find(z(u))~=nil then return "an" else return "a" end end function z(y)return y:sub(1,1):upper()end f=z(c)..c:sub(2).."-"..z(a)..a:sub(2).."-"..z(b)..b:sub(2).."-"..z(a)..a:sub(2)print(z(a).."-"..z(b).."-"..z(c).."-"..z(a).."\n\nI have "..d(a).." "..a..", I have "..d(c).." "..c..".\nUh! "..z(c)..c:sub(2).."-"..z(a)..a:sub(2).."!\n\nI have "..d(a).." "..a..", I have "..d(b).." "..b..".\nUh! "..z(b)..b:sub(2).."-"..z(a)..a:sub(2).."!\n\n"..z(c)..c:sub(2).."-"..z(a)..a:sub(2)..", "..z(b)..b:sub(2).."-"..z(a)..a:sub(2)..".\nUh! "..f..".\n"..f.."!") ``` *I am 100% certain this can be shortened. I am just lazy..* Basically uses **a lot** of string manipulation. There are 3 main functions and one variable: * `d(string)`: returns an if string is vowel (`AEIOUaeiou`), else returns a * `z(string)`: returns the first letter in uppercase * `z(s) .. s:sub(2)`: returns whole word, but first letter uppercase * `f`: the end word (in a variable, to save some bytes). In your test case, it would be `Pen-Pineapple-Apple-Pen`. ## Input: `pen`, `pineapple`, `apple` ## Output: ``` P-P-A-P I have a pen, I have an apple. Uh! Apple-Pen! I have a pen, I have a pineapple. Uh! Pineapple-Pen! Apple-Pen, Pineapple-Pen. Uh! Pen-Pineapple-Apple-Pen. Pen-Pineapple-Apple-Pen! ``` [Answer] # [Python 2](https://docs.python.org/2/), 283 bytes ``` a=input() r='0-1-2-0\n\n9 3, 9 5.\nUh! 8-6!\n\n9 3, 9 4.\nUh! 7-6!\n\n8-6, 7-6.\nUh! 6-7-8-6.\n6-7-8-6!' for j in range(10):r=r.replace(str(j),([i[:1].upper()for i in a]+[['a ','an '][1+'aeiouAEIOU'.find(i[:1])/9]+i for i in a]+[i[:1].upper()+i[1:]for i in a]+['I have'])[j]) print r ``` [Try it online!](https://tio.run/##VY2xboMwEIZ3nuKYzhaYQNomAYmhQ4dMnTIZD1bqFKPoODlQqU9PA2Io0919v777@Xdoe9pPk6098TgIGYUac1WovcobaqiElxRKeMsaurQxnNQh/odfV3xc8TNO52PFB3VUp@VatxijWx@gA08QLH07UeSyCnXIguO7vTrxGILoZCq011VhspHZBSFnyc@SNYnWaAFTtARodJGgdb4f3z/OnxfMbp6@xKLKXWkSDxtz8zPxuqjMJscztPbHoZG6MzLi4GmAME0a2dGzkj05y3x3c/0yzR8 "Python 2 – Try It Online") [Answer] # [TypeScript](https://www.typescriptlang.org)'s Type System, 348 bytes ``` //@ts-nocheck type P<S>=Capitalize<S> type U<S>=P<S extends`${infer A}${any}`?A:S> type N<S>=`I have a${U<S>extends"A"|"E"|"I"|"O"|"U"?"n":""} ${S}` type F<A,B,C,D=P<A>,E=P<B>,F=P<C>,G=`${D}-${E}-${F}-${D}`>=`${U<A>}-${U<B>}-${U<C>}-${U<A>} ${N<A>}, ${N<C>}. Uh! ${F}-${D}! ${N<A>}, ${N<B>}. Uh! ${E}-${D}! ${F}-${D}, ${E}-${D}. Uh! ${G}. ${G}!` ``` [Try it at the TypeScript playground!](https://www.typescriptlang.org/play?#code/PTACBcGcFoDsHsDGALApog1gKHATwA6oAEACgDwDKAfALwDCAhvgJbgMA2zAXqpVTgWIBVPjXIUiqAB7hUsACaQABgBIA3s1gAzVACciAQQC+6hrFxGlAfgMAuagMJEAcqKUBJIsgYA3Yg3URamlZBUgAIgNwgB9wgFEY8PdEgHlEoXCrcNhw23DwoyJ1CktHYgAxMgMAGgAharpqgBExKqpquNba9vLWunaAcRpVNSajaHU48fVy6dHLWhGRAyo5kW61sn7NlaMsLHVXXeqitVdtgDosIWQAQlPZifnb-cO2oxO3jaub+8m5sYvA5qR7qMafNRTJ5jH53U4DIxXdQI25KfYgIiySDgIiIBiQVCQfZ4JwkEgGEhEGhESrhQg5E50zSoJj4diocKM1ns8L8DFEIgAPSsRCwGOQ8D8+klelI5Mp7AYACNUOwykQ6AM6HQqTSyOFEPB5BzGQBzeDsLScogG7zsdmwU2E3li4ACoUi11eGXSqUarU6xUqtVAA) Composes helper types to avoid repeating as much code as possible, then uses them in a type `F<A,B,C>`. Explanation: ``` type P<S>=Capitalize<S> // alias the built-in to uppercase the first // letter of a string type, since it is // used a lot. type U<S>=. // to get the initial of the string, we P<S extends // capitalize the result of matching against `${infer A}${any}` // a string-type to match the first letter ?A // select that letter to capitalize :S> // unless the match failed somehow. type N<S>= // to get the "I have [a/an] [S]" bit, we `I have a${ // take "I have a" and U<S>extends // check if the initial of the word matches "A"|"E"|"I"|"O"|"U" // an uppercase vowel ?"n":"" // if it does, insert "n", otherwise "" } ${S}` // finally, we append a space and the word. type F<A,B,C, // take the three words A, B, and C D=P<A>,E=P<B>,F=P<C>, // assign D, E, F to A, B, C capitalized G=`${D}-${E}-${F}-${D}` // assign G to the "Pen-Pineapple-Apple-Pen" >= `${U<A>}-${U<B>}-${U<C>}-${U<D> /* the P-P-A-P bit */} ${N<A>}, ${N<C> /* I have a pen, I have an apple */}. Uh! ${F}-${D /* Apple-Pen */}! ${N<A>}, ${N<B> /* I have a pen, I have a pineapple. */}. Uh! ${E}-${D /* Pineapple-Pen */}! ${F}-${D /* Apple-Pen */}, ${E}-${D /* Pineapple-Pen */}. Uh! ${G /* Pen-Pineapple-Apple-Pen */}. ${G /* Pen-Pineapple-Apple-Pen */}!` ``` ]
[Question] [ What are your tips for code golfing using Clojure? The aim of this question is to collect a list of techniques that are specific to Clojure and can be used in general code-golfing problems. [Answer] Use reader syntax for lambdas. So use ``` #(+ % %2 %3) ``` instead of ``` (fn [x y z] (+ x y z)) ``` You can also eliminate whitespace some of the time: ``` #(if (< % 0) (- %) %) #(if(< % 0)(- %)%) ``` [Answer] # Where you can remove whitespace: * Between a string and anything else: ``` (println(+"Hello, World!"1)) ``` * Between brackets and anything else: ``` (for[x(range 5)](* x x)) ``` * Between a number and everything other than builtins or variable names: ``` Allowed: (+ 1"Example") (map{1"-1"2"-2"}[1 2 3]) Not allowed: (+1 2) ``` * Between `@` (dereference for atoms) and brackets. [Answer] **Strings can be treated as a sequence of chars** e.g. to sort the characters in a string alphabetically: ``` (sort "hello") => (\e \h \l \l \o) ``` [Answer] # Use `nth ... 0` instead of `first` To get the first element of a collection, using `(nth ... 0)` over `first` saves a byte: ``` (first[2 3 4]): 14 bytes (nth[2 3 4]0): 13 bytes (saves a byte!) ``` [Answer] # Use maps instead of `if`s when testing for equality ``` ;; if n=3 then A else B (if (= 3 n) A B) ; (if(=3n)AB) ({3 A} n B) ; ({3A}nB) -> -3 chars ;; if n=2 or n=3 then A else B (if (#{2 3} n) A B) ; (if(#{23}n)AB) ({2 A 3 A} n B) ; ({2A3A}nB) -> -4 chars ``` [Answer] # Use apply instead of reduce For example `#(apply + %)` is one byte shorter than `#(reduce + %)`. [Answer] ## Avoid let if you already have a for For example: `#(for[a[(sort %)]...)` instead of `#(let[a(sort %)](for ...))`. For does also have a `:let` construct but it is too verbose for code golf. [Answer] # Use `+` and `-` instead of `inc` and `dec` This saves 1 byte if you're using `inc`/`dec` on an expression with parens: ``` (inc(first[1 3 5])) (+(first[1 3 5])1) ``` [Answer] ## Bind long function names at let to a single-byte symbol For example if you need to use `partition` or `frequencies` multiple times, it could be beneficial to bind them to a single-byte symbol in a `let` macro. Then again it might not be worth it if you don't need the `let` otherwise, and the function name is relatively short. [Answer] # Use for instead of map For instance `#(for[i %](Math/abs i))` is a lot shorter than the `map` equvalent. ]
[Question] [ Write a program that, for any \$n\$, generates a triangle made of hexagons as shown, \$2^n\$ to a side. The colors are to be determined as follows. We may give the triangle barycentric coordinates so that every hexagon is described by a triple \$(x,y,z)\$ with \$x+y+z=2^n-1\$. (The three corners will be \$(2^n-1,0,0)\$, \$(0,2^n-1,0)\$, and \$(0,0,2^n-1)\$.) Let \$s\_2(n)\$ refer to the number of 1s in the binary expansion of \$n\$. (This is sometimes called the *bitsum* or the *popcount* function.) If $$s\_2(x)+s\_2(y)+s\_3(z)\equiv n\pmod 2$$ then color the hexagon \$(x,y,z)\$ in a light color; otherwise, color it in a dark color. (These must be *colors*, not simply black and white.) In your answer, I would appreciate seeing several example outputs, ideally including \$n=10\$. This is my first post here, so I apologize if I misunderstand the rules somehow. [![enter image description here](https://i.stack.imgur.com/XGjBz.png)](https://i.stack.imgur.com/XGjBz.png) This is a code golf challenge, so shortest code (in bytes) wins. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 119 bytes -1 byte thanks to [@att](https://codegolf.stackexchange.com/users/81203/att). ``` Graphics@Table[{Hue[Tr[ThueMorse@{x,y,s-x-y}+#+1]/2],RegularPolygon[{2x+y,√3y},{1,Pi/2},6]},{x,0,s=2^#-1},{y,0,s-x}]& ``` [![enter image description here](https://i.stack.imgur.com/npzXy.png)](https://i.stack.imgur.com/npzXy.png) [Answer] ## JavaScript (ES~~7~~6), ~~191~~ ~~187~~ ~~180~~ ~~174~~ ~~172~~ ~~168~~ 152 bytes ``` f= n=>eval('s="<center style=line-height:.7>";for(i=-1;++i<1<<n;s+="<br>")for(j=i+1;j--;)s+=`<font color=#f${(g=n=>n?9-g(n&n-1):9)(i^j^i-j)}0>⬢</font>`') ``` ``` <input type=number min=0 max=10 onchange=o.innerHTML=f(+this.value)><div id=o style=font-size:5px> ``` Output format is HTML. Snippet limited to `n=10` because it triggers my browser's slow script warning if you go any higher. (But the output is too big for my screen anyway.) Edit: Saved ~~4~~\* 11 bytes by simplifying the parity calculation. Saved ~~6~~ ~~8~~ 23 bytes thanks to @Ausername. Saved ~~4~~\* 5 bytes thanks to @EzioMercer. \*crossed out 4 is still regular 4 [Answer] # C++ using SFML : ~~722~~ ~~703~~ ~~683~~ ~~527~~ ~~411~~ 399 bytes -19 bytes thanks to NoLongerBreathedIn, using \_\_builtin\_popcount removes needing a bitsum function. Might work only for GCC. -20 bytes, I used the using keyword for namespaces and components, and stopped using `.f` for magic numbers -156 bytes thanks to pan -116 bytes again thanks to pan -12 bytes thanks to ceilingcat and pan pan's proposed version approximates the value of cos(210) to around -.86, which will produce a slightly different graphic output, but very close to what's required by the challenge. This makes the cmath include useless. He also put the whole code into one function, and used a number of golfy techniques to reduce more the byte count, which makes the result very nice. His second optimization renders the use of vector useless, making an include and object usage useless pan's code : ``` #include<SFML/Graphics.hpp> #define B+__builtin_popcount( void v(int n){sf::CircleShape h(4,6);for(sf::RenderWindow w({1200,1000},"");w.isOpen();w.display()){for(sf::Event e;w.pollEvent(e);)e.type?h.setOrigin(-600,-650):w.close();w.clear();for(int x=0,y,z=1<<n;x<z;)for(y=x++-z;y++;)h.setPosition(4.3*(2*y+z-x),2.5*(2+z-3*x)),h.setFillColor(sf::Color(B-x)B-y)B z+y-x)-n&1?65535:-65281)),w.draw(h);}} ``` [SFML](https://www.sfml-dev.org/index.php) is a library that helps with the development of graphical / audio / network applications. Previous 683 bytes answer (with the "exact" value or cos(210°)) : ``` #include <cmath> #include <vector> #include <SFML/Graphics.hpp> #define B(c) __builtin_popcount(c) using namespace sf;struct t{double x,y;bool b;};using V=std::vector<t>;V d(int n){double r=5;int x,y,z,w=pow(2,n);V o;for(x=0;x<w;++x)for(y=0;y<w-x;++y){z=w-1-x-y;o.push_back({-cos(7*M_PI/6)*(r*y-r*z),r*x-(r*y+r*z)/2,(B(x)+B(y)+B(z))%2==n%2});}return o;}int v(int n){RenderWindow w(VideoMode(1200,1000),"");CircleShape h(4,6);;auto v=d(n);while(w.isOpen()){Event event;while(w.pollEvent(event))if(event.type==Event::Closed)w.close();w.clear();for(auto&a:v){h.setPosition(a.x,-a.y);h.setOrigin(-600,-650);h.setFillColor(a.b?Color::Yellow:Color::Blue);w.draw(h);}w.display();}return 0;} ``` Function to call in the main is `v(int)` with the parameter being n, the number `n` ``` int main() { return v(6); } ``` Compile with : `g++ source.cpp -lsfml-graphics -lsfml-window -lsfml-system` Run with : `./a.out` Due to the screen size and the fact that hexagons have to be visible, the size of a n=10 triangle can't be seen fully in a 'normal' sized screen, triangle is fully visible in the screen at n<=7. Size of hexagon and space between them can be configured in the `d(int)` function with variable `r` and `v(int)` function by modifying the first parameter of the constructor of the `h` variable (the CircleShape object), that value being the radius of the circle. Be free to modify those parameters to draw bigger hexagons on the screens, `r` should be slightly bigger that the circle's radius Here is an image of the result for `n=6` [![Triangle for N=6](https://i.stack.imgur.com/8XwkZ.png)](https://i.stack.imgur.com/8XwkZ.png) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 222 bytes ``` n=6;c=Graphics[{#,Rotate[Polygon@CirclePoints@6,30Degree]},ImageSize->9]&;Column[Row/@TakeList[(Tr@DigitCount[#,2,1]~Mod~2&/@Reverse@Select[Range[0,h=2^n-1]~Tuples~3,Tr@#==h&])/.{1->c@Red,0->c@Blue},Range[2^n]],Center,.01] ``` [![enter image description here](https://i.stack.imgur.com/TYtxJ.png)](https://i.stack.imgur.com/TYtxJ.png) ]
[Question] [ In this challenge, Turing machines operate on a zero-initialized binary tape that is infinite in both directions. You are given an integer \$N\$, where \$1 \le N \le 20000\$. Your program has to output a Turing machine that takes exactly \$N\$ steps to halt, including the final step. Alternatively, you can write a program that outputs all 20000 machines. Your program should complete within 2 hours for all 20000 inputs, when tested on my computer (AMD Ryzen 2600 12-thread CPU). If your program solves all test cases on the same thread, sequentially and independently, your program's running time is divided by 4. Your score is the total number of states in all 20000 outputs of your program. The lowest-scoring program wins. ## Output Below is described the (recommended) output format for a *single* test case. In the first line, output a number \$M\$, the number of states of the machine. In the next \$M\$ lines, output the transitions from the states, in order from the first to the last, if the cell under the pointer is zero. In the next \$M\$ lines, output the corresponding transitions, if the cell under the pointer is one. The output format for transitions is **`movement newval newstate`**, where **`movement`** stands for either `L` - move left, `R` - move right, `S` - do not move, or `H` - halt, **`newval`** is the new value of the cell under the pointer (it can be equal to the original one), and **`newstate`** is an integer from \$1\$ to \$M\$, the state the machine will be in in the next step. [Python 3 checker that inputs in the format described above and outputs the number of steps the Turing machine takes to halt](https://tio.run/##jVE7b4MwEJ7xrzipQ7AKFSQbajpnyBR1Qwxucgmo1CDbNO2vp3eACak6dPHjfN/r3H67stGbvtewhUq7sNJt50IpxQnP0Cpjsa40hlZmIrDUY59sW1fUIQKDrjMacpsnRTSAbZ4W0h/XhYQY0kJYpxzahMD5jdDrwLkxUBEEjNIXDLX0gPT/gLZhawnvTrXIwKQQGi/@Vgilx5ZjZwb64XItqxrh1XRI6ejlWCpDDxNNTnsB1Znv8EL9gLVFmGjzmMoxxQs@mk@MqHxlOB@@nJeYoudedaCbhWbKKfCtTQQPreExkkbkAX9pRMDq9Bmc73ELqQgWhrP7KFtPIAKWzX5HWTYQCzOzydVulcGbQfV@X96vBn6Ivez8cpheRkOLkc@@lzZr1OHkU86OGcuf6PueaVZKn2C06mFTADlH8bBxejQU2fcbcYAU1mJPazqs49nXd3z@AQ "Python 3 – Try It Online"). If you use a different output format, please include a link to a program that can be used to simulate your Turing machines (it's likely a good idea to simply modify my checker). [Answer] # [Python 3](https://docs.python.org/3/), ~~275,467~~ 255,540 states *Thanks @mypronounismonicareinstate for suggesting to add \$I\$ into the \$B \rightarrow C\$ loop, which ultimately saves about \$20k\$ states.* ``` def print_machine(states): print(len(states[0])) for i in 0,1: for s in states[i]: # if s is None (state unused), puts dummy value in there move, new_val, new_state = s or ["H", 0, 0] print(move, new_val, new_state+1) # simple machine that uses ceil(step/2) states # used for small cases def generate_simple_machine(steps): n_states = (steps+1)//2 # states[cur_char][state_id] states = [[], []] for i in range(n_states): states[0].append(["S", 1, i]) states[1].append(["S", 0, i+1]) states[1][-1][0] = "H" if steps%2==1: states[0][-1][0] = "H" return states BASE_STEPS = [(1<<i+2)-i-3 for i in range(20)] BASE_STEPS[0] = -999 def generate_counter_machine(steps, do_print=True): # how many bits/states needed? for n_bits, max_steps in enumerate(BASE_STEPS): if max_steps > steps: break n_bits -= 1 n_states = n_bits + 2 extra = steps - BASE_STEPS[n_bits] if extra >= (1 << (n_bits+1)): n_states += 1 # if small number of steps, use simple machine n_states_simple = (steps+1)//2 if not do_print: return min(n_states_simple, n_states) if n_states >= n_states_simple : states = generate_simple_machine(steps) print_machine(states) return n_states_simple # states[cur_char][state_id] # use 0 indexed state states = [[None]*n_states, [None]*n_states] # state indices I_STATE = 0 B_STATE = 1 E_STATE = n_states - 1 C_STATES = [i+2 for i in range(n_bits)] # initial state states[0][I_STATE] = ["R", 1, C_STATES[0]] states[1][I_STATE] = ["H", 0, 0] # not used initially # go back state states[0][B_STATE] = ["L", 0, B_STATE] states[1][B_STATE] = ["R", 1, C_STATES[0]] # ith-digit check states for i in C_STATES: states[0][i] = ["L", 1, B_STATE] states[1][i] = ["R", 0, i+1] states[1][C_STATES[-1]][0] = "H" # dealing with extras # first, figure out how many half-state # goes between B_1 -> C1_x t = 1<<n_bits q1 = t - 1 q2 = q1 + t q3 = q2 + t if extra < q1: extra_state = I_STATE elif extra < q2: # connect B_1 -> I_0 -> C1_? states[1][B_STATE] = ["S", 0, I_STATE] extra -= q1 extra_state = I_STATE elif extra < q3: # connect B_1 -> I_0 -> I_1 -> C1_x states[1][B_STATE] = ["S", 0, I_STATE] states[0][I_STATE] = ["S", 1, I_STATE] states[1][I_STATE] = ["R", 1, C_STATES[0]] extra -= q2 extra_state = E_STATE else: # connect B_1 -> I_0 -> I_1 -> E_0 -> C1_x states[1][B_STATE] = ["S", 0, I_STATE] states[0][I_STATE] = ["S", 1, I_STATE] states[1][I_STATE] = ["S", 0, E_STATE] states[0][E_STATE] = ["R", 1, C_STATES[0]] extra -= q3 extra_state = E_STATE # then put a half-state between Cx_0 -> B # if needed if extra > 0: states[1][extra_state] = ["L", 1, B_STATE] for i in reversed(C_STATES): if extra%2==1: states[0][i] = ["S", 1, extra_state] extra //= 2 print_machine(states) return n_states ``` [Try it online!](https://tio.run/##vVbLbus2EN3rKwYOCki1VEvyKoGdi@vARQ0URVFnZwiCLNE2cWXKV6Ly@Pp0hqRedpykmy6CmORozpkzD/L0Kg@FmL69ZWwHp5ILGR@T9MAFsyuZSFY5d5bet3MmzN7GjxzHgl1RAgcuwHcDtFLritbGike0CzfAd7RfwV@FYKB9QC3qimWOC6daVpDVx@MrPCV5zciBPLCS0bfH4om5INhzjGf6h/58jh4RbjP6Y@QiPvgRmWui1z4aB45l3UDFj6ecgQkTsRIJyKWClPEc2bHTJHRMDGhONHVoxyTPIU3Q1CK19kywEo1i7bCnGzsp2YSGrZCs3kQCk0looSJGobQu4/SQlNFGbcQ8wzDajzabyIVNFPWULhOxZ3bjmECgTclvyenERGZvRmvUJHCBR053Hpydo2Z8HJBFa7Dx8M@PEBlVtVTWiPUv4Xwe3HU4Z2Ylk3XZ5NyyrMX39TJePy7/XlMIdjCb8XHoeNybnocR@k7UM9c@vdvbW2uob1rUQrJyKLALWRGrfM8fy5qRFDdwKJ4xr@IVtlxWEyOkYCxj2TetoojpyEWrl1j5ITpM1EcFZXdslLYoQWd4r@VQNb0tWfLDMt7Am0MwSLfZHwMmm73IMqF6VU486AWszSIltTa7x1IJYDYDW59hxSgire@xgrJMU6mKRPJbVkJh0uVSxZ4VeUfOFOtFSaI3UchWU8I0iT1yYZ997bbuHP1lw@5@fgHUlShiftwyFrw/gTouZ86tz1pJdS/4mOOMvWAbq6NBh9FIin5t/GK7DTeiDoKc8BRLHFaYvu@PS0AHvgWLboWZWXarVhWPDh70gWoKbIjLlqZ0OxqPCy55kg/pUucZZOqTzegf3eWNYzyP@s08sG2nJI1jSrSaagYnf1Wo@wK2SfrjEnXR9/Sn9tTs9REXn7FTscmDl/E9l5AeWINW9UZc88VgtuFd0qIHffQePO@AzXDrk2uJ4PTqjS@ilLEk52IPz8hN92FF2zteVtLFf/u6ZFDUshsvhyTfeUYnEg6TvGXymTGB1ALw7uEhiF8skFQUs5lOrgU/A1xLXQ8/Q/yNG2OQuJjSItQLbCgzDWZoQDKoVXvxmcTiZMnbuYGWIVneQFoIwVLZ8FjFvqHzbSDWIFfmPlh1qmqvHjH8Kv70I/xVX5Wv07hS@eZ@W71XBZ@3SC@48CK4ZRdcxb4Q0bLV938NzHhcvudx@V8UmF5VgCob32GCHmiQ9Eq@LfWHFx38wlxH@qLt32bg3w1i6CG9289gXpF6MLInVuKYshvy6iZsvetnCe1cjgmjYx@ODDWryWRO9/KVq@bspnnT1/Yc6GHJBWph49O3eRqZCD9@qTiWqSX9Oh2t6yPQva0B7pBqVR/tqz5476Xze4KenPO7AyMNfd/Hp4LzRj/8fwE "Python 3 – Try It Online") or [Verify all machines from 1 to 20k](https://tio.run/##vVZLb9s4EL7rV8zaWECqpVqSTwnsFHFgoAaKxaLpTRAMWaItojLlSnQevz47Q1IvO2mylx4CR5zhNw9@8zg@y7wUs5eXMdT8cCwYHJI054KBzBMJp5rVkDJe2LVkx2noQC0TyWprTKIMdmUF9SEpCkgTVLUytoM9E6xCpY0G3BhAhVA71xaIjQaBBejDSeBMp6EFY4Mepadqk@ZJFUfqYMOz2IL2UhTFLkQxHpF5DlxAlYg9sxtgMtJA@fHn5HhkIrOj0f3IhcAFHjudPDiT@yifBKTRKkQe/vkxWh59HVnAd6C8/jtcLILrzs6ZWsXkqRJNvqzl7f1qc/9j9e89RWAH8zmfhI7Hvdl5FKHvxD11DeldXV1Zw/Sm5UlIVl3mdwx5@YjvKJ5hy2U9NYkTjGUs@6KzJjYkclHraaMukn0mTgeFbXfmVS4x5E7xRodP57CtWPLTMmjgLSAYPK85nwA@LnuSVYJnGsSDXoRaLVap1Wo3SI0A5nOwtQwZohxpsSfKFMVKz6EYiM5vWQWleR6XGHpG6s45Q84LCiJaa@NmcaFOPpiH/T3NrffYrAoIfEx7xp6wkpRoQPJ/SsHiT40HyPjhQdyZIBCeIstgjRm9/bECBPAtWHZfmKxV99WG6JHgTgsUMZGUl1VFL@Boe1xwyZNi6C6R31gmrkaj77rQGmCUx/16Guh@1UWHLEd4UUrdWIyd4llZ3ZewTdKfl1aXfaRvGqk561tcvuedik3mXsb3XEKas8Za3esyzY1Be4l4Zz3oW@@Z551h01/6zrWOYAPpdRByKWNJwcUeHtE3XRo1He94VUsXf/anikF5kl3F50mx80yeKHH4yFsmHxkT6FoA3g3cBZsnCySRYj7Xj2vBrwC/pebDrxD/x4MJSPyY0UeoP7A6TIHOUYHSoL40m1DPPCwWe9GWMmqGpDmGtBSCpbLxY73xjTtfBskavJVpyesuqxrVIw8/an/2O/vrflY@7sYbzDcjZv0aC94vkV5w4UVwqy64mn0golWb3z8amEFcvYa4@j8ZmL2ZAWK2zJHRR2R@0qN8S/W7Jx380kwIPfv6Awb860EMPUuv1jPOml5jZA@swjZlN86r4dSi682ATi7bhMlj3xwpaq@m0wWNysHq8EJDX816PX/tbseRyZHSQi3jE4Q@jYO8PBUZpgEOZaV2OJrq5Wmfu5AUdYkNVuVC7wBsn0j@wBSOBcey1mOD5lWTcl@3P9mNA3Q@9H0/UCEfygfmqvsRXse1rH/XxN5K46iVxmapwOuwUO3uuola0rMXfeE3FJJzer04E343Qr0QGAyalGaa7HCS1Dn1UIxA8gOzLFnKpOiWFN/SC1G7Bl3G2ezEi7e3L3Mf98YBPLpVMGEbLXwpWiwRp/@gRui02wf58RfmjzJ8rLiQ9mgt0rKqqNZxzTELGJLmiCcsQ0qZay6M9qXEb3IE5VzagWMZjFta0zWKq71s142RO3DbefkP) ### Big idea We want to construct a Turing machine that has a large time complexity compared to the number of states. In this answer, I used a binary counter to count all integers with \$n\$ bits, which has a time complexity of \$O(2^n)\$. The binary counter was chosen because it is very simple to construct, easy to scale, and flexible enough to add any small number of steps. ### Binary counter Let's say we want to count all integers with 4 bits. The tape layout will be as follows: ``` 1 x x x x e.g. 1 0 0 0 0 1 1 0 0 0 .... 1 0 1 1 1 1 1 1 1 1 ``` where the left most 1 is used to mark the start of the number, and `xxxx` is the current number in binary, in reverse order (the least significant bit first). We start with `10000`, and end with `11111`. At each cycle, we increase the number by 1 as follows: * Find the left most 0. E.g. ``` 1 1 1 0 1 ^ ``` * Set that digit to 1, and all previous digits to 0. The previous example becomes `1 0 0 1 1`. We then repeat these steps until the tape is `1 1 1 1 1`. ### Binary counter Turing machine The counter machine for \$b\$-bit integers will have \$b+2\$ states: the initial state \$I\$, \$b\$ digit check states \$C\_1\$ to \$C\_b\$, and the "go back" state \$B\$: * The initial state \$I\$ simply sets the left most cell to 1: `R 1 C1 / x x x`. * The \$i^{th}\$ digit check state \$C\_i\$ is only called if all previous digits are 1, and the pointer is currently on the \$i^{th}\$ left most digit. + If the current digit is 0, then we've found the left most 0. Set the current digit to 1, and enter "go back" state: `L 1 B`. + If the current digit is 1, set that digit to 0 and enter the next digit check state: `R 0 C(i+1)`. If this is the last digit check state (\$C\_b\$), then halts, since this means the current number is `111..1`. * "Go back" state \$B\$ is called after the number is incremented, to reset the pointer to the unit digit and start a new cycle. This state simply moves left until it sees the 1 that marks the start of the number. It then moves one step right to the unit digit, and calls the first digit check state \$C\_1\$: `L 0 B / R 1 C1`. [![State diagram for base machine](https://i.stack.imgur.com/jGlzg.png)](https://i.stack.imgur.com/jGlzg.png) ### Time complexity With \$n\$ states (counting \$n-2\$ bit integers), a counter machine runs for \$2^n-n-1\$ steps. ``` states steps 3 4 4 11 5 26 6 57 7 120 8 247 9 502 10 1013 11 2036 12 4083 13 8178 14 16369 15 32752 ``` ### Bridging the gap The above scheme only allows us to generate machines with the exact number of steps in the table above. This means that we are stuck if the number of steps falls in the "gaps" between the above numbers. Thankfully, there is a simple scheme that allow us to add some extra steps to a machine, at the cost of at most 1 state. For example, from the above table, we know that a counter with 6 states runs for 57 steps, and a machine with 7 states runs for 120 steps. There are 62 numbers in the gap between them (58 to 119). This means that we need to be able to extend a 6-state machine to have 1 to 62 extra steps. (In general, we need a scheme to extend an \$n\$-states machine by 1 to \$2^n-2\$ steps). First, some notation: let's \$S^0\$ and \$S^1\$ be the "half-states" of \$S\$, aka \$S\$ when the current cell is 0 or 1. Let's look at how many time each half-state is called in an original 6-state counter machine: ``` I B C1 C2 C3 C4 cur_char = 0 1 11 8 4 2 1 cur_char = 1 0 15 8 4 2 1 ``` **Observation 1** The number of times each digit check half-state is called is always a power of 2. Furthermore, the transition afterward is always \$C\_i^0 \rightarrow B^x\$ (refer to the state transition diagram above). This means that we can add an extra half-state in between (aka \$C\_i^0 \rightarrow X \rightarrow B^x\$). The extra half-state simply wastes a step before transitioning to \$B\$. The number of extra steps gained is equal to the number of times \$C\_i^0\$ is called. By selecting which \$C\_i^0\$ are connected to this extra half-state \$X\$, we can add **any number of extra steps from 1 to 15** (since \$15=8+4+2+1\$), at the cost of 1 extra half-state. [![Extra half-state 1](https://i.stack.imgur.com/rq3Ki.png)](https://i.stack.imgur.com/rq3Ki.png) For example, in the modified counter above, \$C\_1^0\$ and \$C\_3^0\$ transitions through \$X\$ before reaching \$B\$. Since \$C\_1^0\$ is called 8 times and \$C\_3^0\$ is called 2 times, \$X\$ is called 10 times in total, adding an extra 10 steps to the machine. **Observation 2**: Both \$B^1\$ and \$I^0\$ transitions to state \$C\_1\$. Furthermore, both \$B^1\$ and \$I^0\$ sets the current cell to 1, then moves right. Thus, we can have \$B^1 \rightarrow I^0 \rightarrow C\_1^x\$. This gives us an extra 15 steps for free. Furthermore, for each additional half-state inserted between \$I^0\$ and \$C\_1^x\$, the machine runs for 16 extra steps. For example, using 2 extra half-state, we can gain \$15+16+16=47\$ extra steps. By combining the 2 observations, we can reach any number of extra steps between 1 and 62 inclusive, using at most 3 extra half-states (1 half-state in observation 1, 2 in observation 2, which gives at most \$15 + 47 = 62\$ extra steps). [![Extra half-state 2](https://i.stack.imgur.com/V1JXU.png)](https://i.stack.imgur.com/V1JXU.png) For example, in the machine above, \$I^0\$ and 2 extra half-states are added between \$B^1\$ and \$C\_1^x\$, adding \$15+16+16 = 47\$ extra steps. Another extra half-state is added between the digit checks and \$B\$, adding 10 extra steps. In total, this machine has 57 extra steps compared to the base machine. This process can be generalized to any \$n\$-state counter machine. Note that since \$I^1\$ is unused in the base machine, we already start with a free half-state. This means that we only need at most 1 extra state \$E\$ (aka 2 half-states \$E^0\$ and \$E^1\$). ### Code explanation If you want to take a look at the code, the states are ordered as follow: * Initial state \$I\$ * Go back state \$B\$ * Digit check states from \$C\_1\$ to \$C\_b\$ * Extra state \$E\$ (if needed) [Answer] # [Python 2](https://docs.python.org/2/), ~~265426~~ 255462 states ``` t = 0 for i in range(1, 20001): b = bin(i + 3)[2:] if i < 5: t += -~i / 2 else: t += len(b) - (not int(b[1:])) - (not int(b[1])) print t print n = input() if n < 5: m = -~n / 2 print m for i in range(m): print "S" if i * 2 < n - 1 else "H", 1, i + 1 for i in range(m): print "S" if i * 2 < n - 2 else "H", 0, -~i % m + 1 else: b = bin(n + 3)[2:] e1 = int(b[1:]) and 2 e2 = int(b[1]) and 3 m = len(b) - (not e1) - (not e2) print m for i in range(m): if i == e2 - 1: if int(b[2]): print "S", 1, 3 else: print "R", 1, 4 elif i == e1 - 1: print "L", 0, 1 elif i: if int(b[i - m]): print "S", 0, 2 else: print "L", 0, 1 elif int(b[1:3]): print "S", 1, 2 else: print "R", 1, 1 + max(1, e1) for i in range(m): if i == m - 1: print "H", 0, 1 elif i == e2 - 1: print "R", 1, 4 elif i == e1 - 1: if e2: print "S", 0, 3 else: print "R", 1, 3 elif i: print "R", 0, i + 2 else: print "L", 1, 1 ``` [Try it online!](https://tio.run/##lZI7T8MwFIV3/4qjSEgxbYXtAENE9g6dYKw6NMIFS41bFSPBwl8P1482acJzSnJ8c879TrJ/d887q9rWoYJgm90BBsbisLZPOpdTKCGE5CVDTQO1sbnBBAVfqnLFYDY0fYebEg6TCrMPgysoBr190UnbapvXHDPkdufI2eX1UpYrPpRIYfsDPcDFK7MUaOz@1eWcUZANQQwNfJCNQfGNhmGweMPLdJY9ZHHNSyhysBQrw37I5tkUROiB5P8cVM9BTAP3BS3mfQJ615bttaVlIDo2gLV9DGWpTk5qETHPu9Oyu1X8R3aGuHFVeXci9kqQQoxa9eFCCYUfiJ8tHdzHg2vm9ZObDG7HmUXkl6eZ8xxDw80gi8bVKGvkk0oqxosq9vWekopu1m/@l6WifimlOaOYD9N7vf2ljcSs1RD021KLrrD@iYg/4whxkRDb9lZ8Ag "Python 2 – Try It Online") I was trying to come up with a different binary counter that didn't need @SurculoseSputum's initial state, but I then forgot about it, which is why this post is so late. Thanks to his help I was able to remove 9964 states so it's now actually slightly better than his answer. It's based on a basic machine of \$ m \$ states that takes \$ 2 ^ { m + 1 } - 3 \$ steps. The following states are created: 1. A "go back" state. 2. An optional state that is divided into two half states: * An extra half state to drop into state 1 more slowly so that up to \$ 2 ^ { m - 1 } - 1 \$ extra steps can be added. * An extra half state before the first digit state which adds \$ 2 ^ { m - 1 } \$ extra steps. 3. An optional state that is divided into two half states, one or both of which are inserted before the first digit state to add a further \$ 2 ^ { m - 1 } \$ or \$ 2 ^ m \$ extra steps. 4. A number of bit counter states. Note: It's technically possible to save a further state for values of the form \$ 3 \left ( 2 ^ m - 1 \right ) \$ but as it only saves 11 states I haven't bothered to code this up yet. [Answer] # [Python 2](https://docs.python.org/2/), 75012500 states ``` n = input() m, l = n / 8, n & 7 print m * 3 + [0, 1, 1, 2, 2, 3, 2, 3][l] for i in range(m): print "L", 1, i * 3 + 2 print "R", 1, i * 3 + 1 if l or i + 1 < m:print "R", 0, i * 3 + 4 else:print "H", 0, i * 3 + 3 if l == 7: print "L", 1, m * 3 + 2 print "R", 1, m * 3 + 1 print "H", 0, m * 3 + 3 elif l == 6: print "L", 1, m * 3 + 2 print "R", 1, m * 3 + 1 else: for i in range(-~l / 2): if i * 2 < l - 1: print "S", 1, m * 3 + i + 1 else: print "H", 1, m * 3 + i + 1 for i in range(m): print "R", 1, i * 3 + 2 print "R", 0, i * 3 + 3 print "R", 0, i * 3 + 3 if l == 7: print "R", 1, m * 3 + 2 print "R", 0, m * 3 + 3 print "H", 0, m * 3 + 3 elif l == 6: print "R", 1, m * 3 + 2 print "H", 0, m * 3 + 3 else: for i in range(-~l / 2): if i * 2 < l - 2: print "S", 0, m * 3 + i + 2 else: print "H", 0, m * 3 + i + 1 ``` [Try it online!](https://tio.run/##nZGxDoIwFEX3fsWNg0GFCMWoIbI7OOFoHBxQm7SFIA4u/jqWImoRSDRpIM177@S@0/SWnxNJi0IiBJPpNbdGRNjg6ioxxdJWvyEWJM2YzCEwho8Jdq4NTx@qj1999zu@J8ckA1MsZAd5ii0xCgiq6cFmoGfYk0JfhcgseATsqDJokrpiBRF8tLrv1hlBzC9xXV2bVZ9oThhi8ZVCdKUQ7xQmVbyoMa@583@4OjFBw5Rz58o4LX2h3L9cgqrVORx4QQ3bmjBWBUVl4TPwV1PPw0R9D2P47Cy0iI76hBg@fxPdyW0Z/1U0NUS7pkPaKrrR5BWF7z4A "Python 2 – Try It Online") Uses a six-step two-state busy beaver for `n=6`, then anonther state to clear enough tape in two steps to be able to run the busy beaver again. This handles all numbers whose remainder (modulo 8) is 0, 6 or 7; any remaining steps are handled by some probably suboptimal states. [Answer] # C++, score need testing ``` #include <stdio.h> #include <thread> #include <chrono> #include <random> #include <bitset> #include <atomic> #include <string.h> #include <map> // N = space of each buf, D = Amount of threads - 2, TIME = allowed time(ms), W = MaxOut const int N = 50, D = 16, TIME = 7200 * 999, W=20000; struct strat {int n, w, m;} mem[D][W+1][N][2]; int res[D][W+1], spl[W+1]; std::atomic_ullong cnt; volatile bool timeout; void putStrat(int i, int det=0, int then=-1) { //fprintf (stderr, "%6d%5d%4d%6d\n", i, det, then, spl[i]); // printf () if (spl[i] && then<0) { //printf ("(%d=%d+%d)", i, spl[i], i-spl[i]); putStrat(spl[i], det, det + res[0][spl[i]]); //fprintf (stderr, "a"); putStrat(i-spl[i], det + res[0][spl[i]], then); //fprintf (stderr, "b"); return; } int n = res[then==-1][i]; //fprintf (stderr, "c"); strat (*x)[2] = mem[then==-1][i]; if (n>9999) { printf ("Not Found(%d,%d,%d)",i,det,then); } else for (int i=0; i<n; ++i) { int d0 = x[i][0].n<0 ? then : x[i][0].n+det; int d1 = x[i][1].n<0 ? then : x[i][1].n+det; printf ("[%2d %c %c|%2d %c %c]", d0, "01"[x[i][0].w], "LSR"[x[i][0].m], d1, "01"[x[i][1].w], "LSR"[x[i][1].m]); } } int run(strat (*A)[2]) { int p = W+4, i=0; int cur_state = 0; std::bitset<W*2+8> Q; for (i=0; ++i<W+1; ) { //fprintf (stderr, "%d %d %d%d%d%d%d%d%d%d\n", cur_state, p, (int)Q[1020], (int)Q[1021], (int)Q[1022], (int)Q[1023], (int)Q[1024], (int)Q[1025], (int)Q[1026], (int)Q[1027], (int)Q[1028]); auto& o = A[cur_state][Q[p]]; cur_state = o.n; if (cur_state == -1) break; Q[p] = o.w; p += o.m-1; } return i; } void fallbackGen(int k, int v) { strat A[100][2]; A[0][0] = {4,1,2}; A[0][1] = {3,1,2}; A[1][0] = {2,1,0}; A[1][1] = {3,0,2}; A[2][0] = {-1,0,2}; A[2][1] = {1,1,0}; A[3][0] = {1,0,0}; A[3][1] = {0,1,2}; //A[4][0] = {5,1,2}; //A[5][0] = {6,1,2}; //A[6][0] = {1,1,2}; for (int i=4; i<k; ++i) { A[i][0] = {i+1, i%2?1:1&(v>>(k-i)/2), 2}; A[i][1] = {-1,0,2}; } A[k-1][0].n = 1; int r = run(A); for (int i=3; i<k; ++i) { if (r>W) return; if (k<res[1][r]) { res[1][r] = k; memcpy (mem[1][r], A, k*sizeof(*A)); } ++r; if (i==3) { A[2][0].n = 4; } else { A[i][1].n = i+1; } } { r+=2; if (r>W) return; A[k][0] = {-1,0,0}; A[k][1] = {k-1,0,2}; ++k; if (k<res[0][r]) { res[0][r] = k; memcpy (mem[0][r], A, k*sizeof(*A)); } } } void fallbackGene() { mem[0][1][0][0] = {-1,0,0}; res[0][1] = 1; mem[0][2][0][0] = {0,1,1}; mem[0][2][0][1] = {-1,0,0}; res[0][2] = 1; for (int k=5; k<32; k+=2) { for (int v=0; v<std::min(W,1<<(k-1)/2); ++v) { fallbackGen(k, v); } } } void f(int d) { std::mt19937 R(d); for (; !timeout; ++cnt) { strat A[N][2]; static const int Coll[] = {1,2,3,4,4,5,5,5,5,6,6,6,10}; int n = Coll[(unsigned)R()%13]; for (int i=0; i<n; ++i) { for (int j=0; j<2; ++j) { A[i][j].n = (unsigned)R() % n; A[i][j].w = (unsigned)R() % 2; A[i][j].m = (unsigned)R() % 8 ? (unsigned)R() % 2 * 2 : 1; } } int halt_state = (unsigned)R() % N; int halt_bin = (unsigned)R() % 2; A[halt_state][halt_bin].n = -1; int i = run(A); if (i<W+1 && res[d][i]>n) { res[d][i] = n; memcpy (mem[d][i], A, n * sizeof(*A)); } } } int main() { freopen ("unBB.txt", "w", stdout); memset(res, 1, sizeof(res)); std::thread A[D]; A[1] = std::thread(fallbackGene); for (int i=2; i<D; ++i) A[i] = std::thread([i](){f(i);}); std::this_thread::sleep_for(std::chrono::milliseconds(TIME)); timeout = 1; for (int i=1; i<D; ++i) A[i].join(); printf ("%llu Tries\n", (unsigned long long)cnt); int s=0; setvbuf (stdout, 0, _IONBF, 0); for (int i=1; i<W+1; ++i) { int m=0x7fffffff; strat (*x)[2]; //fprintf (stderr, "p"); for (int j=0; j<D; ++j) { if (res[j][i] < m) { m = res[j][i]; x = mem[j][i]; } }//fprintf (stderr, "q"); if (mem[1][i] != x && m<9999) { res[1][i] = m;//fprintf (stderr, "%d", m); memcpy (mem[1][i], x, m*sizeof(*x)); }//fprintf (stderr, "r"); for (int j=1; j<i; ++j) { if (res[0][j] + res[1][i-j] < res[1][i]) { res[1][i] = res[0][j] + res[1][i-j]; spl[i] = j; } }//fprintf (stderr, "s"); printf ("%6d %6d ", i, res[1][i], res[0][i]); putStrat(i); puts(""); } return s; } ``` Build with blocks that run some steps leaving the tape empty [Answer] # [C (gcc)](https://gcc.gnu.org/), Score ~~622410~~ 442766 states ***Now ported from bash to C so it's much faster!*** (The program constructs all 20,000 Turing machines on TIO in about 10 seconds total.) Note that this version of the program always computes all 20,000 Turing machines (saving them in 20,000 separate files). This is handy if you download the program and run it on your own computer. (TIO appears to delete all files as soon as the program halts, so the 20,000 files aren't very useful in that environment.) It also displays one of the Turing machines on stdout (as determined by an argument you pass to it). This is practical for TIO. --- ***Thanks to Surculose Sputum*** for pointing out that state `t+3` in the original version was superfluous. Taking it out reduced the total number of states considerably! ***Other changes:*** Reduced the base cases from 6 to 4. Fixed a few typos in the documentation, and improved the explanation a bit. --- This program is based on a recursive construction: the idea is to construct an \$n\$-step Turing machine by taking a previously constructed \$\frac{n}{2}\$-step Turing machine and running it twice (except that this is adjusted a bit to take overhead into account). I like this construction because it's easy to understand. The program computes the Turing machines for 1 up to 20000, and it writes each Turing machine to a separate file. It also accepts an argument \$n,\$ and displays the \$n\$-step Turing machine that was constructed on stdout (the default value for \$n\$ is 20000). The score is correct for the challenge even if you request one of the smaller Turing machines, since, no matter what you pass as an argument, it always computes all 20,000 Turing machines and prints the correct codegolf challenge score for all 20,000 machines total. If you run this on your own computer, run it in a directory by itself, because it will create files T1, T2, T3, ..., T20000 in the directory it's run in (one for each Turing machine). ``` /********** INTRODUCTION For each n from 1 to 20000, this program computes a Turing machine Tn which takes exactly n steps when it runs. The program writes all the computed Turing machines to files T1, T2, T3, ..., T20000. The total number of states for all 20000 machines is then displayed. (This is the score for the codegolf challenge.) Also, one argument n is accepted on the command line; if provided, it must be a number between 1 and 20000. Turing machine Tn is displayed on stdout. If no argument is provided, the default is 20000. Note that all 20000 machines are always computed and written to the files on disk, but only the one you specify is written to stdout. Total time taken is about 10 seconds on TIO. **********/ /************** HOW TO COMPILE AND RUN Save this file as tm.c, and compile it with the command gcc -O3 -o tm tm.c or, if you prefer, gcc -O3 -Wall -Werror -W -o tm tm.c Run it with a command like ./tm or ./tm 50 This will display the Turing machine requested (T20000 or T50, in the two examples above). But you can look at all 20000 Turing machines in any case, since they're all saved in files T1, T2, T3, ..., T20000. (On TIO, the system will delete the saved files as soon as the program finishes running, so they're not very useful in that environment.) **************/ /*************** FUNDAMENTAL IDEA The idea is to compute a Turing machine which takes n steps to run, by doing something as close as possible to the following: Recursively take a machine that takes about n/2 steps to halt, and run it twice. (The base case for the recursion will be n <= 4.) This needs to be adjusted slightly because there are 3 steps needed for overhead, so we need to use a machine that takes (n-3)/2 steps to halt, instead of n/2 steps. Also, if n is even, this leaves us one step short, so we need to add an extra step in that case. Since the challenge is to compute a machine for each n up to 20,000, there's no need to implement this using recursion in the code. Instead we just run through a loop, computing a Turing machine for each n in turn. But each computation uses the previous results, just as the recursion suggests. ***************/ /*************** PROPERTIES OF THE CONSTRUCTED TURING MACHINES These Turing machines never move to the left of position 0 (the starting position of the tape head). If the all the cells from the starting position to the right are initially 0, then Tn will take exactly n steps to run. Each Turing machine leaves everything exactly as it found it (tape cell data and tape head position). Output format: The program will write Turing machine Tn to a file called Tn (where n is replaced by the actual number). During execution, the Turing machine Tn is divided into 3 separate pieces: The array element stateCountArray[n] holds the number of states. The file An holds tuples in the form movement newval newstate for when the tape head is looking at a 0. The file Bn holds tuples in the form movement newval newstate for when the tape head is looking at a 1. An and Bn have one tuple for each state, in order from state 1 to the number of states. The eventual machine Tn will consist of stateCountArray[n], An, and Bn, in that order. ***************/ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #define MAXn (20000) int stateCountArray[MAXn + 1]; char filenameTemplate[] = "X99999"; int score = 0; void openTupleFiles(int n, FILE **file0, FILE **file, char *fileMode); void createOnePrecomputedTuringMachine(int n, int numberOfStates, char *tuplesFor0, char *tuplesFor1); void adjustStates(int firstUnusedState, FILE *oldFile, FILE *file); /********** The routine adjustStates takes a previously computed Turing machine and makes the changes necessary to incorporate it into the Turing machine currently being computed. **********/ void basis(void); void invalidArgument(void); int getNumericalArgument(int argc, char **argv); void openTupleFiles(int n, FILE **file0, FILE **file1, char *fileMode) /********** Given n, opens the two files An and Bn, and returns them in the file descriptors file1 and file2. The two files are opened in the indicated mode: "r", "w", .... **********/ { sprintf(filenameTemplate, "A%d", n); *file0 = fopen(filenameTemplate, fileMode); *filenameTemplate = 'B'; *file1 = fopen(filenameTemplate, fileMode); } void createOnePrecomputedTuringMachine(int n, int numberOfStates, char *tuplesFor0, char *tuplesFor1) /********** Used by the function basis. Sets up stateCountArray[n], An, and Bn as specified, and updates score. **********/ { FILE *theFile; stateCountArray[n] = numberOfStates; sprintf(filenameTemplate, "A%d", n); theFile = fopen(filenameTemplate, "w"); fputs(tuplesFor0, theFile); fclose(theFile); sprintf(filenameTemplate, "B%d", n); theFile = fopen(filenameTemplate, "w"); fputs(tuplesFor1, theFile); fclose(theFile); score += numberOfStates; } // createOnePrecomputedTuringMachine void adjustStates(int firstUnusedState, FILE *oldFile, FILE *file) /********** The routine adjustStates takes a previously computed Turing machine and makes the changes necessary to incorporate it into the Turing machine currently being computed. oldFile should already be open for reading, and file should be open for writing. Reads tuples from oldFile, writes tuples to file. All states are shifted up by 1. Each halting state is changed to a tuple which moves left and changes the state to firstUnusedState. **********/ { char movement; int newValue; int newState; while (3 == fscanf(oldFile, "%c%d%d%*c", &movement, &newValue, &newState)) { if ('H' == movement) { movement = 'L'; newState = firstUnusedState; } else newState++; fprintf(file, "%c %d %d\n", movement, newValue, newState); } // while } // void adjustStates void basis(void) /********** This handles values of n from 1 through 4, which form the basis of the recursion. These Turing machines are precomputed. **********/ { createOnePrecomputedTuringMachine(1, 1, "H 0 1\n", "H 0 1\n"); createOnePrecomputedTuringMachine(2, 1, "S 1 1\n", "H 0 1\n"); createOnePrecomputedTuringMachine(3, 2, "S 1 1\nH 0 1\n", "S 1 2\nH 0 1\n"); createOnePrecomputedTuringMachine(4, 2, "S 1 1\nS 1 2\n", "S 0 2\nH 0 1\n"); } // basis void invalidArgument(void) { printf("Usage: tm\n or: tm n\nwhere n is a number between 1 and 20000\n(default is 20000).\n"); exit(1); } int getNumericalArgument(int argc, char **argv) { char * arg; char *p; int k = 0; if (argc < 2) return 20000; if (argc > 2) invalidArgument(); arg = argv[1]; if (0 == *arg) return 20000; for (p = arg; *p; p++) { if ((*p < '0') || ('9' < *p)) invalidArgument(); k = 10 * k + *p - '0'; if (k > 20000) invalidArgument(); } return k; } #define BUFFERSIZE (4096) int main(int argc, char **argv) { int n; int m; FILE *An; FILE *Bn; int t; FILE *Am; FILE *Bm; FILE *TuringMachineFile; char byteArray[BUFFERSIZE]; int numberOfBytesRead; int argument; if (argc > 2) invalidArgument(); argument = getNumericalArgument(argc, argv); // For each values of n, we compute stateCountArray[n] and the two files An and Bn. // First take care of the basis, n = 1 through 4. basis(); // Now start the main loop for n = 5 and up: for (n = 5; n <= MAXn; n++) { // We'll go through 2 runs of the machine Tm that we // computed earlier, where m = floor((n-3)/2). // There are 3 steps of overhead, and we add in one // extra step if n happens to be even, because in that // case, 2 * floor((n-3)/2) + 3 is n-1, not n. // This will get us to exactly n steps. m = (n - 3)/2; // Open files An and Bn for writing. openTupleFiles(n, &An, &Bn, "w"); // Go through two runs of machine Tm. // The cell at position 0 will keeep track of which run // we're on (0 for the first run, 1 for the second). // At the beginning, position 0 holds a 0, so we // move right to position 1 and go to state 2. fputs("R 0 2\n", An); // For even n, at the end of the entire run of Tn, we'll // find ourselves back in state 1 at position 0, but the // contents of that cell will be 0, and we'll halt. // (For odd n, the machine will halt without going back // to state 1.) fputs("H 0 1\n", Bn); // Compute the number of states in the new machine Tn. // It's two more than the number if states in Tm. t = stateCountArray[m] + 2; // Open files Am and Bm for reading. openTupleFiles(m, &Am, &Bm, "r"); // The two calls below to the function adjustStates copy machine Tm // into the Turing machine that we're building, with the following // modifications: // - Use states 2 through t+1 instead of 1 through t. // - Halt tuples (H) get altered to tuples that don't halt // but instead move left (L) and change to state t+2. adjustStates(t, Am, An); fclose(Am); adjustStates(t, Bm, Bn); fclose(Bm); // Since we're in state 2 at position 1, we're all set to run // the altered copy of Tm, so that happens next. // After running the altered copy of Tm, we're back at position 0, // since the original Tm would have left us at position 1, but the // altered version changed every H to an L, causing the tape head // to move left one position, to position 0. // If the tape head is looking at 0 in position 0, // we just finished the first of the two runs of Tm. // In that case, write a 1 to position 0 to indicate // that we're on the second run now. // Move right to position 1 and change to state 2. // That will start the second run of Tm. fputs("R 1 2\n", An); fclose(An); // If the tape head is looking at a 1 in position 0, // we just finished our second run of Tm. We're ready // to halt, except that if n is even, we need to add // one extra step. if (n % 2) { // n is odd, so halt. fputs("H 0 1\n", Bn); } else { // n is even, so change to state 1 (which // will take the extra step we need). // State 1 will then halt because it's // looking at a 1. fputs("S 1 1\n", Bn); } fclose(Bn); // Store the number of states for Tn in stateCountArray, // and update the score.. stateCountArray[n] = t; score += t; } // for n // Print the codegolf challenge score (the total number of // states in all 20000 Turing machines). printf("Score (up to 20000) = %d\n\n", score); // Write each Turing machine Tn to the file called Tn (where // n is the actual number). // First write stateCountArray[n], then copy file An, and // after that copy file Bn. // Also delete the files An and Bn. for (n = 1; n <= MAXn; n++) { openTupleFiles(n, &An, &Bn, "r"); sprintf(filenameTemplate, "T%d", n); TuringMachineFile = fopen(filenameTemplate, "w"); fprintf(TuringMachineFile, "%d\n", stateCountArray[n]); numberOfBytesRead = fread(byteArray, sizeof(char), BUFFERSIZE, An); fwrite(byteArray, sizeof(char), numberOfBytesRead, TuringMachineFile); fclose(An); numberOfBytesRead = fread(byteArray, sizeof(char), BUFFERSIZE, Bn); fwrite(byteArray, sizeof(char), numberOfBytesRead, TuringMachineFile); fclose(Bn); fclose(TuringMachineFile); *filenameTemplate = 'A'; unlink(filenameTemplate); *filenameTemplate = 'B'; unlink(filenameTemplate); } // for n // Finally print the requested Turing machine to stdout. (void) printf("Turing machine which halts after exactly %d steps:\n", argument); sprintf(filenameTemplate, "T%d", argument); TuringMachineFile = fopen(filenameTemplate, "r"); numberOfBytesRead = fread(byteArray, sizeof(char), BUFFERSIZE, TuringMachineFile); fwrite(byteArray, sizeof(char), numberOfBytesRead, stdout); fclose(TuringMachineFile); exit(0); } // main ``` [Try it online!](https://tio.run/##1Vrrc9vGEf@Ov@JGGUekTdGk7LQTK@4MZcuxZmzJI1F1prE/QMBRQgUcWDxEq0n@9bq/3b07PEhJzqOZKWM7JHC3u7fvx0U7F1H0@fPjh/4TBIdH85Pjl2cv5ofHR0HwKi@UDqNLZdSiyDM1VVWudif4jFR1mZRqWeQXRZipKM@WdaVLFap5XSTmIsiwLTFazY1aXSYAUYVXeK8/hVGV3gBgWelliXfaqKRSRW3KcRDML7WHuSoShpimwKUditgiUBZBCZKCRZLiy3w6UvNd/H0yUuPxmH4QqRZslVdhqkydnetC5QvgDwn8AkckFLy0AYqzAakJ4qRcpuGNjsdKDeZ0ZHmjyigvNO8W4mJ9kacLFV0CmDYXejwMglla5iOVgwthcVFn2lQ4N/aHUaSXdJTcuKNloYlVCtR7KlkQC66TWMejAKzJ6rJS54DhiD/X1UqDbVNFm@SMqscW4ntSNuQTqrKK87oCOw4XyuQNTSJHQcj0xHoR1im/cBw8yiuw8DKsNjErBCfCdBXelI2UiDSSYAUmQmkIrEgJhICqq5E6ryv8gC7QO2LSTV6rcqmjZHFDqFu7PeVzFmKVZJr1Sbh5jndqOlGljnITMwaoL1Y3iv04CIKWnouuvz5@r@bH6sXx23eHbw7U7OilOjmD1p@G11rUmyhWIQSejaMRH4nORw8hl1VSXbbFFwQwJ7Vz/ETt4LwZbwqCvBiRROlsy0IvdDFqrXtPzNx5r4sCerTzvrMxCE5q4/GELSW50kEwflxlBFy@qW8mAWk5cS0BSCt2pq6nF4X@V61LktBAzEMB9fwbGHQCVpOdrHKy0mxJwgJvr/UQrNwHi@kMUWhUmudXqqMJfZNMDJh1g8WlHqkyMZEm0DfbrCepKsHgmBbdZ7eDYxalaGV5A7Ize0CdalZIbYEJJIiqzCH@kG00cJ5kkZikvMR7eBkDQkETayQTZPJKXeviRtWlXtQpkUV6HmhznRS5IQshW@4qzwZ9gkK9Ojt6OXt7cDSfvVGHLw9m4nhgVyF7jdxZh/eSXiptF@lcI/wa6IWd3Kg4p8VlnmmoJb7hfFGal6yby7wsk/OUHJxYWZ6m@QqrnkGDdFQXZXKtycoAHIgdRrZlQSgGZB7vesQKXqwaBaRuhShhtUoiLT5Qq3PIlYXr/V8hiMB6Fs@5Doz67rl6SpxjtTRaxwyZHFn8z5o1sEyTi0uKBuc6CsF@AkUqgr9PhJaA9pF4gQeaWFzqMGbprTSDJIi0cdO5goHZeTJcOxUEjAdhTDHAn3nsnDVMlZ2KvtbGxrhUQ8NKoGEnRctVeZkXlaUjcHSEMXk92E5VhLLMqhKzChhOyRDEY7gosaYX7hiLJvLWS1KF3cnIhl2waLskB@4QJ2Sr7MmZ3rokFWkkYu2aQhQEeGhPDwaSFFi@1WWR1xfkZGDay5ElhxUt6Clqiy46XV0YwCTnwA9lY1gBbQCxSKSE27tOcrCv0CWiSjkSxGKjLTrL@uICnqkc942NrG3d2N6dHL87OJkfHpyq41dq/voAjvzodH6C3OXgpZqfnRwefa/ezl68Pjw6OGVLLPWaozKQc6Gy/NqbT6oXFakGzCqhc6hJAK1nR1OFBTPFv8Iy9pjhUivSzKHEVnrmsxadpqUkT5thWLQFWQIwke7DW1UJANwokbfhJIrsim24n0IBAoQI1Ackgp68rPLSMW/Ed7jt4D/sepHXMPKk4kPSOYhgFYdVyOHOH80TTGc8riuImXQhC6tn2NpJ24hQzt02pCRkJhJVI7IAJHMG2/EZrNj02fYKjeAV4eW5RDDQW/vUjfC/FLj6E3SHaBptCnScACEScl4DngI1nIpehgXyPrVMdKTLZ4KcyA@LAgFTW0Pi5PAFeFPN6PmP5qNSl3kai872k8hxA4bPNjNucc1RNDHWMxcZlpG2SS6oV9d0Lr1iMIqNixJiAUefjnrReSj2smHCgNSkj3j/T0I8hRB42cywmhBeSprIQTLqxk8wBnK6yDNiMI1MoUEj@KfOCtYZyxGUnDGrQLuoIDVDvlcmZeU3dCQ2AnUjS97I@2KmYqOLCYKv4KDTOtbqOyScaXI@vvxb91mSdx/VyCuqmJ4FXyFpJtLezn4wasAJDGJfskGXeMUjNf24FyAOFCw5E2Z6ruHHsfTHj@q52vrhW/ps7QkILjaeq8leEFznCWLXUps5MfoV5T0DWoMzvqI09uFDAjjp/BopxsTf3yIODPcETFRoIDw2@h3csM3cxYzeCqcdZP4fC@d4ccqicSBF01AoTtaeTIeOXIn4spFBLpKirM4MYkR8Kgoi1EJ5XzG98pPoBZB2hUr6gGhVEa/bYF0u48MNXFyvZPQ1KelExsttMEYkplgAj1CGyAQpphqwfJmzr4CbZPdBKWXPySB2FdBNTmHoucM47tYezARkTUk5oK@eL4mBHSbxzFZi/iWx6EJXR3haJPCUfgG9QN0WOV4/xI9r2kGf36IZ0zXV6HD7e@SOhgAQWGEX1QeSbXvjFysrNKUDvCjzngcLg1iXUZEsq7yQikrqVvq2Oxbn1cCk@Ee4pD4gEImJwQLwNMhA3jO1VWyN1NZqi2uFLp/hUH5i31IuIaVqMeibFjbOHsTYasAzWigcgWUtCOmG9S2L8evbK7B1e3@79XL6xcB@8TL7X5thR6RnZRNZF7WJOAth3aQUVVclJZx3e1Ous7hQT6hHQQ/rZcxWyJ7qFqmI2gEvqeaeRJANgfZ574hu5ZfK1CK4Qw7QHrt2AV6Xgzbz7G73nsusQfPwPlL2/yhSpl9ICkeGR@s8IwVTjx/fr1uN6/hdXvr/0kkH9iRU0NUpOJCCWzGtYyfEWQw94Z6Bc1pucXsR5btYNKaSO2zyL877PbdsQ9O@q8TlceWZum4kub/yMlkQP2CGMNOpS@ypeOUuAKdMyMiEJVJ62qxL2giU55VSyHDLyrLO1h@VDhh1V7S3mCy7Epc3ih4mkkD@PUxr3XnCcKxaghCQM3iinkP1yyg0i4Fnw9aD6EGM/x5GsJSvHXB8dVDlK4MbDl2u@JNPGlGiD7ZfbxNot3nYZJSthe2UF276jXXT9uNQkHH2mNFe94v/rtNSB@v7Hz2yZxYjbjwDn1Q9iPHng8FRm5M2B/Xn9CjZaJl93oTXjDNQwXpO0TNAKAjkHpOmXROukvsdvo1vK/6nI6szXCJU0ttJSlfZ@uJ8fFsBTQq7bDzLbWp0b4CDu8OfrddqoqbMLf/VsuZ@ELsC4hTH@60gnozUbgOiRQw92W2efDHApx2AFooAnKwDZGmzAIK7EsSGr1bbts7K8AKpUZV9MHiaF/RVmQ@mVVTfNT34YAb9lv9w3BxTf0qqwbRJWn5ldtrzJg9pyV7r97LxIle2xnFmTsDUd2rX2bekmEJhf9nfmmV9rrlgiXVAQET9SNWX3z8hX0LE3oGHvPxgKdv3iGi1fPTIrfc@h6ANHi5B8/Zke6h@/hmu6ttt/Hy4HLac1G0E4kMsmE7ApSvUiIC0Q5Ca14Tgis4qBeZdENv@K2gf60rekShd1bp/9urVwcnp4T8O1ODp5Nu/2NI1CxNzr1TZ/TcyzPZayd7MtH/tt5ZVnWWdTfuZPa/87FiUpI5eec5vKi2JY3OCj62oZJOifSwrKTI3r9z0i2qn36BHtY0qG@1AuOVLMxi1H6S2fPGIerCu87shD@b@2@aCa2yhUtySpmDEhdOiceGILaRJjaeXXpEEDCIL@4/ylXQkeRsJmxvArOu0@xslqf2zxgL48Z7i7j41MvC1MQMoBIF9r7eR0VzkHvcuj3cdeb6Jk0lHZqVpk08DdVikiS4oMJHzyig@g6piYNv51ADE@nl/VEDgmxEBjx819@Sp9WQYR7s1T8HwMlxKWctjCWn5u1GEGwMRaTzG2oVNdgmBgT4hh2l2EHdojAS5MGVuDAfloLFBlfd7tuMmY6Dzgas7ikCKWI45q@xKvJtlus29Yh/kf01V2tdUkktlQfC@byRBuuRk0cjBkm2bvxBJ0/yWg1xpDZ6BedEV7ZSUAXBo30rTFA1r4UbdOIgTKsXTq6l/KOPZodXdmSjdub5I7EyuhVSamCH1v2XGgg3cpOc2OTHUL5YwRsqW29R4d9xKx6im2jqRYLtFNazlCRuk7W2EQoo2sVNRGHGCQ9FsBE/mbKrQadoId4llyIp0Sln2ObEkMb6R2WGezLipImEFNxXgWjOgqRAx247LaK2oLJkOpfoskwGRmUOHbYvbjwsTu4qHwzS9u@AJIVFD@zwvpuNhnxlNVrPvmPHCOqFNLVjXhkGm2mq/MnWH1XbJGpVRDYozmTaEpA2BdMy3lqHxfXeXfYQxbVD/TNQ/a1dit6p/RupP/@zjn61iyzlf12GikQMkplO4PTcsdQ2QTpUa5cublnkQDFdb9qcM1oORCZzXSSqVor8Z4GexosBxsqBWFvCVz@iJgtmfldrxabcx00fT9piy8eKiFrTvNUnflpKD10P2NXgEp8gVoSsyibw4N9sVq4ts5jhQVx4DWxaXi4M3w1bJ2KhR9Wi35bI6fQKUM8TzmWlKGNeqmGWtvGZtFwlpf8Ou/czJTealwlxvYrsdE5uO7Hu@VqArOwxjG@ApnDCEBUqWnNnRf1h5528QFSSkzFB2F@6OwK37rbDJ7rvGTiBKP@LN4aoSE6YU5lbcL@AJCbMZMaF3iJafcDgRyngs6sp8HuGp11zuG/UG2Vgok97OqMZafyNSGsk4TKOO55xYT3y4uHPaMyHe947phsf2YkXccvpuJtoKNDbAHLam4bYZQqOkLk3S1pGOr0jR25e9LCVhhH2zyVcM@e1doaGvy7s22hHcRDovNgFqQbZUrweSaTuQ9PXdOM29h6V06i9gKqLMOk2K0iuKTdSostKWew36E90qE451rzG0LksgIaJNpBVNNjTu9FaMetCkwJzVKapLGR5iEVuQRKhWN2VzcPmCNspPHrbQCuB9iU1pOoyMo42PuyR@JM4xu0nu7HmH4/6OUwtPdtJknYOoz/kQ0Ppb@nPP9TM3DYe1M6/5NhdxTysJmXrzhcS58Q6vCZKsJE2vvbmFOG6o2thOrxqifLu46jacOOMPRHnfFVyfbbzVaAHwfYjehUp2fz7g33o3bGityrUuTgUgX3KxVS1IppYZs5TxObN6zz5Db7jmMPcXKbqXC@y9gsDp2KbrBL6QEpe0afTBqsJBwM73OVtjeXDMEL/m33OBRgElhTa3rqqtV3Gdump6R131RRm/pDxe1rdPKeZuSqH86rUq@96hxVrTcw0EdUCl97nO1DaAtTKdcJODG/j6nq4R/lvniwGV/cNRq2Ehvrg5yILFePvONWSj9bPf5tv/IIL3/wSC9zsE24eb9vk1G2ebs3bTvDZpYq7WFOJeIPstILfD2OSP2DYN34VaerfUXGHtJ@Otm8J8qYjbpd7VbLxzSQGgtGbsqvQHsZTpz1h3XbfHknivWfXW/yrDKlzP9Xdq2G0K8ht0TTjaHULeqkfcKp60utnUVAo@f/7812/@Ey3S8KL8vHP85L8 "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 100010000 states ``` n = input() m = -~n / 2 print m for i in range(m): print "S" if i * 2 < n - 1 else "H", 1, i + 1 for i in range(m): print "S" if i * 2 < n - 2 else "H", 0, -~i % m + 1 ``` [Try it online!](https://tio.run/##lY6xCsIwGAb3PMUREFqbogm4iO7uPoFDqgHzN8Q4dPHVY8TF1e2D@zguLeU2i6tVOBIkPUvXq9j2@BI2OJVykEJU05wJ7UG@yNV3sd/zRfqsCVNjaxwHhBGLvz88@qQN1jQ0YP8SuB/B1rSWwIr40dS6ewM "Python 2 – Try It Online") Just to get the ball rolling. ]
[Question] [ *(a paradox, a paradox, a most ingenious paradox)* This is the first part of a multipart series inspired by different R functions. # The Task Given a dataset \$D\$ of positive integers, I need you to compute the [5 number summary](https://en.wikipedia.org/wiki/Five-number_summary) of \$D\$. However, I'm working on large datasets, so I need your code to be as small as possible, allowing me to store it on my computer. The five number summary consists of: * Minimum value * First quartile (Q1) * Median / Second quartile (Q2) * Third quartile (Q3) * Maximum value There are several different ways of defining the quartiles, but we will use the one implemented by R: ## Definitions: * Minimum and maximum: the smallest and largest values, respectively. * Median: the middle value if \$D\$ has an odd number of entries, and the arithmetic mean of the two middle-most values if \$D\$ has an even number of entries. Note that this means the median may be a non-integer value. We have had to [Compute the Median before](https://codegolf.stackexchange.com/questions/106149/compute-the-median). * First and Third Quartiles: Divide the data into two halves, including the central element in each half if \$D\$ has an odd number of entries, and find the median value of each half. The median of the lower half is the First Quartile, and the median of the upper half is the Third Quartile. ## Examples: \$D=[1,2,3,4,5]\$. The median is then \$3\$, and the lower half is \$[1,2,3]\$, yielding a first quartile of \$2\$, and the upper half is \$[3,4,5]\$, yielding a third quartile of \$4\$. \$D=[1,3,3,4,5,6,7,10]\$. The median is \$4.5\$, and the lower half is \$[1,3,3,4]\$, yielding a first quartile of \$3\$, and the upper half is \$[5,6,7,10]\$, yielding a third quartile of \$6.5\$. ### Additional rules: * Input is as an array or your language's nearest equivalent. * You may assume the array is sorted in either ascending or descending order (but please specify which). * You may return/print the results in any **consistent** order, and in whichever flexible format you like, but please denote the order and format in your answer. * Built-in functions equivalent to `fivenum` are allowed, but please also implement your own solution. * You may **not** assume each of the five numbers will be an integer. * Explanations are encouraged. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in each language wins! ## Randomly generated test cases ``` 1 1 1 1 1 2 2 2 2 2 3 3 4 4 4 4 4 5 5 5 -> 1 1.5 2.5 4 5 1 2 2 2 4 4 5 5 6 7 7 8 9 9 9 9 9 10 10 10 -> 1 4 7 9 10 2 2 2 6 8 10 15 16 21 22 23 24 26 33 35 38 38 45 46 47 48 -> 2 10 23 38 48 1 2 9 -> 1 1.5 2 5.5 9 1 2 3 3 3 4 9 -> 1 2.5 3 3.5 9 1 1 2 5 7 7 8 8 15 16 18 24 24 26 26 27 27 28 28 28 29 29 39 39 40 45 46 48 48 48 48 49 50 52 60 63 72 73 79 85 86 87 88 90 91 93 94 95 95 97 100 -> 1 25 45 76 100 2 2 4 4 6 8 10 11 13 14 14 15 17 21 23 24 26 27 27 28 28 30 31 33 33 34 36 36 38 38 39 40 41 42 42 43 45 45 47 47 47 47 47 48 48 48 50 51 53 53 55 56 56 56 57 57 58 62 62 63 64 64 65 65 66 67 67 67 68 69 69 71 71 71 74 79 80 81 81 81 82 82 83 83 86 86 86 87 89 94 94 94 95 95 97 98 99 100 100 100 -> 2 33.5 54 76.5 100 1 3 3 4 -> 1 2 3 3.5 4 1 3 3 3 4 -> 1 3 3 3 4 ``` [Answer] # [R](https://www.r-project.org/), 7 bytes ``` fivenum ``` [Try it online!](https://tio.run/##TY/NCgIxDITvPskuzKFtmjYR9mnEBQ96EPT1a/q3LvNRwpBmknfZt7I/vvfX51n25bZ4TIVDZIqHuGpdL727d0w/IZsEesi7zvjQ25O1VJfhE4INMZMQIkICWRqDpBIZMSFmRDkF6qmmsdzfqy6PNWREeGnD2/xKbshEK9SIbobKCQU7sO3tkAg5INurEIbYKZZkFzuohxLUluFGthv73f5aq/ID "R – Try It Online") Obvious cheeky answer. ;-) Interestingly, `fivenum(x)` is not equivalent to `summary(x)` even when `x` is numeric, as the quantiles are computed differently: `fivenum` averages at discontinuities, whereas `summary` interpolates. You can force `summary` to behave like `fivenum` with the option `quantile.type`, but this is still longer than # [R](https://www.r-project.org/), 51 bytes ``` function(x)quantile(x,(0:4)/4,t=2+5*!sum(!!x)%%4-3) ``` [Try it online!](https://tio.run/##VZLRasMwDEXf9xd5KCTbHbMtWbYH/ZhRFihsHdtS6N9nshJnKToJsVCsq2v/zONxHq@X03T@uvS34fv6dpnOH@/9Db175eGFMR3DU3zsfq@ffdfdhsOBn2mYx/7Ue7QIW5AGbxFrDMPDUr1UtLwgaWSULbxbWH9YykVLajbCC4JuoklCYAQBabcIyhWOYAEncN41LLtvWsX952o2rjLy2sJn29z2ryQjN0qFDHatad5REB2i6nYQQgpI@i7IEVlH0U46sUPxKISiYqKRdMb93NWkNrnqJHg2VGIyF5oFe33kQN5MURgkhrmzyvXgYJBJj@bXnjZGncEjkqGnJY1kZEgwCMJGNASSGlpTKsk32IxwyL4RDDKkoR4Vs4bvDCpqXL0jrj3bMdqx3q1sPf8B "R – Try It Online") which computes the quantiles of order 0 (min), 0.25 (Q1), 0.5 (median), 0.75 (Q3) and 1 (max). The `t=2` specifies how quantiles are defined: there are 9 possible types, and the challenge definition corresponds to type 2 in most cases, and to type 7 when \$n\equiv 3\pmod 4\$. Honestly, this choice of a definition of quantiles is a bit weird. Note that the source code of the `fivenum` built-in is very different (and much longer). [Answer] # [MATL](https://github.com/lmendo/MATL), 18 bytes ``` tno?t.5Xqh]5:q4/Xq ``` Output order is increasing, as in the test cases. [Try it online!](https://tio.run/##y00syfn/vyQv375EzzSiMCPW1KrQRD@i8P//aEMFGDSCQ2MgNIFDUxCMBQA) Or [verify all test cases](https://tio.run/##VZI7bsQwDET7nGJOkJXEj6Q0aXKEFAssFki6FPnAgO/vULRoeMFnW5YJcjjyz@f6vX1s6@/f6/os1@XrLi8LX67L9va@3TIiyhFkwUfIiPvTLTJiT1EtGvoROe1Y8p6q9nnsCLKiWAHbJBRGUZB1EVAbsIAVXMFtNurzSVPM/j52ZLZts2xuXtBrDqrTgj4gh1M0aic6JEFMa4ISakG1e0cTNJNvnWzChJ7RCd2EiFNtrphzGBKTmkZCZsfkVZ86Rj5rowTKboLBIHXcjSk1g4tDLlvcnzMxwtCfIeTYyWhQnQYtDkHZEUehNbCcPqg5YDchoeWgOORoYP50t4UfzOlm2vgfUlx@fH6Ux2qs/wE). ### Explanation MATL, like MATLAB, computes quantiles using linear interpolation if needed (just as specified in the challenge for the median). To achieve the required behaviour for the first and third quartiles, it suffices to repeat the median if the length of the input is odd. Then the results are just the 0, .25, .5, .75 and 1 quantiles. ``` t % Implicit input: numeric row array. Duplicate no % Length, parity ? % If not zero (that is, if input length is odd) .5 % Push .5 Xq % .5-quantile: median. For even length it behaves as required h % Concatenate horizontally ] % End 5:q % Push [0 1 2 3 4] 4/ % Divide by 4, element-wise: gives [0 .25 .5 .75 1] Xq % [0 .25 .5 .75 1]-quantiles. Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` œs2a\;WÆṁ;Ḣ;Ṫ ``` [Try it online!](https://tio.run/##y0rNyan8///o5GKjxBjr8MNtD3c2Wj/cscj64c5V/x/u2BR2uP3opIc7Z/z/b6QAgmYKFgqGBgqGpgqGZgpGhgpGQEFjBSMTBSMzBWNjBWNTBWMLEDIxVTAxUzAxVzCxAAA "Jelly – Try It Online") Order: `[Q1, Q3, Q2/med, min, max]`. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 66 bytes ``` lambda l:[(l[~-i//4]+l[-~i//4])/2for i in[1,n:=len(l),~n-n,~n,-3]] ``` [Try it online!](https://tio.run/##XZLNjuIwEITvPEWJU6IlQ/xvIzFPsTeWQ9CCJlImRAyj0Vx4dbbcGyN21V8M6m471eVM39e382jidLmftr/uQ/d@@N1h2OyqYXdr@vXa7n8Mu@Ym/@q1Pp0v6NGPO7UaN9vhOFZDvbqNzchl1Zj9/v711g9H/Lx8HjcLdKsDtmyfPq9V/fIxDf21WqJ5xbJmkaWh/7hW791U9eN1he7RsqxrdhyeO07DuWPP4b@e6cKt1anq6vquUEI/wjDsI5wEBbDpxUHzYXJRNpQWj8CISI9Q7Yzstazm3OLvNs/WXHVQHpqHMWmgLbSHoQAHEzOWb/OwATbmc3TexMZciaIhPUmD45okbeYp5nJWzcRczg1u1htnDSrK20VAJgixkDJGsG1RFZ9IcC0cB2vhDYJG4JoQHSJn5ZtoTYukkAwSdTkhcJ7ZIO3yscHnzKI4W2yiZgNlBcoNYlnx61mraWGUOEgsjBfEylk6r0ILRsZwYu4zZaQ8j4IzAq/YF4IQ4bVg4K3gBA8fCuxJmaAKVkxpEVVBC0bwBfqVxCb7j1mJJiaxrDzyTZh8sY5He/4y@wc "Python 3.8 (pre-release) – Try It Online") Input and output are in ascending order. [Answer] ## Python 3.8, 97 bytes ``` lambda l:[l[0],l[-1]]+[(i[x(i)//2]+i[~x(i)//2])/2for i in(l[:~((x:=len)(l)//2-1)],l,l[x(l)//2:])] ``` This assumes that the input list is sorted in ascending order. `f` is the function to return the 5-number summary. The 5-number summary is in the order: \$\{min, max, Q1, Q2,Q3\}\$ I took off a few bytes by taking some hints from [FlipTack's answer to Compute the Median.](https://codegolf.stackexchange.com/a/106153/87771) [Try it online!](https://tio.run/##XZLdbuIwEIXveYoRV7YKJf63kehT7F02F0ELaiQXIpqq9Kavzh5PY8Su5kuAmbF95pjxa3o9n0wcL7fj7vct92/7Pz3lbZvbplvldq267qkVQ3sVg9xsdPc0tN/1u9zo4/lCAw0nkdvttxDX7S4fTlLkUl8riS2wyfXn97aT3e3zdcgH@nX5OGwX1K/2tMPq8WMS8vl9zMMklrR@oaVEEaU8vE/irR/FcJpW1N9bllKiY//YccznHj37/3rGC5aKo@ilvCmqoe9hEPYejgMC0PTsSONBclEX1BZPAREp3UM1M7zWolpyi59lHq2l6kh50tgMSUPakvZkIMCRiQWL0zzZQDaWfXRZhMZSiawhPUgjh3fitJmnmMtFNRJzuTS4WW@cNajIp7OAQmBiJRUMY5uqKj6QyDXkMFhD3lDQFPBOFB1FzIqTYE1DSVEylKDLMQHzzAZpV7YNvmQW1dlqEzQbUpaB3MCWVb8etZqGjGIHgSXjGbZylo6r0IzhMRyb@0gdqcyjyBkGV@wrgYnkNWPIW8YxnnyooCcVgqpYNqWhqCqaMYyvwK/ENtl/zEowMbFl9eH/hCkX67C1xyeyfwE) How does it work? ``` lambda l: [l[0],l[-1]] # The minimum and maximum, because l is assumed to be sorted in ascending order +[(i[x(i)//2]+i[~x(i)//2])/2 # This line computes the median... for i in(l[:~((x:=len)(l)//2-1)],l,l[x(l)//2:])] # ...for each of these lists (the first half, the overall list, and the second half) # The (x:=len) is an assignment expression from Python 3.8. # It assigns the len function to the variable x but also returns len. # Therefore, x can be used as len to save a byte (yes, just one byte) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` ≔⊖LθηIE⟦⁰⊘÷η²⊘η⁻η⊘÷η²η⟧⊘⁺§θ⌊ι§θ⌈ι ``` [Try it online!](https://tio.run/##dZBNa8JAFEX3/RWzHGEKzXwHV6KUChXci4uggxlIx5qk0n@f3tFHnUUbckK479x5IYe26Q/nppumxTDEU@KrcOjDR0hjOPL3kE5jyy@zmWDtbP607WMa@bIZRr5pPvnuRbC3prvCXKdxFa/xGHgrmMw@DVq8bmL6GvLgHzmfvv@dbjvIi3GdjuGbXwR77c7nnsdsFekyxC6mU85v13yadjuJ4wTTt9sK5gWr8IlVBRTQhAEOKnKJXCKT0KUj/B2FroKjFAFPWcITNZbB0/C0JOBqQ7g/8A8MugZdowh0jC1wBFwrCXhWE4aAa11B9us7ripAxyHz2OurAkkowhbgPI9OrQsMgVmNXXWd//XL47HfT8/X7gc "Charcoal – Try It Online") Link is to verbose version of code. Outputs in ascending or descending order depending on whether the input is in ascending or descending order. Explanation: ``` ≔⊖Lθη ``` Get the index of the last element. ``` IE ``` Map over the elements of the following array and cast the result to string for implicit print on separate lines. ``` ⟦⁰⊘÷η²⊘η⁻η⊘÷η²η⟧ ``` Calculate the positions of the quartile elements, where an extra `0.5` denotes that the value is the average of two adjacent elements. ``` ⊘⁺§θ⌊ι§θ⌈ι ``` Calculate the quartile at each position by taking the average of the values at the floor and ceiling of the position. [Answer] # [Ruby 2.7-preview1](https://www.ruby-lang.org/en/news/2019/05/30/ruby-2-7-0-preview1-released/), 59 bytes A direct ~~ripoff~~ port of [xnor's Python answer](https://codegolf.stackexchange.com/a/188095/11261). ``` ->a{[1,n=a.size,~n-n,~n,-3].map{(a[~-@1/4]+a[-~@1/4])/2.0}} ``` [Try it online!](https://tio.run/##ZZO7bsMwDEX3fIWALi1qJ9ZbGpIfMTy4QANkaBC06NDm8evppczYtIvwyI5EUSSv/Pn99nPfb@/1rj@3ujpu@/XX4fe9uh3rI4aqtt36oz@dL4fLc9/e6sPGda99W9/o5WVj1s31ej@pfYvNSpqZmy3m5uYH6zr1pOqd0kqvvTLAKa9Wj6hjDLkpVCoWS5XKc9PNgymwU1FlzHDUMWQoAYo3gmr8NXQiLSJdg@MM5ixlj3WbBhzeHeYdznfpcYqh@MbCA5Oz9POiQuUx5pmLFS0S7tQMRCT3leiyKT0YG5Cm9HXitDn1QmSSIA9YxjWirLQA6x7rnhqGZ0CaEe@RnlhL2Jeok5QN6QGfjCwz1jPV45lIrRaqGCjtVQw0K4UZhBbaUNUIph1DxUbWSui0LNRir9WsHwE/GxjWciwefs4wlpvhWeMlojmlMdjrLUP3MwgiA99gGPgFx3gGviEKyD8PRC1w3HScm7TAMJYJAhImsxjuvyiZRCtfTjMN07W2dP88PqGA5yiVHm@sEJQvq1u4zL1s@bn7Hw "Ruby – Try It Online") (one byte longer since TiO is using Ruby 2.5 and doesn't have [numbered block parameters](https://codegolf.stackexchange.com/a/187015/11261) e.g. `@1`). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~123~~ ~~121~~ 119 bytes -2 thanks to ceilingcat. Assumes a list sorted in ascending order. Outputs in order: min, Q1, Q2, Q3, max. ``` #define M(K,x)(K[~-x/2]+K[x/2])/2., f(L,n,m)int*L;{m=n-n/2;printf("%d %f %f %f %d",*L,M(L,m)M(L,n)M((L+n/2),m)L[n-1]);} ``` [Try it online!](https://tio.run/##ZVTbbqNADH0OXzGiqgQN2WQu3MR2fyD0C1AeVrmJh9CqTVeVouyvZ48HF0xW8mHwZWzPMcN2cdxub7eH3f7Qdnv1Eq2TrzhaN38XX0uzma8bWuKl@ZEEh6hOuuQUt935qa4up@du0S1N9fYOwyEKH3fq8fAtuzB5qpMX7DjF9OzwjOo54mNY6qZb6E1cXW9/XtudOkbIoBCvaO3i4BLMDq/vyptb9axWFZafqsMyn8fBbCZqhomqmxbJglkw2Bfqlwp7E3WNnHh/@zx/RCGZr0FAqU@/2y7y1Ug77z/Outmg3EUnSoqZivXippL2cq3GZGZINmyVsVmici9Fosqp6NU3ZD7b5xuSZX6rj0M6DdVQLXKiP4NCBjZL7cJvix4O7w52h8qukPmd7LeUnlR6rGBgEpVJ8ow/43DAYmxSF9wcN@iRMwqBsodluJVovrgD/Cn8KdGCNUN7Od5zWuErsK8gvqgb4hsxJbos4S/pHCkjJ0InrOeS9X5@gng6LHJox6Az5jwIMYT781nstZqHQ0CczRg8qOHMiHOGYZmDlAd4D8GJ5wN7U8ugzy4TyBmIzQwDcZljpAzEZrkAxZc9ci3gmGvULbSAYVhGJkDzKHkG7v9ZlDQrfyFW4@Pq7/Ux8hcWfK7ocveqmao0AT2qRPKo0ec5akSICO2/A/pV3P4B "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2F2äнIR})€ÅmIWsà‚« ``` Output-order is: `[Q1, Q3, Q2, min, max]`. [Try it online](https://tio.run/##ATIAzf9vc2FiaWX//zJGMsOk0L1JUn0p4oKsw4VtSVdzw6DigJrCq///WzEsMiwzLDQsNSw2XQ) or [verify all test cases](https://tio.run/##VZI9SgRBEIWvsmwmPKG7q38TN/MAJgbLBgoGBmKwIAyLIIKXMDIw0yuYuBfwDHuRsap6ah2pb4bp7qLq1Zu@315d396MD8NquTg9WyxXwxjOw/7952u4eDw5PH/uX@6Gy@3@7fD0@v0x7jCu1x4BhIi0wYIX1BfIKPCu71mEY/QsiyTRU/uxbUqRgop2DO86kt1zM5/LVoLPCFyBNwkhImQQ90mgKsSEmBELYrVWzT5oEtRMb@DmvXWdKvuqNbWsUJRqNIGU6KxXndGQHBLLdciEElD43VATKk/AnXhKh@bRCI2VJEU8PM4qrti0LJLgo8L6ik5uY8/FkQN5NYKJoKyoI5NWjxgUUt1JPZpjM8gAHokU/j3ZKEpFDgohRyUpGbkYnNOE4o2oLjhUbwSFlGywQU19if/caeyaXApnz@wS/n3KYvML). (I've added a sort `{` for the test suite, so the test cases are easier to verify in the order `[min, Q1, Q2, Q3, max]`.) **Explanation:** ``` 2F # Loop 2 times: 2ä # Split the list at the top of the stack into two halves # (which is the (implicit) input-list in the first iteration) н # Only leave the first halve IR # Push the input in reverse }) # After the loop: wrap all three lists into a list € # For each of the lists: Åm # Get the middle/median depending on the parity of the size of the list I # Then push the input-list again W # Get the minimum (without popping) s # Swap to get the input-list again à # Get the maximum (by popping the list) ‚ # Pair the min-max together to a pair « # And merge both lists together # (after which the result is output implicitly) ``` ]
[Question] [ **The Challenge:** For an input of one letter X (upper or lower case from A to Z) and one digit N (0-9) print the corresponding letter X made of N \* X. The letter has to be from this list: ``` AAA BBBB CCCC DDDD EEEEE FFFFF GGG H H A A B B C D D E F G H H AAAAA BBBB C D D EEEE FFFF G GG HHHHH A A B B C D D E F G G H H A A BBBB CCCC DDDD EEEEE F GGG H H IIIII J K K L M M N N OOO I J K K L MM MM NN N O O I J KKK L M M M N N N O O I J J K K L M M N NN O O IIIII JJJ K K LLLLL M M N N OOO PPPP QQQ RRRR SSSS TTTTT U U V V W W P P Q Q R R S T U U V V W W PPPP Q Q RRRR SSS T U U V V W W P Q QQ R R S T U U V V W W W P QQQQ R R SSSS T UUU V W W X X Y Y ZZZZZ X X Y Y Z X Y Z X X Y Z X X Y ZZZZZ ``` **Examples:** input: a 1 output: ``` AAA A A AAAAA A A A A ``` --- input: A 0 output: `A` --- input: A 2 output: ``` AAA AAA AAA A AA AA A AAAAAAAAAAAAAAA A AA AA A A AA AA A AAA AAA A A A A AAAAA AAAAA A A A A A A A A AAA AAA AAA AAA AAA A AA AA AA AA A AAAAAAAAAAAAAAAAAAAAAAAAA A AA AA AA AA A A AA AA AA AA A AAA AAA A A A A AAAAA AAAAA A A A A A A A A AAA AAA A A A A AAAAA AAAAA A A A A A A A A ``` --- input: A -1 output: *what ever: it doesn't matter* --- **Additional Rules:** * The input parameters can be separated by what ever character you want. * Each letter must use the capital of itself as the ascii-character to draw it. * Trailing spaces, new lines etc. are allowed * Instead of a program, you may write a function that takes the digit string as an argument. The output should be printed normally. * Stdout / Stderr doesn't matter, just pick one. If stuff gots printed on the other doesn't matter either. * Possible output formats can be printed to STDOUT, returned as a list of strings, returned as a character matrix, etc. as long as the result can simply be printed using the languages default print method.\* \*: like the function f(a,1) returns the string and one can simply say print(f(a,1)) dont make the print() call part of the answer. (This was pointed out by Kevin Cruijssen and Arnauld). **Winning:** This is code-golf, lowest byte-count wins. Have fun! --- **Edit**: this question seems *very identical* to [this](https://codegolf.stackexchange.com/questions/157664/create-an-h-from-smaller-hs) however I would say it is not, as it should not only work for H but for each letter from the alphabet.. Guess you decide rather or not it is a duplicate. [Answer] # JavaScript (ES8), 281 bytes Takes input as `(letter)(N)`. Returns a string. ``` c=>n=>(g=y=>y--?''.padEnd(w).replace(/./g,(_,x)=>(h=d=>~~(d/=5)?(P=parseInt)('hhvhefhfhfu111ufhhhfv1f1v11f1vehp1ehhvhhv444vehgggh979hv1111hhlrhhpljhehhhe11fhfuphheh9fhffge1u4444vehhhh4ahhhalhhhha4ah444ahv248v'[y/d%5+5*P(c,36)-50|0],36)>>x/d%5&1?h(d):' ':c)(w))+` `+g(y):'')(w=5**n) ``` [Try it online!](https://tio.run/##ZY9NS8NAEIbv/RVedHfS5mNroqawKSoevPUuYpfsx1hCsiTt2oD0r8cJ3nQHhnee952BPaighrr/9Me47bSZrJxqWbWy4k6OshrjeMtY4pV@aTX/gqQ3vlG14WmSuhX/WJ2Boii1rC4XrlNZwJbvpFf9YF7bI3CGGNBYpDoJIU4WEW0QVgQxN4NemDmCIc9zGp1zWN6XSLYQiE2P6JsDUgYNbdAVTwpLUtYZccp/1@jlippqZqlIE1cY1vlDYG9jqq@LZRHteL26vYO4yL6z91lV1Xm2bsQWuYYNu2KbGuibsNwv9kvHR2KMgCyiqIWp7tqha0zSdI5bzh7JygAWf/ATYfEfPxNeA0w/ "JavaScript (Node.js) – Try It Online") ## How? ### Font encoding The letters are \$5\times5\$, which means that each row can be encoded as a 5-digit binary value, i.e. \$0\$ to \$31\$ in decimal. These values can conveniently be stored as a single digit in Base36. The pattern that is stored is mirrored both horizontally and vertically. *Example for 'F':* ``` ##### ....# 00001 1 '1' #.... ....# 00001 1 '1' ####. --> .#### --> 01111 --> 15 --> 'f' --> '11f1v' #.... ....# 00001 1 '1' #.... ##### 11111 31 'v' ``` The whole font is stored as a single string of \$26\times5 = 130\$ characters. To test the 'pixel' at \$(x,y)\$ for the \$n^{\text{th}}\$ letter, we do: ``` parseInt('hhvhefhfh...'[y + 5 * n], 36) >> x & 1 ``` ### Main algorithm Given \$n\$, we define \$w=5^n\$, which is the width of the final output. For \$0\le x<w\$ and \$0\le y<w\$, we want to know if the output pixel at \$(x,y)\$ is set or not. We use the recursive function \$h\$, which tests the letter pixel located at: $$\left(\left\lfloor\frac{x}{5^k}\right\rfloor\bmod 5,\left\lfloor\frac{y}{5^k}\right\rfloor\bmod 5\right)$$ for all \$k\$ in \$[0 \dots n-1]\$. The function returns a space as soon as a blank pixel is detected at some depth, or the character corresponding to the input letter if all iterations are successful. [Answer] # [R](https://www.r-project.org/), 348 bytes ``` function(K,N){if(N)for(i in 1:N)T=T%x%matrix(c(15269425,32045630,16269839,32032318,33061407,33061392,15224366,18415153,32641183,1082926,18444881,17318431,18732593,18667121,15255086,32045584,15255151,32045649,16267326,32641156,18400814,18400580,18400938,18157905,18157700,32575775)[utf8ToInt(K)-64]%/%2^(24:0)%%2,5,5) write(c(" ",K)[T+1],1,5^N,,"")} ``` [Try it online!](https://tio.run/##XZDBasMwDIbvfYpgCLWZyiTbsuVuO2y3UcgpsEPXQgkL5LAUQsoKY8@euU0PY7ePz/p/CQ9TWzyupvbUN2N37PUGKvPdtboy7XHQXdH1Ba0rUz/V5bn8PIxDd9aNJrYhecvgLHoODoFCNuLSxTjrSMA5DOQxzuCShZyy3oUAJJ6Y2OXh4InEAaHYZK8v3osQUMwd3mWQ6CynPCIhRLJ0qWFGCfNyFj@b3Hg7x6frOTkXbhv42owo5GdgwRmSkwzEMSHPEBFzimMmNtvT2Ep9fO1HvTGr4HflfWn32vo1mrK0wMBm8TV040f@FVUo2JhtfUc7IOB9BaCU@Zlard4UoHloDqNevvdLs8jqWQH9Uy8K7B81/QI "R – Try It Online") Uses an encoding nearly identical to [Ouros'](https://codegolf.stackexchange.com/a/177397/67312); however, it does not reverse the bits, instead opting to use them directly. It then creates a 5x5 matrix of bits and builds the [Kronecker Power](https://en.wikipedia.org/wiki/Kronecker_product) matrix to generate the necessary pattern, writing the results to stdout. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~436~~ 372 bytes Significantly shorter with new IO format. ``` import StdEnv,StdLib t=transpose f=flatten $0c=[[c]] $n c=f[t(f[t($(n-1)if(isOdd({#18415150,16301615,31491134,16303663,32554047,1096767,15262766,18415153,32641183,15254032,18128177,32539681,18405233,18667121,15255086,1097263,32294446,18136623,16267326,4329631,15255089,4539953,11191857,18157905,4329809,32575775}.[toInt(max'A'c)-65]>>p))c' ')\\p<-[i..i+4]])\\i<-[0,5..20]] ``` [Try it online!](https://tio.run/##PVHdS8MwEH/fXxFw0BbTksvHpQE7GOjDYCDiY@1D13UjsGZjjaKI/7o1qeJDuPzufh9w15361k3Def966snQWjfZ4XK@evLs9w/ujYaytbuFr/y1dePlPPaLQ3U4td73brFkXVXXXdMslo501aH2aXzL1OWQ2UNqx8f9Pv28gVKCAsUooGCAoKgAaQCEnDsCUVDBlZJMagrMoMZQFUeuEemfOlJQApQijgJX8DACXoLWUS0MlhDJTHEROCWiBg4zWbESo7HmcxI3UspoDCGaBy5y1MGdSsENin@NoTLYmhANAAZKpaNGacPUTC2Ziclaaa2@itqfN86nQ/uerJMuy1E1q9Uly7qEJNnLy@Uur21R2FvZNAHaABlVRcFZ00zPvg07r0jc7Mm6fiQpWRJOkqeEZNN3F/rHcco32@n@w7WD7X7B73Xm7/p6DPea8t0P "Clean – Try It Online") Compresses the letter patterns into the bits of integer literals to save ~700 bytes. For example, `A`: 1. Flatten `[[' AAA '],['A A'],['AAAAA'],['A A'],['A A']]` 2. Reverse `[' AAA A AAAAAAA AA A']` 3. Turn `['A AA AAAAAAA A AAA ']` into binary (`'A' = 1, ' ' = 0`) 4. Turn `0b1000110001111111000101110` into decimal 5. Get `18415150` [Answer] # [R](https://www.r-project.org/), 259 bytes ``` function(K,N,`!`=utf8ToInt){if(N)for(i in 1:N)T=T%x%(sapply(!"            ",intToBits)[1:5,5*(-64+!K)-4:0]>0) write(c(" ",K)[T+1],1,5^N,,"")} ``` [Try it online!](https://tio.run/##XVDBagIxECVloTWH3R2KByls1oCY1Ahu0VJsLVTwUCx7aAM9qEURAwHJikbaIn77NhF6aBlmMu/lvXeYbanSh3ap9mZpdWHYWORiXp8P9lbdyeLZWH7QiuVcFVumU23SrJ9zOZCNrwbbLTab9Ter0xAIQOQrQQglEThEUISIHyhENQjBS0gQBCSOYwcr5xVwWkTgqurkl9WTBkKX4RwANZcSVSBBYRx5WwD@1zX2WxW7F3vgAi@CM0KFNlYWQ213fJL1e6J3zdq33VZ9zNvdfmf22OH4c6vtii0ZTakY84lsZTORid5HLgSl/FgqRt@p6PD75cKy5tQ0OXbUExXZP2pIxc0fyt1mvbLWn@dlJOXo9Y0fcJqqE/trp1NDOT6WPw "R – Try It Online") > > ***Disclaimer :*** > > *this solution has been obtained by taking [@Giuseppe's answer](https://codegolf.stackexchange.com/a/177484/41725) and replacing the matrix compression with another approach very very similar to the one used in [@Arnauld's answer](https://codegolf.stackexchange.com/a/177398/41725), so first of all go upvote them* :) > > > The idea is the following : Given this `5 x 26*5` matrix of `0/1` : ``` (1 replaced by '#', 0 replaced by '.' and '|' added for readability) .####|#####|.###.|#####|#####|#####|.###.|#####|#...#|...#.|#####|#####|#####| #.#..|#.#.#|#...#|#...#|#.#.#|#.#..|#...#|..#..|#...#|....#|..#..|....#|.#...| #.#..|#.#.#|#...#|#...#|#.#.#|#.#..|#...#|..#..|#####|....#|..#..|....#|..#..| #.#..|#.#.#|#...#|#...#|#.#.#|#.#..|#.#.#|..#..|#...#|....#|.#.#.|....#|.#...| .####|.#.#.|#...#|.###.|#...#|#....|..##.|#####|#...#|####.|#...#|....#|#####| ... ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ | | | | | | | | | | | | | A B C D E F G H I J K L M ``` each column is considered as binary number and converted to an integer. These integer are then converted to unprintable ASCII in the range 1...31 : e.g. for the columns of `"B"` the final string will be `"\017\021\017\021\017"` (unprintable chars written in octal representation): ``` ##### ####. 11110 15 '\017' #.#.# #...# 10001 17 '\021' #.#.# -------> ####. --> 11110 ------> 15 ------> '\017' #.#.# #...# 10001 17 '\021' .#.#. ####. 11110 15 '\017' (transposed bin to int int to ASCII for reability) ``` Hence, given the final string of `5*26 = 130` characters, we convert that string back to the matrix of `0/1` using : ``` sapply(utf8ToInt(STRING),intToBits) ``` then we simply subsect the matrix selecting only the first 5 rows (intToBits returns 32 bits) and only the columns corresponding to the letter passed as input and finally we apply kronecker as explained in [@Giuseppe's answer](https://codegolf.stackexchange.com/a/177484/41725). ]
[Question] [ ## Background **Sudoku** is a number puzzle where, given an \$ n \times n \$ grid divided into boxes of size \$ n \$, each number of \$ 1 \$ to \$ n \$ should appear exactly once in each row, column and box. In the game of Chess, the **King** can move to any of (at most) 8 adjacent cells in a turn. "Adjacent" here means horizontally, vertically or diagonally adjacent. The **King's tour** is an analogy of the Knight's tour; it is a (possibly open) path that visits every cell exactly once on the given board with Chess King's movements. ## Task Consider a 6-by-6 Sudoku grid: ``` 654 | 321 123 | 654 ----+---- 462 | 135 315 | 246 ----+---- 536 | 412 241 | 563 ``` and a King's tour (from `01` to `36`): ``` 01 02 03 | 34 35 36 31 32 33 | 04 05 06 ---------+--------- 30 23 28 | 27 26 07 22 29 24 | 25 09 08 ---------+--------- 21 19 16 | 10 14 13 20 17 18 | 15 11 12 ``` The tour forms the 36-digit number `654654564463215641325365231214123321`. Taking a different King's tour gives larger numbers; for example, I can find a path that starts with `65<6>56446556...` which is definitely greater than the above. You can change the Sudoku board to get even higher numbers: ``` ... | ... .6. | ... ----+---- ..6 | ... .5. | 6.. ----+---- .45 | .6. 6.. | 5.. ``` This incomplete board gives the starting sequence of `666655546...` which is the optimal sequence of 9 starting digits. Your task is to **find the largest such number for standard 9-by-9 Sudoku with 3-by-3 boxes**, i.e. ``` ... | ... | ... ... | ... | ... ... | ... | ... ----+-----+---- ... | ... | ... ... | ... | ... ... | ... | ... ----+-----+---- ... | ... | ... ... | ... | ... ... | ... | ... ``` Note that **this challenge is not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")**; the focus is to actually find the solutions rather than to write a small program that theoretically works. ## Scoring & winning criterion **The score of a submission is the 81-digit number found by your program.** The submission with the highest score wins. Your program should also output the Sudoku grid and the King's tour in human-readable form; please include them in your submission. Your program may output multiple results; your score is the maximum of them. There's no time limit for your program. If your program continues to run and finds a higher number afterwards, you can update the submission's score by editing the post. Tiebreaker is the earliest time to achieve the score, i.e. either the time of post (if it's not edited yet) or the time of edit when the score was updated (otherwise). [Answer] # Python + [Z3](https://github.com/Z3Prover/z3), 999899898789789787876789658767666545355432471632124566352413452143214125313214321, optimal Runs in about half an hour, producing ``` 1 3 4 8 9 7 6 2 5 2 9 7 1 5 6 8 3 4 5 6 8 4 2 3 7 9 1 4 7 6 2 1 5 9 8 3 8 5 1 6 3 9 2 4 7 9 2 3 7 8 4 1 5 6 3 8 5 9 6 1 4 7 2 6 4 9 5 7 2 3 1 8 7 1 2 3 4 8 5 6 9 81 79 78 14 15 16 54 57 56 80 12 13 77 52 53 17 55 58 34 33 11 51 76 75 18 1 59 35 10 32 50 74 72 2 19 60 9 36 49 31 73 3 71 61 20 8 48 37 30 4 69 70 62 21 47 7 38 5 29 68 65 22 63 46 43 6 39 28 67 66 64 23 44 45 42 41 40 27 26 25 24 999899898789789787876789658767666545355432471632124566352413452143214125313214321 ``` ### Code ``` import z3 def adj(a): x, y = a for x1 in range(max(0, x - 1), min(9, x + 2)): for y1 in range(max(0, y - 1), min(9, y + 2)): if (x1, y1) != a: yield x1, y1 solver = z3.SolverFor("QF_FD") squares = list((x, y) for x in range(9) for y in range(9)) num = {(x, y): z3.Int(f"num{x}_{y}") for x, y in squares} for a in squares: solver += 1 <= num[a], num[a] <= 9 for cells in ( [[(x, y) for y in range(9)] for x in range(9)] + [[(x, y) for x in range(9)] for y in range(9)] + [ [(x, y) for x in range(i, i + 3) for y in range(j, j + 3)] for i in range(0, 9, 3) for j in range(0, 9, 3) ] ): solver += z3.Distinct([num[x, y] for x, y in cells]) for k in range(1, 10): solver += z3.Or([num[x, y] == k for x, y in cells]) move = { ((x0, y0), (x1, y1)): z3.Bool(f"move{x0}_{y0}_{x1}_{y1}") for x0, y0 in squares for x1, y1 in adj((x0, y0)) } tour = {(x, y): z3.Int(f"tour{x}_{y}") for x, y in squares} for a in squares: solver += 0 <= tour[a], tour[a] < 81 for a in squares: solver += z3.PbEq([(move[a, b], 1) for b in adj(a)] + [(tour[a] == 80, 1)], 1) for b in squares: solver += z3.PbEq([(move[a, b], 1) for a in adj(b)] + [(tour[b] == 0, 1)], 1) solver += z3.Distinct([tour[a] for a in squares]) for t in range(81): solver += z3.Or([tour[a] == t for a in squares]) for a in squares: for b in adj(a): solver += move[a, b] == (tour[a] + 1 == tour[b]) value = [z3.Int(f"value{t}") for t in range(81)] for t in range(81): solver += 1 <= value[t], value[t] <= 9 for a in squares: for t in range(81): solver += z3.Implies(tour[a] == t, num[a] == value[t]) assert solver.check() != z3.unsat opt = 0 while opt < 81: model = solver.model() for y in range(9): print(*(model[num[x, y]] for x in range(9))) for y in range(9): print(*(f"{model[tour[x, y]].as_long() + 1:2}" for x in range(9))) best = [model[value[t]].as_long() for t in range(81)] print(*best, sep="") print() while opt < 81: improve = z3.Bool(f"improve{opt}_{best[opt]}") solver += improve == (value[opt] > best[opt]) if solver.check(improve) != z3.unsat: break solver += value[opt] == best[opt] opt += 1 ``` ]
[Question] [ ## Introduction This is a log of length 5: ``` ##### ``` I want to pile a bunch of these logs on top of each other. How I do this is that I slide a new log onto the topmost one from the right, and stop sliding when their left or right ends align (don't ask why). If the new log is longer, it slides all the way to the left end of the topmost log: ``` ######## <- ##### ``` If it is shorter, it only slides until their right ends align: ``` ###### <- ######## ##### ``` As I slide more logs into the pile, their positions are determined by the current topmost log: ``` ## ###### ### #### ## ###### ######## ##### ``` This looks physically impossible, but let's pretend it works. ## The task Your input shall be a non-empty list of positive integers, representing the lengths of my logs. The leftmost number is the first log I put to the pile, so it ends up at the bottom. In the above example, the input would be `[5,8,6,2,4,3,6,2]`. Your output shall be, for each column of the resulting pile, the number of logs that cross that column. In the above example, the correct output would be `[2,2,3,3,3,2,4,6,3,3,1,2,2]`. ## Rules and scoring Input and output can be in any reasonable format. The output can only contain positive integers, i.e. it must not have leading or trailing `0`s. Normal code-golf rules apply: you can write a full program or a function, the lowest byte count wins, and [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/32014) are forbidden. ## Test cases ``` [1] -> [1] [4] -> [1,1,1,1] [3,2] -> [1,2,2] [2,3] -> [2,2,1] [2,2,2] -> [3,3] [2,3,2] -> [2,3,2] [3,2,3] -> [1,3,3,1] [1,3,2,2,1,3,1] -> [2,3,5,1,2] [4,3,4,2,4,3,4,2] -> [1,3,3,5,5,3,4,2] [5,8,6,2,4,3,6,2] -> [2,2,3,3,3,2,4,6,3,3,1,2,2] [5,10,15,1,1,1,1,1,2] -> [3,3,3,3,3,2,2,2,2,2,1,1,1,1,7,1] [13,12,2,10,14,12] -> [1,2,2,2,2,2,2,2,2,2,2,5,5,3,3,3,3,3,3,3,3,2,2,2,2] [12,14,3,6,13,1,1] -> [2,2,2,2,2,2,2,2,2,2,2,5,4,4,2,2,2,1,1,1,1,1,1,3] [7,5,12,5,1,10,14,5] -> [1,1,3,3,3,3,3,1,1,2,2,2,2,5,2,2,2,2,2,2,2,2,3,2,2,2,2] [14,5,1,3,12,6,2,2,1,7,9,15] -> [1,1,1,1,1,1,1,1,1,2,2,2,2,5,2,2,1,1,1,2,2,2,2,4,8,3,3,3,3,3,3,2,2,1,1,1,1,1,1] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes prompted by help from [miles](https://codegolf.stackexchange.com/users/6710/miles) Maybe there is a quicker way using mathematics rather than construction like this does? ``` IN0;»0+\0ẋ;"1ẋ$S ``` **[Try it online!](https://tio.run/##y0rNyan8/9/Tz8D60G4D7RiDh7u6rZUMgaRK8P///6NNdSx0zHSMdEx0jEF0LAA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8/9/Tz8D60G4D7RiDh7u6rZUMgaRK8P@jew63P2pac3TSw50zgDQQZYGohjkKunYKjxrmRv7/Hx1tGKvDpRBtAiaNdRSMwAwjHQVjGMMIWRDGNgaLQ9QYQsTBCMKGmglmm4DFEWywlKmOgoWOghmSlBmSlKEBEJuCDUNGEHlDkPlQy0DqTEBciIwRhAsxDawO5hRzHQVTiDaosVCdphCNJjBxqNlmSN4BarUEOSc2FgA "Jelly – Try It Online"). ### How? ``` IN0;»0+\0ẋ;"1ẋ$S - Link: list of positive integers, logLengths e.g. [4, 3, 3, 1, 4, 3] I - incremental differences [-1, 0,-2, 3,-1] N - negate (vectorises) [ 1, 0, 2,-3, 1] 0; - zero concatenated with that [0, 1, 0, 2,-3, 1] »0 - maximum (vectorises) of that and zero [0, 1, 0, 2, 0, 1] +\ - cumulative reduce with addition [0, 1, 1, 3, 3, 4] 0ẋ - zero repeated (vectorises) [[],[0],[0],[0,0,0],[0,0,0],[0,0,0,0]] $ - last two links as a monad (right is implicitly logLengths): 1ẋ - one repeated [[1,1,1,1],[1,1,1],[1,1,1],[1],[1,1,1,1],[1,1,1]] " - zip with: ; - concatenation [[1,1,1,1],[0,1,1,1],[0,1,1,1],[0,0,0,1],[0,0,0,1,1,1,1],[0,0,0,0,1,1,1]] ... this is an upside-down version of the logs like those in the OP with 0 for spaces and 1 for # with any right-hand-side spaces missing. S - sum [1, 3, 3, 5, 2, 2, 2] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 13 bytes ``` IN0»0;+\+"RṬS ``` [Try it online!](https://tio.run/##PU6xDQIxDNyF9l0k@SQPYgKERAEVCilp0C9AS8MyvwD6DiaBRcz5FJDlO/tsX3I5j@NVdbNzz9mtu1O32L8f00Ff989t2iKPqqX4KiUiewnAID0x/DoykLq3HmHMO3BE3xhKkqXkpuSmeCce@A9TPQzohFlEaVKw0s5sSP9Bkq3xmIvJ9iIFGuT2nUFWeKPWLw "Jelly – Try It Online") Saved 2 bytes thanks to @Jonathan Allan. ## Explanation ``` IN0»0;+\+"RṬS Input: array A I Increments N Negate 0» Max with 0 0; Prepend 0 +\ Cumulative sum +" Vectorized add with R Range, vectorizes over each integer Ṭ Create a list with 1's at the specified indices S Sum ``` [Answer] # [Python 3](https://docs.python.org/3/), 114 109 bytes **Edit:** Saved 5 bytes thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) ``` f=lambda x,i=1:x[i:]and x[i]>=x[~-i]and f(x,i+1)or[i]+f([q-(e<i)for e,q in enumerate(x)if(e<i)<q])if x else[] ``` [Try it online!](https://tio.run/##bVPbboMwDH0uX5G9gepKC7duqOwr9oaiiq1BjdTSFqjEXvbrzDFJoHSyEPHx8bFjzPWnO17qaBiq/FSevw4l60HlPOsLlYmyPjA8iI@8L343ivzKR8KaB5cGA@vKL24bX@5UUF0aJuHGVM1kfT/Lpuyk3weqoujuJvDIeiZPrSzE0Mm223@XrWxZzgqvKLgAfATgMdZHIBuBCEKCQnwTEEKEALqWEVIMkBk5BgHj26pQGkcosonaIR2CRn6CnsmJ0Y0xbN4uO0EbEaIl8AapoaWmbkjEiNB0LDldAEu8Ak@AOzPduyRrNr51HaMQBVAgxqOdzJONPT6aiRmlUCvojrWmuf7/SjFNYd6PNjPrrZ5YSGMbm0rMB5zqcuAztaX@sq@YtOieqSm6hXec17QY88k96D5iMX6Y5f1nuUJ4wvP05rp9BNbI9n7q9B5PS5p5K@fsDSHHX8GBgbfC9fafSC@50Qsydm1U3fmzSku2rY1i@jexGZ/NXQbDHw) [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` Fż+Ṡzo`Ṙ↔ḋ2eo∫Ẋ< ``` [Try it online!](https://tio.run/##yygtzv7/3@3oHu2HOxdU5Sc83DnjUduUhzu6jVLzH3Wsfriry@b////RpjoWOmY6RjomOsYgOhYA "Husk – Try It Online") ### Explanation ``` Ẋ For all adjacent pairs, x y < return max(0,x-y) o∫ Cumulative sum, with an extra 0 at the start Ṡz Zip the input list and ^ with ... e Make a two element list ↔ḋ2 The list [0,1] o`Ṙ Repeat each in ^ by ^^ Fż+ Sum the columns ``` [Answer] # [Perl 5](https://www.perl.org/), 64 + 1 (`-a`) = 65 bytes ``` for(@F){$e<$s+--$_?$e=$s+$_:($s=$e-$_);$_++for@r[$s..$e]}say"@r" ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0jDwU2zWiXVRqVYW1dXJd5eJdUWyFSJt9JQKbZVSQUKaVqrxGtrA5U6FEWrFOvpqaTG1hYnVio5FCn9/29opGBoomCsYKZgaKxgqGD4L7@gJDM/r/i/rq@pnoGhwX/dRAA "Perl 5 – Try It Online") [Answer] # Mathematica, ~~76~~ ~~60~~ ~~58~~ 57 bytes ``` #2&@@@Tally[l=j=0;##&@@(Range@#+(j+=Ramp[l-(l=#)]))&/@#]& ``` [Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com) [Answer] # [Kotlin](https://kotlinlang.org) 1.1, ~~113~~ 103 bytes ``` {var l=0 var r=0 it.flatMap{l=maxOf(l,r-it+1) r=l+it-1 (l..r).toList()}.groupBy{it}.map{it.value.size}} ``` ## Beautified ``` { // Current row leftmost value var l = 0 // Current row rightmost value var r = 0 // For each log it.flatMap { // Work out the new leftmost point l = maxOf( l, r - it+1) // Use it to work out the new rightmost point r = l + it-1 // Record the used columns (l..r).toList()} // Group the column numbers together .groupBy { it } // Count the amount of times each column is used // Put the results into a list .map { it.value.size } } ``` ## Test ``` var z:(List<Int>)->List<Int> = {var l=0 var r=0 it.flatMap{l=maxOf(l,r-it+1) r=l+it-1 (l..r).toList()}.groupBy{it}.map{it.value.size}} fun main(args: Array<String>) { println(z(listOf(5, 8, 6, 2, 4, 3, 6, 2))) println(listOf(2,2,3,3,3,2,4,6,3,3,1,2,2)) } ``` ]
[Question] [ What general tips do you have for golfing in [///](https://esolangs.org/wiki////)? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to /// (e.g. "remove unnecessary whitespace" is not an answer). Tips for [itflabtijtslwi](https://esolangs.org/wiki/Itflabtijtslwi) and [Lines](https://esolangs.org/wiki/Lines) are on-topic and valid here as well. Please post one tip per answer. [Answer] # Use `//` as a replacement When you define a bunch of replacements, e.g.: ``` /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/ ``` (65 bytes). You can use `//` as a replacement: ``` /~/\/\///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/ ``` (61 bytes). [Answer] **When expanding on a basis and printing intermediate results, incorporate previous iterations in future ones** That sounded a bit convoluted. What I mean might better be described using an actual answer. [This challenge](https://codegolf.stackexchange.com/questions/123971/the-curious-case-of-steve-ballmer) requires this specific output: ``` Steve Ballmer still does not know. Steve Ballmer still does not know what he did. Steve Ballmer still does not know what he did wrong. Steve Ballmer still does not know what he did wrong with mobile. ``` One naive solution might be: ``` /1/Steve Ballmer still does not know//2/ what he did//3/ wrong//4/ with mobile./1. 12. 123. 1234 ``` Notice how the pattern `1`, `12`,`123` ... is repeated? Well, not when you do this: ``` /1/Steve Ballmer still does not know//2/1 what he did//3/2 wrong//4/3 with mobile/1. 2. 3. 4. ``` *Once again, thanks go to Martin Ender for pointing this out!* [Answer] ## Incomplete /// blocks are not printed Note that this line of code ``` /Stack/Overflow//x/\//Stack/ignore/DoItyignore ``` prints only `Overflow` - the part from `/ignore` onwards is not included in the output, because `///` only prints things in its third slash-part. [Try the incomplete block online!](https://tio.run/nexus/slashes#@68fXJKYnK3vX5ZalJaTX66vX6Efow8VzEzPyy9K1U/JzyyphLD//wcA) It is however still considered by the replacer: if we were to inject a slash in there, things change: ``` /Stack/Overflow//x/\//Stack/ignore/doitxignore ``` [Try that online!](https://tio.run/nexus/slashes#@68fXJKYnK3vX5ZalJaTX66vX6Efow8VzEzPyy9K1U/JzyypgLD//wcA) Output here is `Overflowdoit`, because replacing `x` with `/` made it valid syntax. [Answer] # Use a character at the end of code to handle edge cases When you have a piece of `///` code that handles all but one case, then you can use a character at the edge of the code to handle the edge case. **Example:** Unary add two numbers together unless the second number is 7, in which case just output the first number. Code that handles all but the "second number is 7" case: ``` /+//<INPUT 1>+<INPUT 2> ``` By adding a `*` to the end of the code, we can handle the edge case by replacing `+0000000*` with nothing (it is necessary to include the `+` to makes sure the number is not greater than 7). Make sure to include code at the end before the input to clean it up. ``` /+0000000*///+///*//<INPUT 1>+<INPUT 2>* ``` [Try it online!](https://tio.run/##K85JLM5ILf7/X1/bAAK09PX1tYEYSBvAxf7/BwA "/// – Try It Online") For a "real-world" example, I used this trick on some of the "Jimmy" problems: * <https://codegolf.stackexchange.com/a/187652/64159> * <https://codegolf.stackexchange.com/a/187789/64159> ]
[Question] [ When code-golfing there will be times where you need a Hex Dump of your code, usually because you've used unprintable characters. So, why not make a program that Hex Dumps itself? ## The Challenge This challenge is to, given no input, output a Hex Dump of your source code in the following formatting: ``` 0000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0030: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ ``` Or, for example, if your program was `print("SomeString"):rep(123)` ``` 0000: 70 72 69 6e 74 28 5c 22 53 6f 6d 65 53 74 72 69 print("SomeStrin 0010: 6e 67 5c 22 29 3a 72 65 70 28 31 32 33 29 g"):rep(123) ``` ## Specifics The hex dump is split into rows of three parts, each row representing 16 bytes of your source code. The first part is the memory address. It specifies where the current row starts in your code. Written as a 2 Byte Hexadecimal number, followed by a `:`, then a space. The Second, is the Hex Dump itself. This is 16 bytes of your Source Code, written in Hexadecimal form separated by spaces. This should be an accurate byte representation using your code's encoding. Lastly, after a two space gap, is the code itself. This is simply 16 characters of your code, with Non printable characters written as `.` ## Notes * This *is* a [quine](/questions/tagged/quine "show questions tagged 'quine'") challenge, so [Standard Quine Rules](http://meta.codegolf.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) apply. * And this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge too, so [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * As shown in the second example, do not write bytes after EOF, instead use whitespace. * Trailing whitespace is fine. * Inbuilts to Hex dump, if you happen to have one in this specific format, are not banned but are frowned upon. * Non printable characters refer to any character that, represented as only a single byte, cannot be represented as a single spaced glyph. For UTF-8, this means `0-31`, `128-255`. For the [Jelly Codepage](https://github.com/DennisMitchell/jelly/wiki/Code-page), as all characters can be represented as a single spaced glyph, there are no Non printable characters. [Answer] # Perl, 81 bytes ``` #!perl -l $_=q($%+=print"00$%0: @{[unpack'(H2)*']} $_"for"\$_=q($_);eval"=~/.{16}/g);eval ``` Counting the shebang as one. Having the code length be a multiple of 16 saves quite a bit on formatting. Using `eval` to reassign `$_` to itself borrowed from [ais523](https://codegolf.stackexchange.com/a/107027/4098). **Output:** ``` 0000: 24 5f 3d 71 28 24 25 2b 3d 70 72 69 6e 74 22 30 $_=q($%+=print"0 0010: 30 24 25 30 3a 20 40 7b 5b 75 6e 70 61 63 6b 27 0$%0: @{[unpack' 0020: 28 48 32 29 2a 27 5d 7d 20 20 24 5f 22 66 6f 72 (H2)*']} $_"for 0030: 22 5c 24 5f 3d 71 28 24 5f 29 3b 65 76 61 6c 22 "\$_=q($_);eval" 0040: 3d 7e 2f 2e 7b 31 36 7d 2f 67 29 3b 65 76 61 6c =~/.{16}/g);eval ``` [Try it online!](https://tio.run/nexus/perl#@68Sb1uooaKqbVtQlJlXomRgoKJqYKXgUB1dmleQmJytruFhpKmlHluroKASr5SWX6QUA9ERr2mdWpaYo2Rbp69XbWhWq58OEfj//79uDgA "Perl – TIO Nexus") [Answer] # [Perl](https://www.perl.org/) + xxd + cut, 61 bytes ``` $_=q(open F,"|xxd -g1|cut -c5-";print F"\$_=q($_);eval");eval ``` [Try it online!](https://tio.run/nexus/perl#@68Sb1uokV@QmqfgpqNUU1GRoqCbbliTXFqioJtsqqtkXVCUmVei4KYUA1aoEq9pnVqWmKMEof7/BwA "Perl – TIO Nexus") This is a universal quine constructor in Perl + a call to `xxd` and `cut` to do the hexdumping. None of the programs in question have a builtin to do a hexdump in the format in the question; however, `xxd -g1` comes very close and so it's possible to use `cut` to trim the output into the correct shape. The universal quine constructor is `$_=q("\$_=q($_);eval");eval`, which creates a copy of its own source code in memory, and can be modified to perform arbitrary operations on it. In this case, I use `open "|"` and `print` to pipe the input into external programs, `xxd` which does the bulk of the hexdumping work and `cut` which changes it into the required format. [Answer] # [V](https://github.com/DJMcMayhem/V), 39 bytes ``` ñi241"qp:%!xxd Î4x Íøø / & f&3i ÿ ``` [Try it online!](https://tio.run/nexus/v#@394Y6aYkYmhtFJhgZWqYkVFCtfhPpMKrsO9h3cc3qGgr6DGlaZmnKlweD/X//8A "V – TIO Nexus") Note that normally V uses the latin1 encoding, where this is 36 bytes (which is what TIO says) but this submission is using UTF-8 where it is 39 bytes. This is pretty much just a modification of the [V-quine template](https://codegolf.stackexchange.com/a/100426/31716) I wrote about. [Answer] # JavaScript (ES6) ~~229~~ ~~219~~ 162 bytes *Thanks to @Neil for saving a lot of bytes* ## Note Quite a few people think accessing the source code of a function the way I do it is cheating, but according to @Dennis, it's fine. As such, I'll leave my answer here. ## Code ``` f=_=>([...c=`f=`+f].map(d=>d.charCodeAt()[t=`toString`](16)).join‌​` `+` `.repeat(46)).match(/.{48}/g).map((s,i)=>`00${i[t](16)}0: `+s+c.substr(i*16,16)).join`\n` ``` ## Usage ``` f() ``` Simply call the function with no arguments. ## Output ``` 0000: 66 3d 5f 3d 3e 28 5b 2e 2e 2e 63 3d 60 66 3d 60 f=_=>([...c=`f=` 0010: 2b 66 5d 2e 6d 61 70 28 63 3d 3e 63 2e 63 68 61 +f].map(c=>c.cha 0020: 72 43 6f 64 65 41 74 28 29 5b 74 3d 60 74 6f 53 rCodeAt()[t=`toS 0030: 74 72 69 6e 67 60 5d 28 31 36 29 29 2e 6a 6f 69 tring`](16)).joi 0040: 6e 60 20 60 2b 60 20 60 2e 72 65 70 65 61 74 28 n` `+` `.repeat( 0050: 34 36 29 29 2e 6d 61 74 63 68 28 2f 2e 7b 34 38 46)).match(/.{48 0060: 7d 2f 67 29 2e 6d 61 70 28 28 73 2c 69 29 3d 3e }/g).map((s,i)=> 0070: 60 30 30 24 7b 69 5b 74 5d 28 31 36 29 7d 30 3a `00${i[t](16)}0: 0080: 20 60 2b 73 2b 63 2e 73 75 62 73 74 72 28 69 2a `+s+c.substr(i* 0090: 31 36 2c 31 36 29 29 2e 6a 6f 69 6e 60 5c 6e 60 16,16)).join`\n` ``` [Answer] ## Ruby, ~~128~~ 112 bytes ``` eval b='7.times{|y|$><<"%04x:"%y*=16;c=("eval b="+(a=39.chr)+b+a)[y,16];c.chars{|x|$><<" %x"%x.ord};puts" "+c}' ``` Without trailing newline. Thanks primo for the idea of aligning to 16-byte boundary. ## Output ``` 0000: 65 76 61 6c 20 62 3d 27 37 2e 74 69 6d 65 73 7b eval b='7.times{ 0010: 7c 79 7c 24 3e 3c 3c 22 25 30 34 78 3a 22 25 79 |y|$><<"%04x:"%y 0020: 2a 3d 31 36 3b 63 3d 28 22 65 76 61 6c 20 62 3d *=16;c=("eval b= 0030: 22 2b 28 61 3d 33 39 2e 63 68 72 29 2b 62 2b 61 "+(a=39.chr)+b+a 0040: 29 5b 79 2c 31 36 5d 3b 63 2e 63 68 61 72 73 7b )[y,16];c.chars{ 0050: 7c 78 7c 24 3e 3c 3c 22 20 25 78 22 25 78 2e 6f |x|$><<" %x"%x.o 0060: 72 64 7d 3b 70 75 74 73 22 20 20 22 2b 63 7d 27 rd};puts" "+c}' ``` ]
[Question] [ *~~Inspired by~~ Copied from [this question](https://stackoverflow.com/q/35516378/2586922) at Stack Overflow.* Given a matrix `A`, create a matrix `B` such that the columns of `A` are arranged in a block-diagonal fashion. For example, given ``` 1 2 3 4 5 6 ``` the output would be ``` 1 0 0 4 0 0 0 2 0 0 5 0 0 0 3 0 0 6 ``` ### Rules Input and output may be in the form of 2D arrays, nested arrays, or strings with different separators for rows and columns. Numbers in the input (matrix `A`) will be positive integers. Unary format is allowed, as long as zeros in the output are displayed in some reasonable way. For example, the above result could be displayed using quotation marks to enclose each number: ``` '1' '' '' '1111' '' '' '' '11' '' '' '11111' '' '' '' '111' '' '' '111111' ``` ### Test cases Input, output: ``` 1 2 3 4 5 6 1 0 0 4 0 0 0 2 0 0 5 0 0 0 3 0 0 6 10 20 10 0 0 20 10 20 10 20 1 2 3 10 20 30 100 200 300 1 0 0 10 0 0 100 0 0 0 2 0 0 20 0 0 200 0 0 0 3 0 0 30 0 0 300 2 4 6 8 10 12 2 0 6 0 10 0 0 4 0 8 0 12 ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 6 bytes ``` "@N$Yd ``` Works in [current version (13.0.0)](https://github.com/lmendo/MATL/releases) of the language/compiler. Input has the following form, with semicolon as row separator, and commas or spaces as column separators within each row: ``` [1, 2, 3; 4, 5, 6] ``` [**Try it online!**](http://matl.tryitonline.net/#code=IkBOJFlk&input=WzEgMiAzOyAxMCAyMCAzMDsgMTAwIDIwMCAzMDBd) ### Explanation ``` " % implicitly input 2D array and loop over its columns @ % push column N$Yd % build block-diagonal matrix from all stack contents. Stack contents are % a single column in the first iteration, or a partially built 2D array % and a new column in all other iterations % end loop % implicit display ``` ### Worked example Consider the input `[1 2 3; 4 5 6]`. The for loop beginning with `"` takes each column of the input. Within each iteration, `@` pushes the current column onto the stack. So in the first iteration it pushes `[1; 4]`. `N$` specifies that all the stack contents will be used as inputs of the following function, `Yd`. This function (corresponding to MATLAB's `blkdiag`) "diagonally concatenates" its inputs to produce a block diagonal matrix (2D array). So in the first iteration `Yd` it takes one input and produces an output equal to that input, `[1; 4]`, which is left on the stack. In the second iteration the second column of the input, `[2; 5]`, is pushed. Now `Yd` takes two 2×1 inputs, namely `[1; 4]` and `[2; 5]`, and produces the 4×2 array `[1 0; 4 0; 0 2; 0 5]`. In the third iteration `Yd` takes the latter 4×2 array and the third column of the input, `[3; 6]`, and produces the final result `[1 0 0; 4 0 0; 0 2 0; 0 5 0; 0 0 3; 0 0 6]`. [Answer] ## ES6, 65 bytes ``` a=>[].concat(...a[0].map((_,i)=>a.map(b=>b.map((c,j)=>i-j?0:c)))) ``` Takes as input and returns as output an array of arrays. [Answer] # Mathematica, ~~40~~ 39 Bytes Credit to @Seeq for `Infix`ing `Flatten`. ``` Transpose[DiagonalMatrix/@#]~Flatten~1& ``` Input is a list of row vectors delimited by `{}` brackets. So the initial example is represented by ``` {{1,2,3},{4,5,6}} ``` Generate an array of `DiagonalMatrix` where each one has diagonal elements from the rows of the input (3-D array). `Transpose` so the `Flatten` operation removes the correct bracket pairs to give the desired matrix (now 2-D array). [Answer] # Pyth, 17 ``` s.em.>+dm0thQkbCQ ``` [Try it online](http://pyth.herokuapp.com/?code=s.em.%3E%2Bdm0thQkbCQ&input=%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%5D&debug=0) or run the [Test Suite](http://pyth.herokuapp.com/?code=s.em.%3E%2Bdm0thQkbCQ&input=%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%5D&test_suite=1&test_suite_input=%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%5D%0A%5B%5B10%2C20%5D%5D%0A%5B%5B10%5D%2C%5B20%5D%5D%0A%5B%5B1%2C2%2C3%5D%2C%5B10%2C20%2C30%5D%2C%5B100%2C200%2C300%5D%5D%0A%5B%5B2%2C4%5D%2C%5B6%2C8%5D%2C%5B10%2C12%5D%5D&debug=0). You can add a leading `j` to help visualize the 2D array. [Answer] # Jelly, 13 bytes ``` ZLR’×L0ẋ;"Zz0 ``` [Try it online!](http://jelly.tryitonline.net/#code=WkxS4oCZw5dMMOG6izsiWnow&input=&args=WyBbMSwgMiwgM10sIFsxMCwgMjAsIDMwXSwgWzEwMCwgMjAwLCAzMDBdIF0) ### How it works ``` ZLR’×L0ẋ;"Zz0 Main link. Input: M (matrix) Z Transpose M. L Get the length of the result. This yields the number of M's columns. R Range; for m columns, yield [1, ..., m]. ’ Decrement to yield [0, ..., m-1]. ×L Multiply each by the length (number of rows) of M. This yields [0, n, ..., n(m-1)], where n is the number of rows. 0ẋ Push a list of lists of zeroes. First element is [], last is n(m-1) zeroes. ;"Z Prepend the kth vector of zeroes to the kth column of M. z0 Zip, filling the non-rectangular 2D array with zeroes. ``` [Answer] # Mathematica, 111 bytes ``` Join@@@ReplacePart[Table[0,#2/#3]~Table~#3~Table~#3,Table[{n,n}->#[[n]],{n,#3}]]&[Length@#,Length@Flatten@#,#]& ``` [Answer] ## Ruby, ~~81~~ ~~78~~ ~~76~~ 62 bytes ``` ->a{i=-1;a[0].flat_map{i+=1;a.map{|b|x=b.map{0};x[i]=b[i];x}}} ``` *sigh* Manually keeping track of the index is shorter than `with_index`. ``` ->a{ i=-1; # index of the flat_map a[0] # duplicate all rows as many times as necessary .flat_map{ # we're wrapping each "group" of original rows with yet another # array, so we need to flat_map to get rid of those i+=1; # increment the index of the current subarray a.map{|b| # for each sub-subarray (these are the rows)... x=b.map{0}; # zero everything out x[i]=b[i]; # replace the desired elements x}}} # finally, return the modified array ``` [Answer] # R, 41 bytes ``` pryr::f(Matrix::.bdiag(plyr::alply(a,2))) ``` Assumes `pryr`, `Matrix` and `plyr` packages are installed. This creates a function that takes a 2D array (a) and returns a "sparseMatrix" where (where 0's are represented as `.`) ``` (a=matrix(1:6,ncol=3)) # [,1] [,2] [,3] # [1,] 1 3 5 # [2,] 2 4 6 pryr::f(Matrix::.bdiag(plyr::alply(a,2)))(a) # 6 x 3 sparse Matrix of class "dgTMatrix" # # [1,] 1 . . # [2,] 2 . . # [3,] . 3 . # [4,] . 4 . # [5,] . . 5 # [6,] . . 6 ``` Explanation: `plyr::alply(a,2)` each column of `a` and returns combines these results in a list `Matrix::.bdiag(lst)` creates a block diagonal matrix from a list of matrices `pryr::f` is a shorthand way to create a function. A fully base `R` solution in 59 bytes (using the logic of @PieCot's Matlab answer): ``` function(a){l=dim(a);diag(l[2])%x%matrix(1,nrow=l[1])*c(a)} ``` [Answer] ## MATLAB, ~~69~~ 68 bytes ``` function h=d(a) [r,c]=size(a);h=repmat(a,c,1).*kron(eye(c),~~(1:r)') ``` One byte was shaved off: thanks to Luis Mendo :) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 11 bytes ``` ⍉⍪⍉↑(0,⊢)\⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/4/6u181LsKRLZN1DDQedS1SDMGqOQ/UPJ/GhdI0FDBSMFYU8NEwVTBTJNLlyuNCyjyqHeLoYGCkQGYDzQAiYPQAhZUMDYAsUBMENtAE67KSMFEU8NMwQKs0NBIEwA "APL (Dyalog Classic) – Try It Online") ]
[Question] [ # The Challenge Create a function that, when given an input of ASCII art (directing a path that may eventually loop), outputs the length of the loop (if there is one) and the length of the "tail" leading into the loop in one of the forms below. --- # Input Your input must be passed to a function. Below is an example of a simple input. ``` # --> # --> # ^ | | | | v # <-- # ``` You could visualize the above blocks like this ![](https://i.stack.imgur.com/wNlPQ.png) The "tail" is one item, while the loop is four long. A more difficult one: ``` # --> # --> # ^ | | | | v # --> # <-- # # --> # ^ ^ | | | | | | v # --> # # <-- # <-- # ``` --- # Output You must output through STDOUT or your language's closest alternative. Your two output integers should be the length of the tail and the length of the loop. This output can be in two forms. 1. a space-delimited string: `"2 10"` 2. an array of integers: `[2, 10]` --- # Rules * Every block, or `#`, will only have a *single path away* from itself. * Every arrow is two line segments and one head. * The starting block will always be in the leftmost column. * The input will never be just a loop. --- # Example ``` # --> # --> # --> # ^ ^ | | | | | | v # # <-- # <-- # ``` This one has a tail length of 2 and a loop length of 6. Below, the tail and loop are separated. ### Tail ``` # --> ^ | | # ``` ### Loop ``` # --> # --> # ^ | | | | v # <-- # <-- # ``` The correct outputs are `[2, 6]` and `"2 6"`. If the input is *only a tail*, the loop length is zero. ``` # --> # --> # --> # | | v <-- # <-- # ``` The correct outputs for the above input are `[6, 0]` and `"6 0"` [Answer] # JavaScript (ES6), 221 ~~229~~ A function with the input as a parameter, output as a string via popup window (alert). Scan repeatedly the input: at each step * remove the end of the tail * count the remaining '#' When there is not more tail to remove, the number of the steps so far is the size of the tail and the number of remaining '# is the size of the loop. All the newlines inside backticks are significant and counted Test running the snippet below with Firefox (not Chrome, as it does not support `...`) ``` F=s=>{s=` ${s} `.split` `.map(r=>[...r]);for(t=0,f=1;f;)s.map((r,y)=>r.map((c,x)=>c=='#'&&((r[x+2]+r[x-2]+s[y-1][x]+s[y+1][x]).match`[v<>^]`?++l:t+=(f=r[x-4]=r[x+4]=s[y-3][x]=s[y+3][x]=r[x]=1))),f=l=0);alert(t+' '+l)} // Less golfed U=s=>{ s=`\n\n\n${s}\n\n\n`.split`\n`.map(r=>[...r]) t=0 do { f=l=0 s.forEach((r,y) => { r.forEach((c,x) => { if (c == '#') { if (!(r[x+2] == '<' || r[x-2] == '>' || s[y-1][x] == 'v' || s[y+1][x] == '^')) t+=(f=r[x-4]=r[x+4]=s[y-3][x]=s[y+3][x]=r[x]=1) else ++l } }) }) } while(f) alert(t+' '+l) } //Test // Redefine console.log alert=(...x)=>O.innerHTML+=x+'\n' test=[` # --> # --> # ^ | | | | v # <-- #` ,` # --> # --> # ^ | | | | v # --> # <-- # # --> # ^ ^ | | | | | | v # --> # # <-- # <-- #` ,` # --> # --> # --> # ^ ^ | | | | | | v # # <-- # <-- #` ] test.forEach(t=>(alert(t),F(t))) ``` ``` <pre id=O></pre> ``` [Answer] # Ruby, ~~287~~ 278 bytes ``` ->i{n={} g=->x{n[x]||=[0,p]} t=y=0 i.lines{|l|x=0 l.chars{|c|x+=1 '><'[c]&&(r=c.ord-61;s,d=[y,x-4*r],[y,x+2*r]) '^v'[c]&&(r=c<?_?1:-1;s,d=[y+r*3,x],[y-r,x]) s&&(g[s][1]=g[d])[0]+=1} y+=1} c,*_,s=n.values.sort_by{|v|v[0]} l=n.size s[0]>1?((t+=1;c=c[1])while c!=s):t=l-=1 [t,l-t]} ``` Try it [here](http://ideone.com/Iegydd). This builds a hash (dictionary) of nodes. For each node, the number of incoming connections and the (possibly null) next node are stored. Finally: * If there is no node with 2 incoming connections (meaning no loop), return 0 for the tail and the number of existing nodes for the loop. * Otherwise, start iterating from the node with 0 incoming connections (start) via next->...->next until the node with 2 incoming connections (loop start) is reached. Return the appropriate counts. The readable version of the code is available [here](http://ideone.com/xCvRd0). [Answer] # Ruby, 276 ``` ->s{a=k=w=s.index(r=' ')*2+2 s=r*w+s+r*w (s.size).times{|i|s[i,2]==' #'&&(s[3+j=i+1]+s[j+w]+s[j-w]).strip.size<2&&(a=[j] d=0 loop{("|-|-"[d])+?#=~/#{s[k=j+[-w,3,w,-3][d]]}/?(a.include?(k)&&break;a<<(j=k);d-=1):d=(d+1)%4} )} u=a.size v=a.index(k) t=(u-v)/4*2 print u/2-t," ",t} ``` ]
[Question] [ You are given a string and two characters. You have to print the string between these characters from the string. # Input Input will first contain a string (not empty or `null`). In the next line, there will be two characters separated by a space. # Challenge Return the string between the two characters # Example ``` Hello! What's your name? ! ? ``` should result in the output: ``` " What's your name" ``` # Rules * The string will not be longer than 100 characters and will only contain ASCII characters in range (space) to `~`(tilde) (character codes 0x20 to 0x7E, inclusive). See [ASCII table](http://c10.ilbe.com/files/attach/new/20150514/377678/1372975772/5819899987/f146bf39e73cde248d508e5e1b534865.gif) for reference. * You must take input from the `stdin`( or closest alternative ). * The output should be surrounded with quotes(`"`). * You can write a full program, or a function which takes input, and outputs the final string * The two characters will only contain ASCII characters in range (space) to `~`(tilde) (character codes 0x20 to 0x7E, inclusive). See [ASCII table](http://c10.ilbe.com/files/attach/new/20150514/377678/1372975772/5819899987/f146bf39e73cde248d508e5e1b534865.gif) for reference. * There is no guarantee that both the characters will be in the string. * If any of the characters is not found in the string, print `"null"`. * If any of the characters is found more than one times (unless both the characters are same) in a string, print `"null"`. * If both the characters are the same character, print the string `"null"`. # Test Cases 1) ``` <HTML>code</HTML> > < --> "null" ``` 2) ``` What's what? ' ' --> "null" ``` 3) ``` abcdefghijklmnopqrstuvwxyz n k --> "lm" ``` 4) ``` Testing... e T --> "" ``` 5) ``` Last test-case - --> "test" ``` # Scoring This is code golf, so the shortest submission (in bytes) wins. [Answer] # CJam, ~~34~~ ~~33~~ 32 bytes ``` '"l_l2%&2*2>NerN/0"null"t_,3=='" ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code='%22l_l2%25%262*2%3ENerN%2F0%22null%22t_%2C3%3D%3D'%22&input=abcdefghijklmnopqrstuvwxyz%0An%20k). ### Idea 1. Remove the second character from line 2. 2. Form a string consisting of a single copy of all characters that both lines have in common. 3. Repeat the resulting string twice and discard its first two characters. This results in a two-character string (if the characters from line 2 are different and both occur in line 1) or an empty string. 4. Replace the characters of the resulting string in line 1 by linefeeds. 5. Split line 1 at linefeeds. The resulting array's second element will be the desired string if the array contains exactly three chunks. 6. Replace the first element of the array with the string **null**. 7. Retrieve the second element of the array if its length is 3 and the first otherwise. 8. Prepend and append a double quote. ### Code ``` '" e# Push a double quote. l_ e# Read one line from STDIN. Push a copy. l2% e# Read one line from STDIN. Only keep characters at odd indexes. & e# Intersect both strings. 2*2> e# Repeat the intersection twice and discard the first two characters. Ner e# Replace the characters of the resulting string with linefeeds. N/ e# Split the result at linefeeds. 0"null"t e# Replace the first element of the resulting array with "null". _,3= e# Push 1 if the length of the array is 3 and 0 otherwise. = e# Retrieve the corresponding element from the array. '" e# Push a double quote. ``` [Answer] # CJam, 38 bytes ``` l:Tl2%f#_W-$2,=2,@f#$~T<>1>"null"?'"_o ``` Too long... ### Explanation ``` l:T e# Read a line and store in T. l2% e# Read the two characters into a list. f# e# Find each character in the list of two characters. _W- e# Copy and remove not found results. $2,= e# Sort and check if the result is exactly [0 1]. e# If true: 2,@f# e# Find 0 and 1 in the original results. $ e# Sort. ~T<> e# Get a slice of T between the two positions (left-closed). 1> e# Remove the first character. e# If false: "null" e# The string "null". ? e# End if. '"_o e# Append a quote and output another quote at the beginning. ``` [Answer] # Pyth, ~~37~~ ~~36~~ 34 bytes ``` p?"null"njT9m/zd{J%2wt:z.uSmxzdJNN ``` Thanks to @isaacg for the two bytes save. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=p%3F%22null%22njT9m%2Fzd%7BJ%252wt%3Az.uSmxzdJNN&input=Last+test-case%0A++-&debug=0) ### Explanation: ``` implicit: z = first input line w second input line %2 only use every 2nd char J and store in J {J set(J), gets rid of duplicates m/zd count the number of appearances of each char njT1 != [1, 1] ([1,1] is 10 in base 9) ? njT1m/zd{J%2w ... if [1,1] != number of appearances else ... "null" string "null" mxzdJ find the index for each char S sort the indices :z.u take the substring of z using these indices t remove the first char p NN print '"' + ... + '"' ``` [Answer] # Python 3, 149 bytes ``` s,i=input(),input();a,b=s.find(i[0]),s.find(i[2]);print('"'+('null',[s[a+1:b],s[b+1:a]][b<a])[(s.count(i[0])==s.count(i[2])==1)*(a!=b)*(a*b>-1)]+'"') ``` Ungolfed Version: ``` string, chars = input(), input() a, b = string.find(chars[0]), string.find(chars[2]) if string.count(chars[0]) == string.count(chars[2]) == 1 and a!=b and a*b>-1: if b<a: print('"' + string[b+1:a] + '"') else: print('"' + string[a+1:b] + '"') else: print('"null"') ``` This is my first answer here, so tips and criticism are much appreciated. [Answer] # Ruby, ~~108~~ ~~95~~ 94 ``` ->s,f,l{a,b=[f,l].map{|u|(f==l||s.count(u)>1)&&abort('"null"');s.index u}.minmax;p s[a+1...b]} ``` And for the ungolfed version ``` def between(string, first, last) left, right = [first, last].map do |substring| abort('"null"') if first == last || string.count(substring) != 1 string.index(substring) end.minmax p string[left + 1 ... right] end ``` [Answer] # [TypeScript](https://www.typescriptlang.org/)'s Type System, 160 bytes ``` //@ts-ignore type F<S,U,Y=any,O={[K in U]:S extends`${Y}${K}${infer X}${Exclude<U,K>}${Y}`?S extends`${Y}${K}${Y}${K}${Y}`?0&1:X:0&1}[U]>=O extends 0&1?"null":O ``` [Try it at the TypeScript playground!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAMQB4BlAGgFVKBNAXgENEdKB5BgbwG0BpQrESFqAXQBc5QugAe4dIgAmkAAYASLnQC+Gvjq5CAZulSEAGvoCiMgMYAbAK6L0pWnwB8+7SoD8U2fJKqhraul76eiFavgAMAGQAjOJm4vEJWjxi7gzs0nIKyoRpPgBEiA52diXi7JjY+EQAKuiQ4AmEDCSkJQAS6JXIAISEAOoAFkzgAOSQhDjIDqaITAC26KWUhCWDJYQAPlul7pgghGcAej51uASEza0ATB1dJaQ9jQCyADLuNsjOpGA72+7hKm1euwOJVBx1OFyu9Vu93AAGZnmQSuNJjNCAB3CbgDZbKaQ4nQk7AM6ES7XBp3FrgAAs6O6TAARjZnIZ4GNYAArADWdhWKDwAEdUK0HAA3XEyHAALzBWwFpLK5Lh1IRNyaDIArCySsihPAAHTm5VGtXoDWU+G0pEMgBshq+TFahHkrWgNndNvBW32W2gtqpNKAA) This is a generic type `F` taking the string as the first type parameter `S` and the characters as a union type `U`. If the input was two distinct characters that were guaranteed only to each appear once in the string, this would be 59 bytes: ``` type F<S,A,B>=S extends`${any}${A}${infer X}${B}${any}`?X:0 ``` My original solution was around 150 bytes before I realized that the program had to check for the characters in either order, adding many bytes. I came up with the following solution at 161 bytes: ``` //@ts-ignore type F<S,A,B,Y=any,Z="null">=S extends`${Y}${`${A}${infer X}${B}`|`${B}${infer X}${A}`}${Y}`?S extends{[K in A|B]:`${Y}${K}${Y}${K}${Y}`}[A|B]?Z:X:Z ``` ...but then I thought of the current solution and it ended up exactly 1 byte shorter. Explanation coming soon. [Answer] # C, 192 bytes ``` f(){char b[101],c,d,*p,*t;scanf("%[^\n]%*c%c%*c%c",b,&c,&d);p=strchr(b,c);t=strchr(b,d);c==d||!p||!t||strchr(p+1,c)||strchr(t+1,d)?puts("\"null\""):printf("\"%s\"",p<t?(*t=0,p+1):(*p=0,t+1));} ``` Ungolfed code: ``` f() { char b[101],c,d,*p,*t; //Variables scanf("%[^\n]%*c%c%*c%c",b,&c,&d); //Scan input p=strchr(b,c); t=strchr(b,d); //Find occurrence of characters c==d || //If both characters are the same !p || //If no occurrence of first character found !t || //If no occurrence of second character found strchr(p+1,c)|| //If two occurrence of first character found strchr(t+1,d) ? //If two occurrence of second character found puts("\"null\"") //Print "null" : //else printf("\"%s\"",p<t?(*t=0,p+1):(*p=0,t+1)); //print the string } ``` # Test it [here](http://rextester.com/VDJG42865) [Answer] # Python 3, 172 bytes ``` x=input() a=input() a,b=a[0],a[2] if(a!=b)&(x.count(b)==x.count(a)==1): if x.index(a)>x.index(b):q=a;a=b;b=q print('"'+x.split(a)[1].split(b)[0]+'"') else:print('"null"') ``` [Answer] # Javascript (*ES6*), 125 123 bytes Idea stolen heavily from @edc65's solution. ``` [a,,b]=(p=prompt)(s=p()),[,c,d,e,,f]=s.split(RegExp('(['+(a+b).replace(/\W/g,'\\$&')+'])')) p('"'+(!e||f||c==e?null:d)+'"') ``` [Answer] ## Python, 161 bytes ``` import re,sys s,p=sys.stdin m=re.match('[^%s]*([%s])([^%s]*)([%s])[^%s]*$'%((p[0]+p[2],)*5),s) if m:g=m.group print'"null"'if not m or g(1)==g(3)else'"'+g(2)+'"' ``` The solution mostly just uses a regular expression to extract the string. To accommodate that the letters could match in either direction, the start and end of the matched part allows either letter. Checking that the letters that actually matched to be different excludes the same letter being matched twice, as well as the two letters in the input being the same. This is my first attempt at using Python for an answer here. So feedback on possible improvements is very welcome. I particularly have a feeling that there must be a way to make the condition in the print statement shorter. [Answer] # Python 3, 155 bytes ``` s,n,a,b=[input(),'null']+list(input())[::2];q,w=[s.find(a),s.find(b)];print('"'+{0>1:n,0<1:s[min(q,w)+1:max(q,w)],a==b:n}[s.count(a)==s.count(b)==1]+'"') ``` [Try it online](http://repl.it/obM) [Answer] # golflua, 132 bytes ``` L=I.r()I,J=I.r():m("(.) (.)")i=L:f(I)j=L:f(J)K,c=L:g(I,'')_,b=K:g(J,'')?i>j i,j=j,i$w((i==j|c+b!=2)&'"null"'|'"'..L:s(i+1,j-1)..'"') ``` Pretty ugly answer. The input bit is a bit rough (and requires two lines, first with the string & second with the slice characters ). Finding the locations of the flags is straight-forward, but just too long to compete with other answers. Output is pretty easy. An equivalent Lua program would be ``` Line1 = io.read() Line2 = io.read() I,J = Line2:match("(.) (.)") -- boobs return the char flags i = Line1:find(I) -- find location of flags j = Line1:find(J) K,c = Line1:gsub(I,'') -- replace flag w/ empty & store in K _,b = K:gsub(J,'') -- taking K ensures single flags fail if i > j then i,j=j,i end -- ensure we start low to high if i==j or not (c+b == 2) then -- if i & j are the same or not 2 counts, fail print('"null"') else -- print the string otherwise print('"'..Line1:sub(i+1,j-1)..'"') end ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 164 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 20.5 bytes ``` "`(.*)`wYḂ"ṠẎf:₃[h|`¨β ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiXCJgKC4qKWB3WeG4glwi4bmg4bqOZjrigoNbaHxgwqjOsiIsIiIsIi1cbiBcbkxhc3QgdGVzdC1jYXNlIl0=) Bitstring: ``` 00110000111000011110010000000100111011101000001101101000101001101101100110001100010100001110111101111111011010011000110000000101010010101011001110001001000110010001 ``` Hello to all the people answering this as a result of me bumping it to the front page :p ## Explained ``` "`(.*)`wYḂ"ṠẎf:₃[h|`¨β­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁤‏⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌­ " # ‎⁡Pair the two characters into a list `(.*)` # ‎⁢Push the string "(.*)", representing a capturing group of any number of characters. The `()` is so that only the .* is returned in a regex match wY # ‎⁣Create a list of [first char, ^, second char] Ḃ" # ‎⁤And wrap it in a list with its reverse Ṡ # ‎⁢⁡Summate each list, giving two regexes: "<first char>(.*)<second char>", "<second char>(.*)<first char>" Ẏf # ‎⁢⁢Get all regex matches of both regexes and flatten into a single list :₃[ # ‎⁢⁣If the length is 1 (i.e. there was only one match, meaning the characters aren't the same and there's a unique span): h # ‎⁢⁤ Print the span |`¨β # ‎⁣⁡ Otherwise, print "null" 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] **APL(NARS), 50 chars** ``` {1 1≢↑+/⍵=⊂a←∪1↓1⌽⍺:'"null"'⋄1⌽'""',⍵[↑../⍸⍵∊a]∼a} ``` the use. For result not sure 100% ``` '4 5' {1 1≢↑+/⍵=⊂a←∪1↓1⌽⍺:'"null"'⋄1⌽'""',⍵[↑../⍸⍵∊a]∼a} 'aifdji5ijj4' "ijj" ``` [Answer] # Perl, 65 ``` #!perl -p0 $.*=s/\Q$1/ /g while s/ ?(.)\z//;/ (.*) /;$_=$.-1?null:"\"$1\"" ``` This requires there is no newline character at in the second line of the input. [Answer] # [Kotlin](https://kotlinlang.org/), 238 bytes ``` "\""+v[0].let{s->v[1].let{val(a,b)=it.split("").drop(1).let{c->c[0] to c[2]};if(s.count{""+it==a}!=1||s.count{""+it==b}!=1||a==b)"null" else{val(c,d)= s.indexOf(a) to s.indexOf(b);s.substring((if(c<=d)c else d)+1,if(c<=d)d else c)}}}+"\"" ``` Formatted version: ``` "\"" + v[0].let { s -> v[1].let { val (a, b) = it.split("") .drop(1) .let { c -> c[0] to c[2] } // get first and third char that we are looking fir if (s.count { "" + it == a } != 1 || s.count { "" + it == b } != 1 || a == b) { // check if there 0 or more times the character of the first or second char. also check if both are equal "null" } else { val (c, d) = s.indexOf(a) to s.indexOf(b) // fetch indices of thise two chars s.substring((if (c <= d) c else d) + 1, if (c <= d) d else c) // build a substring considering the reverse looking } } } + "\"" ``` [Try it online!](https://tio.run/##XZDBitswEIZfZSIKlUisNnvc2F72UNhCSg8N9LDNQZbkRGtFcq1xuqnjZ9fKDkuht38@vvkHqfFojYt17@AkjKOiO4R7eOw6ccl/YGfcoWQwTJSj35qAlHF57F2jFb1jvPbdFyGPMJyzEtqko3WUfHVtj/fwYTg/f96PcIWt902qgqTf8Ho/ErZ5X4jkFyHLSeZW4xCycjLmfBaWilXFCoM8tNYgJYRx1fmWrtlsyKyUaRPQg3y@248bU9PApe8dDqnVYFGIcVGsr9f/aHWjIiVGXG8tAW2Dnk/KlWIFBG6c0q/fayrY1P9vrtgm8NBXYf4iStNNmReKybkCFFuuV@9M3Zhk4zgup5fGlGLcioCAOmAmRdARIIu7NKU6znnUsIuikkrXh6N5aezJ@fZ3F7A//3m9/I0Ompg/7b5tS@mVzj/NMZaQxydtrV/Az6PAjwEuvu/AiZN@iAt4eAM "Kotlin – Try It Online") [Answer] # [Scala 3](https://www.scala-lang.org/), ~~192~~ 187 bytes Saved 5 bytes thanks to @ceilingcat --- Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=hVDBTgIxEL3zFcMesCPLRuRi0EK8aYLxYIwHJGZ2t4Wa0jVtVyGEL_FiTPTiJ-iP8DeWXWK4eZqZ995M5r3XT5eRpt7XOOqY4oWsiSabXpE-iszDFSkDq0YD4Jk0yD6wG2-VmcZQV-SDugHgH6WXnZPNN3NxFvBV2GAUp8iZS5TJxeJasowdIcb78zEinirJRsr5io4rLJGFJa3Zgg9ckhWl8eyB8wVy3sUWNXnaosN0AJ0uRvdR1GZKAkvPCF3iytRVL7G03Y0JhXYC9mEKcIrY3i5uyVBNqXWY1jsL7wC5kDAP5hnZqevDubW0HNdWJ9iHW6M88JAMQB1NfTtAVZiJKpIbn1-axArKR8oIhn_SbEbW_at8Cve8Nkwyt0u82sMtu27sPn37uRBaF024m5E_cLAsSguG5mLYaMKw1vwC) ``` (s,c)=>{val(a,b)=(s.indexOf(c(0)),s.indexOf(c(2)));if(List(c(0),c(2)).forall(x=>s.count(_==x)==1)&a!=b&a*b> -1)"\""+(if (b<a)s.substring(b+1,a)else s.substring(a+1,b))+"\""else"\"null\""} ``` Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=jZIxTsMwFIYlxpzib4fi0DaiZUGIULGBBGKoEAMg5CROa-Q6yHYQCPUkLF3gFJyE0-DYSQuoFQy237O__9ny_17fdUoF3Vss3kqT9_c_t3iR3LPU4JxyiZcAyFiOnMtsXCbaKC4nxC8HGLu1h3RKlW7SsAkQOznwSAWozbwssqXY00VOnIrshuESSjZBwxpyE89RvyBKi1Iacoc4xrJalQzQ6WATM_zGULRie62LdmxwhP4grJ_tb0pwCLraAto37Ta6TXW9_JTEbg56Fdt1TC2YgwnN_qGnXp_81gdrqthzWQrRUBVTjdqsmXWOUDWxlhwrRZ-vvR-31plLyc0PX3RjlWuDiBfR2GSnMlKMZmdcMrJyx_3en-SDrWeEJOs6pu4UZ-Y8mPuOqxtv8XHChChauJpSs63xXJQKks7YKGhh5Jkv) ``` object Main { def findSubstring(string: String, chars: String): String = { val a = string.indexOf(chars(0)) val b = string.indexOf(chars(2)) if (string.count(_ == chars(0)) == 1 && string.count(_ == chars(2)) == 1 && a != b && a * b > -1) { if (b < a) { "\"" + string.substring(b + 1, a) + "\"" } else { "\"" + string.substring(a + 1, b) + "\"" } } else { "\"null\"" } } def main(args: Array[String]): Unit = { val string = scala.io.StdIn.readLine() val chars = scala.io.StdIn.readLine() println(findSubstring(string, chars)) } } ``` ]
[Question] [ You should write a program or function which outputs or returns as much of [Chapter I of The Little Prince](http://pastebin.com/raw.php?i=5RBHAM08) as it can. Your program or function has to be an M-by-N block of code containing only printable ascii characters (codepoint from 32 to 126) and newlines at the end of each row. You can only **use at most 26 characters** of your choosing from the 96 printable ascii characters (and the newlines at the end of the rows). **In each row and column every character has to be distinct** similar to a sudoku puzzle i.e. there can't be a letter in a row or column twice. A correct example codeblock with `M = 4`, `N = 3` and `alphabet = {a,b,c,d,/,*}`: ``` abcd bcd* */ac ``` ## Code details * You can choose the shape of your code-block (i.e. `M` and `N`). * The block has to be filled with characters entirely i.e. every row has to have the same length. * A trailing newline at the end of the last row is optional. * As written above in each row and column every character has to be distinct. ## Output details * You should output or return a prefix of [Chapter I of The Little Prince](http://pastebin.com/raw.php?i=5RBHAM08) without any additional output. * If you reach a newline in the text you can represent it as any common variant (\r,\n,\r\n) but use only one of them and count it as 1 byte to the score. * An extra trailing newline is optional. **Your score is the length of the output text** excluding an additional newline if present. Higher score is better. ## Example answer ``` ##Python3, score = 6 alphabet = `print('O\ce w)#X` (alphabet element count = 16) print('O\ nce w')#X ``` You can check the validity of your code with [this Python 3 (ideone) program](http://ideone.com/e6LsiQ) or [this CJam program (online)](http://goo.gl/fwYbyd) provided by @MartinBüttner. [Answer] # [Pip](http://github.com/dloscutoff/pip), score = 38 ``` eyli: "Once when0 I was si01x year5 old I 0sMw1 1M 0" X1RMh Rnsxy iR:'M 'aiR :5'si ``` Alphabet: `"'015:IMORXacdehilnorswxy` (I sure would hate to try this in a *real* programming language.) Explanation: ``` eyl Statements consisting of single variables are no-ops i: Assign to i the following: "Once when0 I was si01x year5 old I 0sMw1 1M 0" ...this string X1 ...repeated once (no-op to get alignment right) RMh ...with all 1s and 0s removed (h is preinitialized to 100) Rns ...and all newlines replaced with spaces. xy More no-ops iR:'M'a Replace every M with a, assigning result back to i iR:5's Replace every 5 with s, assigning result back to i i Auto-print i ``` [Answer] # CJam, 47 ``` "Once wh en Imwas msix yea r2s oldm I "N-'m/ Sc*2s-O" saw"N/SO o'aS"m2 a"Oo2s-N -S/OI*so 'yI-a"nr wiNadI"c cel'iaIS /m2*Oo'x I-scel* Ooel'c 2 2/'e*ON- ``` [Try it online](http://cjam.aditsu.net/#code=%22Once%20wh%0Aen%20Imwas%0Amsix%20yea%0Ar2s%20oldm%0AI%20%22N-'m%2F%0ASc*2s-O%22%0Asaw%22N%2FSO%0Ao'aS%22m2%20%0Aa%22Oo2s-N%0A-S%2FOI*so%0A'yI-a%22nr%0AwiNadI%22c%0Acel'iaIS%0A%2Fm2*Oo'x%0A%20I-scel*%0AOoel'c%202%0A2%2F'e*ON-) Alphabet: `"'*-/2INOSacdehilmnorswxy` **Explanation:** ``` "Once wh en Imwas msix yea r2s oldm I " push this string N- remove newlines 'm/Sc* replace m's with spaces (the c is redundant) 2s- convert 2 to string and remove 2's O push an empty string " saw" push this string N/ split into lines (effectively removes the newline) S push a space Oo print empty string (no-op) 'a push 'a' S push a space "m2 a" push this string Oo print empty string (no-op) 2s- convert 2 to string and remove 2's N- remove newline S/ split by space (effectively removes the space) OI*so print an empty string repeated 18 times (no-op) 'y push 'y' I- subtract 18 -> 'g' a wrap in array (string) -> "g" "nr wiNadI" push this string c convert to (first) character -> 'n' c convert to character (no-op) el convert to lowercase (no-op) 'i push 'i' a wrap in array (string) -> "i" IS/ split " " into slices of length 18 -> [" "] m (acting as -) remove space strings from "i" (no-op) 2* repeat "i" 2 times -> "ii" Oo print empty string (no-op) 'x push 'x' I- subtract 18 -> 'f' sc convert to string and back to char (no-op) el convert to lowercase (no-op) * join "ii" with separator 'f' -> "ifi" Oo print empty string (no-op) el convert to lowercase (no-op) 'c push 'c' 2 2/ divide 2 by 2 -> 1 'e push 'e' * repeat 'e' 1 time -> "e" O push empty string N- remove newlines (no-op) ``` [Answer] # Python 3, score=11 This is a really tough problem for Python, as the restrictions on repeating characters on a line or column make it nearly impossible to make more than one string literal. The various ways of joining strings together are thus fairly useless, since you can't get the strings to start with in any useful way. Here's my best attempt: ``` x=chr print( "Once\ when" ,x(73) )#prin ``` Note that there is a space at the end of the first line. The alias `x` for `chr` is necessary to avoid the same character ending up in more than one column. The comment characters at the end could be almost anything. The alphabet is 21 printable characters, plus newline (note the space at the start): ``` "#(),37=O\cehinprtwx ``` Output is: > > Once when I > > > [Answer] # CJam, score = 21 ``` "Once wh en I"N-o N;S"was six y"N- ``` Alphabet: `-;INOSacehinoswxy` Just to get the ball rolling; this can probably be beaten easily. [Answer] # CJam, score = 15 I've had this idea for a while now but I haven't had time to sit down and shuffle things around until I get the needed column uniqueness, so here's a baby version for now: ``` 79c32"*)+#,105468:;=>Ibef ,:=>Ibcef";7 6)#*219435+80 50I=>;9)6#*127438+ ":,bcfe ),68:>=Ibcef";20 5#*17394+ 6)4*b123,97>:c"80f5=+;e# I "9>+f=e# ),*0481362bI:;5c7 ``` Alphabet (26): `" #)*+,0123456789:;=>Ibcef` [Try it online](http://cjam.aditsu.net/#code=%2079c32%22*%29%2B%23%2C105468%3A%3B%3D%3EIbef%0A%2C%3A%3D%3EIbcef%22%3B7%206%29%23*219435%2B80%0A50I%3D%3E%3B9%296%23*127438%2B%20%22%3A%2Cbcfe%0A%29%2C68%3A%3E%3DIbcef%22%3B20%205%23*17394%2B%0A6%294*b123%2C97%3E%3Ac%2280f5%3D%2B%3Be%23%20I%0A%229%3E%2Bf%3De%23%20%29%2C*0481362bI%3A%3B5c7). ## Explanation The basic idea is to make use of base encoding so we can print more than 26 types of chars. The core code is ``` 79c e# Push "O" 85032995607801617394 28b e# Push array of indices, encoding using base 28 123,97>:c" I e# Push "abcdefghijklmnopqrstuvwxyz I\n" "+ f= e# Map indices to chars ``` Note that we treat the first `"O"` for `"Once"` separately because including it in our string would take too much of our alphabet. If we wanted to we could try extended our indexing string, but since no more uppercase characters happen for a while apart from `"I"` I didn't bother too much with this. We then need to build the big number on the second line somehow. The approach I took was to repeatedly multiply by some power, then add a constant, and repeat, so in the above code `85032995607801617394` is replaced by ``` 32 7 6) # * 219435 + 9) 6 # * 127438 + 20 5 # * 17394 + ``` where `)` is increment and `#` is exponentiation in CJam. Then the rest (the most annoying part) is padding each row to fulfill the column criteria. To do this we dump chars in strings and use `;` to pop them. Unfortunately, while we would very much like to use `e#` for comments as well to make things easier, the fact that `#` is exponentiation forbids this, so this is only done on the last line. I'm fairly certain this method can be extended up until the comma in the first sentence, but unfortunately shuffling things around to meet the column criteria is proving difficult, so I might need another method of generating the base-encoded integer. [Answer] # Python 2, score = 13 (invalid) Python isn't the best language for this.... Upon further inspection, there are two `n`s in my first line. There is no worthwhile remedy, and I'm going to stop wasting my time with Python. I'm currently working on making a solution in another language, but will not share which one yet. ``` print"Once wh\ en I",#Oncehtp chr(0167)#Onwt ``` Alphabet (22): `"#(),0167IOcehinprtw` Output: `Once when I w` ]
[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 2 years ago. [Improve this question](/posts/2952/edit) Let's say we have a non-negative integer that is "hefty" (that is, "heavy") if its average digit value is greater than 7. The number 6959 is "hefty" because: (6 + 9 + 5 + 9) / 4 = 7.5 The number 1234 is not, because: (1 + 2 + 3 + 4) / 4 = 2.5 Write a function, in any language, `HeftyDecimalCount(a, b)` which, when provided two positive integers a and b returns an integer indicating how many "hefty" integers are within the interval [a..b], inclusive. For example, given a=9480 and b=9489: ``` 9480 (9+4+8+0)/4 21/4 = 5.25 9481 (9+4+8+1)/4 22/4 = 5.5 9482 (9+4+8+2)/4 23/4 = 5.75 9483 (9+4+8+3)/4 24/4 = 6 9484 (9+4+8+4)/4 25/4 = 6.25 9485 (9+4+8+5)/4 26/4 = 6.5 9486 (9+4+8+6)/4 27/4 = 6.75 9487 (9+4+8+7)/4 28/4 = 7 9488 (9+4+8+8)/4 29/4 = 7.25 hefty 9489 (9+4+8+9)/4 30/4 = 7.5 hefty ``` Two of the numbers in this range are "hefty" and so the function should return 2. Some guidelines: * assume that neither a or b exceeds 200,000,000. * an n-squared solution will work, but will be slow -- what's the fastest we can solve this? [Answer] The problem can be solved in \$O(\operatorname{polylog}(b))\$. We define \$f(d, n)\$ to be the number of integers of up to \$d\$ decimal digits with digit sum less than or equal to \$n\$. It can be seen that this function is given by the formula $$f(d, n) = \sum\_{i=0}^d (-1)^i \binom d i \binom {n+d - 10i} d$$ > > Let's derive this function, starting with something simpler. > > > $$h(n,d) = \binom{n+d-1}{d-1} = \binom{(n+1)+(d-1)-1}{d-1}$$ > > > The function \$h\$ counts the number of ways to choose \$d - 1\$ elements from a multi-set containing \$n + 1\$ different elements. It's also the number of ways to partition \$n\$ into \$d\$ bins, which can be easily seen by building \$d - 1\$ fences around \$n\$ ones and summing up each separated section . Example for \$n = 2, d = 3\$: > > > > > > | 3-choose-2 | fences | number | > | --- | --- | --- | > | `11` | `||11` | `002` | > | `12` | `|1|1` | `011` | > | `13` | `|11|` | `020` | > | `22` | `1||1` | `101` | > | `23` | `1|1|` | `110` | > | `33` | `11||` | `200` | > > > > So, \$h\$ counts all numbers having a digit-sum of \$n\$ and \$d\$ digits. Except it only works for \$n < 10\$, since digits are limited to 0 to 9. In order to fix this for values 10 to 19, we need to subtract the number of partitions having one bin with a number greater than 9, which I'll call overflown bins from now on. > > > This term can be computed by reusing \$h\$ in the following way. We count the number of ways to partition \$n - 10\$, and then choose one of the bins to put the 10 into, which results in the number of partitions having one overflown bin. The result is the following preliminary function. > > > $$g(n,d) = \binom{n+d-1}{d-1} - \binom{d}{1} \binom{n+d-1-10}{d-1}$$ > > > We continue this way for n less or equal 29, by counting all the ways of partitioning \$n - 20\$, then choosing 2 bins where we put the 10's into, thereby counting the number of partitions containing 2 overflown bins. > > > But at this point we have to be careful, because we already counted the partitions having 2 overflown bins in the previous term. Not only that, but actually we counted them twice. Let's use an example and look at the partition \$(10,0,11)\$ with sum 21. In the previous term, we subtracted 10, computed all partitions of the remaining 11 and put the 10 into one of the 3 bins. But this particular partition can be reached in one of two ways: > > > $$(10, 0, 1) \to (10, 0, 11) \\ (0, 0, 11) \to (10, 0, 11)$$ > > > Since we also counted these partitions once in the first term, the total count of partitions with 2 overflown bins amounts to 1 - 2 = -1, so we need to count them once more by adding the next term. > > > $$g(n,d) = \binom{n+d-1}{d-1} - \binom{d}{1} \binom{n+d-1-10}{d-1} + \binom{d}{2} \binom{n+d-1-20}{d-1}$$ > > > Thinking about this a bit more, we soon discover that the number of times a partition with a specific number of overflown bins is counted in a specific term can be expressed by the following table (column \$i\$ represents term \$i\$, row \$j\$ partitions with \$j\$ overflown bins). > > > > ``` > 1 0 0 0 0 0 . . > 1 1 0 0 0 0 . . > 1 2 1 0 0 0 . . > 1 4 6 4 1 0 . . > . . . . . . > . . . . . . > > ``` > > Yes, it's Pascals triangle. The only count we are interested in is the one in the first row/column, i.e. the number of partitions with zero overflown bins. And since the alternating sum of every row but the first equals 0 (e.g. \$1 - 4 + 6 - 4 + 1 = 0\$), that's how we get rid of them and arrive at the penultimate formula. > > > $$g(n,d) = \sum\_{i=0}^{d} (-1)^i \binom{d}{i} \binom{n+d-1 - 10i}{d-1}$$ > > > This function counts all numbers with \$d\$ digits having a digit-sum of \$n\$. > > > Now, what about the numbers with digit-sum less than \$n\$ ? We can use a standard recurrence for binomials plus an inductive argument, to show that > > > $$\begin{align} \bar{h}(n,d) & = \binom{n+d}{d} \\ & = \binom{n+d-1}{d-1} + \binom{n+d-1}{d} \\ & = h(n,d) + \bar{h}(n-1,d)\end{align}$$ > > > counts the number of partitions with digit-sum at most \$n\$. And from this \$f\$ can be derived using the same arguments as for \$g\$. > > > Using this formula, we can for example find the number of heavy numbers in the interval from 8000 to 8999 as \$1000 - f(3, 20)\$, because there are thousand numbers in this interval, and we have to subtract the number of numbers with digit sum less than or equal to 28 while taking in to account that the first digit already contributes 8 to the digit sum. As a more complex example let's look at the number of heavy numbers in the interval \$[1234, 5678]\$. We can first go from 1234 to 1240 in steps of 1. Then we go from 1240 to 1300 in steps of 10. The above formula gives us the number of heavy numbers in each such interval: | | | | --- | --- | | \$[1240, 1249]\$ | \$10 - f(1, 28 - (1+2+4))\$ | | \$[1250, 1259]\$ | \$10 - f(1, 28 - (1+2+5))\$ | | \$[1260, 1269]\$ | \$10 - f(1, 28 - (1+2+6))\$ | | \$[1270, 1279]\$ | \$10 - f(1, 28 - (1+2+7))\$ | | \$[1280, 1289]\$ | \$10 - f(1, 28 - (1+2+8))\$ | | \$[1290, 1299]\$ | \$10 - f(1, 28 - (1+2+9))\$ | Now we go from 1300 to 2000 in steps of 100: | | | | --- | --- | | \$[1300, 1399]\$ | \$100 - f(2, 28 - (1+3))\$ | | \$[1400, 1499]\$ | \$100 - f(2, 28 - (1+4))\$ | | \$[1500, 1599]\$ | \$100 - f(2, 28 - (1+5))\$ | | \$[1600, 1699]\$ | \$100 - f(2, 28 - (1+6))\$ | | \$[1700, 1799]\$ | \$100 - f(2, 28 - (1+7))\$ | | \$[1800, 1899]\$ | \$100 - f(2, 28 - (1+8))\$ | | \$[1900, 1999]\$ | \$100 - f(2, 28 - (1+9))\$ | From 2000 to 5000 in steps of 1000: | | | | --- | --- | | \$[2000, 2999]\$ | \$1000 - f(3, 28 - 2)\$ | | \$[3000, 3999]\$ | \$1000 - f(3, 28 - 3)\$ | | \$[4000, 4999]\$ | \$1000 - f(3, 28 - 4)\$ | Now we have to reduce the step size again, going from 5000 to 5600 in steps of 100, from 5600 to 5670 in steps of 10 and finally from 5670 to 5678 in steps of 1. An example Python implementation (which received slight optimisations and testing meanwhile): ``` def binomial(n, k): if k < 0 or k > n: return 0 result = 1 for i in range(k): result *= n - i result //= i + 1 return result binomial_lut = [ [1], [1, -1], [1, -2, 1], [1, -3, 3, -1], [1, -4, 6, -4, 1], [1, -5, 10, -10, 5, -1], [1, -6, 15, -20, 15, -6, 1], [1, -7, 21, -35, 35, -21, 7, -1], [1, -8, 28, -56, 70, -56, 28, -8, 1], [1, -9, 36, -84, 126, -126, 84, -36, 9, -1]] def f(d, n): return sum(binomial_lut[d][i] * binomial(n + d - 10*i, d) for i in range(d + 1)) def digits(i): d = map(int, str(i)) d.reverse() return d def heavy(a, b): b += 1 a_digits = digits(a) b_digits = digits(b) a_digits = a_digits + [0] * (len(b_digits) - len(a_digits)) max_digits = next(i for i in range(len(a_digits) - 1, -1, -1) if a_digits[i] != b_digits[i]) a_digits = digits(a) count = 0 digit = 0 while digit < max_digits: while a_digits[digit] == 0: digit += 1 inc = 10 ** digit for i in range(10 - a_digits[digit]): if a + inc > b: break count += inc - f(digit, 7 * len(a_digits) - sum(a_digits)) a += inc a_digits = digits(a) while a < b: while digit and a_digits[digit] == b_digits[digit]: digit -= 1 inc = 10 ** digit for i in range(b_digits[digit] - a_digits[digit]): count += inc - f(digit, 7 * len(a_digits) - sum(a_digits)) a += inc a_digits = digits(a) return count ``` **Edit**: Replaced the code by an optimised version (that looks even uglier than the original code). Also fixed a few corner cases while I was at it. `heavy(1234, 100000000)` takes about a millisecond on my machine. [Answer] Recurse, and use permutations. Suppose we define a general function that finds the values between a and b with a heaviness more than x: ``` heavy_decimal_count(a,b,x) ``` With your example of a=8675 to b=8689, the first digit is 8, so throw it away - the answer will be the same as 675 to 689, and again from 75 to 89. The average weight of the first two digits 86 is 7, so the remaining digits need an average weight of more than 7 to qualify. Thus, the call ``` heavy_decimal_count(8675,8689,7) ``` is equivalent to ``` heavy_decimal_count(75,89,7) ``` So our range for the (new) first digit is 7 to 8, with these possibilities: ``` 7: 5-9 8: 0-9 ``` For 7, we still need an average of more than 7, which can only come from a final digit of 8 or 9, giving us 2 possible values. For 8, we need an average of more than 6, which can only come from a final digit of 7-9, giving us 3 possible values. So, 2+3 yields 5 possible values. What is happening is that the algorithm is starting with the 4-digit number and dividing it into smaller problems. The function would call itself repeatedly with easier versions of the problem until it has something it can handle. [Answer] Maybe you can skip many candidates in the interval from a to b by accumulating their "heaviness". if you know the length of you number you know that every digit can change the heaviness by only 1/length. So, if you start at one number which is not heavy you should be able to calculate the next number which will be heavy, if you increase them by one. In your example above starting at 8680 avg=5.5, which is 7-5.5=1.5 point away from you heaviness border, you'd know that there are 1.5/(1/4)=6 numbers in between, which are NOT heavy. That should to the trick! [Answer] How about a simple recursive function? To keep things simple, it calculates all heavy numbers with `digits` digits, and a minimal digit sum of `min_sum`. ``` int count_heavy(int digits,int min_sum) { if (digits * 9 < min_sum)//impossible (ie, 2 digits and min_sum=19) return 0; //this pruning is what makes it fast if (min_sum <= 0) return pow(10,digits);//any digit will do, // (ie, 2 digits gives 10*10 possibilities) if (digits == 1) //recursion base return 10-min_sum;//only the highest digits //recursion step int count = 0; for (i = 0; i <= 9; i++) { //let the first digit be i, then count += count_heavy(digits - 1, min_sum - i); } return count; } count_heavy(9,7*9+1); //average of 7,thus sum is 7*9, the +1 is 'exceeds'. ``` Implemented this in python and it found all 9-digit heavy numbers in ~2 seconds. A little bit of dynamic programming could improve this. [Answer] # C, for interval [a,b] it is O(b-a) ``` c(n,s,j){return n?c(n/10,s+n%10,j+1):s>7*j;} HeftyDecimalCount(a,b){int r; for(r=0;a<=b;++a)r+=c(a,0,0); return r;} ``` //the exercise ``` main() { printf("[9480,9489]=%d\n", HeftyDecimalCount(9480,9489)); printf("[0,9489000]=%d\n", HeftyDecimalCount(9480,9489000)); return 0; } ``` //the results ``` //[9480,9489]=2 //[0,9489000]=66575 ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/464/edit). Closed 3 years ago. [Improve this question](/posts/464/edit) Create the shortest regular expression that will roughly match a URL in text when run in JavaScript Example: ``` "some text exampley.com".match(/your regular expression goes here/); ``` The regular expression needs to * **capture** all valid URLS that are for http and https. * not worry about not matching for URL looking strings that aren't actually valid URLS like `super.awesome/cool` * be valid when run as a JavaScript regex **Test criteria:** Match: * <http://example.com> * <http://example.com/> * <http://example.com/super> * <https://example.com/super> * example.com/super * example.com * example.com/su-per\_duper/?add=yes&subtract=no * example.com/archive/index.html * twitter.com/#!/reply * example.com/234ret2398oent/234nth * codegolf.stackexchange.com/questions/464 * crazy.wow.really.example.com/?cat=nth%3E * example-example.com * example1.com Not Match: * example * super/cool * Good Morning * i:can * hello. Here is a test that might help clarify a bit <http://jsfiddle.net/MikeGrace/gsJyr/> I apologize for the lack of clarity, I hadn't realized how awful matching URLs was. [Answer] This one works: ``` var re = /(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi; /* (^|\s) : ensure that we are not matching an url embeded in an other string (https?:\/\/)? : the http or https schemes (optional) [\w-]+(\.[\w-]+)+\.? : domain name with at least two components; allows a trailing dot (:\d+)? : the port (optional) (\/\S*)? : the path (optional) */ ``` Passes the tests at <http://jsfiddle.net/9BYdp/1/> Also matches: * example.com. (trailing dot) * example.com:8080 (port) [Answer] This obviously doesn't do what you intend, but it meets your criteria: ``` /.*/ ``` * **"match all valid URLS that are for http and https."** yep, definately will match. * **"not worry about not matching for URL looking strings that aren't actually valid URLS like 'super.awesome/cool'"** yeah, sure, there will be *lots* of false positives, but you said that doesn't matter. * **be valid when run as a JavaScript regex** sure as eggs works as you say it should. If this result is NOT a right answer, then you need to be more selective with your criteria. In order to be a rule that works as you intend, you actually **do** need to implement a full RFC compliant matcher, and a full RFC compliant matcher will "worry about not matching". So, in terms of "permit not matching", you need to specify **exactly** which deviations from RFC are permissible. Anything else, and this whole exercise is a sham, because people will just write whatever works for them, or how they like it, and sacrifice "making any sense" in favour of being short ( like I did ). ### On your update The most Naïve regex I can come up with that matches (and captures) all your pasted examples so far is: ``` /(\S+\.[^/\s]+(\/\S+|\/|))/g; ``` Its quite simple in nature, and assumes only 3 basic forms are possible. ``` x.y x.y/ x.y/z ``` `z` can be anthing not whitespace. `x` can be anything not whitespace. `y` can be anything that is neither whitespace or a '/' character. There are a lot of things that will be valid to this rule, lots, but they'll at least *look* like a valid URI to a human, they just won't be specifications compatible. eg: ``` hello.0/1 # valid 1.2/1 # valid muffins://¥.µ/€ # probably valid ``` I think the sane approach is to extract things that are likely to be URI's, then validate them with something stricter, I'm looking at working out how to use the browsers URI class to validate them =). But you can see the above reasoning working on this sample here: <http://jsfiddle.net/mHbXx/> [Answer] ``` /.+\.\w\w.*/ ``` doesn't match 3 strings that it shouldn't, matches almost anything else ;) **upd:** it still doesn't match all 5 [Answer] ``` /https?\:\/\/\w+((\:\d+)?\/\S*)?/ ``` Try that. I'm including the leading and trailing slashes that delimit the regular expression, so hopefully that doesn't hurt my character count! This pattern limits the protocol to either http or https, allows for an optional port number, and then allows any character except whitespace. ]
[Question] [ Given a string \$X\$ we will say two strings, \$a\$ and \$b\$, are **building blocks** of \$X\$ if \$X\$ can be made by concatenating some \$n\$ \$a\$s with \$m\$ \$b\$s in any order. For example the string `tomato` has building blocks `to` and `ma`: ``` to ++ ma ++ to ``` We will say that the **fineness** of a set of building blocks is the sum \$n+m\$. That is the number of blocks required to build \$X\$. So in the example `tomato` here are some building blocks with their fineness: ``` to, ma -> 3 tom, ato -> 2 tomato, z -> 1 ``` ## Task Given a non-empty string as input output a set of two building blocks with maximal fineness. In the case of a tie you may output any or all of the maximal building blocks. You may assume the input will contain only the alphabetic ASCII characters. If there is a correct output where \$a\$ is the empty string, you may output only the \$b\$ value. 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. *However*, I make explicit what is usually implicit: you should consider submissions of differing time complexity as belonging to different categories for scoring. I encourage people to try and golf both efficient and inefficient algorithms to this problem. ## Test cases The following examples have unambiguous (up to order) solutions: ``` tomato -> to ma F=3 tomcat -> t omca F=3 banana -> ba na F=3 axaaaaaaxa -> a x F=10 axaaaaaaja -> a xaaaaaaj F=3 aaxaaaajaaaajaaaaxaa -> a xaaaajaaaajaaaax F=5 ``` The following have ambiguous solutions. I've given a possible valid solution and its fineness to compare to your result. I've used the character `*` in the output to represent cases where that string may be empty or omitted (these two options are non-exhaustive). ``` bobcat -> bob cat F=2 axaaaajaaaaxa -> axa aaajaaa F=3 axaaaajaaaajaaaaxa -> axa aaajaaaajaaa F=3 aaaaaaaaaa -> a * F=10 x -> x * F=1 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~14~~ ~~13~~ ~~10~~ 9 bytes, \$O(2^n)\$ -1 byte thanks to [@isaacg](https://codegolf.stackexchange.com/users/20080/isaacg) ``` e<I#2{M./ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72koLIkY8Fit8DApaUlaboWK1NtPJWNqn319CH8BRBqWbSSbopS7M2kaKWS_NzEknwlHQWlpMQ8IASxEisSwaAChZcF4UG4WXACyIWIJ0IYFSACYmpuolIsxEIA) ``` e<I#2{M./Q ./Q # all partitions of input {M # remove duplicates in each partition <I#2 # filter for elements where elem[:2] == elem e # last element ``` [Answer] # JavaScript (ES11), 107 bytes, \$O(n^3)\$ \* *\* or worse, depending on the time complexity of the regular expression algorithm, which is likely to be implementation-dependent* A regex-based solution. Much more convoluted than I would like. ``` f=(s,n=(w=s.length)*w)=>n--?s.match(`^(.+)\\1{${x=n%w}}(.+)(\\1|\\2){${n/w-x|0}}$`)?.slice(1,3)||f(s,n):[s] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZJBTsMwEEXFllNYVZFsaBwKG4Tk9iAE1ElI2oZ0vLCrWGpyEjZdtIeCo7DCIW0hsctYsuT5_3k81rzvUL6m2-1-rbPg4eMtE1SNUNBSKF6kONcLdl0yMcEgmCq-Ap0s6OyF8hsWRePNcGMEXpV13SSozVRRdMdsGsMyMNVtXQ9nbMpVsUxSOh7ds6rKmvvZ45N6bkt-XnwlEpUsUl7IOc3oQEtbRg4YI90IQ6IlWcFlzx8D2uX1x0DQ8YOBnzA9xvqBmHPu3Os-aA7UUvlps8cG_4X-SE4_Mk5A-_uRMbGa_42501RTzgA5aP9QHbRL-dFTuJ_S9xq3k6PXtCNwnL5v) --- # JavaScript (ES6), 107 bytes, \$O(2^n)\$ ``` f=([c,...a],k,u=o=[],s,b=[...u,s])=>c?f(a,k,u,[s]+c)|f(a,-~k,b,c)||new Set(o):new Set(b).size>2||o[k]?0:o=b ``` [Try it online!](https://tio.run/##fZDBTgMhEIbvPgXpCVJKjccmtA/hkXAYkDXdbRkjVInZ@Oorq211F@qQbJj9vy8wtPAGwb7uX@LK45MbhkZSZbkQAjTv@EmiVJoHbqTK/048aCa3dtdQGFOugl5a1o/t6rPjhuem9@6dPLpIkW0uW8NE2H@47UPfo@r07n6D0gwWfcCDEwd8pg1dRDxCxAVjZFrrNYlIjnA34w34vKq8AeILHhJ8V5o5mQeSbtFtlT5nhfRjtddPbkf9V/oTFfOgsRDr86AhOavfsS2GGo9LQM7ZP9ZEnVp19Vrlo8zZVE5yYdPwBQ "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org), 155 bytes, \$O(n^3)\$ ``` (%)=splitAt l=length x#w=maximum$((w==[],0),x):[((a,b+1),c)|((a,b),c)<-[x#p|y<-x,(s,p)<-[l y%w],s==y]++[(s:x)#p|l x<2,(s,p)<-map(%w)[1..l w]]] f x=snd$[]#x ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZLRboIwFIazW57iBFTaWIxuWbIYerF32F3TxOrqxBUktEpJ3JN4482yZ9qeZi2oUSGh5_zfd2gTOPyshP6USh2P31uzTF5-D6iPqS5VZl5NoKiSxYdZBTaqaS5slm_zHkI1pYyTMSYWTxlCgsyHE0wWeN_WvkoTZqNy36SJJUiT0gcKmn7Niaa04cMhQ3pqsXMU2PTxLOWiRP0as8lopKDmnAdLsFQX7z3GI9sd8e_hKxdZARTKKisMsAoohbdqK2EwgF3su50vURPDTCqZz4A1BCq5k5WW0HAMe0CWgAt3GNIEjNRmIbTUBBCqXBpjR-OWMcYhAuuOElw0tzcLAFBoNrkwm5AAC9slzEXICTxhcsYLYTrsqW-v-VwU7m753C9hcYOFFe1lO6U1rBcm4ztjfW2cops3deL68nDt3cQV85PPp0nbat2u2CU86L7C-Yf5Bw) Outputs a list of two strings if the input has length \$\geq 2\$, otherwise a list of a single string. Can be reduced to [136 bytes](https://ato.pxeger.com/run?1=XZLRasIwFIbZbZ_iUKdNMBXdGAxpLvYOuwsBo2SzLqmliW3KfIC9w268GXum7WmWtCq6Fnpy_u87SaH9_F4L8yaVOhy-dvYlffz5QENMTaly-2QjRZUsXu06coOGauFyvdO3qKGUcTIlDs8ZEmQ5npEV3oeVr1nK3KDct1nqCDKkDIGCdthwYiht-XjMkJk77B0FLrs7SVqUaNhgNptMFDSc8_59fm_etcgLoFBWeWGBVUApPFc7CaMR1Eno6rBEbQILqaReAGsJVLKWlZHQcgx7QI6AD2sMWQpWGrsSRhoCqPJh4lnSEcY4DMBxHkVnyZ_MIgAU260WdhsTYHFXYi1iTuAekxNeCdvjQEN7yZei8HfHl6HExRUWTnSX65XOcEGYTf8Zm0vjGF3t1Iub88O3_yYuWJh8OE66TutPxT7hUf8NTv_GHw) if outputting more stuff is allowed. [Answer] # [Perl 5](https://www.perl.org/) `-pF`, ~~134~~ 115 bytes \$O(n2^n)\$ ``` $o=$_;map{$l.=$_;$n=$_=$o;if(/^($l)*(.*?)(\2|$l)*$/){$r=$2||0;$n+=s/^$l//+s/^$r// while$_}$;[$n]="$l,$r"}@F;$_=pop@ ``` [Try it online!](https://tio.run/##FYy9CoMwHMRfpcgNiR/5W8EphDq59QnaKg6WCjEJUeigvnpTM9zd7@A4N3pdhwCr0Mt5cBu0iAhzuoKV05tRx6B5ykR64@xZ7bGA@AavUO17eY4ztVAHTZTF9ESX72fSI/oD8gHzUgl0Dp8cTSvPX2ddE8Jq5yHqZ906WbOE4l6L8lqGwrV/ "Perl 5 – Try It Online") Complexity? It depends on the complexity of the Perl regular expression engine. I've seen some references that it's fixed based on the size of the string or pattern and others that say it's exponential in the worst case. I'm going to assume worst case here, because any parser that backtracks (which is most of the ones in use by common languages) can end up there. [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 9 bytes, \$O(2^n)\$ ``` ṗSᵛuᶻϩḢḢt ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCLhtZvOuyIsIuG5l1PhtZt14ba7z6nhuKLhuKJ0IiwifSIsIltcInRvbWF0b1wiLCBcImJhbmFuYVwiLCBcImF4YWF4YVwiLCBcImF4YWFhamFcIiwgXCJhYWFhYVwiLCBcInhcIiwgXCJ0b21hdG9tYVwiXSIsIjMuNC4xIl0=) ``` ṗSᵛuᶻϩḢḢt­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌­ ṗ # ‎⁡all partitions of input S # ‎⁢sort by length ᵛu # ‎⁣uniquify each ᶻϩḢḢ # ‎⁤keep only elements with length less than 3 t # ‎⁢⁡last element ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes, \$O(2^n)\$ ``` ŒṖLÞQ€ṫÐḟ3Ṫ ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7p/kcnhf4qGnNw52rD094uGO@8cOdq/5bP2qYo6Brp/CoYa714XZvFa6Hu7ccbgeqivz/vyQ/NzmxhAtIJZbkcyUl5gEhV2JFIhhUIJhZiVwVAA "Jelly – Try It Online") A monadic link taking a string and returning a list of two strings. ## Explanation ``` ŒṖ | Partition LÞ | Sort by length (number of pieces in the partition) Q€ | Ubiquity each ṫÐḟ3 | Filter out those length 3 or longer (technically those where taking the tail starting at position 3 is non-empty) Ṫ | Tail ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 65 bytes, \$ O(n^3) \$ ``` L$w`(.+)(?=((.+?)\3*)?$(?<=^(\1|\3)+)) $#4¶$1¶$3 N^`.+¶.+¶.* 1G`¶ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8N9HpTxBQ09bU8PeVgNI22vGGGtp2qto2NvYxmnEGNbEGGtqa2pyqSibHNqmYgjExlx@cQl62oe2gbEWl6F7wqFt/1W4gERJfm5iST4XkEpOLOFKSswDQq7EikQwqEAws4BMCDsLTgC5XEn5SSCNSFJwTVkoQnDAVQEA "Retina – Try It Online") Link includes test cases. Explanation: ``` L$w`(.+)(?=((.+?)\3*)?$(?<=^(\1|\3)+)) $#4¶$1¶$3 ``` List the fineness and pair of building blocks all substrings of the input whose suffix is a multiple of a second building block whereby the input string can be constructed using only the two building blocks, unless the suffix is empty, in which case it is not counted (this would otherwise throw off the count by `1`). ``` N^`.+¶.+¶.* ``` Sort in descending order of fineness. ``` 1G`¶ ``` Keep only the pair of building blocks with the greatest fineness. (Alternatively, the `^` can be removed to sort the building blocks in ascending order in which case a `-` must be prefixed to this line so that the greatest fineness is selected.) [Answer] # [Python](https://www.python.org), 116 bytes, between \$O(n^3)\$ and \$O(2^n)\$ Port of [Xcali's answer](https://codegolf.stackexchange.com/a/269516/91267) ``` lambda x,l="":max((subn(a:=(l:=l+i)+sub(r'^(%s)*(.+?)(\2|\1)*$'%l,"|\\2",x),i,x)[1],a)for i in x)[1] from re import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZHNTtwwEMfFEb9Bb0PEau1ds-puW7WKFLhx5AUIpc6X1ktiR45XCmJ5Ei5c4J3K03T8wSqXJpE98_uPZ8aTl_f-0W61en1rIIP8bW-bi19_bSu6ohIw8jZLkrQTI6XDvlBUpBlt06xdSrZEQM38N50NbEFXyytG880hX7PF-XzW8uSQ55uEj4xLXG7Xd1ywRhuQIBV4QBqjOzA1yK7Xxi5C7Y-TL1XdQLmtywdaCSs4FK0uHwYOiqXk1NR2bxR0wpZbahJf_mlWPZ8nMAOaHJLVTktFwxnmDnFwaRicZXCjVU1IqAfD40BcR61UtWsK_dVgK6mwilQ9h3rscSZORm5kT9lq6Ftp6RwuLmHOyOm9D7pXGIb7UfXapyCVpd6-3aR3yPXeIm0olkCvN04Pt_VFUY558C4s5meeszCh14-TP1bjALRrA9dOAFxn3wjCUlgPwZmBFkLh62ghQEUoRuGf0Qv4ox1efz3y3SePbjwV5N1xQXcSN-Eu_gcpdBEbQguciXhDJllifdwimba3-3_YNPb4hFYW8Sqjc8foEoGdxM-HYTtO-EnCJDsRZtmBz_o9TPof) # [Python](https://www.python.org), 135 bytes, between \$O(n^3)\$ and \$O(2^n)\$ Port of [Arnauld's regex answer](https://codegolf.stackexchange.com/a/269511/91267) ``` lambda x:[n:=len(x),[x],*[[m[1],m[2]]for i in range(n*n)if(m:=re.match(r"^(.+)\1{%d}(.+)(\1|\2){%d}$"%(i/n-i%n,i%n),x))]][-1] import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVHBbpwwEFWO4dY_mK6KYm9ZGraqFCGRY4_9AZZGBkzXGxgj45WImp77Eb3kkvxT8jUZg3fFpUbY894b-83Y_176B7vX-PTcQAa756NtNjevf1vRlbWAMc0xzVqJbORRPhbROs-7PCmiLt8WRaMNKFAIRuAvyXCNXDWsSzMj407Yas_M6ieLP_Nd8jus_7iI7ZLH3ZY7-GkVMvUFNyrEiH4ejZwXRb5JikB1vTYWjJzLebv4UMsGqr2s7lktrIigbHV1P0SAPA0ujbRHQ1UsXcPBm0AIbPW4ig9aIZu3cbcvAncSh48Z_NAog5Pp8DAErrFWoXS9EY4HWyskI4V9BHLs6aacTLxRPePx0LfKsivY3MIVDy7vpqQ7pDRaz-qknQSFlk1xvk0L4vXREtswsiDUG6fPDU-mJPtD-QT4fDNPbxfXVlPX2nnT3AmA79nXgMhK2IkEF85sKZA-x5YC0JNiFNMYJ4He3NHJ9Zk_nHgP_a5ZPpwngou8Be_yvwWlLn1BFIELid4Gi1O8Py2eWZZ3-H_aMvc85lLWvpXRwdHD-ebeAQ) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), \$O(2^n)\$ ``` .œé€Ùʒg3‹}θ ``` [Try it online](https://tio.run/##ASQA2/9vc2FiaWX//y7Fk8Op4oKsw5nKkmcz4oC5fc64//90b21hdG8) or [verify (almost) all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vaOTD6981LTm8MxTk9KNHzXsrD2347/O/2ilkvzcxJJ8JR0QIzmxBMhISswDQiAjsSIRDCqQOVkgTlJ@EkQtRDQLoQoOgJwKpVgA). **Explanation:** ``` .œ # Get all partitions of the (implicit) input-string é # Sort them by length €Ù # Uniquify the parts of each partition ʒ # Filter the partitions by: g # Where the length (aka the amount of unique parts) 3‹ # Is smaller than 3 }θ # After the filter: pop and keep the last one # (which is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 88 bytes, worst case \$ O(2^n) \$ ``` FLθ⊞υ⟦¹…θ⊕ιω✂θ⊕ι⟧FυFΦ⎇§ι²✂ι¹¦³¦¹⊞OE§ι³…§ι³⊕λ§ι¹¬⌕§ι³κ⊞υ⟦⊕§ι⁰§ι¹⎇⁼κ§ι¹§ι²κ✂§ι³Lκ⟧✂⌈Φυ¬⊟ι¹ ``` [Try it online!](https://tio.run/##bVHNT8MgFL/7V3B8L8HEbcedzKLJEqdN9GY8vFC0WAotA@3@emTUGqxygLzP3weiIScs6RhfrWNwJ82bb2BAZFU4NhA4e15xtjsJLXeN7WHgbG@Ek500XtagEDn75OxRKyH/Kb7g9iIvDsjye6u0lw6epDPkTnDt96aWIyjO1jivSUHC3KQ7pc40HnrpyFsHB@rLkQ2W1BaFkonGM8@iYZUT99YnQqZejrapWhhQbio6r/7s5GzWdTME0kdol6C/4nWGmlUvOHz/RDt5WDllPEyNBxpVF7rZyjDpqJIDCrOshLONkWikdN5/rhTGyw/9BQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FLθ⊞υ⟦¹…θ⊕ιω✂θ⊕ι⟧ ``` Get all the prefixes of the input string as a list `[1, prefix, empty string, suffix]` where `1` represents the number of building blocks used so far. ``` Fυ ``` Perform a search over the possible building blocks. ``` FΦ⎇§ι²✂ι¹¦³¦¹⊞OE§ι³…§ι³⊕λ§ι¹¬⌕§ι³κ ``` If two building blocks have already been picked for this entry then just search those entries otherwise search both the original building block and all of the prefixes of the string remaining. Keep only those where the string remaining starts with the prefix. ``` ⊞υ⟦⊕§ι⁰§ι¹⎇⁼κ§ι¹§ι²κ✂§ι³Lκ⟧ ``` Create a new entry with `1` more building block and the block removed from the suffix, updating the second building block if it is new. ``` ✂⌈Φυ¬⊟ι¹ ``` Get the entries where the entire string was successfully built, find the one with the most blocks used and output the blocks. The performance is \$ O(2^n) \$ because on an input of `n` `a`s the code will try both the building block `a` as the first possible building block and also `a` as the next possible building block for each character, generating two child entries each time. An input of `16` `a`s takes about half a minute on TIO. This can be improved at a cost of `6` bytes so something probably about \$ O(n^3) \$: ``` FLθ⊞υ⟦¹…θ⊕ιω✂θ⊕ι⟧FυFΦ⎇§ι²✂ι¹¦³¦¹⊞OΦE§ι³…§ι³⊕λ⁻κ§ι¹§ι¹¬⌕§ι³κ⊞υ⟦⊕§ι⁰§ι¹⎇⁼κ§ι¹§ι²κ✂§ι³Lκ⟧✂⌈Φυ¬⊟ι¹ ``` [Try it online!](https://tio.run/##bVHBTsMwDL3zFT46UpDYdtwJTSBNolAJbohDlBoaNU3aLIHt60OWUil0yyGR/Wy/5xfZCiet0DF@Wgf4RObLtzgyBnU4tBg4vK847E5S0661A44c9kY66sl4alAxxuGHw6tWkq6AH2x7kwcHBvl9VNqTwzdyRrgT3vu9aeiIisOazWNSkDg36U6ps4yXgZzw1s3dlRjKzg0rFS6AUpBmZ7mVMuGAHYeicpWRi8Sz9YnTNMuhXUILh0qOovLuYiaHefGHMQh9RcW/eJ2pZlsWGv6@qptMrp0yHqfCShxVH/rZrTDtUSdvFMtrJZ5tjGJx4u23/gU "Charcoal – Try It Online") Link is to verbose version of code. Explanation: As above, but when choosing the second building block, does not allow it to be the same as the first building block (or a multiple, not that that makes much difference, since the pathological case was for the two being equal). [Answer] # [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 16 bytes, \$\mathcal{O}(n2^n)\$ ``` g1 lL3<nb<<sJ<pt ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNxczcgvyiEoUALiijsDQxJzMtMzVFIaAoNac0JXVpaUmarsWmNNt0Q4UcH2ObvCQbm2Ivm4ISiMTNsNzEzDzblHwuBYWCIgUVhTQFpZL83MSSfCUkkcTExAogzgJiZOGk_KTkxBI0hWCgBDF9wQIIDQA) ## Explanation * `pt`: get all partitions * `sJ`: sort them by length * `nb`: remove duplicate elements from each partition * `g1`: get the first one such that ... * `lL3`: its length is shorter than 3 ## Reflection I've tried many ways to do this. I was working on a fast version, but there were so many serious gaps where I couldn't make it work. * There should be versions of `pt` and `pST` which output partitions sorted by length. There should also be functions to get partitions of a certain size. This would not only shorten the existing code, but it would make it \$\mathcal{O}(2^n)\$. * There should be joined versions of `l2q` and `l3q`. While we're at it, there should also be a joined version of `l2`. * There are a bunch of related things I really would have liked here: + There should be a function to take a substring and split along that. (There exists one for elements, but not substrings.) + There should be a function to take a substring and split along the substring leaving occurences of it in place. e.g. `f "ma" "tomato" = ["to", "ma", "to"]`. + There should be a function to take a string and replace all instances of that string with another string. (There exists one that replaces the *first* instances but no more.) + There should be a function to take two elements `a` and `b` and replace all instances of `a` with `b`. + There should be a function to take a predicate and an element and replace all elements in a structure satisfying the predicate with the given element. ]
[Question] [ *A Knight in chess moves two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of a capital L)* --- Given a Knight current square in a chess board and an array of unavailable squares, calculate the minimum number of **valid** jumps required to reach a target square. If no route is available to reach the required target return 0. A **valid** jump is a move that: * Does not go out of the board (8x8 square board) * Does not overlap with another piece * Follows the Knight L shape move pattern --- **Input** Knight square, array of occupied squares, target square. Input might look like: ``` f("b3", ["c4", "h7", "g5", "a8"], "b7") ``` * You can use a set of coordinates instead of chess algebraic notation. It can be 0 or 1-index. Example: `b3 -> (2,3)` or `b3 -> (1,2)` * You can assume that `Knight Square != Target Square` for every input. * You can assume every input square is valid and non overlapping * Input values can be taken in any order you'd like **Output** Minimal number of **valid** jumps to reach a square, or 0 in case no route can be found --- **Test Cases** ``` "e3", [], "f5" -> 1 "e3", [], "f6" -> 2 "c4", [], "f6" -> 3 "g1", ["f3", "g3"], "h4" -> 4 "c4", ["d6", "b6", "e5", "e3", "e4"], "f6" -> 5 "a1", [], "h8" -> 6 "g1", ["h3","h5","g2","g3","g6","f3", "e5", "e6", "d4", "d5", "c1", "c3", "c5", "b2"], "b7" -> 7 "h1", ["f2", "g3"], "h3" -> 0 "d4", ["b3", "b5", "c2", "c6", "e2", "e6", "f3", "f5"], "a8" -> 0 ``` [Answer] # [Python](https://www.python.org), 154 bytes *-17 bytes, thanks to The Thonnu* ``` def f(s,b,t,k=0): p=s, while(t in p)*64<64>k:p=[[u,v]for i in range(64)if([u:=i//8,v:=i%8]in b)<any((x-u)**2+(y-v)**2==5for x,y in p)];k+=1 return k%64 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZNdToQwFIUTH1lFU2PSjkUH6CAZxY0QHigUSmYEws84bEVffNE96WrsD-gEx5cL9H73nNMCrx_N2Iu6ent7H_rcDj5fMp6DHHWEkZ7swjXeWqAJO2KBZ1HuOepBWYEGr3z64NPH3bYJo2gghzivW1CqXptUBUc-xWWOomEblre3ATnI61UQyzbDD0k1InS0B7xauddotA_qJgw3SuJIRmMQ3--uQ8cCLe-HtgK7K5-ahF8XjYqY1nWboU7Fm5kIJiyVvULAm7LK-BF10TrGpKx6eefE2HZiy1LDgu8b3qJEbjI9VciRkU0w2Zddj56SxqwQhjExvRRjy2paJTrJQO5BAqKYAJhvIMbg0n4Ezv-MPzPugknpX8ZbMIWjGJgrOVh4UNGCzjQ9qwgzX9FMV77RVc9zCic3gLGa3yzmE2dOJALpcQkk459PJKQiFFIcFq4q6rGQjlPUyVZHyKiueiV1dNVMqleYq0Oxu3lTdwtDMR2Be3oE3kyvF3RmjoBpB2Y89WRqjsP9zWWSyneoFJPgR9F8ePMv8g0) Goes through all reachable fields until target is reached, aborts after 64 steps and returns 0 [Answer] # [JavaScript (Node.js)](https://nodejs.org), 143 bytes Expects `[source, target, occupied_0, occupied_1, ...]` where each square is a pair of 0-indexed coordinates. ``` f=(a,n)=>(g=(n,s)=>(i=b.indexOf(s))>1|s&136?0:i>0|Buffer(' "/3OS`b').some(v=>n&&g(n-1,s+v-65)))(n,...b=a.map(([x,y])=>x|y<<4))?n:n>9?0:f(a,-~n) ``` [Try it online!](https://tio.run/##tZRNb9swDIbv@RWEDqmEyUps56NtahfbsHMR5GgYqCRbdopWbqM2SLF0fz2jpQzb0MswND6QMiHoeV8S0p3cSqc368fnyHZVfTiYjEpuWZbTJqOWu361zpRY26re3RjqGMvjvRvG6ex6fLnOx/svL8bUG3oGZJTerG7VGROue6jpNsvtcNhQG8XcfdpGsyljDI8UQqhMigf5SGmx468lInb716urCWPX9tLmF3iwQRXRD8sOqyVk4CDLoQAndCs3X1Hn52c6ZhDBxZzDOWZXxCWUi0ExANxH6pRwIGaKscA6h4/9RiOI/wLNTgdKAkhPTg1KA6iJe1Db4wpivL0mJR@GRNDkvSNS9YkoH@upjx5dT/4XjaBpAMng6Px0rZv92To1945a1E9atEKapA/9b4P@jj09mvSGK9@Jyle0P0P7PdpXVHJsAYLmAdQGR2mYUXKCGY0DKCiTvnVEeVEqyPRQHeaV/LZifl08FPOPoHIgTLf5JnWLzwFIDoqDe4KS9Xf@O@rQnXXdfS3uu4YaWqyWVDIOmBQmfEzck39LVktWMrYYvLHF4Sc "JavaScript (Node.js) – Try It Online") ### How? This is internally using the [0x88 encoding](https://www.chessprogramming.org/0x88). Converting the input to this format is a bit costly, but it makes basically everything else easier and shorter (moves, square comparisons and out-of-board detections). [Answer] # Excel, 236 bytes Define `z` as: ``` =LAMBDA(p,q, LET( a,OFFSET( INDIRECT(p), {-2,-2,-1,-1,1,1,2,2}, {-1,1,-2,2,-2,2,-1,1} ), b,ROW(a), c,COLUMN(a), d,TOCOL(IF((b<9)*(c<9),ADDRESS(b,c,4),NA()),2), e,FILTER(d,ISNA(XMATCH(d,$B1#))), IF(SUM(N(e=$C1))>0,q+1,z(e,q+1)) ) ) ``` Within the worksheet: ``` =IFERROR(z($A1,),) ``` Knight square in cell `A1`, target square in cell `C1` and occupied squares in spilled, vertical range `B1#`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes ``` F…β⁸F⁸⊞υ⁺ι⊕κ≔⟦θ⟧θW∧¬№θζΦ⁻υ⁺θη⊙θ⁼⁵ΣXEμ⁻℅ξ℅§κπ²«→≔⁺θιθ»I∧№θζⅈ ``` [Try it online!](https://tio.run/##TZA/b8MgEMXn@FOcmA6JLm0SRe1kWa2UIa3VLpWsDMQmAQWDjSF/WvWzu9hupDI8Dp7e3Q9KyV1pue77vXWA2bXUIpO2wR2DFaUw3q4o5KGTGBjkOnSoGKxN6UQtjBcVHimlT0nadepgsGi3DNp4PkulBWBqKny1HjMbjMeWwRelDF6U9sLhRpnY7tY2mnIwU3Md6uc2cN3hgsFHqDG35yHAG6wZTLk3VynDNV5i5lanfm0qccEjgyZiReeeTgu@k9nGngQ@vquD9JFw9od8G67oRP6T5E5F2Ix3fuT/x87gE4fn9n1ByjlhUJBqGTeyG1UsRn0YdU7iV5D9kmz7u5P@BQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F…β⁸F⁸⊞υ⁺ι⊕κ ``` Create a list of all valid chess board squares. ``` ≔⟦θ⟧θ ``` Start with one reachable square. ``` W∧¬№θζΦ⁻υ⁺θη⊙θ⁼⁵ΣXEμ⁻℅ξ℅§κ𲫠``` While the target has not been reached and there are still more squares that can be reached... ``` → ``` ... increment the count of jumps, and... ``` ≔⁺θιθ ``` ... append the newly reachable squares to the list of reachable squares. ``` »I∧№θζⅈ ``` Output the count of jumps or `0` if the target was not reached. 51 bytes by taking input as Gaussian integers: ``` ≔⟦θ⟧θW∧¬№θζΦ⁻ΣE⁸E⁸⁺κ×μI1j⁺θη⊙θ⁼₂⁵↔⁻μκ«→≔⁺θιθ»I∧№θζⅈ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVCxTsMwFJybr7AyvSju0KaRKjpFFWxBVWFAijKkwTROnZjEdhEgvoSlAwh-qV8DL46R8HBn-9n37t77d1kVfSkLcTp9Gv0wXZ5_EqX4voWsyynpgpX3VHHBCCTtPVxLDWtpWg0dJS9BQMkVF5r1kPLWKLgxDaTFIywpcbQReH2g5JY3TEFDybpQGvxZ7Qd2uReoVg2HpH0e9pedKQTKIfVsK7FpPBR3SgqjmWuGYodRhLx6k1QeGVxs-b7SaHniMvyJ82CM8uZteo7urYsh0L8wlNwBiq0-1K5UbhhfmT89Cj8_02weRjUlWRTGSDOLi3BhcW4xqnFeMRby8e8v "Charcoal - Attempt This Online") Link is to verbose version of code. [Answer] # [Scala](http://www.scala-lang.org/), ~~378~~ 336 bytes Port of [@bsoelch's Python answer](https://codegolf.stackexchange.com/a/264739/110802) in Scala. Saved 42 bytes thanks to the comment of [@Kjetil S](https://codegolf.stackexchange.com/users/64733/kjetil-s) --- Golfed version. [Try it online!](https://tio.run/##hVFNb6MwFLznV7iWWj1vIQmEkBTqSqucqm5PVU9VD@bbG0pYcLKJEL89a5uUZJG6i8SYZ2bejJ/rkOXsuAl@xqFAz4wXqDlGcYISqD14LIQhX2IE3kv8662v3w1x8fPJkwudEtrsWIVKKqlQE18Va/rk/854HsNVOQ43hZAGNQhyc7O@dx3SlBSSTQX83pyibSF4jlzH31I@Wfo7yq@XPk/QVXBWwtbYEakux/Ge16JuQlbHsDcOhD7A3tySbxpv4WDu5LdCSuctOfA4jzrxWGx@SKm/vqVW66@vXacdqQOv5IFfRMWLlFCoYUrMu4VRg0VM545oRgbsxJDzUD3euurdCHtlAitgcl7jD1bCihgrCAk5IqT0H/IIwKq09tD3qmKHTznx0GvBBaKoGSH5lHJX5AVkgOMZNpCyAmIgnMwxIWgyMR@Q9R@m2zPtITN0vmDOhszU@mTiRLXH6QwrTeb0Gufr7jhylSbQGM816i6xgwfO82EXZl1mzJY90/1Hxkx2x5k0wqmtQJWpdD@FP0XQcSJHo94JLY2aE@qdwNYBg0VvuxjaZhejsS9HM@s106EmOo8m0G5B56/1YTcm@5yxS63uXC5s@VffdtQe/wA) ``` def f(s:(Int,Int),b:Seq[(Int,Int)],t:(Int,Int),K:Int=0)={var p=Seq(s);var k=K;while(!p.contains(t)&&k<64){p=(for(i<-0 until 64;u=i/8;v=i%8;if !b.contains((u,v))&&p.exists{case(x,y)=>(x-u)*(x-u)+(y-v)*(y-v)==5})yield(u,v)).toList;k+=1};k%64} def C(s:String)=(s(0)-97,s(1)-49) def h(a:String,b:List[String],c:String)=f(C(a),b.map(C),C(c)) ``` Ungolfed version. [Try it online!](https://tio.run/##hVJNb9swDL3nV7ACWkir48SJkwZZXaDALgM67DC0l2EHWf7S4tqGrWQJivz2jJId2xk8xAeapJ74nkhWgqf8dMr936FQ8I3LDD5GAEEYQUSrNdCvmbIADbPAX8OLrNTPLvfLAnWJ2ay1Ax5M2dnT9QB2vIQCI12BVqzNbd7QeLAxiT@JTEOgN4Ut8kyhmIoqBnd3NeoRli5ryoEpRqO8BCrhcQxT2GZKpgj5DA2i@7aIlTCB1cDZzpzdDp7JCG78TgvdWrBjRlBhh3t8SQUfIHiFmvcWHBh4T@jBGLYMPrXePdADejuTazzPgwUc2SXlQYZpAA2LrXLdqwZgGnDvgWPi46jN3eKLRzrTTE3keRnoyf1Qpcxi1h9POwxKuC8QHSfEllkQ7r/jsG2R8PJZ0SnDObaRw2xefZGxVCjcYX2qJEyLsKT8zNVtSB3jdoiejv42RLTWyfVa2e@8qGOM6rxgNRNAw/WOA6C8jPFhz2XJD2cKrPuaya5wgVmVZrTRRsI5seqdw9okWhAc32QyfmoaeQW@bOGzQbhw/wOfD8Jj5wwnkSYi8Zzoi4nbXnSv8JBgqS/6xoYLY02p0CX/aFgMluJOX3KyauHLa5IT5CEJUpJ4po0OY9TRvKURY4QFrrEmIxxjDUaYjD8zUv2HlvthkDvptWvWb9e8vTgdvBh07fINr18rMUVE3bpZp7bWr3cDf3x1Ufw4Op5OfwE) ``` object Main { def f(s: (Int, Int), b: List[(Int, Int)], t: (Int, Int), k: Int = 0): Int = { var p = List(s) var kVar = k while (!p.contains(t) && kVar < 64) { p = (for (i <- 0 until 64; u = i / 8; v = i % 8; if !b.contains((u, v)) && p.exists { case (x, y) => (x - u) * (x - u) + (y - v) * (y - v) == 5 }) yield (u, v)).toList kVar += 1 } kVar % 64 } def coord(s: String): (Int, Int) = { ("abcdefgh".indexOf(s.charAt(0)), s.charAt(1).asDigit - 1) } def helper(a: String, b: List[String], c: String): Int = { f(coord(a), b.map(coord), coord(c)) } def main(args: Array[String]): Unit = { println(helper("e3", List(), "f5")) //-> 1 println(helper("e3", List(), "f6")) //-> 2 println(helper("c4", List(), "f6")) //-> 3 println(helper("g1", List("f3", "g3"), "h4")) //-> 4 println(helper("c4", List("d6", "b6", "e5", "e3", "e4"), "f6")) //-> 5 println(helper("a1", List(), "h8")) //-> 6 println(helper("g1", List("h3","h5","g2","g3","g6","f3", "e5", "e6", "d4", "d5", "c1", "c3", "c5", "b2"), "b7")) //-> 7 println(helper("h1", List("f2", "g3"), "h3")) //-> 0 println(helper("d4", List("b3", "b5", "c2", "c6", "e2", "e6", "f3", "f5"), "a8")) //-> 0 } } ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 62 bytes ``` {0^*&~^?[;z]'64{?,/x@y}[i!i@&'(4=*/4#)''i-\:/:i:(+!8 8)^y]\,x} ``` [Try it online!](https://ngn.codeberg.page/k#eJy9k01ugzAQhfecwnGl8NOkxMQYYqsK9wgBxQ4YbkBK6dnLTEt/Vu0i4MVIIxh/772Ra9nvimD9VhxP6uXsCt4fN2GX3YZTu2qztevx5yDkD77rtttchrKV3uMqJalf3M75phscx8reC6TaspKVKnhlpZ/lsht/PiSEHwanfiLWo9WeKlrH1CchYWSJ8wssEBwtCTb8G7xfEmwZgMG2hdJwlMDnB6PjqxiLhlLFUEBC9SOKeAbwBRw3Kd4v7nn/X2CMusGUwayNptCtmHbwkQK0V4wHWgNjBr4aaDWM6QTlJ/8DN7jjL9woAYZ38ztGExqYGp2ABIPbjiaf9edTV/SS3kGW8w6bHb6X) [Answer] # [J](https://www.jsoftware.com), 59 bytes ``` 1 :'1{.[:I.[e."1(u-.~,j./~i.8)(]~.@,&;[<@#~2j1=&|-/~)^:a:]' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZLPattAEMahx32KYQ3SbiKNvZJsi3UcRAOFQOmhV6EUSdYfC4eW1oYENXqRXtxDHyKP0j5Nd0dOmpYedsR-M_P7dgZ9-94dHzm6Naw1uODBDLQ5PsLV-7dvfhz2tR__XCnQruox1deYVsiVOPg4eB1Ohy3GUmQDJp6zSi-SyRB0au189aeDvNG5ztwR8evVrWTvXiNYUgqiQsc7u9DJJMkkiMlg7uKZJxPip9oTIIR3LlUXyLPprFM3W4xAnk8zAxfKr5BMXMbK20-7u7UWbl6Um6puWhe2xszpJXQIrgrCaL5YxqQGTs_21Ze9GTgEPWMAhzUCEZxLcDkid-HzXb7bwb1J2lcLjr2-99HuRIKvQfTmPOCDPsgaepRwMJX_ESVjVdl-TKzfCj8EkNkFzxivQu5BmnnA6zkH_xLUX9qCtIDxMvpHCxlvlNV4bct5E3KbbSPKRk8dfLOw2YJiNadI9VXEX9DmjOfqyaGNSVs8O7Smg7emmTeBDfbaGOLJ-oQli01EkZRSUaSakpQiINNiSQZLxtvTCMHLEULKmuVsxhEKIhQjkyrLcZzgj-_4ErNDS8jjE0GOf93xOH5_Aw) Takes input as complex numbers. To handle all 3 args, we use a J adverb which modifies the list of illegal positions, and takes the target and start positions as the left and right args, respectively. * `(u-.~,j./~i.8)` Generate the full board minus the illegal spaces * `(]~.@,&;[<@#~2j1=&|-/~)^:a:]` Collecting each step's results until you reach a fixed point, starting the initial square, find all legal spaces that are \$\sqrt{5}\$ away from the current positions. In this way, we spider out stepwise to every reachable position * `[e."1` For each steps results, is the target position in that list? Now our list of lists (the step results) will become a single 0-1 list, with the first `1` representing the index we seek * `[:I.` All `1` indexes. Returns empty list for no matches. * `1{.` Take the first. Exactly what we need, and since taking 1 from the empty list returns 0, it also handles the no match case. [Answer] # [Haskell](https://www.haskell.org), 192 bytes ``` n=99 q=[-1,1] (#)=elem g a b p c=last$last(1+g[w|s<-a,x<-[1,2],y<-q,z<-q,w<-[zipWith(+)s[y*x,z*(3-x)]],all(`elem`[0..7])w&&not(w#b)]b(p++a)c:[n|all(#p)a]):[0|c#a] f a b c= min(g[a]b[]c)n`mod`n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVNNjpswFJa69CmeSDWxJ2YUyO9Eobsuup5FF5alGGMgKhASSPOj3KSb2VS9Rq8xc41eoLZhhnRaNYsXeN_Pe4aPbz9SUX1RWfb4-H1fx-786WcR3N-jbcBcj3oc4R4JVKZylICAEEqQQSaq-r0p2Bsk7HCplq6gx6XLPOpzelq6W3o25aBb53X5eV2neEAqdro90vMtHrlHwjkVWYZXxnnFhnd3M04ONzfFpsaHXkh4iMvBQBC5YMXFEHslEZws2PAie4Kj2O4iA8jXBU6Y4CHjkhSrfBOtiuYcz-9-1adSwcN2L3YKAmCfipojJDfFV7WrYbGAh3q3LhJwP7SkV4wdKZy40cRwBBdi6Is-1X-n5sbrczikSitA_2JNjHeb_GOxzxGqVVVLUanKyC2OsaNGDgXGKTjxxCEUPEL_AU0N5HeQHP8JjToo8QzkxEbsJCPHkNKxIY3f6p1oakihrWpiq5WpsdN5TzqZ8F7GpnMDTf8am2q9k2orJ_FNMbeJ9m_3aYfYgdHYVtuRnq2WI20n9O0K4czMmXVz0vZ4_vXxRoY07EhRc7zQ-oXNBCuQzVH9botmL_3sjZGYN0bWh1-9sb4JBcO4SYP2bi60prnQKp0hwq8VgRHoOFLIRamjEJqYSM2MCMBFr6kR3Ws7SxdetW8j1IYPIZSLdaEbpU5nbSJosw5BANH_HfscNdl_-ZZ_Aw) [Answer] # [Perl 5](https://www.perl.org/), 166 bytes ``` sub{($s,$e,%o)=@_;@w=(0,$s);while(($n,$s,@w)=@w){$s-$e||last,push@w,map{$n+1,$_}grep{($a,$b,$c,$d)=map{$_>>3,$_%8}$s,$_;!(($a-$c)**2+($b-$d)**2-5||$o{$_}++)}0..63}$n} ``` [Try it online!](https://tio.run/##nZPfj5pAEMff/SumZD1Bd1VYQXsEy3uT3kvfrCH8WMDUA8JibKP0X7ezeoc926S1PO3Ozny@35kMlai39omk3knuooNOJCWC9kvD8wPX33v6lBJpuPt8sxW6Tgq8UX@Pr3vjQCQj4njchrKh1U7m/p4@h9WBFCOTkqDNalEhMKQkoiSmJDG883OwXHJ87y9aJRa475AbMhIbw6E10knEMBOPzD4eSYnp7WhktNPx2OEtKdqT20vLWu@tADTB2TK1Nbjn85ZgAqzpFeDcDbA6QDz7LwDvAJnJlvkMoymHjGv/CpjdOMBo4kDkgLBBcBAz7S8AuwOEysHi7hacNy1Ec4zmHHIbMgsbgcxRHSk3DiQzSGyITYg5xDZElqYA8w6QKwdczcC6ZwbTDpDgDMIFRiMOESpZEOMkLKWNJv68IR3AOPTU/fm7TjZFtWsoEPGtEnEjkkA2opIGeODjnnZpsgnrc1qRUPDLON5VG5GoNLXfMBlP3MVQJwNmGuz9fFTWCXmAFi548H7AZBWyfL0y2WI9yV65QM5qSHkg6Y3I5b@hZntVu5bVQu62yO0A3m0H8AEG5dcBPMLg09NnePo4uFRX9aZoUq3PHAnwtuQR@glm/Ho@28ez/FJo9FX2t2nRFxv0pV@3155@Ag "Perl 5 – Try It Online") ``` sub steps { ($s,$e,%o)=@_; #start, end, occupied set as hash from input args in @_ @w=(0,$s); #initial work (steps,square) while(($n,$s,@w)=@w){ #while work left to be done $s-$e||last, #bail if current square $s equals $e end square push@w, #register new work/new squares to be checked map{$n+1,$_} # (new steps, new square) grep{ #filter ($a,$b,$c,$d) #coords of current square ($a,$b) =map{$_>>3,$_%8}$s,$_; #...and potential new square ($c,$d) !(($a-$c)**2+($b-$d)**2-5 #pythagorean horsyness check of new vs current ||$o{$_}++) #...non-occupied new squares #...and register new square as occupied #...with ++ to not enter it again } 0..63 #loop through potential new squares } $n #return n steps from last work } ``` ]
[Question] [ If we have a finite list of elements we can determine the probability of any one element being drawn at random as the number of times it occurs divided by the total number of elements in the list. For example if the list is `[2,3,2,4]` the probability of drawing `2` is \$\frac 1 2\$ since there are \$2\$ `2`s and \$4\$ elements total. For an infinite sequence we can't use this method. Instead what we can do is look at every prefix of the sequence determine the probability using the above method and then see if the limit of the probabilities converges. This looks like $$ P(x, s\_i) = \displaystyle\lim\_{n\rightarrow\infty} \dfrac{\left|\left\{s\_m\mid m<n,s\_m=x\right\}\right|}{n} $$ For example if we have the sequence which alternates between `0` and `1`, `[0,1,0,1,0,1...`, then the probability of drawing a `0` is \$\frac 1 2\$. Now this is neat but sometimes the limit just doesn't converge, and so the probability of an element being drawn is undefined. Your task will be to implement a sequence where for *every* positive integer its probability is undefined. This means that no matter what you pick this limit must not converge. It also means just as a side effect that every positive integer must appear an infinite number of times. Otherwise the probability would converge to \$0\$. You may implement any sequence you wish as long as it fulfills the above. Your sequence should output non-negative integers. Zero is permitted to appear in the sequence but is not required to. This challenge uses the defaults for sequence IO which can be found [here](https://codegolf.stackexchange.com/tags/sequence/info). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your source code with answers being scored in bytes. [Answer] # x86 32-bit machine code, 7 bytes ``` 0F BD C1 0F BC C0 C3 ``` [Try it online!](https://tio.run/##XZDdTsMwDIWvyVOYomnJ/jTKBdO28gbcIzFUpWnSRkpTlKYQCfHqFKfrJkEubJ3P8rEdsa6EGIY7bYXpSwnHzpe63dRP5A8yuvjPnLZVZCTPuUdV9F7mOaWKd15wYxgDbT0oGiNnB8K7BihJTnZTmbbgBlQSldqP6aboHEgeViBFuBA1ET4RJ31C0IpEz4ZrezZ3lViBqLmDxQLFByNfBPDFYoAM7g@j/Ky1kUADHDNIdzs2wvje8RavaDLTkKxw47BcMnbuuZRO9pmLWlsJoi3lPpnKqnXRMIPtASfdZvCIGbuvfTDbpi9oSmlvO11ZWY6LLphir@HtMqT3EdL5yc4nhJf2zqIt@SbD8COU4VU3rJuHFAP@ZIb20vwC "C (gcc) – Try It Online") Following the `fastcall` calling convention, this takes the 1-indexed `n` in ECX and returns the `n`th value in EAX. In assembly: ``` .global f f: bsr eax, ecx bsf eax, eax ret ``` This produces blocks of size 1, 2, 4, 8, 16, ... of the same number, so that each block raises its number's proportion to more than half. `bsr` (find highest position of a 1 bit) is used to obtain the 0-indexed block number. The values used for the blocks are (0), 0, 1, 0, 2, 0, 1, 0, 3, ...; these values are produced by `bsf` (find lowest position of a 1 bit) on the block number. (The result of `bsf` is officially undefined for a value of 0, but on at least some systems it consistently leaves the destination register unchanged, producing 0 for block 0.) [Answer] # [Python 2](https://docs.python.org/2/), 24 bytes ``` lambda n:`n`.find("1")+1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMHiNNuYpaUlaboWO3ISc5NSEhXyrBLyEvTSMvNSNJQMlTS1DSHSN_XS8osUMhUy8xSKEvPSUzUMDYBA06qgKDOvRCFNI1NThwvMtgaTXBBdCxZAaAA) This is heavily based on @xnor's idea in the comments. It returns the (1-based) index of the most significant decimal "1" and 0 if there is none. Why does it work? for any cutoff 10^k the fraction of numbers below it that have the first "1" at position n (n<k) is asymptotically the same, in particular, it is bounded below by a positive number. But between 10^k and 2x10^k there are no such numbers, meaning that frequency will eventually fall to half its value (and then rise again) which is incompatible with convergence. The case k=1 must be dealt with separately (easy) and k=0 is exempt by OP. # [Python](https://www.python.org), 36 bytes ``` lambda n:int(bin(len(bin(n)))[3:],2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3VXISc5NSEhXyrDLzSjSSMvM0clLzwHSepqZmtLFVrI6RJlRtSVp-kUKmQmaeQlFiXnqqhqGBgYGmVUERSGeaRqamTmpeiq2SgpImF0RM0xpKc-HVaGhjg0cvxO4FCyA0AA) Takes an index and returns the corresponding value. Numbers are first mapped to the length of their binary representation. That way whatever this finally maps to is elevated to a probability of roughly 0.5. As a simple way to make sure every number comes back eventually, we take again the binary representation and use the most significant bit for modulo. In other words we remove it and all leading zeros that may be exposed. The test code first shows the first 1000 items and then the unique values of the first 1000 blocks. [Answer] # [Python 3](https://docs.python.org/3/), 41 bytes ``` j=1 while j:j+=1;print([str(j)[1:]]*2**j) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8vWkKs8IzMnVSHLKkvb1tC6oCgzr0QjurikSCNLM9rQKjZWy0hLK0vz/38A "Python 3 – Try It Online") Here, we increment `j` and strip the leading digit, to get a sequence where every number appears infinitely often. Let's call the stripped number `k`. Then we output `2**j` copies of `k`. This has the property that the probability of `k` jumps up to 50%, when we ouput `k`, then decreseas by half after every iteration. This means that the probability of `k` doesn't converge. The probability jumps occur because \$2^j>\displaystyle\sum\_{n=1}^{j-1}2^n\$ The IO format is a bit rough, to say the least. The output is a non-digit separated list of numbers, which may have leading zeros. # [Python 3](https://docs.python.org/3/), 48 bytes ``` j=10 while j:j+=1;print(*[int(str(j)[1:])]*2**j) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8vW0ICrPCMzJ1UhyypL29bQuqAoM69EQysaRBaXFGlkaUYbWsVqxmoZaWllaf7/DwA "Python 3 – Try It Online") Same idea, except the output looks a bit nicer. Numbers don't have leading zeros and the output is whitespace separated. # [Python 3](https://docs.python.org/3/), 39 bytes ``` j=2 while j:j+=1;print([~-2**j%j]*2**j) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8vWiKs8IzMnVSHLKkvb1tC6oCgzr0Qjuk7XSEsrSzUrVgtEa/7/DwA "Python 3 – Try It Online") This is based on a conjecture that \$2^n\mod n\$ will take all values, except 1, infinitely often. To fix the missing \$1\$, we can compute \$2^n-1\mod n\$, and now \$0\$ will be the missing value. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 29 bytes ``` n=>parseInt(10+Math.log(n),2) ``` [Try it online!](https://tio.run/##HcoxDoAgDADArzjSoAZcFXcHH9EoaA1pDRC@j4k334MV85HoLQPL6Vtwjd36Ysp@46Ks0TuWe4xyKYZ@ghYkqYqpI2dnWqwxs9YEh3CW6P8XFAG0Dw "JavaScript (Node.js) – Try It Online") Like m90's idea, output each number for a time, making it go up to parseInt(k,2), which every number happen for infinite times(`10012xxxx` for 9, etc.) ]
[Question] [ The **edit distance** between two strings is the minimum number of single character insertions, deletions and substitutions needed to transform one string into the other. This task is simply to write code that determines if two strings have edit distance exactly 2 from each other. The twist is that your code must run in **linear time**. That is if the sum of the lengths of the two strings is n then your code should run in O(n) time. # Example of strings with edit distance 2. ``` elephant elepanto elephant elephapntv elephant elephapntt elephant lephapnt elephant blemphant elephant lmphant elephant velepphant ``` # Examples where the edit distance is not 2. The last number in each row is the edit distance. ``` elephant elephant 0 elephant lephant 1 elephant leowan 4 elephant leowanb 4 elephant mleowanb 4 elephant leowanb 4 elephant leolanb 4 elephant lgeolanb 5 elephant lgeodanb 5 elephant lgeodawb 6 elephant mgeodawb 6 elephant mgeodawb 6 elephant mgeodawm 6 elephant mygeodawm 7 elephant myeodawm 6 elephant myeodapwm 7 elephant myeoapwm 7 elephant myoapwm 8 ``` You can assume the input strings have only lower case ASCII letters (a-z). Your code should output something Truthy if the edit distance is 2 and Falsey otherwise. If you are not sure if your code is linear time, try timing it with pairs of strings of increasing length where the first is all 0s and the second string is one shorter with one of the 0s changed to a 1. These all have edit distance 2. This is not a good test of correctness of course but a quadratic time solution will timeout for strings of length 100,000 or more where a linear time solution should still be fast. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~76~~ 58 bytes ``` ^(.*)(.*¶)\1 $2 (.*)(¶.*)\1$ $2 ^.?¶.?$ ^.?(.*).?¶.?\1.?$ ``` [Try it online!](https://tio.run/##jc1BCsMgEAXQvafIIoWki4C9QA7RrYQaKk1BjRRJ6MVygFzMqiWo01l0of7/HPQl7FNzd2qut8oNTXdu/dq3llFSX0js@@Z3RusAQ9f72tckpHD77Yx6c05IYSaubRWCP2dSyMSNtgtiNtlBSUYpVEzZEIQlJGBHAG@XMK9cwz4mUD@CgSzhgckdkTX/6X9RmbwRwsVAghLhAw "Retina 0.8.2 – Try It Online") Takes the two strings on separate lines, but link includes test suite which takes space-separated strings instead, so that I can easily use the test cases. Explanation: ``` ^(.*)(.*¶)\1 $2 ``` Delete the common prefix. ``` (.*)(¶.*)\1$ $2 ``` Delete the common suffix. ``` ^.?¶.?$ ``` Ignore an edit distance of less than two. ``` ^.?(.*).?¶.?\1.?$ ``` Check that only the first and last characters have been edited, so that the edit distance cannot be greater than two in this case. From a code golf point of view this can be done in 51 bytes but then the regex becomes unbearably slow to execute for longer strings: ``` ^(?!(.*).?(.*)¶\1.?\2$)(.*).?(.*).?(.*)¶\3.?\4.?\5$ ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZyg8D9Ow15RQ09LU88eRB7aFmOoZx9jpKKJEIPLGANlTIDYVOX//9Sc1IKMxLwSBRADSOdzoYhkJBbklZRhEStBiMGEECJJOam5YBaSInSBMhALTQzGQDMbVSC/PDEPnZ@EEMjFEMEmkIMqkI5NJAWLSDmyTcSL5CKJVGIRwi5SgC6ELgIWAAA "Retina 0.8.2 – Try It Online") Takes the two strings on separate lines, but link includes test suite which takes space-separated strings instead, so that I can easily use the test cases. Explanation: ``` ^ ``` Match the whole input. ``` (?!(.*).?(.*)¶\1.?\2$) ``` Don't match strings with an edit distance less than two. ``` (.*).?(.*).?(.*)¶\3.?\4.?\5$ ``` Match strings with an edit distance less than three. [Answer] # [Haskell](https://www.haskell.org/), ~~124~~ ~~121~~ ~~99~~ 88 bytes *3 bytes saved by [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)* ``` x%y=[0,0]==x#y u@(a:b)#v@(c:d)|a==c=b#d|k<-zipWith(+)=0:k(d#u)(k(b#v)$b#d) a#b=a++b>>[0] ``` [Try it online!](https://tio.run/##bU5Na4NAEL37K2Q34i42wVyXrgQKOQUq9NCCeJh1t1FcP8iqiSW/vVZrD7E4h3kz783HS8HkSuthuDk9j/wnP@b8hnurPRBgguLuQBIm6R04T7jA8p4/b7@y@j1rUuJR7rOcSNxSkhOBO7oZJ6gFWHDwPBEEkR8PBZT9q@HRfrfb@78RBwGqkFVAVnJZWbZdt81bczmVNgrBGGUYmshLVjYbBCKRyEFjVg@sWGWVVnUKZTMq3VTPzaqui38icYXL3MRls1/qzGgt7B0h0wt3jxdVdV2@@7OuJlhfOatKwlWg4Tv51HA2w/bjJQx/AA "Haskell – Try It Online") This is a modification of the below algorithm which uses a bit of complex short-circuiting to accomplish the task. I owe much to xnor's comment that initially proposed the idea, and to [Noughtmare's SO answer](https://stackoverflow.com/a/69032186/4040600) which explained why xnor's initial version didn't work. ## 99 Bytes ``` x%y=2==(x#y)0 (u@(a:b)#v@(c:d))x|a==c=b#d$x|x<2=minimum$[d#u,b#v,b#d]<*>[x+1] (a#b)x=x+length(a++b) ``` [Try it online!](https://tio.run/##bU5Ni8IwFLz3V5SkQmJdcD0WI8LCnjwU9rIgHl6abBs2ScWkNYK/fWPLerDQw/uaYWZeA@5Xah1jWNzYhjES8I2uE9LtCRSc4n5PqkJQGu7AWMU4Flm4h@2GGWWV6Ux2FLhbcdwPJU7b5e4Y8vdTQgBzGljItbS1bwjkOafRgLJMtEmanjv/5S8Hm6ISnJOuQCN4UdZnCHgl0AINXb6gfBaVWp4bsH5g@nH/P2Z5bZ7kJP4TlJ6kvypke53aPV@T45iX1LIVcOUo/lU/GmoX374/yvIB "Haskell – Try It Online") We start by looking at a naive version of edit distance: ``` lDistance :: ( Eq a ) => [a] -> [a] -> Int lDistance [] t = length t -- If s is empty the distance is the number of characters in t lDistance s [] = length s -- If t is empty the distance is the number of characters in s lDistance (a:s') (b:t') = if a == b then lDistance s' t' -- If the first characters are the same they can be ignored else 1 + minimum -- Otherwise try all three possible actions and select the best one [ lDistance (a:s') t' -- Character is inserted (b inserted) , lDistance s' (b:t') -- Character is deleted (a deleted) , lDistance s' t' -- Character is replaced (a replaced with b) ] ``` (I wrote this program for Wikipedia [here](https://en.wikipedia.org/wiki/Levenshtein_distance#Recursive)) This is pretty bad because every time it finds a discrepancy between the two strings it branches into 3 options (insert, delete or replace) so in the worst case it will have the time complexity of \$O(3^n)\$. The thing to notice though is that whenever we branch we increase the total distance by 1. So if we are on a particular search path that has already branched 2 times and we would branch another time, we can just stop there and say return the total we have for the branch. All values above 2 are the same as far as we are concerned. Now there is a hard limit on the number of branches that can occur, \$3^2 = 9\$, so our computation is \$O(n)\$. In general this strategy has a complexity of \$O(3^mn)\$ where \$m\$ is the limiting distance and \$m < n\$. [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~273~~ \$\cdots\$~~316~~ 312 bytes Added 30 bytes to fix bugs kindly pointed out by [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler). Added 12 bytes to fix a bug kindly pointed out by [ovs](https://codegolf.stackexchange.com/users/64121/ovs). Saved 9 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! ``` def f(*x,i=0): b,a=w=sorted(x,key=len);d,c=map(len,w) while a[i]==b[i]: if(i:=i+1)==d:return i==c-2 while a[c-1]==b[d-1]: if d==1:return c==3 c-=1;d-=1 a=a[i:c] b=b[i:d] return c-i>1and((x:=a[1:-1])==(y:=b[1:-1])or a[:-1]==y or a[1:]==y or a[:-1]==b[1:]or a[1:]==b[:-1]or x==b[:-1]or x==b[1:]or x==b) ``` [Try it online!](https://tio.run/##rZLPcpswEMbvPMU2F4kEZ0KcNoky22OfoLfEB/1zrAkWDMix/fTuCkzBhEtnykH69qddPkmr6hg2pV8@VfXpZOwa1vz6kDm8S0UCKpO4x6asgzX8kH3YIxbWpy8m07iVFacg26cJ7DeusCBf3QpR0Uil4NbcCXQ3eYpoRG3DrvbgEPXifijQi7wtMTR3RWAQ8z5dIy6J6gXmL4aGBCSSi9Ar2lt0EoZUn7xwP3PpDecHQVm5oH@SNz8KyuyisiZP0XoeoQ1yMWhx3gyxYU21mOLDVHdpUaanAMgYS6TSBqQ5zyqxha020geIgubykmxk5cPnDAsD69FAVGG3rRolTcFnVB2L@6qR79jb7v7xQbOsU/mSpck6njNT4DxwfdtUhQucAUshLuiIw20TalfxtF998yyNT6PBNadSan5VOx@izpqsfm0Qf9c7u0qT/k60pKuQkJ9vBZbTA5O4mxyY5nyMyr308DAlaoy2M2weFVP0fmbfL5mZZXsFP0au/8a2F@zYw8cxnEuMrPqa@JV16Knt@rm7mf7P/f0liyY2WCLrndn1c/vdwIASNbPOhpfJkr8encWVcu9Qevvt6vIlnf4A "Python 3.8 (pre-release) – Try It Online") [Answer] # JavaScript, 120 bytes ``` a=>b=>a.reduce((t,c,i)=>t.map((n,j)=>p=Math.min(n-(c==b[i+j-2]),p,t[j+1]||4)+1,p=4),[4,4,1,2,3])[b.length-a.length+2]==3 ``` [Try it online!](https://tio.run/##ldLdboMgFAfwe5/iXK2QIpmt@0gavNvlnsCZFCxWDCJR1mZZ9@xO@7Fa682uzp8fh0NCKPiON2mtrPNNtZFtxlrOIsEiTmu5@UwlQo6kRGEWOVpyi5AhRbew7J27nJbKIOOjlDERq3nhLxJMLHFxMQ@SwyHE84BYFmIShyQkAVmQZYJjQbU0W5f7/Bzmi4SxZetk41LeyAYYrD2ppc25cdCHrla3knNr3G7C3NUudBWhZXlMg6Yx7Pp0svH4LjyOxnc1GFK15wbCsYghlRM2TXpM27M93dpm0vYCnge3/s/KG/u64MsQpxp7s/eN93aiV29NXa1KhGljtXJo9mFmeOX9/QWaVfUbT3OklZHAIvj2oHsaBzEnIJLuq/Qbl8PQnwVQGSAODw8gMKSVaSotqa62KEMxpZQn@FhFgrvuH7xqfwE "JavaScript (Node.js) – Try It Online") [Try a large one!](https://tio.run/##bY47DoMwEESPw1perPBplxvkBJaLtTE/gbHAScXdCSgpM9XMvClm4jfvbhtjysPa@rOjk6mx1LDafPtyHiChw1FQk9TCESDgdIVIT06DWsYAIQdHZPUop7w0AiMmPcnCHEctZIGRaoG6xhoLLLEyQls1@9CnIeefkaUhqk63hn2dvZrXHjrQSqnMZjLj7LoSPScoHreEvGojvoN/8Kbi/AA) Traditional DP solution, with modification the formula by \$dp\_{i,k}=\infty \text{ if } \left|i-k\right|>2 \$. And we use \$ k=i+j-2 \$ here. `t` is initialed to `[4,4,1,2,3]` which means (the edit distance of an empty string and first `j-2` characters of `b`) plus 1. Any number greater than 3 here means `Infinity`. After `i`-th iteration, `t[j]` is (the edit distance of substring `a[0..i]`, and, `b[0..(i+j-2)]`) plus 1; Or anything greater than 3 if the edit distance is greater than 2. ]
[Question] [ [Related](https://codegolf.stackexchange.com/questions/55197/magic-the-gathering-combat-golf) # Goal: Given two creatures with optional combat abilities, return unique but consistent values that represent which creatures died, if any. # Input: ``` #Longest form: [[P,T, "<abilities>"], [P,T, "<abilities>"]] #Shortest form: [[P,T], [P,T]] ``` Each creature will be given in the form of `[P,T,"<abilities>"]`. It will be in the form `[P,T]`, `[P,T,""]`, or `[P,T,0]` if it has no abilities, your choice on form. P is an integer >=0, T is an integer >=1. `<abilities>` is a subset of `"DFI"`, or can be represented via a single number/bitstring if you wish. Order of the flags is also up to you. # Combat Mechanics: Each creature has two stats, Power and Toughness in that order, and optional abilities. A creature's power is >=0. A creature's Toughness is >=1. Each creature will simultaneously do damage equal to its power to the opposing creature (unless one has first-strike). If the value is greater than or equal to the opponent's toughness, it will die (unless it is indestructible). Example: Alice is a `2/2`, Bob is a `3/4`, both with no abilities. Alice will do 2 damage to Bob and take 3 damage in return. Alice's toughness is 2 so it will die, Bob's toughness is 4 so it will live. There are only 3 optional abilities we will consider for this (although there are more in the game). These will be one character flags: * [D]eathtouch: Any amount of damage (X>0) is considered lethal. * [F]irst Strike: Will deal its damage first, able to kill the other creature before it can attack back. If both creatures have First Strike, Resolve combat as normal. * [I]ndestructible: No amount of damage is considered lethal, including Deathtouch. # Output: Any consistent value for each of the following four cases. State the four values in your answer, please. Example return value in parens: * Neither creature died (0) * 1st creature died (1) * 2nd creature died (2) * Both creatures died (3) # Rules: * Input is guaranteed to have two correctly formatted creatures. * If you are using characters for abilities, you can assume they're ordered how you want but post the order used if relevant. * If you are using a number/bitstring for abilities, post what encoding you're using. e.g.: `111` is `D/F/I`, `7` is `D/F/I`, etc. * If a creature has no abilities, It can also be taken as `[P,T, ""]` or number equivalent * Standard Loopholes Forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins. # Examples: ``` Input: [[2,2], [1,1]] Output: 2nd Dies Input: [[0,2], [0,1]] #0/2 vs 0/1 Output: Neither Die Input: [[2,1], [2,1]] #2/1 vs 2/1 Output: Both Die Input: [[1,1, "D"], [2,2]] #1/1 Deathtoucher vs 2/2 Output: Both Die Input: [[2,2], [0,1, "D"]] #2/2 vs 0/1 Deathtoucher Output: 2nd Dies Input: [[2,2], [1,1, "DF"]] #2/2 vs 1/1 Deathtouch First-striker Output: 1st Dies Input: [[0,2, "D"], [0,1, "DF"]] #0/2 Deathtoucher vs 0/1 Deathtouch First-striker Output: Neither Die Input: [[2,2], [2,2, "F"]] #2/2 vs 2/2 First-striker Output: 1st Dies Input: [[2,2, "I"], [1,1, "DF"]] #2/2 Indestructible vs 1/1 Deathtouch First-striker Output: 2nd Dies Input: [[9999,9999], [1,1, "I"]] #9999/9999 vs 1/1 Indestructible Output: Neither Die Input: [[2,2, "F"], [1,1, "F"]] #2/2 First-Striker vs 1/1 First-Striker Output: 2nd Dies #9/9 Deathtouch, Indestructible First-Striker vs 9/9 Deathtouch, Indestructible First-Striker Input: [[9,9, "DFI"], [9,9, "DFI"]] Output: Neither Die ``` [Answer] # [Perl 5](https://www.perl.org/), 248 bytes ...without spaces and newlines: ``` sub c{eval' (P,T,A,p,t,a)=@_; A=~/F/&&a!~/F/&&a!~/I/ ? c( P,2e9,A=~s/F//r,p,t, a ) :a=~/F/&&A!~/F/&&A!~/I/ ? c( P,T, A, p,2e9,a=~s/F//r ) : do{ P=1e9 ifA=~/D/&&P>0; p=1e9 ifa=~/D/&&p>0; T=3e9 ifA=~/I/; t=3e9 ifa=~/I/; T-=p; t-=P; T>0&&t>0 ? 0 : T>0 ? 2 : t>0 ? 1 : 3 }'=~s,[pta],\$$&,gri } ``` [Try it online!](https://tio.run/##lVNdb9owFH3PrzAhokkxJHa1hyYLlAkh8dIilTdgKIXQZoUkcpxuFWV/vbuO8wVDrWopsX3vOed@2I59tv32/p6kD2i191@87YU@wVM8wDHm2DPcm6UzcP@aI7PV8hrVPDb7KwBS/xqDOwG7yXKK7eX4QaOac7wUFiyvYBn2OtpPXOJfBxsRaQiMSc9yYmnyclMMpql7VaDGpsPlzpO7aceNHd5xJ860Z7VavGf1LRuWfWqLNbGvDhcQEs9i7i3wXNNa@JEFB1l4hPaouYp2Dx5XEIzdq67FBGscPo9gpMUUNvB5NOtIBmI@T1kI5AwragJs2Ys6B@XDQMEGZSDAIC9cw4Y2TjZQyxn5MpViCHkZk5adlPK0Lk8aJ5tCHkRFg6uMhjkqJtDpHEIrCK1DaAnhRJxCpVLKc1o56JGDdFxQKGFiR0pfz0KtljDDoo/UWz/gTz5Dw8BXBcSWkHIAhEJG4E4KPz3xk4RX/tNhI/VHxJ@k/kHZvaIb7ifc3XnxfmaOwzjlNupe9pE@X7cNnP31vo3nyaWqz0bD8aJtqEb/nDSMrxEF@i7lWUiAIR0y74rM36BEuRC5itVb3hexNvrI/JMEi0OllcTbgJvzcB6a@FcUhKqKvw8H00HPERVq3IXT20RMz2o19mBpt8UJCCdzV/qNtjScJvOTdAvvoZmboyM7Rmn4GG03/hq9@CwJohAEAAZPzMK1Y8NObr3CRaexiBWzIORI05azDlnA/fipMVPJj@zuGVKah/LE4IhuI46iZ4zkCwUf6nR6IIvRbxaFjw2kq11Rp65iFYsku6oh6AdluRR1L5dKfpSzGbyaBUYzgslioRTtLu6QUuEsibMEDjUtk6KXBFkmKTm1GpW6PBE0KmnUJIJGa7SiCTUO5IKROlQlkQoiAeLQ9/gTj9KViJKp0I9UaJmwFMvCF1kfiX1UdtUeoTKqy4icRgFLeCfhLHj28XnR4r39LwoTiB5piqmu@ZkM8Mfq2QTH4RouM0tXPHjY@l/I90wTrsXA2b@KNc5CZUYz@xcxjiN/ej/yHpS6VQky2XvZiOMK7k@6Uyb9/g8 "Perl 5 – Try It Online") My ungolfed version with the ten tests from @Veskah (OP), tests passes: ``` sub co { #combat my($p1,$t1,$a1, $p2,$t2,$a2)=@_; #p=power, t=toughness, a=abilities $a1=~s/F// and $a2=~s/F// if "$a1$a2"=~/F.*F/; #both F, no F return co($p1,2e9,$a1=~s/F//r, $p2,$t2,$a2 ) if $a1=~/F/ && $a2!~/I/; return co($p1,$t1,$a1, $p2,2e9,$a2=~s/F//r) if $a2=~/F/ && $a1!~/I/; $p1=1e9 if $a1=~/D/ and $p1>0; $p2=1e9 if $a2=~/D/ and $p2>0; $t1=3e9 if $a1=~/I/; $t2=3e9 if $a2=~/I/; $t1-=$p2; $t2-=$p1; $t1<=0 && $t2<=0 ? "Both Die" :$t1<=0 ? "1st Dies" :$t2<=0 ? "2nd Dies" : "Neither Die" } my @test=map{[/Input: .*? (\d+),(\d+)(?:,\s*"([FDI]+)")? .*? (\d+),(\d+)(?:,\s*"([FDI]+)")? .*? Output: \s* (1st.Dies|2nd.Dies|Both.Die|Neither.Die)? /xsi]} split/\n\n/,join"",<DATA>; my $t=0; for(@test){ $t++; my $r=co(@$_);#result $r=~s,0,Neither Die,; $r=~s,3,Both Die,; print $$_[-1]=~/^$r/ ? "Ok $t\n" : "Not ok, combat $t --> $r, wrong! (".join(",",@$_).")\n" } __DATA__ Input: [[2,2], [1,1]] Output: 2nd Dies Input: [[0,2], [0,1]] #0/2 vs 0/1 Output: Neither Die Input: [[2,1], [2,1]] #2/1 vs 2/1 Output: Both Die Input: [[1,1, "D"], [2,2]] #1/1 Deathtoucher vs 2/2 Output: Both Die Input: [[2,2], [0,1, "D"]] #2/2 vs 0/1 Deathtoucher Output: 2nd Dies Input: [[2,2], [1,1, "DF"]] #2/2 vs 1/1 First-strike, Deathtoucher Output: 1st Dies Input: [[2,2], [2,2, "F"]] #2/2 vs 2/2 First-striker Output: 1st Dies Input: [[2,2, "I"], [1,1, "DF"]] #2/2 Indestructible vs 1/1 First-strike, Deatht. Output: 2nd Dies Input: [[99999,99999], [1,1, "I"]] #99999/99999 vs 1/1 Indestructible Output: Neither Die Input: [[2,2, "F"], [1,1, "F"]] #2/2 First-Striker vs 1/1 First-Striker Output: 2nd Dies ``` [Answer] # JavaScript, ~~137~~ ~~125~~ ~~120~~ 111 bytes ``` i=>(k=(a,b)=>!(b[2]%2)&&a[0]/(a[2]<=3)>=b[1],[c,d]=i,g=c[2]&2,h=k(c,d),j=k(d,c),d[2]&2-g&&(g?h&&2:j&&1)||j+2*h) ``` I am using bitmap numbers for abilities D=4 F=2 I=1 do `"DFI"` would be `7`. My output is Neither Died `0`, 1st Died `1`, 2nd Died `2`, Both died `3`. Tests with: ``` f([[2, 2, 0], [1,1, 0]]); // 2 f([[0, 2, 0], [0,1, 0]]); // 0 f([[2, 1, 0], [2,1, 0]]); // 3 f([[1, 1, 4], [2,2, 0]]); // 3 f([[2, 2, 0], [0,1, 4]]); // 2 f([[2, 2, 0], [1,1, 6]]); // 1 f([[2, 2, 0], [2,2, 2]]); // 1 f([[2, 2, 1], [1,1, 6]]); // 2 f([[99999, 99999, 0], [1,1, 1]]); // 0 f([[2, 2, 2], [1,1, 2]]); // 2) ``` This was my my first working code ``` const kills = (c1, c2) => { // Return true if c1 kills c2 if (c2[2] % 2) { console.log("Indestructible"); return false; } const c1p = c1[0] / (c1[2] <= 3); // Infinity if Deathtoucher && P > 0 const c2t = c2[1]; return c1p >= c2t; } const f = (input) => { console.log("Match:", input); const [c1, c2] = input; const f1 = (c1[2] & 2); const f2 = (c2[2] & 2); if (f2 !== f1) { if (f1) { if (kills(c1, c2)) { console.log("c1 killed c2 in first round"); return 2; } } else { if (kills(c2, c1)) { console.log("c2 killed c1 in first round"); return 1; } } } return kills(c2, c1) + 2 * kills(c1, c2); }; ``` Which I reduced to this intermediate: ``` const f = i => { const k = (a, b) => !(b[2] % 2) && a[0] / (a[2] <= 3) >= b[1]; const [c, d] = i; const g = c[2] & 2; const h = k(c, d); const j = k(d, c); return d[2] & 2 - g && (g ? h && 2 : j && 1 ) || j + 2 * h } ``` [Answer] # JavaScript (ES6), ~~83~~ 76 bytes Takes input as 6 distinct arguments: 2 x (Power, Toughness, Abilities). Abilities are expected as bitmasks with: * \$1\$ = Death Touch * \$2\$ = First Strike * \$4\$ = Indestructible Returns \$0\$ for *Neither Die*, \$1\$ for *1st Dies*, \$2\$ for *2nd Dies* or \$3\$ for *Both Die*. ``` (p,t,a,P,T,A)=>(x=A<4&&p>=T|a&!!p)&(y=a<4&&P>=t|A&!!P)&&(a^A)&2?a+2>>1:x*2+y ``` [Try it online!](https://tio.run/##lZJRb4IwFIXf@RX1pYHZTWh82VhZUFgkLo5ofV3SKE4WA0SaBRP@OwMcE3CA3NykzXn4es69/WLfLNwc3YDfe/7WSXYkEQPEEUM2okiXiCZGRH8eQxhohMYMDgaBBMUTYZlma4THeqrZEoQi@9AliF/YEGua8hTd4eEpMUydzuj7ejoDWREgR4oqvFrLFV3RpTU3CxWrgrUwzFRcT6k1eTNzdawKwsb3Qv/gPBz8T3EnYgTSlhFQ8pYlCdxSoxHA3hYYrhPWgHIBlPsCF47L984xg16bVHIg7suc@Hz/D/Ac9jLMnIw7yc1AXE19IXcCG8ZY20tp7zEorbuOT4FKyFuB50sLoxew@slusNsc@TErBH6Pv@jVF67Ndv2catiC2p6/ZDL5AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` (p, t, a, P, T, A) => // (p, t, a) = arguments for the first player (P1) // (P, T, A) = arguments for the second player (P2) ( x = // x is a flag which means 'P1 can kill P2', // regardless of the 'First Strike' abilities A < 4 && // it is set to 1 if P2 is not Indestructible and: p >= T | // the power of P1 is greater than or equal to the toughness of P2 a & !!p // or the power of P1 is not zero and P1 has the Death Touch ) & // ( y = a < 4 && // y is the counterpart of x and is computed the same way P >= t | // A & !!P // ) && // if both x and y are set (a ^ A) & 2 ? // and exactly one player has the First Strike: a + 2 >> 1 // return 2 if P1 has the First Strike, or 1 otherwise : // else: x * 2 + y // return the default outcome: x * 2 + y ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~114~~ ~~113~~ 95 bytes A lot of golfing thanks to ceilingcat and Logern. ``` g(Z{return F&1|F&4&&!(f&4||P<t)||!(f&2)&T>p;} f(Z{return g(Z+2*g(p,t,f,P,T,F);} ``` Compile with `-DZ=P,T,F,p,t,f)`. [Try it online!](https://tio.run/##rVKxboMwEN39FVekWJAcSiAkqkSTqcqcIVOphxQwsZSSCDtdgF8vtd1QyN7TDe89vXu2T079Ik27rnDf6ipXt6qEHQ2aHY0ofXI5jZpm/6K8pjEk9Ohhe41bwge3HpyF08K9okKOezzgzovbbj4HGsAGRJkh0FCjTGkQacAlEaUClUslE5asmdZqUi8QQoSFbQNaJHWAEFjhDgZN96rXwIqrkTG0YthP/4Kodz70ELnsteVde0ZYW8EArZHaD/CxW9LGJD0dK5hClcvb2TzJvMf5uKgTZCJ3EByZp5cyM0waykUl1R@zxrP4yh0d9XkUJbievicQ0MUvFbhmW0KHLuL70gRLFgy2VhGzmWetuq6VtnJwnSSZZGCbIQyYgb@FiXwv9bn9jKlRKg4kGJNwTJZjEo3Jij0m9zvh7n@e4TEvBtJ23yk/HwvZ@a9vG/vz0P5C7wc "C (gcc) – Try It Online") We check (independently, because of the symmetry of combat mechanics) whether each of creatures survives the combat, which happens if either is true: * the creature is indestructible; * the creature has first strike AND the other one does not AND its power is greater or equal to other's toughnes (therefore we may disregard other's death touch); * other creature does not have death touch AND its power is less than our toughness. (The former conditions are more important). The inputs are power and toughness as integers, and abilities as a bitfield (1 = Indestructible, 2 = Death touch, 4 = First strike), the output is also a bitfield (1 = First creature survives, 2 = Second creature survives). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 123 bytes ``` \d+ $* (.*1)(.*;)(.*1) $3$2$1 F(.*)F $1 1+D 1 1*(,1+)I $1 (1+)(F?;1*,)(1+) $3$2$1 (1*)1*,\1(1+)? $#2 0(F)?;0(F)? $#1;$#2 F ``` [Try it online!](https://tio.run/##NYuxDgIxCIZ3XsOaQNuYA6dLhy4Npu9wgyY6uDgY379CPQd@Pj7g/fg8X7dxxMt1bPcEIQKeIpNFoUkQzkECg9pECkacGlhGzJyou0ED1Fo4ZnL@/yBHMrexywrhILCgUi0zbebiTmEMyVI4MyzWF@uSuViBuWYgIL9Fg/2y6SSrCX13a16dujt10i8 "Retina 0.8.2 – Try It Online") Link includes test cases, although I've substituted `9` for `99999` for speed. Input uses the letters `DFI` although `D` must precede `I`. Output is in the format `1` for survives and `0` for dies. Explanation: ``` \d+ $* ``` Convert the stats to unary. ``` (.*1)(.*;)(.*1) $3$2$1 ``` Exchange the stats temporarily. ``` F(.*)F $1 ``` Two `F`s cancel out. ``` 1+D 1 ``` Death Touch lowers the opponent's Toughness to 1. ``` 1*(,1+)I $1 ``` Indestructable lowers the opponent's Power to 0. ``` (1+)(;1*,)(1+) $3$2$1 ``` Switch the Toughness back, so now you have P2,T1,F1;P1,T2,F2 ``` (1*)1*,\1(1+)? $#2 ``` If the Toughness is higher than the opponent's Power then it survives. ``` 0(F)?;0(F)? $#1;$#2 ``` If both would die, the one with First Strike survives. ``` F ``` Otherwise First Strike makes no difference. [Answer] ## C++, 177 131 127 121 bytes Here's my not so short solution in C++. Abilities are 3 bits for each creature: 1. D = 0x1 (0001) 2. F = 0x2 (0010) 3. I = 0x4 (0100) And it simply returns ***0***: if nobody dies, ***1***: if the first creatures dies, ***2***: if the second creature dies and ***3***: if both creatures die. ``` [](int p,int t,int a,int r,int k,int b){return(a&2&&b^4)^(b&2&&a^4)?1+(a&2):((t<r||b&1&&r)&&a^4)+((k<p||a&1&&p)&&b^4)*2;} ``` [Try it Online!](https://tio.run/##ldPvS4NAGAfw9/dXPDiQu2Z0d62gzQpCBAnqTe@WgXO3ksqJ3iDI/vZ1P5qtpcMd8ng/Nj48XzUtiuPnNF0Psjx9W80F@NmykqVI3q9Qlkt4T7IcE/hEyUouYQGXsJ7GWJ8Unq7S1MTU0tRXU2fksxRyVeY4cbnrzp5G5AnP9DRR02s21PtkjLH0y7qeucx1S2IPhxi/@kVdJ3qzIPbPR3zytZ4gNJiLRZYLCIB@sGYVqhVvVpFajRCq5Hw8TpcrCb4PC8w9UBf1gJmLEtgMdew85s4ETk5gwOBBVHIM0yn3eOzBlHksjuHvOL4Cns8hyERlNzjg@1uyS9INSfeSvCGpJWk7eScy@SJKzaoN2kpyKxl4D3m61SXTJG8nb5by5cdT47SVtHkGhuTd5KghVaIeOIFjXb7t9iT532CDDvJs91nSjRwf/Cx3Xp@gDkkbed7y@mgy3DYVySq5RbL9pJ2EHV3@I9VNkeFul/3J6KAulRU5La32DPZCDw9@bk3AEeki7S9N/VUjg/b/SHSeG6pXsDbRxmvS7eoSoS@0/gY) ## C++, 85 81 bytes (Alternative) By slightly cheating and capture the variables in lambda and not pass them as arguments it is possible to get down to 81 bytes. I don't know if that's an acceptable solution so I post it as an alternative. ``` [&]{s=(a&2&&b^4)^(b&2&&a^4)?1+(a&2):((t<r||b&1&&r)&&a^4)+((k<p||a&1&&p)&&b^4)*2;} ``` [Try it Online!](https://tio.run/##rdPRSsMwFAbg@zzFoYOSasQkTsG1VZBSKILeeDc7aLtOi9qVNgPB@uwzabe4acvmMBdZTkabj/@kSVGcPCXJcpDlyetimoKTzStRptHbFcpyAW9RlmMLPpqiICAIRARKAi8EYgKVjaKFmMMMXFiOzfCjcnFkctOMJ0NrgmO1jOTymh2rfWuEsXDKuo5NZpql1f55jPGLU9R1pDYLq334iNufSxuhwTSdZXkKHtB3pitfVlxXgayGCBUul0A1RS6VSJdJpppil9ozbNmVmI5GyXwhwHGggvWQhfGYGzacnsKAwUNaiRGMx5zwkMCYERaGsD1OroDnU/CydPUWDvj@1pICui2gBwi4FtBWQLsFd2kmntNSKeQGXQuaDJgW8AMEZxsZMCXg3YKbuXheHS/H2VrAtMDTAv43wVALZPwEDM9oGXyT0S/gfV3w9hac/7wHdA0J97kHvTfRq/1@w5bgouMmKoG/SZACVokNAesRfHfB3zuDXwL5IwX@zwx2CoJ/yUAeHRgdQfR34VINpVgtfnUj6HL0CNp3NPM3ImgMO77GJgN/@@QDu9DGr4/XrejLAKFPtPwC) [Answer] # Perl 5, 245 bytes ``` $F[0]*=$F[4]if$F[2]=~/D/;$F[3]*=$F[1]if$F[5]=~/D/;$F[3]=0 if$F[2]=~/I/;$F[0]=0 if$F[5]=~/I/;$F[4]-=$F[0]if$F[2]=~/F/;$F[1]-=$F[3]if$F[5]=~/F/;if($F[1]>0&&$F[4]>0){$F[4]-=$F[0]if$F[2]!~/F/;$F[1]-=$F[3]if$F[5]!~/F/}$_=(0+($F[1]<=0)).(0+($F[4]<=0)) ``` Run with `-lapE` Ungolfed: ``` # Takes input in one lines, of the form: # PPP TTT "<abilities>" PPP TTT "<abilities>" $F[0] *= $F[4] if $F[2] =~ /D/; $F[3] *= $F[1] if $F[5] =~ /D/; $F[3] = 0 if $F[2] =~ /I/; $F[0] = 0 if $F[5] =~ /I/; $F[4] -= $F[0] if $F[2] =~ /F/; $F[1] -= $F[3] if $F[5] =~ /F/; if ($F[1] > 0 && $F[4] > 0) { $F[4] -= $F[0] if $F[2] !~ /F/; $F[1] -= $F[3] if $F[5] !~ /F/; } $_ = (0+ ($F[1] <= 0)) . (0+ ($F[4] <= 0)); ``` "Deathtouch" translates to "your power is now multiplied by your enemy's toughness", and "indestructible" translates to "your enemy's power is now zero", with the latter taking precedent. The code runs two rounds, one where only the first-strikers get to attack, and the other where only non-first-strikers can attack. If the first round results in a death, the second round doesn't happen. Since we already dealt with the deathtouch and indestructible at the beginning, "death" is as simple as checking whether toughness is greater than zero or not. ]
[Question] [ This is a [quine](/questions/tagged/quine "show questions tagged 'quine'") variation. ## Introduction We all write short code, because [some obscure reasons](https://i.stack.imgur.com/0DDnF.png), but whatever we do, the'll take up at least 144 pixels/byte (with a 12px font). But what would happen, if we would encode our code in images? This is your task today. ## Challenge You task is to read in your own source code (non-proper quines are allowed, e.g. literally reading the source file), and create an image out of it, by setting the red, green and blue components of a pixel based on the ASCII value of the character. Example: We have the string "Hello world!" ``` Hello world! ``` Let's convert this to ASCII values: ``` 72 101 108 108 111 32 119 111 114 108 100 33 ``` Map the RGB values to it (If the source code's length is not divisible by 3, use 0s as the remaining characters): ``` __________________________________________________ | R | G | B || R | G | B || R | G | B || R | G | B | ---------------------------------------------------- |72 |101|108||108|111|32 ||119|111|114||108|100|33 | ---------------------------------------------------- ``` We then create the image with the smallest area out of it. We have 4 sets of RGB values, so the smallest image will be a 2\*2 image, going from the top left pixel to the right: [![enter image description here](https://i.stack.imgur.com/0DDnF.png)](https://i.stack.imgur.com/0DDnF.png) And we get this awfully colored image (resized, so it's at least visible, also proves the fact how small it can get) ## Rules/Additional information * There's no input * The output should be as a separate file, or in a separate window. * For multibyte characters, split the character in 2 bytes. * The source code must be at least 1 byte long * The image should be the one from the possible sizes, wich has the closest width/height ratio to 1 * The pixel count on the image should exactly be ceil(byte count / 3), no extra pixels should be added ## Scoring This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the smallest answer in bytes wins. [Answer] # MATLAB, ~~81~~ ~~72~~ 69 bytes ``` @()image(shiftdim(reshape(evalin('base','char(ans)'),3,1,23)/255,1.)) ``` This creates an anonymous function which can be pasted into the command window and run using `ans()`. When run this creates a 23-pixel image (a prime) therefore the most square representation is a simple array of pixels. [![enter image description here](https://i.stack.imgur.com/J4vKx.png)](https://i.stack.imgur.com/J4vKx.png) **Explanation** When pasted into the command window, the anonymous function will automatically assign itself to the variable `ans`. Then from within the anonymous function, we use: ``` evalin('base', 'char(ans)') ``` which evaluates `char(ans)` within the namespace of the command window rather than within the local namespace of the anonymous function. It is therefore able to convert the anonymous function itself into a string representation. Then we have the following operations which are more straightforward: ``` %// Reshape the result into a 3 x 1 x 23 matrix where the first dimension is RGB %// due to column-major ordering of MATLAB R = reshape(string, 3, 1, 23); %// Divide the result by 255. This implicitly converts the char to a double %// and in order for RGB interpreted properly by MATLAB, doubles must be %// normalized between 0 and 1. R = R / 255; %// Shift the dimensions to the left 1 to move the RGB channel values into %// the third dimension. Note the extra decimal point. This is because it %// is far shorter to lengthen the code by one byte than to pad the string %// to give us a length divisible by 3 R = shiftdim(R, 1.); %// Display the RGB image image(R); ``` [Answer] ## Javascript(ES6) ~~324~~ ~~312~~ 309 Bytes I'm sure this could be golfed a bit: ``` f=()=>{s="f="+f;l=s.length/3;c=document.createElement('canvas');for(i=0;++i<l/i;l%i?0:w=i,h=l/w);c.s=c.setAttribute;c.s("width",w);c.s("height",h);(i=(t=c.getContext('2d')).createImageData(w,h)).data.map((a,b)=>i.data[b]=b%4<3?s.charCodeAt(b-~~(b/4)):255);t.putImageData(i,0,0);open(c.toDataURL('image/png'))} ``` * creates a canvas * builds image in it * Opens data url for image in new tab New lines for readability: ``` f=()=>{ s="f="+f;l=s.length/3; c=document.createElement('canvas'); for(i=0;++i<l/i;l%i?0:w=i,h=l/w); c.s=c.setAttribute; c.s("width",w); c.s("height",h); (i=(t=c.getContext('2d')).createImageData(w,h)).data.map((a,b)=>i.data[b]=b%4<3?s.charCodeAt(b-~~(b/4)):255); t.putImageData(i,0,0); open(c.toDataURL('image/png')) } ``` ### Output [![JavaScript](https://i.stack.imgur.com/QYRrF.png)](https://i.stack.imgur.com/QYRrF.png) [Answer] # Javascript ES6 - 216 bytes ``` f=( )=>((d=(x=(v=document.createElement`canvas`).getContext`2d`).createImageData(v.width=9,v.height=8)).data.set([..."f="+f].reduce((p,c,i)=>(c=c.charCodeAt(0),[...p,...i%3<2?[c]:[c,255]]))),x.putImageData(d,0,0),v) ``` Ungolfed: ``` f=( )=>( // define function f (extra spaces to account for missing pixel + alpha channel calculation) (d=(x=(v=document.createElement`canvas`). // assign html5 canvas to v getContext`2d`). // assign graphics context to x createImageData(v.width=9,v.height=8)). // create & assign ImageData to d // set width and height of both d and v data.set([..."f="+f]. // get f's source, convert to array of chars reduce((p,c,i)=>(c=c.charCodeAt(0), // convert char array to int array [...p,...i%3<2?[c]:[c,255]]))), // insert alpha values 255 x.putImageData(d,0,0), // draw source RGBA array to canvas v) // return canvas ``` Note: `f` returns a canvas. Example run (assumes there's a `<body>` to append to): ``` document.body.appendChild(f()) ``` Should dump the following image to the page (enlarged): [![QuineImage](https://i.stack.imgur.com/hkVQ9.png)](https://i.stack.imgur.com/hkVQ9.png) [Answer] ## PowerShell v4, 64 bytes ``` "P6 11 2 255"+[char[]](gc $MyInvocation.MyCommand.Name)|sc a.ppm ``` It gets the content of its own filename, casts the string as a char array, adds some PPM header and sets the content to a.ppm as output. 64 bytes makes it 11x2 pixels: [![PowerShell source encoded as picture](https://i.stack.imgur.com/8y3RM.png)](https://i.stack.imgur.com/8y3RM.png) [Answer] ## Actually, 12 bytes ``` Q"P6 4 1 255 ``` [Try it online!](http://actually.tryitonline.net/#code=USJQNiA0IDEgMjU1&input=) This program also works in Seriously. This program outputs a [PPM image](http://netpbm.sourceforge.net/doc/ppm.html), which is [acceptable by default](http://meta.codegolf.stackexchange.com/a/9095/45941). Output image (scaled up 50x): [![output](https://i.stack.imgur.com/i6O47.png)](https://i.stack.imgur.com/i6O47.png) Explanation: ``` Q"P6 4 1 255 Q push source code "P6 4 1 255 push header for a 4x1 raw (type P6) 8-bit PPM image (the closing " is implicitly added at EOF) ``` [Answer] # Node.js, 63 bytes ``` (F=x=>require('fs').writeFile('P6','P6 7 3 255 (F='+F+')()'))() ``` Outputs image into a file named `P6` which is in the [PPM](https://en.wikipedia.org/wiki/Netpbm_format) (P6) format. Here's a PNG rendition (7x3 pixels): [![enter image description here](https://i.stack.imgur.com/XQmIT.png)](https://i.stack.imgur.com/XQmIT.png) [Answer] ## Java 511 chars The length of the solution leads to a greater picture which is cool, because these pictures are really nice. ``` import java.awt.image.*;import java.io.*;import java.nio.file.*;import javax.imageio.*; public class Q{public static void main(String[]a)throws Throwable{int w=19,h=9;byte[]e=Files.readAllBytes(Paths.get("Q.java"));String t=new String(e);while(t.length()%3!=0)t+='\0';BufferedImage I=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);int r,c=r=0;for(int i=0;i<t.length();i++){I.setRGB(c,r,255<<24|t.charAt(i)<< 16|t.charAt(++i)<< 8|t.charAt(++i));if(++c==w){c=0;r++;}}ImageIO.write(I,"png",new File("Q.png"));}} ``` Note that there is an invisible trailing newline! It reads the source file, which has to be "Q.java" and creates a picture "Q.png" which looks like this: [![The image generated by the code](https://i.stack.imgur.com/K44iv.png)](https://i.stack.imgur.com/K44iv.png) or scaled 100x [![enter image description here](https://i.stack.imgur.com/zBohT.png)](https://i.stack.imgur.com/zBohT.png) [Answer] ## PHP, 226 bytes **Golfed** ``` <?$b=strlen($w=join(file('p.php')));$z=imagecreatetruecolor(5,15);for($c--;++$c<$b+1|$i%3;$i%3?:$a=!imagesetpixel($z,$x%5,(int)$x++/5,$a))$a+=($c<$b?ord($w[$c]):0)*256**(2-$i++%3);header("Content-Type:image/png");imagepng($z); ``` **Ungolfed version** ``` <? // Read the file into an array and join it together. Store the length of the resulting string. $b=strlen($w=join(file('p.php'))); // Create the image. Our file is 226 bytes, 226/3 = 75 = 5 * 15 $z=imagecreatetruecolor(5,15); // Loop through the script string, converting each character into a pixel. // Once three characters have been converted, draw the pixel with the converted RGB value and reset the color to 0. for($c--;++$c<$b+1|$i%3;$i%3?:$a=!imagesetpixel($z,$x%5,(int)$x++/5,$a))$a+=($c<$b?ord($w[$c]):0)*256**(2-$i++%3); // Tell the program we're sending an image header("Content-Type:image/png"); // And send it! imagepng($z); ``` Enter this script into a file named 'p.php' and run it. You need your own method of running PHP script, because this reads from a local file. Output image: ![color coded](https://i.stack.imgur.com/Hvg6a.png) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 33 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429) Requires `⎕IO←0` which is default on many systems. Also, AutoFormat should be off to preserve the program exactly as given. ``` (⊂⎕NPUT⊃)'P',⍕⎕AV⍳'␍ɫ␉⍣',⊃⌽⎕NR'f' ``` Hex B9 BA FD 4E 50 55 54 BB F8 0D 50 0D C2 CD FD 41 56 B2 0D 03 0B 01 FF 0D C2 BB C8 FD 4E 52 0D 16 0D Unicode 28 2282 2395 4E 50 55 54 2283 29 27 50 27 2C 2355 2395 41 56 2373 27 0D 026B 08 2363 27 2C 2283 233D 2395 4E 52 27 66 27 Creates `P`: P3 11 1 255 185 186 253 78 80 85 84 187 248 13 80 13 194 205 253 65 86 178 13 3 11 1 255 13 194 187 200 253 78 82 13 22 13 Which you save and drop [here](http://paulcuth.me.uk/netpbm-viewer/) to see: [![code image](https://i.stack.imgur.com/uJWDY.png)](https://i.stack.imgur.com/uJWDY.png) `⎕NR'f'` **N**ested **R**epresentation of the program *f* `⊃⌽` pick the last (lit. first of the reversed) element (line) `'␍ɫ␉⍣',` prepend the four characters (filetype, width, height, max) `⎕AV⍳` find corresponding indices in the **A**tomic **V**ector (the character set `⍕` format as text `'P',` prepend a letter `(`…`)` apply the following tacit function:  `⊂` take the entire argument [and into a]  `⎕NPUT` **N**ative [file,] **Put** [it, with a filename consisting of]  `⊃` the first character ("P") [Answer] # Processing, 193 bytes ``` byte a[]=loadBytes("s.pde");noStroke();int x=0,y=0;for(int k=0;k<a.length%3;k++){append(a,byte(0));}for(int i=0;i<a.length-2;i+=3,x++){if(x>0){x=0;y+=1;}fill(a[i],a[i+1],a[i+2]);rect(x,y,1,1);} ``` ## Original [![enter image description here](https://i.stack.imgur.com/qOTEm.png)](https://i.stack.imgur.com/qOTEm.png) ## Resized [![enter image description here](https://i.stack.imgur.com/mFAXK.png)](https://i.stack.imgur.com/mFAXK.png) Even with Processing's builtins, this was very difficult. [Answer] # Python, 81 bytes ``` q=open(__file__).read() print'P3\n9 3 256 '+' '.join(map(lambda x:str(ord(x)),q)) ``` Output is in PPM format. This is what the image looks like: [![Image](https://i.stack.imgur.com/lraNa.png)](https://i.stack.imgur.com/lraNa.png) Scaled up: [![Scaled up](https://i.stack.imgur.com/8Biww.png)](https://i.stack.imgur.com/8Biww.png) ]
[Question] [ # Challenge ¡We're going to give exclamation and question marks inverted buddies! Given a body of text containing sentences ending in `.`, `?`, or `!`, prepend inverted question marks, `¿`, to interrogative sentences (sentences ending in `?`) and inverted exclamation marks, `¡`, to exclamatory (sentences ending in `!`). Sentences ending in `.` are to be ignored. Sentences will be separated by whitespace (spaces, tabs, and/or newlines) and will only contain alphanumerics, commas, apostrophes, and spaces. Every sentence will have at least one word. The first word of every sentence is guaranteed to be capitalized. Input can start and end with any whitespace. ## Example Input: ``` Hello there! What is your name? My name is Ron. What's your name? My name is Alex. Nice to meet you! Nice to meet you to! How was your break? It was great, I spent all my time code golfing! What's that? Wow, you're such a n00b! Here, let me show you. ``` Output: ``` ¡Hello there! ¿What is your name? My name is Ron. ¿What's your name? My name is Alex. ¡Nice to meet you! ¡Nice to meet you to! ¿How was your break? ¡It was great, I spent all my time code golfing! ¿What's that? ¡Wow, you're such a n00b! Here, let me show you. ``` ## Rules * All default Code Golf rules apply. * The program with the shortest amount of bytes wins. # Bonus (17% off) - Parse multiple marks A sentence can also end in multiple exclamation/question marks. Give each of these marks a paired inverse exclamation/question mark for an extra 17% off your byte count. ## Example Input: ``` I am a man in a can doing a dance?? Maybe... Doing it for the views??!???! ``` Output: ``` ¿¿I am a man in a can doing a dance?? Maybe... ¡¿¿¿¡¿¿Doing it for the views??!???! ``` *Incorrect* output: ``` ¿¿I am a man in a can doing a dance?? Maybe... ¿¿¡¿¿¿¡Doing it for the views??!???! ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~39~~ ~~37~~ 34 bytes ``` \w[^.]*?([!?]) $1$0 T`?!`¿¡`\S\b ``` [Try it online.](http://retina.tryitonline.net/#code=XHdbXi5dKj8oWyE_XSkKJDEkMApUYD8hYMK_wqFgXFNcYg&input=ICAgSGVsbG8gdGhlcmUhICAgICAgV2hhdCBpcyB5b3VyIG5hbWU_Ck15IG5hbWUgaXMgUm9uLiBXaGF0J3MgeW91ciBuYW1lPwpNeSBuYW1lIGlzIEFsZXguICBOaWNlIHRvIG1lZXQgeW91IQpOaWNlIHRvIG1lZXQgeW91IHRvISAgSG93IHdhcyB5b3VyIGJyZWFrPwpJdCB3YXMgZ3JlYXQsIEkgc3BlbnQgYWxsIG15IHRpbWUgY29kZSBnb2xmaW5nIQpXaGF0J3MgdGhhdD8KICAgICAgICBXb3csIHlvdSdyZSBzdWNoIGEgbjAwYiEgSGVyZSwgbGV0IG1lIHNob3cgeW91LgpBLiBCPyBDLiBEIQ) ### Explanation ``` \w[^.]*?([!?]) $1$0 ``` This matches a sentence ending in an exclamation or question mark, and prepends that punctuation character to the sentence. Now we know that all the `!` or `?` which are immediately followed by a non-space character must be those we inserted, because the original ones should be separated from the next character by a space. ``` T`!?`¡¿`\S\b ``` This transliteration stage turns all `!` and `?` into `¡` and `¿`, respectively, provided they're found in a match of `\S\b`, which applies only to the ones we just inserted. Replacing both in two separate substitutions in the same byte count, but I prefer the semantics of a transliteration stage here. [Answer] # Mathematica 137 bytes Not the shortest, but it was fun to do. `TextSentences` breaks up the input text into sentences and `StringPosition` finds the beginning and end positions of each sentence in the text. The upside down punctuation is inserted at the beginning of each sentence as required. ``` w=StringPosition;f[x_,y_,q_]:=StringInsert[x,q,x~w~y/.{a_,a_}->a/.(x~w~#&/@TextSentences@#&@x/.{{c_,d_}}:>d->c)];f[f[t,"!","¡"],"?","¿"]& ``` --- Usage, assuming the text is input at `t`, ``` f[f[#,"!","¡"],"?","¿"]&[t] ``` [![output](https://i.stack.imgur.com/SQZjC.png)](https://i.stack.imgur.com/SQZjC.png) [Answer] # Sed, 61 bytes ``` s/\(\s*\)\([^.!?]*!\)/\1¡\2/g;s/\(\s*\)\([^.!?]*?\)/\1¿\2/g ``` --- Test run : ``` $ echo """Hello there! What is your name? My name is Ron. What's your name? My name is Alex. Nice to meet you! Nice to meet you to! How was your break? It was great, I spent all my time code golfing! What's that? Wow, you're such a n00b! Here, let me show you.""" | sed 's/\(\s*\)\([^.!?]*!\)/\1¡\2/g;s/\(\s*\)\([^.!?]*?\)/\1¿\2/g' ¡Hello there! ¿What is your name? My name is Ron. ¿What's your name? My name is Alex. ¡Nice to meet you! ¡Nice to meet you to! ¿How was your break? ¡It was great, I spent all my time code golfing! ¿What's that? ¡Wow, you're such a n00b! Here, let me show you. ``` [Answer] ## Javascript (ES6), ~~86~~ ~~79~~ ~~66~~ 63 bytes ``` i=>i.replace(/\w[^.!?]*[!?]/g,k=>(k.slice(-1)>'>'?'¿':'¡')+k) ``` Ungolfed: ``` func = inp => inp.replace(/\w[^.!?]*[!?]/g, sentence => (sentence.slice(-1) > '>' ? '¿' : '¡') + sentence) ``` Usage: ``` console.log(func(`Hello there! What is your name? My name is Ron. What's your name? My name is Alex. Nice to meet you! Nice to meet you to! How was your break? It was great, I spent all my time code golfing! What's that? Wow, you're such a n00b! Here, let me show you.`)) ``` Will implement bonus solution soon. *Thanks to: [@user81655](https://codegolf.stackexchange.com/users/46855/user81655), [86 => 79 bytes](https://codegolf.stackexchange.com/q/65719/#comment-159181)* [Answer] ## Mathematica, ~~101~~ ~~92~~ 91 bytes ``` StringReplace[#,RegularExpression@"[A-Z][^.]*?([?!])":><|"?"->"¿","!"->"¡"|>@"$1"<>"$0"]& ``` [Answer] # Python 2, 127.82 (154-17%) bytes ``` import re print re.sub("([A-Z][\w ,']*)([\.!\?]+)",lambda m:''.join({'!':'¡','?':'¿','.':''}[c]for c in m.group(2))[::-1]+m.group(1)+m.group(2),input()) ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 36 chars / 53 bytes ``` ïċ/\w⁅.!?]*[!?]⌿,⇏(aē-1>⍘>?⍘¿:⍘¡)+a) ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=My%20name%20is%20Ron.%20What%27s%20your%20name%3F&code=%C3%AF%C4%8B%2F%5Cw%E2%81%85.!%3F%5D*%5B!%3F%5D%E2%8C%BF%2C%E2%87%8F%28a%C4%93-1%3E%E2%8D%98%3E%3F%E2%8D%98%C2%BF%3A%E2%8D%98%C2%A1%29%2Ba%29)` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 41 bytes ``` 0ị⁾!?iị“¡¿ ”t⁶ e€“!?.”kµOe€“µ½ ‘«\nƝkjÇ)F ``` [Try it online!](https://tio.run/##dY8xTsNAEEVr9hR/qwjJsnwDiwYlBSDRpKHZmMF2st5F9kbGXUJDwQUoSEENbWgQIC0S98AXMWPLFRLTzN@nr/9nl6R103XRz9t9u/2Qcd6LzaN/8p9oNzvXbl8FtbcvzGQcMln5/dkI/N6/s@nBP1@Y791q@XV3eNx1HTDlUAuXUUkSw8wz5ZBXaOy6hFEFxeKkGURPz60JB8vkP8eRppsQOM0TgrMoiFzvlOIvYc2VU1ujVmPYoiS1isXMDSjllwswQ3VNxkFpjaKBy7knsZeE1Oqr3KRSjPc4XrE4mNs66OMmJaFaJxkUTBQtJP@1pACa2zmhyriYXeEv "Jelly – Try It Online") Bah, who needs regex? ## How it works ``` e€“!?.”kµOe€“µ½ ‘«\nƝkjÇ)F - Main link. Takes a string S on the left “!?.” - Yield "!?." € - For each character in S: e - Is it in "!?."? k - Split S after occurrences of any of "!?." µ - Call this list of lists of characters L and use it as the argument ) - For each list of characters C in L: O - Convert to a list of char codes “µ½ ‘ - Yield [9, 10, 32] € - For each char code in C: e - Is it in [9, 10, 32]? This yields 1s at whitespace characters else 0 However, we only want to consider leading whitespace, not whitespace in the string, when inserting ¡¿ \ - Scan: « - Minimum This changes all non-leading 1s to 0s Ɲ - Over overlapping pairs: n - Does not equal? This turns the leading run of 1s into 0s with a final 1 k - Split C at this 1 Ç - Call the helper link on C j - Join the split C on the helper link F - Flatten into a single string 0ị⁾!?iị“¡¿ ”t⁶ - Helper link. Takes a list of characters C on the left 0ị - Last character of C, c ⁾!? - "!?" i - Index of c in "!?" or 0 (for sentences ending with ".") “¡¿ ” - "¡¿ " ị - 1-index into this string. "." -> " " ⁶ - " " t - Trim spaces. "." -> "" ``` ]
[Question] [ ## The challenge This challenge is very straightforward. Given four 3-dimensional points, calculate the surface area of the tetrahedron that they form. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. Standard loopholes apply, with the added stipulation that any built-in function to do this task given four points is prohibited. You can assume all four points will be distinct, and will be given via STDIN, 1 point per line. Each point will consist of three 16-bit unsigned integers. The exact format of each point can be modified if it makes things easier, such as three space separated integers. Having each point on a separate line is mandatory however. Output should be through STDOUT, to at least 2 decimal places. For those of you who do not know, a [tetrahedron](http://en.wikipedia.org/wiki/Tetrahedron) is a 3-d solid, formed by 4 triangular faces. ### Example ``` # input (format is up to you, see clarification above) [23822, 47484, 57901] [3305, 23847, 42159] [19804, 11366, 14013] [52278, 28626, 52757] # output 2932496435.95 ``` Please leave a note if you notice my math is wrong. [Answer] ## Python, 198 178 161 chars ``` V=eval('input(),'*4) A=0 for i in range(4):F=V[:i]+V[i+1:];a,b,c=map(lambda e:sum((a-b)**2for a,b in zip(*e)),zip(F,F[1:]+F));A+=(4*a*b-(a+b-c)**2)**.5 print A/4 ``` The input format is as given in the question. It calculates the length of the edges adjacent to each of the faces and then uses [Heron's formula](http://en.wikipedia.org/wiki/Heron's_formula). [Answer] ## APL, 59 ``` f←{+.×⍨⊃1 2-.⌽(⊂⍵)×1 2⌽¨⊂⍺} .5×.5+.*⍨(f/2-/x),2f/4⍴x←⎕⎕⎕-⊂⎕ ``` Works by calculating cross products **Explanation** The first line defines a function that takes two arguments (implicity named `⍺` and `⍵`), implicitly expects them to be numerical arrays of length 3, treat them as 3d vectors, and calculates the **squared** magnitude of their cross product. ``` ⊂⍺ # Wrap the argument in a scalar 1 2⌽¨ # Create an array of 2 arrays, by rotating `⊂⍺` by 1 and 2 places (⊂⍵)× # Coordinate-wise multiply each of them with the other argument 1 2-.⌽ # This is a shorthand for: 1 2 ⌽ # Rotate the first array item by 1 and the second by 2 -. # Then subtract the second from the first, coordinate-wise ⊃ # Unwrap the resulting scalar to get the (sorta) cross product +.× # Calculate the dot product of that... ⍨ # ...with itself f←{+.×⍨⊃1 2-.⌽(⊂⍵)×1 2⌽¨⊂⍺} # Assign function to `f` ``` The second line does the rest. ``` ⎕⎕⎕-⊂⎕ # Take 4 array inputs, create an array of arrays by subtracting one of them from the other 3 x← # Assign that to x 4⍴ # Duplicate the first item and append to the end 2f/ # Apply f to each consecutive pair 2-/x # Apply subtraction to consecutive pairs in x f/ # Apply f to the 2 resulting arrays (f/2-/x),2f/4⍴x←⎕⎕⎕-⊂⎕ # Concatenate to an array of 4 squared cross products .5+.*⍨ # Again a shorthand for: .5 *⍨ # Take square root of each element (by raising to 0.5) +. # And sum the results .5× # Finally, divide by 2 to get the answer ``` [Answer] # Matlab/Octave 103 I assume the values to be stored in the variable `c`. This uses the fact that the area of a triangle is the half length of the cross product of two of its side vectors. ``` %input [23822, 47484, 57901; 3305, 23847, 42159; 19804, 11366, 14013; 52278, 28626, 52757] %actual code c=input(''); a=0; for i=1:4; d=c;d(i,:)=[]; d=d(1:2,:)-[1 1]'*d(3,:); a=a+norm(cross(d(1,:),d(2,:)))/2; end a ``` [Answer] # Python 3, ~~308 298 292 279 258~~ 254 ``` from itertools import* def a(t,u,v):w=(t+u+v)/2;return(w*(w-t)*(w-u)*(w-v))**.5 z,x,c,v,b,n=((lambda i,j:(sum((i[x]-j[x])**2for x in[0,1,2]))**.5)(x[0],x[1])for*x,in combinations([eval(input())for i in">"*4],2)) print(a(z,x,v)+a(z,c,b)+a(b,v,n)+a(x,c,n)) ``` This uses: * The Pythagorean Theorem (in 3D) to work out the length of each line * Heron's Formula to work out the area of each triangle [Answer] # Mathematica ~~168~~ 154 This finds the lengths of the edges of the tetrahedron and uses [Heron's formula](http://en.wikipedia.org/wiki/Heron%27s_formula) to determine the areas of the faces. ``` t = Subsets; p = Table[Input[], {4}]; f@{a_, b_, c_} := Module[{s = (a + b + c)/2}, N[Sqrt[s (s - #) (s - #2) (s -#3)] &[a, b, c], 25]] Tr[f /@ (EuclideanDistance @@@ t[#, {2}] & /@ t[p, {3}])] ``` --- There is a more direct route that requires only **60 chars**, but it violates the rules insofar as it computes the area of each face with a built-in function, `Area`: ``` p = Table[Input[], {4}]; N[Tr[Area /@ Polygon /@ Subsets[p, {3}]], 25] ``` [Answer] ## Sage – 103 ``` print sum((x*x*y*y-x*y*x*y)^.5for x,y in map(differences,Combinations(eval('vector(input()),'*4),3)))/2 ``` The input-reading part is adapted from [Keith Randall’s answer](https://codegolf.stackexchange.com/a/38510/11354). [Answer] ## Python - 260 I'm not sure what the etiquette on posting answers to your own questions is, but her is my solution, which I used to verify my example, golfed: ``` import copy,math P=[input()for i in"1234"] def e(a, b):return math.sqrt(sum([(b[i]-a[i])**2 for i in range(3)])) o=0 for j in range(4):p=copy.copy(P);p.pop(j);a,b,c=[e(p[i],p[(i+1)%3])for i in range(3)];s=(a+b+c)/2;A=math.sqrt(s*(s-a)*(s-b)*(s-c));o+=A print o ``` It uses the same procedure as laurencevs. [Answer] # C, 303 Excluding unnecessary whitespace. However, there's still a lot of golfing to be done here (I will try to come back and do it later.) It's the first time I've declared a `for` loop in a `#define`. I've always found ways to minmalise the number of loops before. I had to change from `float` to `double` to get the same answer as the OP for the test case. Before that, it was a round 300. `scanf` works the same whether you separate your input with spaces or newlines, so you can format it into as many or as few lines as you like. ``` #define F ;for(i=0;i<12;i++) #define D(k) (q[i]-q[(i+k)%12]) double q[12],r[12],s[4],p,n; main(i){ F scanf("%lf",&q[i]) F r[i/3*3]+=D(3)*D(3),r[i/3*3+1]+=D(6)*D(6) F r[i]=sqrt(r[i]) F i%3||(s[i/3]=r[(i+3)%12]/2),s[i/3]+=r[i]/2 F i%3||(p=s[i/3]-r[(i+3)%12]),p*=s[i/3]-r[i],n+=(i%3>1)*sqrt(p) ;printf("%lf",n); } ``` ]
[Question] [ Given a maze on stdin and an entry point, write a program that prints a path to the exit on stdout. Any path is acceptable, as long as your program does not generate the trivial path (passing through every point in the maze) for every maze. In the input, walls are marked by a `#` and the entry point by a `@`. You may use any characters to draw the maze and the path in the output, as long as they're all distinct. You may assume that: * The entry and exit points are on the edges of the input * Every line of the input has the same length * The maze is solvable and has no cycles * There is only one exit point Shortest solution by (Unicode) character count wins. ## Examples (note that the inputs are padded with spaces) ``` #### # # @ ##### # # # ####### #### # # @*##### #* # #****** ####### ### ################### ### # # ## ######### # # # ##### # ############### #@## ###*################### ###*********#*********# ## *#########* # *# # *********** #####**# ############### #@## ``` [Answer] **ANSI C (384 373 368 characters)** Here's my C attempt. Compiled and run on Mac OS X. ``` m[9999],*r=m,*s=m,c,R=0,*a,L; P(){while(*s++)putchar(*(s-1));} C(int*l){if((l-s+2)%R==0||(l-s)%R==0||l-s<R||l>r-R)*l=42,P(),exit(0);} e(int*l){if(*l==32)C(l),*l=42,e(l-1),*l=32,*l=42,e(l-R),*l=32,*l=42,e(l+1),*l=32,*l=42,e(l+R),*l=32;} main(){while(~(c=getchar()))*r++=c,R=!R&&c==10?r-s:R,L=c==64?r-s-1:L;L%R==0&&e(s+L+1);(L+2)%R==0&&e(s+L-1);L<R&&e(s+L+R);e(s+L-R);} ``` Sample output for a couple of tests: ``` #### # # @*##### #*****# # *# #####*# ###*################### ###* #******** # ##**#########** #* # #*************#####* # ############### #@## ``` Limitations: Only works for mazes up to 1000 characters, but this can easily be increased. I just picked an arbitrary number rather than bother to malloc/remalloc. Also, this is the most warning-laden code I've ever written. 19 warnings, though it looks like even more with the XCode code highlighting. :D EDITS: Edited and tested to drop int from main, to use ~ instead of !=EOF and putchar instead of printf. Thanks for the comments! [Answer] ## Ruby 1.9, 244 characters ``` l=*$< i=l*"" e=[] d=[1,-1,x=l[0].size,-x] r=[f=9e9]*s=x*b=l.size;r[i=~/@/]=0 r.map{i.gsub(/ /){r[p=$`.size]=d.map{|u|p>-u&&r[u+p]||f}.min+1;e<<p if p%x%~-~-x*(p/-~x%~-b)<1}} r[g=e.find{|i|r[i]<f}].times{i[g]=?*;g+=d.find{|l|r[g]>r[g+l]}} puts i ``` Output for the two examples: ``` #### # # @*##### #* # #****** ####### ###*################### ###* # *** # ## *######### *****#* # # ************#####* # ############### #@## ``` Edits: * (247 -> 245) Inlined e and renamed it to g * (245 -> 249) Fix a bug when the exit is directly above the entrance * (249 -> 246) Inlining + simplifications * (246 -> 244) Shorter way to iterate over every field [Answer] ## Python, 339 chars ``` import sys M=list(sys.stdin.read()) L=len(M) R=range(L) N=M.index('\n')+1 D=2*L*[9e9] D[M.index('@')+N]=0 J=(1,-1,N,-N) for x in R: for i in[N+i for i in R if' '==M[i]]:D[i]=min(1+D[i+j]for j in J) e=[i+N for i in R[:N]+R[::N]+R[N-2::N]+R[-N:]if 0<D[i+N]<9e9][0] while D[e]:M[e-N]='*';e=[e+j for j in J if D[e+j]<D[e]][0] print''.join(M) ``` Generates a shortest path through the maze. Output for example mazes: ``` #### # # @*##### #* # #****** ####### ###*################### ###* # *** # ## *######### *****#* # # ************#####* # ############### #@## ``` [Answer] **Python - 510 421 chars** ``` m=[] i=raw_input l=i() x=y=-1 while l: if y<0:x+=1;y=l.find('@') m.append(list(l));l=i() s=(x,y) t={} q=[s] v={s:1} while 1: try:(i,j),q=q[0],q[1:];c=m[i][j] except:continue if c==' 'and(i*j==0)|(i+1==len(m))|(j+1==len(m[0])):break for d,D in(-1,0),(0,-1),(1,0),(0,1): p=(i+d,j+D) if not p in v and'#'!=c:v[p]=0;q.append(p);t[p]=(i,j) while(i,j)!=s:m[i][j]='*';i,j=t[(i,j)] print'\n'.join(''.join(l)for l in m) ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~23~~ 22 bytes ``` [¾#4Føí„ *„@*δJ`:¬'*¢½ ``` [Try it online!](https://tio.run/##MzBNTDJM/V/zP/rQPmUTt8M7Dq991DBPQQtIOGid2@KVYHVojbrWoUWH9v6PPbT7v7KysoIyJuACicMAEosLJAxXBZdW5kJSBBaDSIPEUQFIzkFZGQA "05AB1E (legacy) – Try It Online") ### Modern [05AB1E](https://github.com/Adriandmen/05AB1E), 26 bytes ``` [¾#4F€SøíJ„ *„@*â2ô`:¬'*¢½ ``` [Try it online!](https://tio.run/##yy9OTMpM/V/zP/rQPmUTt0dNa4IP7zi81utRwzwFLSDhoHV4kdHhLQlWh9aoax1adGjv/9hDu/8rKysrKGMCLpA4DCCxuEDCcFVwaWUuJEVgMYg0SBwVgOQclJUB "05AB1E – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 270 bytes ``` import sys def q(g,*s):w=len(g[0])+1;k='@'.join(g)+w*'@';*p,x=s or[k.find('#')];return'@'>k[x]and{x}-{*p}and[p,min((q(g,*s,x+a)or k for a in(-1,1,-w,w)),key=len)]['*'>k[x]] g=''.join(sys.stdin.read());s=q(g.split('\n')) for i,c in enumerate(g):print(end=[c,'+'][i in s]) ``` [Try it online!](https://tio.run/##ZU/BboQgFLz7FSR7gKdoanpbw4b/oBzMipa6IgU2ajb77RZru9mmk0AeM5N5g13C@2he11UPdnQB@cUnjWrRJ@lo6uE4sYsypBMvErKy6hnmuPgYdaQgm9L4qlJLZ@bR6ERftNo0BB8wyMqpcHUmGk69mGVtmtt8z2@pvcdRWDrECLIvoXNWw@hQj9p41ygqeUlLmk90AqC9WrYOIAVO9zCZdAz/1Ih9Cx8abQqn6oYAVJ7F2MLbiw4EvxkMkGy5mp5jMlLmOihXBxU/cLROm0CUaZg4U5xhKfTm8RLWlXOe8v9I4kG/eJqSjX64HjJPnkzf3C5v/F9s2oHzLw "Python 3 – Try It Online") Port of my answer to [Find the shortest route on an ASCII road](https://codegolf.stackexchange.com/a/195042/87681). Uses `'#'` for start, `'*'` for end, `'@'` for wall and `' '` for empty space. In this, the function `q` is a helper function which returns a one-dimensional array with the shortest path in the maze. Function `f` can be shortened 4 bytes by not assigning the variable `s`. This is incredibly inefficient and will likely time out, since it calls the path-finding function for each character in the maze. ]
[Question] [ *The shortest code to pass all possibilities wins* Many grid based games have been made that start off with a grid of lights that are switched on. Pressing any of the lights causes that light and the four lights adjacent to it to be toggled. When a light is toggled, it is turned off or turned on, depending on if it was intially turned on or off. The goal is to hit the lights in a sequence that results in all of the lights being turned off at the end. "X" represents lights that are turned on. "O" represents lights that are turned off. "P" represents that square that is pressed. ``` XOO XOO XOX XOX XXX XOX XOP -> XXO -> OPO -> XOX OOX OOX POO XXO XOO Intial Grid Press 1 Press 2 Press 3 Ending Grid ``` Input can be taken directly from a file passed as an argument, or as standard input. The first line of input will contain *x* (1 <= *x* <= 20), the size of the grid of lights, meaning *x* by *x*. The second line will contain *y* (0 <= *y* <= (*x* \* 3)2), the number of lights initially lit up. The next *y* lines contain coordinates of lit up lights on the grid, in the format of "row column". Lights that are already switched on (have been toggled previously) should be toggled off again. The next line will contain *z*, the number of lights pressed. The final *z* lines contain coordinates of the pressed lights, in the order that they were pressed, in the format of "row column". No input will be incorrect. All numbers will be within the given boundaries of the grid. The output will be the final grid after all lights have been toggled. It should be an *n* by *n* grid. For each area that has a light which is on, the uppercase character "X" should be used. For each area that has a light which is off, the uppercase character "O" should be used. Lights that are affected that are off the grid should be ignored. Toggling a light on the edge of a grid should only affect the lights that are on the grid itself. ## Test Cases --- **Input** ``` 4 5 2 3 2 4 3 1 3 4 4 3 7 3 3 4 4 3 4 4 2 4 1 2 2 3 2 ``` **Output** ``` OXOO XOXO XOXO OXOO ``` --- **Input** ``` 1 3 1 1 1 1 1 1 2 1 1 1 1 ``` **Output** ``` X ``` [Answer] ## Python, 209 203 199 characters ``` I=input x=I()+1 s=0 C=lambda:eval(raw_input().replace(' ','*%d+'%x)) exec's^=1<<C();'*I() exec's^=1+(7<<x)/2+(1<<x<<x)<<(C()-x);'*I() R=range(1,x) for r in R:print''.join('OX'[s>>r*x+c&1]for c in R) ``` The state of the lights is kept in a single (big) integer variable, `s`. XORs with bitmasks are used to toggle the lights. I keep an extra bit per row to prevent wraparound. [Answer] ## Ruby 1.9, 167 characters ``` n=gets.to_i y=z=[*[1]*n,0]*n $<.map{|i|a,b=i.split.map &:to_i;b ?[*y&&[b>1&&-1,b<n&&1,a>1&&~n,a<n&&n+1],0].map{|f|f&&z[n*a+a-n-2+b+f]*=-1}:y=!y} z.map{|a|putc" OX"[a]} ``` Edits: * (198 -> 191) Removed some unnecessary stuff * (191 -> 180) Simplified the way the input is parsed * (180 -> 172) Removed parentheses, use `z[u]*=-1` instead of `z[u]=-z[u]`, remove unused variable * (172 -> 169) Some simplifications * (169 -> 167) Simplified a conditional [Answer] # J, 132 ``` 'x f'=:0 2{,i=:".;._2(1!:1)3 echo u:79+9*}:"1}."1}.}:2|+/(1:`[`]}&(0$~,~x+2))"0<"1(f{.2}.i),;([:<[,[:|:(2 4$0 0,,~1 _1)+])"1(3+f)}.i ``` Probably can be golfed a lot further. * Console only, stdin->stdout. Tested on j602 on Linux. * Passes both tests given. * Assumes sane upper limit on X (no extended precision) Original ungolfed version: ``` NB. Whole input as two column grid i=:".;._2(1!:1)3 NB. x is x, f is number of initial toggles 'x f'=:0 2{,i NB. z is 1..x z =: >:i.x NB. Take a boxed pair of indices, generate 'cross' indices (boxed) f2=:3 :'y,,<"1(>y)+"1>0 1;1 0;0 _1;_1 0' NB. List of initial toggles, individually boxed init=: <"1 f {. 2 }. i NB. List of Ps, individually boxed toggle=: <"1 (3 + f) }. i NB. Grid of 0s padded on all sides g =:0$~(x+2),(x+2) NB. For each initial toggle, make a grid with a 1 in that position. Sum each 'position'. grid =: +/ (1:`[`]}&g)"0 init NB. For each position in the cross (f2) of each press, make a grid with a 1 in that position. NB. Sum each 'position', add to 'grid', take mod 2, and select inner rows/columns. gfinal =: z {"1 z { 2|grid + +/ (1:`([:f2[)`]}&g)"0 toggle NB. Translate 0/1 to O/X through ascii and print echo u:79+9*gfinal ``` [Answer] # Perl, 139 chars ``` @s=1..<>;<>=~/ /,$f{$`,$'+0}=1for 1..<>;<>=~/ /,map$f{$`+$_*($_&1),$'+int$_/2}^=1,-2..2for 1..<>;$\=$/;for$x(@s){print map$f{$x,$_}?X:O,@s} ``` ### Explanation: ``` # Read size and generate an array of integers from 1 to the size. # We’ll need to iterate over this array often, but otherwise we don’t need the size @s = 1..<>; # Read number of prelit lights for (1..<>) { # Find the space; sets $` and $' to row and column, respectively <> =~ / /; # Set the relevant light; need +0 because $' includes the newline $f{$`, $'+0} = 1; } # Read number of light switchings for (1..<>) { # As above <> =~ / /; # Some nice formulas that flip the 5 relevant lights, # including the ones “off the board”, but we don’t care about those map { $f{ $`+$_*($_&1), $'+int$_/2 } ^= 1 }, (-2..2); } # Cause each subsequent print statement to print a newline after it $\ = $/; # For each row... for $x (@s) { # Print X’s and O’s as required print map { $f{$x,$_} ? X : O }, @s; } ``` [Answer] ## APL (71) ``` 'OX'[1+⊃{⍵≠(⍳⍴⍵)∊(⊂⍺)+K,⌽¨K←(0 1)(0 0)(0 ¯1)}/({⎕}¨⍳⎕),⊂({⎕}¨⍳⎕)∊⍨⍳2/⎕] ``` ]
[Question] [ Implement polynomial long division, an algorithm that divides two polynomials and gets the quotient and remainder: (12x^3 - 5x^2 + 3x - 1) / (x^2 - 5) = 12x - 5 R 63x - 26 In your programs, you will represent polynomials as an array, with the constant term on the tail. for example, x^5 - 3x^4 + 2x^2 - x + 1 will become [1, -3, 0, 2, -1, 1]. The long division function you are going to write will return two values: the quotient and the remainder. You do not need to handle numerical imprecisions and arithmetic errors. Do not use math library to do your job, however, you may make your function able to deal with symbolic values. Shortest code wins. EXAMPLE: `div([12, -5, 3, -1], [1, 0, -5]) == ([12, -5], [63, -26])` [Answer] ## J, 94 ``` f=:>@(0&{) d=:0{[%~0{[:f] D=:4 :'x((1}.([:f])-((#@]{.[)f)*d);([:>1{]),d)^:(>:((#f y)-(#x)))y' ``` eg. ``` (1 0 _5) D (12 _5 3 _1;'') 63 _26 | 12 _5 ``` Explanation of some snippets, given that a: (12 -5 3 -1) and b: (1 0 -5) length of a: ``` #a 4 ``` make a and b same order by appending zeroes to b: ``` (#a) {. b 1 0 -5 0 ``` divide higher powers (first elements) of a, b: ``` (0{a) % (0{b) 12 ``` multiply b by that and subtract it from a: ``` a - 12*b 12 0 _60 ``` repeat n times b = f(a,b): ``` a f^:n b ``` [Answer] # Python 2, ~~260~~ ~~258~~ ~~257~~ 255 bytes ``` exec'''def d(p,q): R=range;D=len(p);F=len(q)-1;d=q[0];q=[q[i]/-d@R(1,F+1)];r=[0@R(D)];a=[[0@R(F)]@R(D)] @R(D): p[i]/=d;r[i]=sum(a[i])+p[i] for j in R(F): if i<D-F:a[i+j+1][F-j-1]=r[i]*q[j] return r[:D-F],[d*i@r[D-F:]]'''.replace('@',' for i in ') ``` This executes: ``` def d(p,q): R=range;D=len(p);F=len(q)-1;d=q[0];q=[q[i]/-d for i in R(1,F+1)];r=[0 for i in R(D)];a=[[0 for i in R(F)] for i in R(D)] for i in R(D): p[i]/=d;r[i]=sum(a[i])+p[i] for j in R(F): if i<D-F:a[i+j+1][F-j-1]=r[i]*q[j] return r[:D-F],[d*i for i in r[D-F:]] ``` Use like so: ``` >>>d([12., -5., 3., -1.],[1.,0.,-5.]) ([12.0, -5.0], [63.0, -26.0]) ``` [Answer] ## Haskell, 126 For a start: ``` l s _ 0=s l(x:s)(y:t)n=x/y:l(zipWith(-)s$map(*(x/y))t++repeat 0)(y:t)(n-1) d s t=splitAt n$l s t n where n=length s-length t+1 ``` Sample use: ``` *Main> d [12, -5, 3, -1] [1, 0, -5] ([12.0,-5.0],[63.0,-26.0]) ``` [Answer] ## Javascript with lambdas, 108 ``` f=(a,b)=>{for(n=b.length;a.length>=n;a.shift())for(b.push(k=a[q=0]/b[0]);q<n;++q)a[q]-=k*b[q];b.splice(0,n)} ``` It replaces first argument by reminder and second by result. Example of usage in Firefox: ``` f(x=[12,-5,3,-1], y=[1,0,-5]), console.log(x, y) // Array [ 63, -26 ] Array [ 12, -5 ] ``` Sorry for the bug. Already fixed. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/) 18.0, 63 [bytes](https://github.com/abrudz/SBCS) ``` {0≥d←1+⍺-⍥≢⍵:⍬⍺⋄q(r↓⍨⊥⍨0=⌽r←⍺-m+.×q←(d↑⍺)⌹d↑m←⍉{⍵,⍨⍺⍴0}∘⍵⍤0⍳d)} ``` [Try it online!](https://tio.run/##bY@xSgNBEIb7e4rpckvuZPfOpBCuSmMqwdhIuCKwrAiJSQwIclylBC/mjohErSUBCyGFplCwSd5kXuScWdRKGP7Zmf@bGbYz6Pr6stPtn5RYzJsHOJ5JZ/tAKXExX1MA5p@ChQL@Wuu0TCRmS02kqpLl01D2TMYe5q9M314P3XMc32P@gpMlqYxw@kWdGdO96s72cUiFSxvu@AROP/jZs0CW0CaPR/nuu0zx5sneXkjM37RIS2O5AidXm1XIK4p567BBerTfbPFfGscVbc5GFUefjgagAtisahCSKjCgQHL9rxdYT8kfk2pjNYRdxxF9Y8i4cNsq8MCveRBSUrEHbeWB5FYsIIrgF2CnzkxQj8U3 "APL (Dyalog Unicode) – Try It Online") The TIO link (which uses 17.1) has a polyfill for `⍥`. Well, it uses `⌹` to solve a system of equations, but technically it's not a library, so... ### How it works Illustration for the inputs `x←12 ¯5 3 ¯1` and `y←1 0 ¯5`: * We know that, from the lengths of `x` and `y`, the quotient will have two terms. * Construct a matrix which, when matrix-multiplied with the quotient, will give the polynomial product of quotient with `y`: ``` 1 0 0 1 ¯5 0 0 ¯5 ``` * Calculate the quotient `q` so that first two terms of `x` agree with those of `y×q`, using matrix division `⌹`. * Calculate the remainder `r` using `x - y×q`, then remove leading zeros of `r`. (`q` is guaranteed to have no leading zeros.) ``` { ⍝ x←dividend, y←divisor d←1+⍺-⍥≢⍵ ⍝ Degree of the quotient; 1 + length of x - length of y 0≥d: ⍬⍺ ⍝ If degree is zero or lower: quotient is zero, remainder is x m←⍉{⍵,⍨⍺⍴0}∘⍵⍤0⍳d ⍝ Construct the matrix ⍳d ⍝ 0..d-1 { }∘⍵⍤0 ⍝ For each number i, yielding a matrix row ⍵,⍨⍺⍴0 ⍝ Make i copies of 0, and append y ⍝ (Implicitly right-pad with zeros for short rows) ⍉ ⍝ Transpose q←(d↑⍺)⌹d↑m ⍝ Get the quotient d↑m ⍝ Take first d rows of the matrix (d↑⍺) ⍝ Take first d numbers of x ⌹ ⍝ Matrix divide aka. solve linear system of equations r←⍺-m+.×q ⍝ Get the remainder q(r↓⍨⊥⍨0=⌽r) ⍝ Remove leading zeros from r, and join with q ⊥⍨0=⌽ ⍝ Reverse r, test equal to zero, and count trailing ones (⊥⍨) r↓⍨ ⍝ Drop that many numbers from start of r q( ) ⍝ Join with q } ``` ]
[Question] [ # Problem Assume you have a single 7-segment display without a decimal point, so 7 "lines" that can be labelled A through G as seen here. [![a labeled 7-segment display](https://i.stack.imgur.com/s39bwm.png)](https://i.stack.imgur.com/s39bwm.png) This display will only show the numbers from 0 to 9 as usual, like so: [![7-segment numbers visual representation](https://i.stack.imgur.com/EjXykm.png)](https://i.stack.imgur.com/EjXykm.png) Any time this display changes from one number to another, some of its lights will have to change their state from on to off or vice versa, or they can simply stay on, e.g. in the case of 1 -> 2, segment B can stay on, while segments A, G, E, D need to turn on, and C needs to turn off; for the change 6 -> 8, only segment B needs to be changed from off to on. # Task Your task is to take a sequence of numbers as reasonably formatted input and output the amount of on and off changes as the display shows each number in the sequence in input order. You should output a separate score for "on" and "off" in a reasonable format. A light that stays on between numbers shall not be counted towards either on or off. The initial state of the display is all lights off, so the first number will always count as only "on" changes. The final state will be the last number displayed. # Test cases ``` 123 -> 7, 2 (7 on, 2 off) 111 -> 2, 0 (2 segments on, then no changes) 987 -> 7, 4 2468 -> 11, 4 (thanks to @ovs for catching a mistake here!) ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. Also, this is my first post here, so I hope I made no mistakes for my submission :) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 34 bytes Anonymous tacit prefix function taking a list of numbers. Requires 0-based indexing (`⎕IO←0`). ``` 2(<⌿,⍥(≢⍸)>⌿)0⍪11⎕DR'~0my3[_p␡{'⊇⍪ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXECWa4R6UGZ6RklwRn5qKFC6KCmxSP1RdwuGIFBD9aPeXdGPerfG1io86p2rEJCfU5mWmZOjEOLpr16skF9akpJYkpqiUJZaVJyZn/ffSMPmUc9@nUe9SzUedS561LtD0w7I1zR41LvK0BBotUuQep1BbqVxdHxBfbX6o652oMT/NKA9j3r7HnU1P@pd86h3y6H1xo/aJgJVBwc5A8kQD8/g/2kKhgpGCsZcIBoIgbSlgoWCOZA2UjBRMFOwAAA "APL (Dyalog Extended) – Try It Online") `⍪` change list into column matrix `'~0my3[_p␡{'⊇` map to ASCII characters with corresponding pit pattern `11⎕DR` get corresponding binary **D**ata **R**epresentation as 8-column table `0⍪` prepend an all-zero row `2(`…`)` apply the following tacit function with 2 as left argument:  `>⌿` indicate where a 1 is above a 0 (lit. greater-than reduction over vertical windows of size 2)  `<⌿,⍥(`…`)` concatenate with where-0-is-above-1 as follows:   `⍸` list of indices where there are 1s   `≢` tally the indices (this gives the count of 1s) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~40~~ 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •z]∍1:pIªy•2в7ôDIнè(sã€øÆIü2諘®1‚¢ ``` -5 bytes thanks to *@Steffan* [Try it online](https://tio.run/##AUkAtv9vc2FiaWX//@KAonpd4oiNMTpwScKqeeKAojLQsjfDtERJ0L3DqChzw6PigqzDuMOGScO8MsOowqvLnMKuMeKAmsKi//8yNDY4) or [verify all test cases](https://tio.run/##AWQAm/9vc2FiaWX/dnk/IiDihpIgIj95/@KAonpd4oiNMTpwScKqeeKAojLQsjfDtER50L3DqChzw6PigqzDuMOGecO8MsOowqvLnMKuMeKAmsKi/yz/WzEyMywxMTEsOTg3LDI0Njhd). **Explanation:** ``` •z]∍1:pIªy• # Push compressed integer 1098931065668123279355 2в # Convert it to base-2 as list: [1,1,1,0,1,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,0,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1] 7ô # Split it into parts of size 7: [[1,1,1,0,1,1,1],[0,0,1,0,0,1,0],[1,0,1,1,1,0,1],[1,0,1,1,0,1,1],[0,1,1,1,0,1,0],[1,1,0,1,0,1,1],[1,1,0,1,1,1,1],[1,0,1,0,0,1,0],[1,1,1,1,1,1,1],[1,1,1,1,0,1,1]] D # Duplicate it Iн # Push the first digit of the input è # Use it to index into this list of lists ( # Negate all 1s to -1s in the list s # Swap so the duplicated list is at the top again ã # Create all possible pairs using the cartesian power with itself €ø # Zip/transpose each inner pair of lists; swapping rows/columns Æ # Reduce each inner-most pair by subtracting I # Push the input-integer again ü2 # Create overlapping pairs of it è # Use that to index into the other list « # Merge the two lists together ˜ # Flatten it ®1‚ # Push pair [-1,1] ¢ # Count the amount of -1s and 1s in the list # (after which this pair is output implicitly as result) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•z]∍1:pIªy•` is `1098931065668123279355` and `•z]∍1:pIªy•2в` is `[1,1,1,0,1,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,0,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1]`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 92 bytes Expects a list of digits. Returns `[off, on]`. Contains some unprintable characters. ``` a=>a.map(n=>(g=k=>k&&g(k/2,o[q&1]+=k&1,q/=2))(x^(x=q=Buffer('?[Ofm}o')[n])),o=[x=0,0])&&o ``` [Try it online!](https://tio.run/##bcpLDoIwFIXhmSYupLTxyqMaxcHFxA24gAaTBinRQi8PNUyMS6/MJWf2nf@h33oo@nv73Di6ld6g15jpsNEtd5jxCi1mlrGK20gCqY4l@RotS6CLUArBxysfscPzy5iy58FpoS6m@Sy/FAjlciGAUI0YQ5wLxsgX5Aaqy7CmihuuEpCwnarVn0@b8SOkcJhxCTvYQzo9/gc "JavaScript (Node.js) – Try It Online") ### How? Given the segment bitmask \$x\$ of the previous digit and the segment bitmask \$q\$ of the new digit, we compute \$k=x\operatorname{XOR}q\$ and use the helper function \$g\$ to update the *off* and *on* counters which are stored in the array \$o[\:]\$: ``` g = k => // k = result of the XOR between the 2 bitmasks k && // stop when k = 0, which actually happens because // of arithmetic underflow because we use k / 2 // rather than k >> 1 to save a byte g( // otherwise, do a recursive call: k / 2, // pass k / 2 for the next iteration o[q & 1] += // select the counter according to the LSB of q k & 1, // increment it if the LSB of k is set q /= 2 // divide q by 2 ) // end of recursive call ``` --- # JavaScript (ES6), 99 bytes An alternate version without `Buffer()`. The order of the segment bits and the XOR value were chosen to optimize the overall length of the lookup code. ``` a=>a.map(n=>(g=k=>k&&g(k/2,o[q&1]+=k&1,q/=2))(x^(x=q=[6,90,44,8,80,1,5,74,4][n]^123)),o=[x=0,0])&&o ``` [Try it online!](https://tio.run/##bc1NDoIwGIThvQdp2jhCWyo/i4@LNCVpEIkWKYgx3B7ZS2b3zOJ9@q9f2vdj@lzGeOu2O22eap@8/MRHqnlPgerAWM9DqhHtzJQ7U2AKc0paCL42fKWZbI5KwhiUKCUUrigMjLOja5TOhEAku5KEdIKxuLVxXOLQJUPs@Z1bBY3MCXH6830HXu2Z4sA1DHKU@7P9AA "JavaScript (Node.js) – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), 147 bytes ``` |a|{let(b,mut e,f)=(b"~0my3[_p{",0,|a,b:u8,c:u8|a+(b^c&b).count_ones());a.iter().fold((0,0),|(l,r),&d|{let c=(f(l,b[d],e),f(r,e,b[d]));e=b[d];c})} ``` [Try it online!](https://tio.run/##fY9RaoRAEET/9xQTP6SbVMS4ITGKyUFks@g4A4KOi858JGpydDPrAaSh6G5eUdToJrtpI/qqNcTzqVNWaGdkpg2FpZvaH3Xhpw9y5wTCC4tCbEu1zB6kGr2zQkFzQXXwG/ff5/J6@5sDxFgq1JlLIb0s1SPVXzKsOZKDM/Y6GDURc15FrVUjcaSHriGKETMW6jAywmbPELIg7T912VygGJpGqP3ydlXcl1yuvG756Ta2xnbmgYI5@1wD7D18iWckON/xA8LPIfGOFG@HRIIXvCLdmXX7Bw "Rust – Try It Online") Note that the space in the byte string is really the ASCII delete character (code point `0x7f`). The basic idea is that the set bits are stored as a mask packed in a byte string, and the changed bits are detected with some bit twiddling, similar to the other answers from practical langs (although not the same- we've all taken different approaches for the same general technique, at least so far). [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 107 bytes -4 bytes and fixed a bug thanks to [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld). ``` a->d=127;sum(i=1,#a,[g(c=[2,91,40,9,81,5,4,27,0,1][1+a[i]],d),g(d,d=c)]) g(a,b)=sumdigits(bitand(-1-a,b),2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY5BigIxFET3c4qgm4SpQP-o0y0Sb-AJQpCvoUMYlaDtwrO4aRDxTHObSVD-ol5RUL_ur8zntI15fPTCPq9Dr7u_X9brYMm0q8v1KJMlTBkuyr11BkvCvMESHWGBOUyLBuQdfbNL3iMoRBkQ7F559RUlY6dsqQkppuEid2ngU5CadA1g1OflhnM-3CQLvRb5nE5DwUk1E9FLVgrCOYLBzBcilKtQVqCtYMqSH3QVG-8_peP41n8) [Answer] # [Python](https://www.python.org), ~~116~~ 112 bytes *-4 bytes thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)* ``` def f(s): A=X=Y=0 for b in s:B=b'~0my3[_p\x7f{'[b];X+=(~A&B).bit_count();Y+=(A&~B).bit_count();A=B print(X,Y) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3C1JS0xTSNIo1rbg4HW0jbCNtDbg40_KLFJIUMvMUiq2cbJPU6wxyK42j4wtiKszTqtWjk2KtI7RtNeoc1Zw09ZIyS-KT80vzSjQ0rSOBoo5qdWiijrZOXJwFRZlAToROpCbE3jVpGtFGOiY6ZjoWsVAhmJMA) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~136~~ 134 bytes ``` #define B+=__builtin_popcount((d^c) i;c;d;x;y;f(a,n)int*a;{for(i=x=y=d=0;n--;d=c)c="{HW^l>?X\x7f~"[a[i++]],x B&c),y B&d);*a=x;a[1]=y;} ``` [Try it online!](https://tio.run/##bVLRjpswEHzPV6yoEmHiqCGkTa@u76SrKvUDIrUS4SJqzNUqMShwKrko/fTSBRNIaJDBZmd2vOO1mD0LUVVvIhkrLeFxyrfbHy8qKZTeZmkm0hdd2Hb0JMhIMcEiVrIDi@2QaqJ04YTsGKd7W/GSH3jE50zPZizigghuHb9@e0ruH75vylX8x/JDX02nQUBLeJwIQg84RYQ5IS9Z6LsBP7BThZKwC5W2CRxHgE8dKGReuH4AHI4uhQUF78SuwEUH1mMAega8o/CBwmoALg2ImksK75EywLeJIXi4aTOWPcFpGLkhNDVSU42ZPDNdJIAsMykKGbVmVmjmBrroaprfQL0u95Zy68d1B5WecQN3ddB@037p9cuzhkh1XoD4Ge4d/ErxS@6NkrUpvyw25d1nfN9ZFC7/PavNxgsCdl2l0pEsMW3O2uUnyNWrTGP7vCF52wacLsJgOm3YpBEz16JvAcqZNjScgF3CkLQotvEG7MAacREmSSrsBE@M9PBO7kR2sNfYRAqJcwn1dloraCNpqiQdp36yPZJi2xrn4wiPRj3U5/PR8nFa@yq4VKz3Sch17alG@bU/H1hK47iJu0MvEsNdm28dhtw2kvI/SQQaUTkUhSzMcwTqPG7yJxNTATdZPf3sNoDZPYwjii@M841Gt6mmdRLtrk4te@V/L6W9bgOn0an6K@IkfM6r2e9/ "C (gcc) – Try It Online") *Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs a pointer to an array of digits to display and its length (because C pointers carry no length info). Return the number of lights turned on and the number turned off through the input pointer. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 41 bytes ``` k-»>xWƛo4ø₅=»b7ẇ:?hiN$2ẋΠv∩vvƒ-?S2l⌊İJfvO ``` [Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrLcK7PnhXxptvNMO44oKFPcK7Yjfhuoc6P2hpTiQy4bqLzqB24oipdnbGki0/UzJs4oyKxLBKZnZPIiwiIiwiMjQ2OCJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyIiLCLGmyIsImstwrs+eFfGm280w7jigoU9wrtiN+G6hzpuaGlOJDLhuovOoHbiiKl2dsaSLW5TMmzijIrEsEpmdk8iLCI7Wsabw7dgLCBgasO4QlwiYCBcXOKGkiBgajvigYsiLCJbMTIzLDExMSw5ODcsMjQ2OF0iXQ==). ## How? ``` k-»>xWƛo4ø₅=»b7ẇ:?hiN$2ẋΠv∩vvƒ-?S2l⌊İJfvO k- # Push [-1, 1] (will be used later) »>xWƛo4ø₅=» # Push compressed integer 1098931065668123279355 b # Convert to binary as a list 7ẇ # Split into chunks of size 7 : # Duplicate ?h # Push the first digit of the input i # Index it into the list N # Negate: replace all 1s with -1 $ # Swap so the list of size-7 chunks are at the top again 2ẋΠ # Cartesian product with self v∩ # For each, transpose vvƒ- # For each inner pair, reduce by subtraction ?S # Push stringified input 2l # Get all overlapping pairs ⌊ # Convert them to integers İ # Index these into the other list J # Join the two lists together f # Flatten vO # Count the number of -1s and 1s in this list ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes ``` IE²L⭆⪪”←&⊞YJΣζ⁹)G;⧴4L⁴↷U³”¶Φθ‹⁼ι№λ§⁺ θξ⁼ι№λν ``` [Try it online!](https://tio.run/##bY1LC8IwEIT/SshpAxFs@lI8SVEQFAq99hJqaQMhfWQr/fdx24Mn9/DB7OzsNL2em0HbEMrZOIRCe4SXHkFJ9mxdhz1USE637arRGgTOIhXntWNRQkgzwjHadZyk@Xk3Nqm4ZLx2XEh2NxbbGabtp/dwmxZtPRjJimGhUivZFR/u3a5Q2sVTA0Unyq1CEP@cO/GbSwgqyU7h8LFf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ² Literal integer `2` E Map over implicit range ... Compressed string ⪪ Split on ¶ Literal newline ⭆ Map over elements and join θ Input string Φ Filtered where ι Outer value ⁼ Equals № Count of Literal space ⁺ Concatenated with θ Input string § Indexed by ξ Inner index λ In current string piece ‹ Is less than ι Outer value ⁼ Equals № Count of ν Current input character λ In current string piece L Take the length I Cast to string Implicitly print ``` The compressed string splits to the list `1237`, `14`, `56`, `017`, `134579`, `147`, `2` which for each segment contains the digits (including the initial "off" state as a "digit") where the segment is off. [Answer] # [Perl 5](https://www.perl.org/), 96 bytes ``` tr/0-9/\167\3\136\37\53\75\175\7\177\77/;@_=($_,"\0$_");print unpack"%b*",$_[$_]&~$_[!$_]for 0,1 ``` [Try it online!](https://tio.run/##DYbdCsIgFIDv9xRLLCocemZ6NkbQe3RCKgpGQ8XstkfPvPh@4iMtppScpOpGSWCRNIG2pJGMJjQEFaxGQpTTyR233AlGiju2m2KafW4/Pl7vL7a@7Zng7szdZfOtXdV5htQqAaVArxsAaMYBm/5gh1@IeQ7@XbrF/wE "Perl 5 – Try It Online") ## Explanation Input arrives in `$_`, pre-trimmed to just digits Convert each digit into a pattern of bits corresponding to the segments that are turned on. The order of bits doesn't matter as long as they're consistent, so this order was chosen so that the whole list is represented with the fewest (octal) digits. (`tr` modifies `$_` in-place) ``` tr/0-9/\167\3\136\37\53\75\175\7\177\77/; ``` Make a copy with the starting blank included; keep both in the predefined `@_` array ``` @_ = ($_, "\0$_"); ``` (Now when we perform bitwise operations on these two values, it will apply the operation to each pair of consecutive bytes.) Loop (twice) ... ``` for 0,1 ``` ... to perform the following forwards and backwards, so we get both the "turned on" and "turned off" counts. (Note: loop iterator is `$_`, which we no longer need it to hold the input.) Mask each byte (of the transformed input string) with the "previous" byte, resulting in a string of bytes with bits set indicating change in one direction (which is why we do the whole thing twice): ``` $_[$_] & ~ $_[!$_] ``` (`!$_` changes 0 to 1 and 1 to 0; `(B & ~ A)` gives you the bits that aren't set in A that are set in B) Count the `1` bits from the expression above: ``` unpack "%b*", ``` Output the result: ``` print ``` Invoke Perl with the `-l` and `-n` options, for example, as: ``` perl -ln -e '«program here»' <<<'«input here»' ``` Each line of input is treated as a separate test case; after each test, the "turn on" and "turn off" counts are output on two separate lines. ]
[Question] [ ## Challenge: Given a list of non-negative integers, determine by how much you should increase each item to create the closest binary box with the resulting integer-list. **What is a binary box?** A binary box is where the first and last rows consists of `1`-bits; the first and last columns consist of `1`-bits; and everything else (if applicable) consists of `0`-bits. Some examples of binary boxes, with their corresponding integer-list below it: ``` 111 1111 101 1111111 111 1001 11 11111 101 1000001 11 101 1001 11 10001 101 1111111 1000001 11 111 1111 11 11111 111 1111111 1 11 1111111 [3,3] [7,5,7] [15,9,9,15] [3,3,3] [31,17,31] [7,5,5,5,7] [255,255] [1] [3] [127,65,65,127] ``` **Example I/O:** * If the input is `[0,2]`, the output would be `[3,1]`, because `[3,3]` is the closest binary box to reach by increasing numbers: `[0+3,2+1]`. * If the input is `[3,4,1]`, the output would be `[4,1,6]`, because `[7,5,7]` is the closest binary box to reach by increasing numbers: `[3+4,4+1,1+6]`. * If the input is `[2]`, the output would be `[1]`, because `[3]` is the closest binary box to reach by increasing numbers: `[2+1]`. ## Challenge rules: * The goal is to find the closest binary box. If the input is `[1,2,3]` the output should be `[2,1,0]`; so `[62,31,60]` wouldn't be allowed as output, even though [it does form a binary box](https://tio.run/##yy9OTMpM/f9fO@nQ7v//ow11jHSMY7mizYCUoY6ZQSwA) as well. * I/O can be taken in any reasonable format. Can be a list/array/stream of integers; read one by one from STDIN; etc. **You are not allowed to take the input-integers as binary-strings.** * The input-integers are guaranteed to be non-negative; and the output-integers may not be negative. * If the input is already a binary-box of itself, you can choose to output a corresponding list of 0s, or the result for the next binary-box in line. I.e. input `[3,3,3]` may result in both `[0,0,0]` or `[4,2,4]`. The first/last rows of the binary-boxes with binary `111...111` form the OEIS sequences [A000042](http://oeis.org/A000042) (literal) and [A000225](http://oeis.org/A000225): \$a(n)=2^n-1\$ (as base-10 integers). The middle rows of the binary-boxes with binary `100...001` form the OEIS sequences [A000533](http://oeis.org/A000533) (literal) and [A083318](http://oeis.org/A083318): \$a(n)=2^n+1\$ (as base-10 integers). ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Input: [0,2] Output: [3,1] Input: [3,4,1] Output: [4,1,6] Input: [2] Output: [1] Input: [3,3,3] Output: [0,0,0] OR [4,2,4] Input: [1,27,40] Output: [62,6,23] Input: [7,20,6,44,14] Output: [120,45,59,21,113] Input: [7,20,6,33,14] Output: [56,13,27,0,49] Input: [7,2,6,3,14] Output: [8,7,3,6,1] Input: [1,0,1] Output: [0,1,0] Input: [1,2,3] Output: [2,1,0] Input: [0] Output: [1] Input: [6,6,6] Output: [9,3,9] ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~47 46~~ 48 bytes ``` {x←0⋄⍵{x≡|x⊢←⍺-⍨⊥(1@1)∘⌽∘⍉⍣4⊢0×⍵:x⋄⍺∇⍵⍪0}⊤⍵+~×⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v7riUdsEg0fdLY96twLZnQtrKh51LQKKPerdpfuod8WjrqUahg6Gmo86Zjzq2Qsiezsf9S42ASoyODwdqMmqAqx516OOdiDvUe8qg9pHXUuATO06sHzt/zSwaX2Pupof9a551Lvl0HrjR20TH/VNDQ5yBpIhHp7B/9OBaqqBHK9gfz@FNJBBXYuBXKCounotF1e6goGCEZA0VjBRMATSOiCOjgFYBAiBtKGCkbmCCUjEXMHIQMFMwQSo0gTBNTaGc0E8CMcQaKwhRLOCMQA "APL (Dyalog Extended) – Try It Online") A dfn which takes a vector as its right argument. Outputs a list of 0's if the input is already a binary-box. +2 bytes after a fix.(Thanks, Arnauld) ## Explanation ``` {x←0⋄⍵{x≡|x⊢←⍺-⍨⊥(1@1)∘⌽∘⍉⍣4⊢0×⍵:x⋄⍺∇⍵⍪0}⊤⍵+~×⍵} x←0 set var x to 0(required for extended) {x≡|x⊢←⍺-⍨⊥(1@1)∘⌽∘⍉⍣4⊢0×⍵:x⋄⍺∇⍵⍪0} call the following recursive function with ⍵+~×⍵ add !(signum(input)) to itself (special casing for [0]) ⊤ converted to binary matrix ⍵ and the input list as right arg : If: 0×⍵ the matrix converted to zeroes (1@1)∘⌽∘⍉⍣4⊢ with 1s added on each side ⊥ convert from binary ⍺-⍨ subtract from the input x⊢← assign to x x≡| if x matches its absolute value x then return x ⋄⍺∇⍵⍪0 otherwise add a row of zeroes, and try again ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ ~~21~~ 18 bytes -4 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! ``` [NoD<Id¦¦s.ø~I-Wd# ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/2i/fxcYz5dCyQ8uK9Q7vqPPUDU9RBgob65joGMYCAA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##S0oszvj/PzU5I19BN09BKdov38XGM@XQskPLivUO76jz1A1PUVZSsFNIzk9J1UtMSuUqz8jMSVUoSk1MUcjM40rJ51JQ0M8vKNHPL05MykyFUnDlCjY2NgoqYIV5qf//RxvoGMVyRRvrmOgYAmkIGwiBtKGOkbmOiQGQZa5jZKBjpmMCVGOC4Bobw7kgHoRjqGMANgioGWQIAA) **Commented**: ``` [ # infinite loop, for N=0,1, ... No # push 2**N D # duplicate this value < # decrement Id # push a list of 1's in the same length as the input ¦¦ # remove the first 2 elements s # swap to 2**N-1 .ø # surround the list of 1's to get a new list of the same length as the input # => [2**N-1, 1, ..., 1, 2**N-1] ~ # bitwise OR with 2**N, this is now the binary grid of width N+1 # => [2**n|2**N-1, 2**N|1, ..., 2**N|1, 2**N|2**N-1] I- # subtract the input list element-wise from the binary grid W # take the minimum without popping the list d # if this is non-negative # # break the infinite loop and implicitly print the list ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 95 bytes ``` f=lambda s,n=1:(b:=[x-y for x,y in zip(([n|n-1]+[n|1]*(len(s)-2))*2,s)])*(min(b)>=0)or f(s,n*2) ``` [Try it online!](https://tio.run/##RYzBCoJQEEX3fcXsnLER3ntKhqQ/Ii6UeiToU9SFVn67TQnFLO49MPf0y3TvXHjuh22zaVO21bWEkV2qE6ySNJ@DBWw3wMwL1A4edY@Yu5cLdHGU1IWPzc3hSIEh8g2PVJCPbe2woixVJFOL4vMNbV/Px5IrNgXnIUesJfcuJ6nZxBwpaTEbxSeO5Cf6Yxj@8EM7aFZfkYxFkhwA@qF2E1rvOU4DzpRc9HmFIIOnFVo92t4 "Python 3.8 (pre-release) – Try It Online") **Commented**: ``` f=lambda s,n=1: # f is a recursive function taking two arguments: # a list of integers: s, and the current power of 2: n # it tries all binary boxes with the correct number of rows # until it finds one where all row numbers are >= the values in s (b:= ... ) # construct a list of differences between row numbers and s * (min(b)>=0) # if there is no negative value in this list, return it or f(s,n*2) # otherwise try the next power of 2 [x-y for x,y in zip(...,s)])] # take the differences of each pair of row numbers and integers in s [n|n-1] # the first and last row are equal to n|n-1; # example: n=8, n|n-1 = 8|7 = 0b1000|0b0111 = 0b1111 = 15 +[n|1]*(len(s)-2) # the middle rows are n|1 # example: n=8, n|1 = 8|1 = 0b1000|0b0001 = 0b1001 = 9 (...)*2 # repeat this list twice to get the first row twice, # zip will ignore all extra elements ``` [Answer] # JavaScript (ES6), ~~72~~ 71 bytes Outputs a list of 0's if the input is already a binary-box. ``` a=>(g=k=>/-/.test(b=a.map((v,i)=>(i/a[i+1]?k^k/2|1:k)-v))?g(k-~k):b)(1) ``` [Try it online!](https://tio.run/##jVBBboMwELz3FRxtZcGsbUyJRPKESr0iV3JSgqjTEAXEqerX6XJIRIFK9d5mZ8az8@F61x5v9bULL817OZzyweU7VuU@34lQRF3ZduyQu@jTXRnroea0rYUr6g3avX/zQn7h1vOw53xfMR9@e749cIZ8ODaXtjmX0bmp2IkVMUgb3B/ngRBBoQDt04ynQBP6m0cImAVz4vdgrvnRzPxioLHBy@toLUEvRAgyBR3bqchIMCDVgpuCjGmjKaS29xgE6QSSDCQC4p8ipSaixACq8WPSZmuKUTDyH5GeISXErLSIZIKLqwldO3XRj1xlxv/q21AeM/PLKGVmhx8 "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array (g = k => // g is a recursive function taking a bit mask k // of the form (2 ** n) - 1 /-/.test( // test whether there is a minus side in the ... b = a.map( // ... array b[] defined as the result of this map() (v, i) => // for each value v at position i in a[]: ( i / a[i + 1] ? // if this is neither the first nor the last item // (i.e. i is not equal to 0 and a[i + 1] is defined): k ^ k / 2 // use the vertical borders | 1 // e.g. (0b111111 XOR (0b111111 >> 1)) OR 1 = 0b100001 : // else: k // use the horizontal border (i.e. the full bit mask k) ) - v // subtract v ) // end of map() ) // end of test() ? // if there's a minus sign: g(k - ~k) // try again with 2 * k + 1 : // else: b // success: return b[] )(1) // initial call to g with k = 1 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~39~~ 37 bytes ``` ≔¹ζ≔⁻¹θηW‹⌊η⁰«≦⊗ζ≔Eθ⁻⎇﹪λ⊖Lθ⊕ζ⊖⊗ζκη»Iη ``` [Try it online!](https://tio.run/##VY4/C8IwEMXn9lNkvEAEXVw6iV0ECw5upUNsgwmmSZs/ihU/e0xpROSme@/d717LqWk1lSHsrBVXBRuCJlzkaauE8nbWRkwQj/qDC8kQHJm1syl63wOP3hpj9Mqzig7pstT@Ilm30LIvjg4wErRQz8woap5Q6c5LDZKgkrWG9Uw51sUP6uo4jDjCD@qnT/g/l/5EfU7ecOr5zk9GKAd7al0siIsQ6npL4jRNWN3lBw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: I tried directly calculating the correct box size, but there were too many edge cases. ``` ≔¹ζ ``` Start with a box of width 1. ``` ≔⁻¹θη ``` See whether this box can hold the input. ``` W‹⌊η⁰« ``` Repeat until a large enough box is found. ``` ≦⊗ζ ``` Increase the size of the box. ``` ≔Eθ⁻⎇﹪λ⊖Lθ⊕ζ⊖⊗ζκη ``` Calculate the box and subtract the original input. ``` »Iη ``` Output the final increments. [Answer] ## Python 3.8+, 91 bytes ``` f=lambda b,n=1:f(b,n*2)if min(u:=r_[(t:=2*n-1),b[2:]*0+n|1,t]-b)<0else u from numpy import* ``` The parameter `b` must be a numpy array of integers. Therefore, no try it online. Recurse with `n` take values `1, 2, 4, 8,...`, and construct the array ``` r_[ (t:=2*n-1), #first line b[2:]*0+n|1, #middle lines, all values are n|1, length=len(b[2:]) t #last line, same as first line ] ``` being the binary boxes, then return the first one that is no smaller than `b`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ ~~31~~ ~~25~~ 26 bytes +6 for bug fix for input [1,0,1] -6 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) +1 for bug fix for single-element lists ``` d¸∞εoIg<и¨>y>o<.ø}«.ΔI@P}α ``` [Try it online!](https://tio.run/##ATEAzv9vc2FiaWX//2TCuOKIns61b0lnPNC4wqg@eT5vPC7DuH3Cqy7OlElAUH3Osf//WzJd "05AB1E – Try It Online") or [Try all cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf6XJo5f@UQzsedcw7tzX/0Lp0mws7Dq2wq7TLt9E7vKP20Gq9c1MOrXMIqD238b/O/@hoAx2jWJ1oYx0THUMgDWEDIZA21DEy1zExALLMdYwMdMx0TIBqTBBcY2M4F8SDcAx1DMAGATWDDQFpNwNKm8XGAgA) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~181~~ ~~175~~ 166 bytes -6 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) -9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ``` i,j,m;f(n,l)int*n;{for(i=m=0;i<l;i++)if(m<n[i])for(j=1;(j*=2)<(m=n[i]););for(i=0,m-2&&(j/=2);++i<l-1;)n[i]>j+1?j*=2:0;for(i=l;i--;)n[i]=j-n[i]+(!i|i==l-1|m<4?j-1:1);} ``` [Try it online!](https://tio.run/##jVJtb4IwEP7Or@g0W1o5NoqoiaWa/Qe/ET4Yga1E6oKwZFF@u7uiE3AvWfvh2ufuubunvY3zstmchkpvtlWckGBfxmr3@Lo4KcggFynVsGVKlyMtDumuoErm0hUq2Apl20ylNA90qCJmfJnkgmYj6bGA5rKBBRNnlgu54z080OwJ3cK2MYPDBTNBi8zmS0Obu5dgTO44Z6fMHGNseqeOSkokHfPAX2YOn3Mm6tMwTlKlE7Ii3LOs952KyVuB/T4XxfqDEjyRkYbGbhNNmLAsc87XSlNGDpZFcBlEh6sonEQSMXJZBxe8GtrrGHzgXeDGi7sLcPBm4LtdaAaeC1PwMY//Az4ef8cNfINycPt9YKV@6V7RKaaY1s29Fo25isYnQdkERXumilEAk2aPz/cuofkbJJUY7wo0AVmhwTG4vNm1ZOcHdFhG0NQpcRr6Yemf3t@TtCFVuaeDwYVZt/wiKatCY5dW/Z@hsA49gdVZYIUC0Y2HVuLX6neZ0sF9TAaAQ1RFvW7aDuvTJw "C (gcc) – Try It Online") ]
[Question] [ Just over seven years ago, [everybody suddenly stopped talking about the Maya people](https://www.xkcd.com/998/). It is time to rectify that! For clarification, I am talking about the [Mesoamerican Long Count Calendar](https://en.wikipedia.org/wiki/Mesoamerican_Long_Count_calendar). Your program will have as input a date in the Gregorian Calendar, and as output the corresponding date from the aforementioned Mesoamerican calendar. That calendar counts days since August 11, 3114 BCE. It divides that number of days into periods of different lengths. There's the single day, the Winal (20 days), the Tun (18 Winal, or 360 days), the K'atun (20 Tun, 7200 days), and the B'ak'tun (20 K'atun, 144 000 days). So you have your number of days since the epoch, then you find out how many of each period fit in there. Let's take William the Conqueror's coronation date of December 25, 1066. We're not bothering with the Julian Calendar here - we're using the [Proleptic Gregorian Calendar](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar) for dates in the distant past (including the Maya epoch): basically the system of leap days every four years, except years divisible by 100 but not by 400, which I trust you're all familiar with. Between Christmas Day in 1066 and the Maya epoch date of August 11, 3114 BCE, there's 1526484 days. In that number, you can fit 10 periods of 144000 days, so that's our B'ak'tun. The remainder, 86484, can fit 12 periods of 7200 days, so that's the K'atun. The remainder is 84. That's less than 360, so our Tun is 0. You can fit 4 Winal though, leaving a remainder of 4 days. Now concatenate all those numbers with full stops in between, in decreasing order of period length. The date of 25 December 1066 becomes 10.12.0.4.4. ([luckily, Wolfram|Alpha can verify it too](https://www.wolframalpha.com/input/?i=25%20december%201066%20in%20mesoamerican%20long%20count%20calendar)) ### Specification Your program will take as input a date in the Gregorian Calendar, between January 1, 1 AD (7.17.18.13.3), and 31 December, 3999 AD (18.0.15.17.6). The date can be in any format you want (my test cases will be using ISO 8601) as long as it is in the Gregorian calendar. That means, valid input formats include (but are not limited to) "22 MAR 2233", "7/13/2305", "20200107T000000Z", and "2020-01-07T00:00:00+00:00", even an array like "[7], [1], [2020]", depending on what your language parses the most easily or what approach you want to use. It is not allowed however to include any information beyond year, month, day of the month, time (has to be 00:00:00) and time zone (has to be GMT). Once I start allowing the day of the year, the Unix timestamp, a full-fledged DateTime data object (which contains a host of other values) or some other date tracking scheme, this issue would no longer be about converting a Gregorian date into a Mayan date, but only about representing a Mayan date. So basically, just stick with a primitive or a list of primitives for input. It will output a string containing the corresponding Mayan date, as discussed above. It has to be a single string of numbers separated by periods; an int array is not allowed. Using a built-in Maya converter in your language (though I would be surprised if it had one) is not permitted either. The question is tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in byte count wins! ### Test cases ``` Gregorian; Mayan 1-1-1; 7.17.18.13.3 1-1-2; 7.17.18.13.4 1066-12-25; 10.12.0.4.4 2000-2-29; 12.19.7.0.1 2012-12-21; 13.0.0.0.0 2020-1-5; 13.0.7.2.11 2100-3-1; 13.4.8.8.6 2154-4-11; 13.7.3.6.10 3999-12-31; 18.0.15.17.6 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~149~~ \$\cdots\$ ~~145~~ 140 bytes ``` from datetime import* def f(d): n,s=(date(*d)-date(1,1,1)).days+1137143,"" for i in[144000,7200,360,20,1]:s+=f".{n//i}";n%=i return s[1:] ``` [Try it online!](https://tio.run/##bZDRboMwDEXf@Yoo0qSk9dKYBCid@JKqD5WALlIJCLKHatq3MyddeRpGCOnc62t7eoTP0Zt17edxYO01dMENHXPDNM5hl7Vdz3rRylPGPCyNiAKxa@V7@kGgklK118eyRzQVWgOcZ6wfZ@aY82e0VmsNVU4fU2rINeDltOybnqtvfzi4H/7h3xqXsbkLX7NnyxlPlzV0S6C0jIlzyrgASw@vFNJ7VGiU4RJegvw/gX0JdFkC5pAXpOKoFeZKK7vxPE5IuI5NOEGsVUUK3DiZox@T3xBKteG4FBRphCeuFDXZ7Bh3/9shcquOVOWGCwsWEJ/phsxGlQpf7U1d1zHdPNOPcbAiLpkayGyanQ/ier@LXtxk0wzp@DcY6Pws3VHK9Rc "Python 3 – Try It Online") Takes Gregorian date as `[year, month, day]` list and returns Mayan date as `f"{B'ak'tun}.{K'atun}.{Tun}.{Winal}.{Day}"`(loosely as a python f-string). [Answer] # JavaScript (ES6), 96 bytes *Assumes that the system is set up to UTC time (as the TIO servers are)* Takes input as 3 distinct parameters `(year, month, day)`. ``` (y,m,d)=>[144e3,7200,360,20,1].map(k=>n/(n%=k,k)|0,n=new Date(y+4e3,m-1,d+395335)/864e5).join`.` ``` [Try it online!](https://tio.run/##ddDRbsIgFAbg@z0FN0sgHk85UGi5qFd7i2WJjeKitdRMs8Vk796B7eIiWYC7j5//cGg/2/PmY3@6LMOw9eOuGfkVetiKZvVKZek1VEpK0FaCkkBv2Lcn3jWrUPDw3HTQiW8JoQn@i720F8@vi3SnXxJsF9oZrY0oalt6I/Aw7MMa1@NmCOfh6PE4vPMdZ4wRzEcIVhSsQoq7RtKon/7FKsPlAyZpLTBSwJSZMEkkhRLLzMYZZQqN1s1WITmsoqbMpsxb7tw4Pi6nlVEl577mD60whmexdKug7x@RZsI6LptRU0YWD91phRot0mMF7Zyb2upfW6ehTPo4O/4A "JavaScript (Node.js) – Try It Online") ### How? We can't safely pass a year \$y<100\$ to the `Date` constructor, as it gets interpreted as \$1900+y\$. To work around this issue, we add \$4000\$ to the year. We make sure to use a multiple of \$400\$ so that we have the same properties regarding leap years. The remaining number of days to reach Epoch from August 11, 3114 BCE + 4000 years is \$395335\$. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~54~~ 52 bytes ``` 365*Š3‹¹α4т‚DPª÷®β•똿•ºS₂+²£`•H`Ø•OŽQív₂y-‰R`})R'.ý ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f2MxU6@gC40cNOw/tPLfR5GLTo4ZZLgGHVh3efmjduU2PGhYdXn16zqH9QMahXcGPmpq0D206tDgByPVIODwDSPkf3Rt4eG0ZUKZS91HDhqCEWs0gdb3De///NzIwMOAy4jKyBAA "05AB1E – Try It Online") First step: compute the day number. ``` 365 # literal 365 * # multiply # => 365*year is left on the stack for now Š # get the other two inputs # => day is left on the stack 3‹ # is month less than 3? (returns 0 or 1) ¹α # absolute difference with year 4 # literal 4 т # 100 ‚ # pair the two: [4, 100] DP # product of (a copy of) the pair: 400 ª # append it to to the pair: [4, 100, 400] ÷ # int divide the year by each of those numbers ®β # convert from base -1: y/4 - y/100 + y/400 # => number of leap days is left on the stack •똿• # compressed integer 15254545 º # mirrored: 1525454554545251 S # split to a list of digits ₂+ # add 26 to each: [27, 31, 28, 31, 30, ...] ²£ # month first values of that list ` # dump all on the stack # => days in previous months is left on the stack •H`Ø• # compressed integer 1136750 # => gregorian-mayan offset is left on the stack O # sum the stack, giving the # of days since 0.0.0.0.0 ``` Second step: convert that number to the appropriate notation. ``` ŽQí # compressed integer 6866 v } # for each digit: ₂y- # 26 - digit (20, 18, 20, 20) ‰R` # divmod, reverse, then dump # (pushes the mod then the div) ) # wrap the stack in an array R # reverse '.ý # join by "." ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 74 bytes ``` d=>(i=5,g=(a,m=20-8%--i)=>i?g(a/m|0)+'.'+a%m:a)(new Date(d)/864e5+1856305) ``` [Try it online!](https://tio.run/##VZDLboMwEEX3/go2FbbAExswjyKnm/YLukwjxQKSUvGIwGoVtf12Om6Kquhasnx853rGb@bdzNXUni0fxrpZjnqp9Za2WoUnTU3Y60jw/I7zlult@3CiZtN/CRb44Afmrr83jA7Nh/dobENrtsnTpFGBzFUaC8UW28y2MnPjae9AJEeVXgYSVw4yhviXRTcsIVKkKZcRj1TpSQEyAgEJ8kgIwREXiCOQBWR4IRGj19kxG@vFVYixccnVH8wAS9AsMSPmV2sCOSpFqBKecHmlGcSQghQkLorCBceO5@4t5dpMyaEk62Bgp7anDOZz11rqvww@g@M4PZnqlXbtgINvvU@yu4R9WO@1I6u19NlO7NcT9xmZ7aQvcDb1szWTpUnovpn7Qf/PopXVt4xU4zCPXQPdeKKYE3pHtzFGvlm5/AA "JavaScript (Node.js) – Try It Online") Input as `yyyy-MM-dd` format string. Thanks [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld), save 4 bytes. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 186 ~~163~~ bytes ``` string f(int[]t){int x,n=(int)(new DateTime(t[0],t[1],t[2])-new DateTime(1,1,1)).TotalDays+1137143;return string.Join(".",new[]{144000,7200,360,20,1}.Select(e=>{x=n/e;n%=e;return x;}));} ``` [Try it online!](https://tio.run/##VU/BqsJADPyVUniwwXXdbKs9lPXkSbw9wUPpoZQoCxqhjVgp/fa@VvHwCExgwkxm6nZZt2EcW2kCX6KzCixFKdBPO@o0@5kAxfSMdpXQMdxISWFLLQXO4EpY/juingbAHO9SXXfVq10gJhmmSd6QPBqOPp/M/h5YxSbWk7ooe0xTa63O3ATJxmpnNQ7ml65UiyK/7TvPK8r5x9PXqMsHgHwYT00QOgQmdX7nfDfonZ0t9HoA72NMjDWZcQYxhvEP "C# (Visual C# Interactive Compiler) – Try It Online") Edit: Use `int[]` as input instead of DateTime to meet the specification better. Thanks @keizerharm for the hint [Answer] # C (GCC) ~~239~~ 200 -39 bytes ceilingcat ``` #define S d/m;d%=m;m l(y){y=y%(y%25?4:16)<1;}b,k,t;D(y,m,d){for(d+=1137110+L" ?[z˜·ÕôēıŐŮ"[m-1]+(m>2?l(y):0);--y;d+=365+l(y));m=144e3;b=S=7200;k=S=360;t=S=20;y=S=1;printf("%d.%d.%d.%d.%d",b,k,t,y,d);} ``` [Try it online!](https://tio.run/##XY7PSsNAEIfvfYoQCeySje7sJinpGHPp0VuPxYPNHwl1Y6nxsIa8gyDefAZBELzb9uRDxY14sMsMzPAx8/HLg5s8H4aToqzqpnQWTnGmsPBShWpySzTtdKo9oj0RZeEMYnoO2K/YmrU4J5opVtCuutuSwk8B5BSA@5euky0fv1@/Pncvu4/98/798HR4c5cqgCufqAuRjd4ZpxgEGs2jjCN/RBRVCmFYSlyli3QqOMe1WWTMsTVTcNRmAG62ddNWxPWK03/tst9YTJtI2A/qum4I7SZzAswUxc1De09cl@IfEhbiccxAMBEdc5OCM4MTG5vb8RxsLriR2xIwEmmnEBCFLGRgYZkkyaiWR7wffgA "C (gcc) – Try It Online") ]
[Question] [ A Hamiltonian path in a graph is a path that visits each vertex exactly once; a Hamiltonian cycle is a Hamiltonian path that is a cycle – the path forms a simple closed loop. In this challenge the graph will be a `n x n` grid, where n is an even number greater than 2. Here is an example of a Hamiltonian cycle on 12x12 rectangular grid: ``` +---------------+ +-----------------------+ | | | | +-----------+ | +---+ +-----------+ | | | | | | | +-------+ | +---+ | +-------+ | | | | | | | | | | | +---+ | +---+ | +-------+ +---+ | | | | | | | +-------+ +---+ | +---------------+ | | | | +---+ +-------+ | | +-----------+ | | | | | | | | | +---+ +---+ | +---+ +---+ +---+ | | | | | | | +---+ +---+ | +-----------+ +---+ | | | | | | | +---+ +---+ | +---+ +-------+ | | | | | | | | | | +-------+ | +-------+ +---+ | | | | | | | | | +-------+ | +---------------+ +---+ | | | | | +-----------+ +---------------------------+ ``` The path visits each vertex exactly once and forms a simple closed loop that do not intersect or touches itself. The grid points are not shown so that the ASCII graphic is not cluttered. There are three `-` (`---`) between two horizontally connected vertices or 3 spaces if the vertices are not connected. A single `|` connects two vertically adjacent vertices, spaces are used otherwise. Since the grid is not visible, the `+` is used only where the path takes a turn. The path will never be broken - if a segment connects two vertices, it will be `---` and never `- -`. ## Task: You will be given an ASCII representation of a path and you need to check if it is a Hamiltonian cycle on a grid. Write a full program or a function that solves this problem. ## Input: ASCII representation of a path. It can be: - A mutliline string; - A list of strings - A list/array of characters or any format that is convenient for you. You can have an optional parameter `n` for the size of the grid. You can use alternatve ASCII representation, just explain it. ## Output: * A consistent value indicating that the path is a Hamiltonian cycle on a grid * A consistent value indicating that the path is not a Hamiltonian cycle on a grid. There can be several reasons for this: The path doesn’t visit all vertices; the path crosses/touches itself; there are two or more paths and not a single one. You don’t need to specify the reason – just return/print a consistent falsy value. ## Test cases: Truthy: ``` Optional `n` = 6 +-----------+ +---+ | | | | | +-------+ | | | | | | | +-----------+ | | | +---+ +-------+ | | | | | +---+ +---+ | | | | | | +-----------+ +---+ +-------------------+ | | | +---------------+ | | | | +-----------+ | | | | | | | +---+ | | | | | | | | +---+ | | | | | | | +-----------+ +---+ +---+ +-----------+ | | | | | | | +-------+ | | | | | | | +-------+ | | | | | +---+ +-------+ | | | +---+ +-------+ | | | | +---+ +-----------+ Optional `n` = 8 +---------------------------+ | | +---+ +-----------+ +---+ | | | | +---+ +---+ +---+ +---+ | | | | | +---+ | +---+ +---+ | | | | | | +---+ | +---+ | +---+ | | | | +---+ +-------+ +---+ | | | | | | +-------------------+ | | | +---------------------------+ +-------------------+ +---+ | | | | +-------+ +---+ | | | | | | | | | +---+ | | | +---+ | | | | | | | | | +---+ | +---+ | | | | | | | | +-----------+ | | | | | | | +---+ +-----------+ | | | | | | +---+ +-----------+ | | | | | | +-------------------+ +---+ +---+ +-------------------+ | | | | | | +---+ +-----------+ | | | | | +---+ | +-----------+ | | | | | +---+ +---+ +---+ | | | | | | | | +-----------+ | | | | | | | | +-------+ +---+ | | | | | | | | | | +---+ +---+ | | | | | | | | +---+ +-----------+ +---+ Optional `n` = 12 +---+ +-----------+ +-------------------+ | | | | | | | | +-------+ | +---+ +-----------+ | | | | | | | +-------+ | +-------+ +---+ +---+ | | | | | | | +-------+ +---+ +-------+ | | | | | | | | | | | | +---------------+ | +---+ +---+ | | | | | | +-------+ +-------+ +-----------+ | | | | | | | | | +---+ | +-------------------+ | | | | | | | | | +-------+ +-----------------------+ | | | +-------------------------------+ +---+ | | | | +-------+ +-------+ +---+ +---+ | | | | | | | | | | +-------+ +---+ | | | +-------+ | | | | | | | +---------------+ +---+ +---------------+ +---+ +---------------------------+ +---+ | | | | | | | | | +-------+ +-----------+ | | | | | | | | | | | | | +---+ | +-------+ +---+ | | | | | | | | | | | +---+ | | +---+ | | +---+ | | | | | | | | | | | +-------+ | +---+ | +---+ +---+ | | | | +---+ +---+ | +---+ +-------+ +---+ | | | | | | | | +---+ | | +---+ +---+ +---+ +---+ | | | | | | | +---+ +---------------+ +---+ +---+ | | | | | +-----------+ +---+ +-------+ +---+ | | | | | | | +-------+ | | | | +-------+ | | | | | | | | | | | | | +---+ | | +---+ +---+ | | | | | | | | | | +---+ +-------+ +---------------+ +---+ +---------------------------+ +---+ +---+ | | | | | | | +---------------+ +---+ | +---+ | | | | | | | | | +---+ +---+ +-------+ +---+ | | | | | | | | | | +---+ | +---------------+ | | | | | | | | | +-------+ +---+ +-----------+ | | | | | | | | | +---+ | +---+ | +-----------+ | | | | | | | | | | | +---+ | +---+ | +-----------+ | | | | | | | | +-------+ +---+ | | +-------+ | | | | | | | | | | | +-----------+ | | | +---+ | | | | | | | | | | | | +-------+ | +---+ +---+ | | | | | | | | | | | | | +---+ +-------+ +---+ | | | | | | | | | +---+ +---+ +---------------+ +-------+ ``` Falsy: ``` Optional `n` = 6 ; Two paths +-------------------+ | | | +-----------+ | | | | | | +-----------+ | | | +-------+ +-------+ | | +-------+ +-------+ | | +-------------------+ ; Two paths +-------+ +-------+ | | | | | +---+ +-------+ | | | +---------------+ | | | +-----------+ | | | | | | +---+ +---+ | | | | | +-------+ +-------+ ; The path doesn't visit each vertex +-----------+ +---+ | | | | | | | | | | | | +-------+ +---+ | | | +---+ +---+ +---+ | | | | | +-------+ +---+ | | +-------------------+ ; The path doesn't visit each vertex and touches itself ; (so visits some points more than once) +-------------------+ | | | +-----------+ | | | | | | | +-------+ | | | | | | | +-------+ | | | | | +---+-----------+ | | | +---------------+ ; The path doesn't form a loop and touches itself +---+ +---+ +---+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +---+---+ +---+---+ Optional `n` = 8 ; Two paths +-------------------+ +---+ | | | | | +-----------+ | | | | | | | | | | +-------+ | +---+ | | | | | +-------+ | +-----------+ | | +---+ +---+ +-----------+ | | | | | | +---+ | +-------+ | | | | | | | +---+ +---+ +-------+ | | +---------------------------+ ; The path doesn't visit each vertex +---------------+ +-------+ | | | | | +-------+ +---+ | | | | | | | +---+ +---+ | | | | | | | | | +-------+ +-------+ | | | | +-------------------+ | | | | | +---+ +---+ +---+ | | | | | | | | +---+ | | | | | | | | | | | | | +---+ +---+ +---+ +---+ ; The path doesn't visit each vertex +---------------+ +-------+ | | | | | +-----------+ +---+ | | | | | | +---+ +-----------+ | | | | | +---+ | +-------+ +---+ | | | | +---+ +-------+ | | | | | | | +-----------+ | | | | | | | +---------------+ +---+ | | +---------------------------+ ; Two paths +-----------+ +-----------+ | | | | | +---+ | | +-------+ | | | | | | | | | | | +-------+ | | | | | | +---+ | | +-------+ | | | | | +---+ | +-----------+ | | | | | | | | +-----------+ | | | | | | | | +---+ +-----------+ | | | +---------------------------+ ; The path touches itself (so visits some points more than once) +---+ +-------------------+ | | | | | | | +---+ +-------+ | | | | | | | +---+ | | | +---+ | | | | | | +---+ +---+ | | | | | | | | | | +---+ +-------+---+---+ | | | | | +-------+ +---+ +---+ | | | | | +-------+ +-----------+ | | | +---------------------------+ ; The path doesn't form a loop +---------------+ +-------+ | | | +-------+ + +-------+ | | | | | +-------+ +-----------+ | | | | +-------------------+ | | | | | | +---+ +-----------+ | | | | | | +---+ +-----------+ | | | | | | +---------------+ | | | | | | +-------------------+ +---+ ``` ## Wining criteria: The shortest solution in bytes in each language wins. I'll highly appreciate if you add explanation of the code and the algorithm you used. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~63~~ ~~55~~ 46 bytes ``` AM↗ W⁼№KV#¹«✳⊗⁻¹⌕KV#¦ ¿¬∨﹪ⅈ⁴﹪ⅉ²⊞υω»¿‹LυXN²⎚«⎚¹ ``` [Try it online!](https://tio.run/##nVRRT8IwEH5mv@JSXrpkPkB8kkfQxERwMdFoCA9jVNZYWtxWeDD@9nkDRNa1hdik3V2v3329b7elWZKnKhFVFedclvRernVJw3AQjNWG0Zvn9RNfZiX6@zgBgvY244IBvf3UiSjoUGmMxIx9vCg5YXqVSEnDCEiX4NoLQ/gKOnv4iOcsLbmSdKT0XLAFHXOpC9qL4I7LhSMJDjR2zB3@DnSiSvqY07FaaKHoa33sGufBf6v9fg2CWBcZ1RFsEfkd1NAHVhS4yGWJATwXqy3L91VP9GqO9gEMQ8ES9AYBEwWrKzhuHGrp1UmrajoNSNc3AKDxJBECwD265vwFeDOf2keAIzMYsQbAemdzrwEwMltradRwymTWYwLAcl@rUjuAS3MXg5ndp9ofg6mUi8WmkpfFqZKLxaaSl6XVSyaDGTvXSy3GVi/ZtPf10lmWlqwmwyXdetl7sN33v99DuwZfp5p7ZIa/0v6sutqIHw "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 8 bytes by using a more cumbersome but still acceptable input format. Saved 9 bytes by requiring the path only uses `#`s. Explanation: ``` A ``` Copy the path to the canvas. ``` M↗ ``` Print a space one square in from the bottom-left corner (the print command left the cursor one square below the bottom-left corner). This should break the loop of `#`s into a line. ``` W⁼№KV#¹« ``` Try to follow the line to its end, following the path of `#`s that used to have two neighbours. ``` ✳⊗⁻¹⌕KV#¦ ``` Overwrite the line as we go. ``` ¿¬∨﹪ⅈ⁴﹪ⅉ²⊞υω» ``` Keep track of how many vertices we meet along the way. ``` ¿‹LυXN²⎚ ``` Check whether we managed to visit every vertex. If not, then just clear the canvas. ``` «⎚¹ ``` If we visited every vertex then output `1` as a truthy value (which actually prints as `-`). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ø1©ȧn⁶µŒṪạ®SỊƊƇḢ©Wḟ@ƲƬṖṪ<3Ȧȧm2m€4Ȧ ``` A monadic Link accepting a list of lists of characters (the lines) which yields `1` for a Hamiltonian or `0` otherwise. Uses the layout in the question (any non-space chars as path parts will work). **[Try it online!](https://tio.run/##y0rNyan8///wDMNDK08sz3vUuO3Q1qOTHu5c9XDXwkPrgh/u7jrWdaz94Y5Fh1aGP9wx3@HYpmNrHu6cBlRgY3xi2YnluUa5j5rWmJxY9v/h7i2H2///19ZFAG0FBQUQX5urRgEBamCYJFFtdDPBosjq4GwubTR1CDfUoJkLFtTG61xUY9GBNgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##zVq7blRBDO3nK6a3puDRhYJ/oOALaFBCj@Qi0ERKSYEoQCggJQqKKBCghHQbsdrfuPsjS4jgvuxje@7eIFbaYie@vjN@HB978vTJ7u7zzebqzZ3F6erk2frF98W3n6@ai0/Nj6PF50fN5eHycHnQnH9YnD5uzt8/XH5ZnjUXr68FHtxbHa9O9u7urV@e3V8db5rLr83Fx/X@2531/rurg@vVzYZK96Gc8@/flDh3H/77vVmlnmy3KuQHsq38QG8rn6j37k62/@5Ob192uAe5X/1sO4P19u9gb@NzdLJj@XaRVFEWavvyJFal2Ums1h2ZJu5NyvL4yFhUWpKEbP8YrVpdVKrVT6Y72Xa2o7O1Ztb28ecr4pPcvNItxOqzrOVE/7WqijQ28ECFmn4yJoWVYHrY6T60MvYQSFPVlDgPSM0dIS@epdGqnaMyd1R/JBQ1BmSq@a6fl9DzasTm4LMxO5cK3LHxB9uSIASPdaiZJJNfNYkAH/pHLmSUguK9sipqppLPclXomKWjyqUxFxeAfLjqhkKgKGFQB8xxVxF0OwNdfgghs9gIa4d2AYgv0Zsdm@AQ9CtDWL8aJmTWdqvyZBQmsBiZRSdehApCFbUoZVBoAgVOcGkUfnqYEDq/yoVtkNdt6LmIVewyw1UtznbhUwu8S4SQ3iGp0vTC38ny@fibLMBkE9mysmXMfBEY60wYciKNolo1lvwaHeotign2HMxitaRji9QlGqOaAZPYCxIbj@MUwTI77hhKRcNdQrU4O/bE9TLGwDXAtRkohQAiziFQrbS7fdMuiRzgxt1Q3Pcmxd4CkMP6U5QKZp9em7mW3WLMlg3MDtLVDwsgm@1JfQHkreMbTxUsfCgzDOVoxkGk3Jt2PiDK4UFH/8i6DhkGeCTmUto5Lal3INL7npcj4@boqh6xKudJ5JICSLVoCy/fhjswcLHfZwO9N2cUe9DpYg50BHiCyc7Q@79cza2B2oPNMK/0B0exoZPOeDBxRhMSjHy5j4BUNavxx6QFxwm6G/ABePrE2datA/QYhbLK3XOIZ2aXm9uzEbvVUWlLzXDWnpL6lJ0qsg7d/5HTakx14dSLEDLpBptNN7tNtnndNMaNbHaj2cScbDJgu@maMQkJzu5jN2iVuAL7b@fWx@4lsjUwSn6P44/P/Wd5YsBOd@G2tz7@HbBZGlidsWFMImOWCv4XAY9DegSBk98mwblwIHTKLbqwDkdBGzUhHaaeKXblMD9@@8/WXaDPcvn6Cw "Jelly – Try It Online"). ### How? Starts at the top-left, `[1,1]`, and finds a neighbouring non-space until no neighbours can be found, then checks if the final position is the neighbour below the top-left, `[2,1]`, (to confirm the path was a loop) and that no other non-spaces remain (to confirm there were not multiple paths). If so a final check is made that all the vertices were non-spaces too. ``` Ø1©ȧn⁶µŒṪạ®SỊƊƇḢ©Wḟ@ƲƬṖṪ<3Ȧȧm2m€4Ȧ - Link: list of lines, M Ø1 - literal [1,1] © - (copy this to the register and yield it) ȧ - logical AND (with M) -> M ⁶ - literal space character n - not equal? (vectorises) µ - new monadic chain, call that N ŒṪ - truthy multidimensional indices Ƭ - collect up while distinct, applying: Ʋ - last four links as a monad: Ƈ - filter keep if (find neighbours): Ɗ - last three links as a monad: ạ - absolute difference (vectorises): ® - current register value S - sum Ị - insignificant? (abs(z)<=1) Ḣ - head (a neighbour [x,y] or 0 if none) © - (copy this to the register and yield it) W - wrap in a list @ - with swapped arguments: ḟ - filter discard Ṗ - remove rightmost Ṫ - get rightmost (or 0 if none) <3 - less than three? (vectorises) Ȧ - all non-zero when flattened? ȧ - logical AND (with N) -> - (i.e. N if the entire path looped from [1,1] - back to [2,1] leaving nothing unconsumed - else 0) m2 - every 2nd value m€4 - every 4th value of each Ȧ - all non-zero when flattened? ``` [Answer] # JavaScript (ES7), ~~126 124~~ 122 bytes Takes input as `(n)(matrix)`. Returns a Boolean value. ``` n=>g=(m,X=k=0,Y=0,d=0)=>m.map((r,y)=>r.map((c,x)=>++c|(x-X)**2+(y-Y)**2-1||g(m,x,r[++d,x%4|y%2||k++,x]=y)))|d>1?k=g:k==n*n ``` [Try it online!](https://tio.run/##3VpRSxtBEH73VyyCeOfcBhUp0nLpW39BH5Q0DyHRtI1JJNqSwP73NLYYj8vOzDebSyIVAh7Lzt7Nzn7fNzP7s/e799Sf/Xh89pPp4G55Xy4nZXtYZuPiphyV58Xt6jcoz/OyPW6Ne49ZNisWq4fZv4d@MV89EPVDNvc3@dnZJWULf/vyj78IYbgyMy9mHaJBMT@5CouTyxBGRMW8Wy7yPA@D9sXnUTn8OCrLydlk2Z9OnqYPd62H6TA77Xyd/Xr@vuie5p@OqgP32Yc86xw512m1Wsfk3/7IOffyTMfd4nU8uLe/8PqrjVNlfmx8wwYzf22DWX9tozJOlfeOza@@d2z96nzu/aXvZ/x31M1Xbgf9vp5v@O6632LzN2xExkmZH4T1qzZIGJfihoTxXfmdGvxuaX4Q/I7Ml/adhPlVv8XW1@ZL6zP@i/r9Wol3NO7h94jgl4t9z@uzgANkwENtn4JiL8Qwinm/qN3a97qYLQA3pXO8sRcAHqF4zu2vEC9J8abtJ4I3pODWhg3BHtXGURyVcCkaJxofo7ys4LTmP@JsKufVbWHPur/ewCvXCq@g/ILsJwE8v2FXwSMJf6N7IPAIvbN4Cxy2Ce8n6cTYfkj2QuJ5kOLt4lITMokBaA1IzxAbIkStAesjQZtK0CkBQ0BABsa@JeA5n6IEih5YzxC/RNhB8SdyYCwCAV5TiU8CBackShwQn6xQAQVHigDxHPgqgsQxgsIkeISEmzsLWnwS57t4opsGkOgGaUERFOQXD5ei8FAFFFWOBkXPrcVlDLG12GcFQLgfQgBIRuViWTAQgCSsgWSYrFJXMjpJTZFFoRkrBx4k1AACllMUHeLPVAAJHFkDgKXFJ0pwKQpR2kckY/fbKEgVGI0MFhIUjzVljbEZmkKRESBTFCSndtBSp@hThaGRFEoqESEBKKaSDRMcvCaQAaQoZDICiDMorCD5DywJqWsCAgXJOLYVKKHB84eUNCVw5BXk6bdJ50vv4cnSNGuieQMVTRpumnmhCRCVE4b56PqIpo/5XVtXOgFI88OS8x1i37XagHRCsJPQfJN4m3ENMZyiBMggcZFUhPYc74eMN4T5EAWWsv5fPwvvr6V0zlA74JrESNMuOHvz@38cd/WNWzvvQF07S1fB2qXQUhYkJ@cK3BAhM8RMiUV5S1fRIwcCuH1gERD76BKj76MJjDpZOaXm4IwprDPUFNAiOVzzUVKYbbueaFfRUnKgFEADbotRQpd4V/HW5C0OAhMMpKjP1qW3vKVTx3MH1hAdyA8OLUGhJa4D45vGBym3mprgA7ZOm3ALBi3ZOKn3ocSvN5RkkBKMB0suTZzXfcTbLm7BWG4tovojKD0rhF9IaJCqt5CRGn9FR4cEfhAbxYnnwb@zeEvlU7Uw1hB@NOkv6yWKffO9xV7qrdJd3/Jb/gE "JavaScript (Node.js) – Try It Online") ### How? Starting at \$(0,0)\$, we flood-fill the path and increment a counter \$k\$ each time we go through a cell \$(x,y)\$ such that \$x\equiv 0\pmod 4\$ and \$y\equiv 0\pmod 2\$. At the end of the process, we must have \$k=n^2\$. We additionally make sure that no cell has more than 2 neighbors. If it does happen, we set \$k\$ to a non-numeric value to force the final test to fail. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 54 bytes ``` n⁶,Z$µØ0jm2N,¹ƇɗƝ)m2)Z×LƊ€2¦Ẏ€;"/µØ-ḟN}Ḣɗ,+¥ƭƒịṪ¥¥ƬL=L ``` [Try it online!](https://tio.run/##rVi9bhNBEO7vKUYoTTRegdJGoDxAlAdITxMl9EiLFGgsEYkCilAQIYFCgUIHVky6s7CUxzi/iDnfz@43P2c7CKfI3u7c7sw33/zsnTw/PX25XL5YvJ6MjnfKX7OPT07O9o5G5XQ@vr@cX@2e7e0ezy4P528Xb272ym/V73f1YP/R45VoqG4/H72qbr/cX464vJ7/mL@v7i6q6ffyun66OXx6uNxfnH8qJ@EZLc6v9qu7n7PxTvHnQzX92swflJN6fjautzxpJprn5ZLD6sfEgYtIq19c/dVjbubbcVrp5puVTr5ZKbjZo51v92jl2/l@n7w/nnvQPTUzYtf@tHY@rTRjhvmY5NsVTuNsDafxsBa8dtc8H5MWcj5rzWm@Pa2Vx/ksj@ciFhoPI93oTQT@qU/pEWfjVdQuwnrM/ureB5mi17@TAU9nnJN2wmeaJb3@0j7hfdBYeonBg2klrXcrxvPZf2AV8llzGhiC5zNKAOLkrnv6hwGmabZJjVlwP8mADzNHQKfENP5HiyMJzMX5UeiX1@MAYia2Biz3EAjAVJkFPERCwmSI/b6FLJAAzzqIoUaa3doDASIlR0NU@khEbfS4bwA@rLKFjDcS@IjIU7Hmx1xAHkHsEYm8oWM01QJEE/Fh1AKyvI4N1FTbFoF7CmfIAjpaIVOYPIbSfb7L0uJ/IVFIpxWSt1ExkQgqAuRT5DnmdZHJID/LCGebA5xqFFRkRMfzBLlB6jPkyYjxIzyv8dFM93OItEHWmzDQNQQn5knpK2PYqweZ2ToLs8MUP6dgBOuOQ2lUsOK/rG8@Eirzb2C6@0bhZlCb9ZUnycR8JFVHVCSpN0SkRlWdhiM1bsRfdiaSJ2Gr/pK37nLzrhBlYj66vU6vBUplXGRfaHP29lpjXcq4WCy8jt8fI/KQvwo2uUTmP96IxcNsk3yMtk8Q8vXpaR/MtuTUGtkHR3N3@P/jlXbNqVv1v7Zb87o5zGeyAmBnpJjbsZcHeizbPweJFF5rbABsavj1GxgQPekISgk5iZlM6dDNkSl1kLiG2m/dPttCwr5rxaWXTalab/H6SxWrpBRVExFN86AvhT2FSBVzUhQjXRJ16dzaxyyuKN411CcVwbNeR4sjfHQQNhe26NkLhl2PaxHfZPHmS539BIAWi4usYR2LBlt8ZpGNUmDTepNqN3zEwoMtHmK1KJdrfLT@RO8y9JCosOtDnyq2urj/BQ "Jelly – Try It Online") A monadic link which takes a list of strings as input and returns a boolean. The strings use the format of the question but omitting every other character (so half the width). Full explanation to follow. [Answer] # [J](http://jsoftware.com/), 125 bytes ``` p=.((,-)#:1 2)|.!.0] f=.([:(''-:2 0~.@-.~[:,]*+/@p)' '~:])*1-1 e.[:([:,@(,]+1=(2|#\)*/4|#\@|:)([:>./]*"2 p)^:_)_(<0 0)}' '~:] ``` [Try it online!](https://tio.run/##zVpLbxNBDL7PrzD0kGzd2SYRp6WpIg4cOXEroUKoDyEkKh4HJNO/HtIUNpsdf/bMJkVUippOvM6MH58/e/pptbqb1@PxSayOminNKqmf1ZNluF4vXjTj0Sg2M5rc14tY3180J8tjPl3cVSMa3TfL6ngap3RVr@XWHy3GJ0uezsczOXpXHZ@@WP9aSFOtPzqvT5fHz2d0V71vLqvL8dmEJtWvRx2rm3lNFw1dL5rzl/Xl7OH92ebNMoQ3r2p6@/XH99uf4erj7Re6oQk1k8Bx@8NE9PA3B6Htj/x9bVa5I7tdTeR3ZFv5Hb2t/GYP3Ncdut@91duV3d1Dul/9bPOd9fZzsLf@Obayffl2kVVRSdR25TlZTc3OyWrZkXng3lJZ6R8Zi6aW5ES2e4xWrS6aqtVPpjvZdrajs7Umafv480rik9280i0k6rOi5UT3a1UVoW/gHRVq@qUxmVgJpoed7rtWxh4CaaqaEucBq7mTyCfPcm/VztE0d1R/BBQ1BmSq@a6fl9HzasRS5rN5do4FuGPjD7YlQwju61AzKU1@1SQJ@PA/cqGgFEy@N62KmqnSZ6UodMzSUeTSPBdHgHy46maFQFTCoAyY813F0O0CdPkhhMxiI6wd2hEgfore4tgEh6BfGbL1q2HCZm23Kg@hMIHFyCw6@UUoIlRRixKBQpNR4BIujcJPDxNG51e5sA3yug09F4mKXWa4qsXZLnxqgXeJENK7S6o0vfDvYPm8/woWYIqJbKRsGTNfBMY6E4acSKOoVo1lv0Zn9RbRBHvJzGK1pGOLlCWaoJoBk9gLEhuP8ymCZXbcMcSChjtm1WJy7InrZR4D1wDXZqCcBRD5HALVSrvbN@0S2AFu3A3l@96k2HsAcrb@kEsFyafXZq6RW4zFsoHZQbr6YQEUsz0pL4Cyd3zjqYKFD39JRPU4onz94fM3PKEsndbxASeU6aa1gwNRyZ6AdPFS15HGB56VuVz3kJbUW5M0LDT3l86hc1f1UFbJUGCXLUAOxnt4@SncgRFN/AYc6N2cMdmDziMpo1XAo01xpuH/5Sq1BmoPdoBBpj9RyptG6VQIM2o0OsHIR10E5KIhjj8/jThO0KWBD8DDR9G2bh2g@yhEKqmnLAJKLmm3hyZ2D6TymZKprT0@9bk8F2QduhhkpwcZ6sKhNyRs0g0xu3Fxu2/zHqqPG2S2qWRiDpnU2O7GDpiEDIf6eVdrhbgCG3PnOshuMsiaJAW/@fHn6v6zMjBgh7tw3@sg/3LYLA2iDt8wJrExZAX/pIDnJB2CIMHvn@DAOCN04hO6sAxHQRs1IB2GninvLuLw@O0/W3azfqhb2Wr1Gw "J – Try It Online") Just a first draft, but all test cases are passing. Will attempt to golf and add explanation this week. ]
[Question] [ Given a list of date ranges `r` as input, output or return any ranges not found in `r`. For the sake of this example, input will be in `YYYY-MM-DD` format. Let's say you have three date ranges: ``` [2019-01-01, 2019-02-01] [2019-02-02, 2019-04-05] [2019-06-01, 2019-07-01] ``` You can see that there is a gap in between `2019-04-05` and `2019-06-01`. The output will be that gap: `[2019-04-06, 2019-05-31]` ## Rules * Input and output can be in any reasonable date or collection format, as long as it is consistent. * Assume the input is not ordered. * Your date range does not have to be `[latest, earliest]`, but it does have to follow rule 2. * Assume there are no overlapping dates in the input ## Test Cases: Input: `[[2019-01-01, 2019-02-01],[2019-02-02, 2019-04-05],[2019-06-01, 2019-07-01]]` Output: `[[2019-04-06, 2019-05-31]]` --- Input: `[[2019-01-01, 2019-02-01],[2018-02-02, 2018-04-05],[2019-06-01, 2019-07-01]]` Output: `[[2018-04-06, 2018-12-31], [2019-02-02, 2019-05-31]]` --- Input: `[[2019-01-01, 2019-02-01],[2019-02-02, 2019-03-02],[2019-03-03, 2019-07-01]]` Output: `[]` --- Input: `[[2019-01-01, 2019-02-01], [2019-11-02, 2019-11-20]]` Output: `[[2019-02-02, 2019-11-01]]` --- Input: `[[2019-01-01, 2019-02-01],[2019-02-03, 2019-04-05]]` Output: `[[2019-02-02, 2019-02-02]]` or `[[2019-02-02]]` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~28~~ ~~25~~ 24 bytes Anonymous tacit prefix function. Argument and result are 2-column matrices of day numbers since an epoch, each row representing a range. ``` 1 ¯1+⍤1∘{⍵⌿⍨1<-⍨/⍵}1⌽⍢,∧ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfnvmfeobUK10aO@qX6ByuouiSWpIfmeLn7qj3q31h5a8ahtIpd/aQlIiTGQDVMGVBCSD1ILVfbfUOHQekPtR71LDB91zKgGCiY86tn/qHeFoY0ukNQHqTJ81LP3Ue8inUcdy/@nAQ181NsHNM3T/1FX86H1IMOBvOAgZyAZ4uEZ/B9oq0KagmeegoaGkYGhpYKBIRBpQtlGILYmXArINYJJmSgYmCJJmSHpMgfr4tLV1eUi2nQLJNMtqG46mtuNQWyEFJBrjGo6AA "APL (Dyalog Extended) – Try It Online") The `In` pre-processor function converts from a list of pairs of 3-element lists (dates in ISO order) to a 2-column matrix of IDNs, International Day Numbers (days since 1899-12-31). The `Out` post-processor function converts from a matrix of IDNs to a matrix of 3-element lists. `∧` sort rows ascending `1⌽` cyclically rotate the dates one step left  `⍢,` while ravelled (flattened) — afterwards, reshape back to original shape `1 ¯1+` add one and negative one `⍤1` using that list for each row `∘` of the result of `{`…`}` the following lambda:  `⍵` the argument  `-⍨/` subtract left-hand date from right-hand date, row-wise  `1<` mask where differences exceed one (i.e. where ranges are not adjacent)  `⍵⌿⍨` filter the rows by that mask [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 108 bytes ``` n=>{n.Sort();for(int i=0;;)Write(n[i].b.AddDays(1)==n[++i].a?"":n[i-1].b.AddDays(1)+""+n[i].a.AddDays(-1));} ``` Outputs by printing in the format `DD/MM/YYYY 12:00:00 AMDD/MM/YYYY 12:00:00 AM`. Will cause an IndexOutOfRange exception, which is fine per meta consensus. [Try it online!](https://tio.run/##1ZA9a8MwEIb3/Arj6YRlY9n9SKPIJZAxWwMdTAZFkckNkcEWhGD8210pkECounVoJx3PvToeXtWnqsdppSy2ZrnB3i5hLa3e4klHkt7HPamqRkxGVIPJPtrOAuFN2wEaG6HIOSefHVoNpsZdts9Wh8NaXnpgRAhTJ4mD8j2OF26dssdAEsfJ9Ze8w5QRwseJz2x3GRow@lzvBv9ENx8ocvZGGWWEfseFw4RCaFGE8k/0OZx/Cd9/9ffHbNv6usCrKmnVcRhn1w42aLRr53fl52H5@b@Q/7H50uFgvqTl35FnLGzveR72mb4A "C# (Visual C# Interactive Compiler) – Try It Online") If we take input in the form of days since the unix epoch, we can get this down to... # 83 bytes ``` n=>{n.Sort();for(int i=0;;)Print(n[i].b+1==n[++i].a?"":n[i-1].b+1+" "+(n[i].a-1));} ``` [Try it online!](https://tio.run/##vY@xCsIwEIZ3n6JkSkhbmmCb1JiKewdBwaE41NBilhTSgEjps9dEHQU3b7j7/@O4706NiRr1sldOD2Zb69FtoTYuauOQr6iqerkYWU0mPQ7WQST6wb4mtMyEQAfrNTSNvqRXTKQ0DcZetzsANr6bkFcfgwjg91SbEITEvIiVs4@ph6a7N5cJEsZLFhNWUo5iGGoZXEmC49maxz4zjub0NIQrYViiWqdu07w6W@26WpsOguRnAPQDnRdr7wpa/B/9@Tpnb5f/D81pRj2M0uwrbHkC "C# (Visual C# Interactive Compiler) – Try It Online") We can golf this down even further with the `/u:System.Array` flag, for... # 78 bytes ``` n=>{Sort(n);for(int i=0;;)Print(++n[i].b==n[++i].a--?"":n[i-1].b+" "+n[i].a);} ``` [Try it online!](https://tio.run/##vZGxbsMgEIb3PEXEBMKkNooNDiVR9gyVMnSwPBBkqwzFFaaKLMuvXgpJh26Z2hvu/v90p0@n0yPRowlH7c1gn6Gxfq2ylC@oafe9DFbu5/PgPLRI9IO7TRiZC4FeXNQQY9uYdnOR0jYYR6UIOQCwi11SxD4Ga3AfUUgsQay8m@Ye2u7atDMsGK9ZVrCacpTBVOvk6iI5nm95FjPjaIm7Wnn9Ni@rV2d8dzK2g4A8DIAeEMtqG11Fq38j/txYsrsr/5zIaU4jg9L8NyN8DR/p6WN4@tydp9F375ujc2r6Bg "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # Perl 5, 130 bytes ``` /-(\d+)-/,$_=strftime"%Y-%m-%d",0,0,0,$'+($|--||-1),$1-1,$`-1900 for@F=sort@F;$,lt$;&&say"$, $;"while($,,$;)=@F[++$i,$i+1],++$i<@F ``` [TIO](https://tio.run/##nZHBSsNAEIbveYqwTGpCduxMarRlDeQU8CAKXioqWmiKC0lTkgUp5NldN1pSPAhFZg4fPz8fA7Mr2yq19R60slMMn9dxhFMJr1ln2o3RdSmCRwxqDNZC0vfAWRxCj9j3yJEERpbwhrwg8jdNmxdZ17QmLxTIyoCaTLrVXoD0QYmPd12VIUgJKsry4imOQUvQMb/IAa/zwqqhjYjCJsQLJHbr/2Di0BsxOaQXSOkhvTx2r4au96diflTM/6n4fcXMoTfi7FQF86hwmNBnszO62XYWV9WWyOLt/d3DzXL8hQvSc@Iv) [Answer] # Bash, 125 bytes ``` set `sort<<<$1`;shift;for a;{ s=$[x++%2?-1:1]day;c=`date -d$a\ $s +%Y-%m-%d`;[ $p ]&&{ [[ $p < $c ]]&&echo $p $c;p=;}||p=$c;} ``` [TIO](https://tio.run/##nY7faoMwHIXvfYofXdJCJdTY/ekWw55jaCGZSTHgVBq3dVif3SWutfRiMAZefH45OTmv0haD4SJZKf2xsq0ylQg@C1NqSFNABjgs0SKrsmqxhO12Pu@g5KgzGJ9tz4wXN@dYz/rjcUwZd8J65ntKd5epGqxugRCYoXLG4L3yvwdowIIcPAtb79skSRAVzBZm17JdvQfJOrAcpYcwxPEzoU90q@QXy7lQstVAFJIZIAshfiH4jWAlmHuygXFtOmICKB/n67yovUA5a7hf2nCH/TB6Qkig6koPcUQfSUTdBz8YOwwmjE/2lkR3J3t/yT74bPBrxeZSsflnxfWKtcNgwvVfKyidKhzG0Tc) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` FṢṖḊs2+Ø+>/Ðḟ ``` Jelly (currently) has no built-in dates, so this uses days-since-epoch. The input list of ranges (pairs of integers) may be in mixed order and mixed directions. The result is a list of ascending ranges in ascending order. **[Try it online!](https://tio.run/##y0rNyan8/9/t4c5FD3dOe7ijq9hI@/AMbTv9wxMe7pj//3D70UkPd874/z862txcx9DAIFYn2txSx8wMSJvqmIG4RjomsbEA "Jelly – Try It Online")** (footer formats in order to show an empty list as `[]`) ### How? Note: This relies on the assurance that "there are no overlapping dates in the input" as stated in the rules. ``` FṢṖḊs2+Ø+>/Ðḟ - Link: list of pairs of integers F - flatten Ṣ - sort Ṗ - pop (remove tail) Ḋ - dequeue (remove head) s2 - split into twos Ø+ - literal [1,-1] + - add (vectorises) Ðḟ - filter discard those for which: / - reduce by: > - greater than? ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 46 bytes ``` {@_.sort[1..*-2].map:{$^a+1,$^b-1 if $b>$a+1}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2iFerzi/qCTaUE9PS9coVi83scCqWiUuUdtQRyUuSddQITNNQSXJTgUoUFv7vzixUiFNo0Yl3s4OpFKj2iWxJFUvL7VcQyVes1ZTUyEtv4hLQ0PdyMDQUtfAEIjUdRSgPCMQT1NHQQPBN0LImugamCLLmqHoNQfr1dQhymwLFLMtqGo2hruNQTwkWSDfmGyzDQ2RzQbyjAxIdJkxeohq6vwHAA "Perl 6 – Try It Online") Takes a list of `Date` pairs. [Answer] # PHP, ~~208 197 190~~ 177 bytes hunky chunky sat on a wall ... though the new approach had quite some golfing potential. ``` function($a){sort($a);for($m=$x=$a[0][0];$f=$m<=$x;$f^$g&&print($g=$f)?"$m/":"$n ",$m=date("Y-m-d",strtotime($n=$m)+9e4))foreach($a as$d)$x=max($x,$d[1|$f&=$m<$d[0]|$m>$d[1]]);} ``` function takes array of ranges [start,end] in ISO format, prints gap intervals. [Try it online](http://sandbox.onlinephpfunctions.com/code/d08ba50b9b6ff0531d16c7f9df644c4eabd270c4). --- ## breakdown ``` function($a){ sort($a); # sort ranges (for easy access to min date) for($m=$x=$a[0][0];$f=$m<=$x; # loop from min date to max date, 1. set flag $f^$g&&print($g=$f)?"$m/":"$n\n", # 4. flag changed: backup flag, print date $m=date("Y-m-d",strtotime($n=$m)+9e4) # 5. backup and increment date )foreach($a as$d) $x=max($x,$d[1 # 2. find max date |$f&=$m<$d[0]|$m>$d[1] # 3. date found in ranges: clear flag ]); } ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 103 bytes ``` x=>{var(a,_)=x[0];foreach(var(b,c)in x.OrderBy(y=>y)){if(a<b)Print((a,b.AddDays(-1)));a=c.AddDays(1);}} ``` [Try it online!](https://tio.run/##tVLfa9swEH7PX3Foe9AR29jO1nV1ZOjoS0vCSlPogzFDsZVUkDjF0lqb4L89O@VHmzx0MLYZGT59p/vuO@kK4xdGby4Lq1fV8HqkjR3yK2nVvV4q7wAwTWdi04h0/SxrLr0fKJoszJPZqlayeOSOnXoF6gqa4Htdqvpby1uRtohrPeNyOMXbWleWU@40uCzLK9ka7keImEhRvDIRJl23SXq9d33AnazmyvAnWculAWNJdp7l8CwXP5VBke5ADyCYqIUqLCfXnLYAB5HgVtZG8SaYPC205UiNoPf7E1FOTp3m/co540gWqWewylgDAir1kuVrOrB3t1VjcRh99cOIFuxgTJB5x0Fi4n3wkx9@Pg2evWV@cZkU2xr9oyLnb0XO/1uR004GBE@DxAz@QZEoei1CMA7/xuzg@Np3Ol3So4HmNKegRZhoGO4eOBipam4fE9D9PrpXPjy92IYznSdEPtTaqpGuFGcfGPRB088uIHN4sh3T4GalK848oOUyjyb0I1s3wbVVy@iipc8fj/2y7GBPxsckQ3TKOUNXdcadEp4aoG23@QU "C# (Visual C# Interactive Compiler) – Try It Online") Input is a list of start/end date tuples. Outputs each missing range to STDOUT. ``` // x: input list of start/end date tuples x=>{ // variable definitions... // a: 1 day after the end date of the previous range // b: start of the current range // c: end of the current range // start by deconstructing the start date of the first tuple // into a. a will then be a DateTime and will contain a value // at least a large as the smallest start date. var(a,_)=x[0]; // iterate over sorted ranges foreach(var(b,c)in x.OrderBy(y=>y)){ // if the day after the end of the previous range is less // than the start of the current range, then print the // missing days. if(a<b) Print((a,b.AddDays(-1))); // save the day after the current range to a for next iteration a=c.AddDays(1); } } ``` [Answer] # [R](https://www.r-project.org/), 88 bytes ``` function(a,b=a[order(a$x),],d=c(b$x[-1]-b$y[-nrow(b)],0))data.frame(b$y+1,b$y+d-1)[d>1,] ``` [Try it online!](https://tio.run/##TctNa4QwEAbguz9DBBM6ESP9WtgUhN097a3HkMPEiUXYVUnSVn@9q9sWCsPAM@@8fmn3Ymk/@yZ2Q88QrEI9eHKeYTZxMECqYTabtJBG2GzWovfDN7PcQMk5YcSi9Xh168/8IGHbJCTX9CbBLKS8Qyqa8MWim6LKJ5iTtCrlTpRynRR@UW24J693VD/JikdRPqV/nef/nZcNeQIh@q7/CHU4YRMHH9SpPr8feULa7MUFx/EyMwIMxQGjW89Jy4gvNw "R – Try It Online") This takes a data frame of date ranges as input and outputs a data frame with the ranges that are missing. I’m fairly sure this could be golfed more, but I ran into issues with `c`, `cbind` and others stripping the date class. ]
[Question] [ In this challenge I will ask you to find a QR decomposition of a square matrix. The QR decomposition of matrix **A** is two Matrices **Q** and **R** such that **A = QR**. In particular we are looking for **Q** to be an orthogonal matrix (that is **QTQ=QQT=I** where **I** is the multiplicative identity and **T** is the transpose) and **R** to be a upper triangular matrix (every value below its diagonal must be zero). You will write code that takes a square matrix by any reasonable method and outputs a QR decomposition by any method. Many matrices have multiple QR decompositions however you only ever need output one. Elements of your resultant matrices should be within two decimal places of an actual answer for every entry in the matrix. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") competition so answers will be scored in bytes with fewer bytes being a better score. --- ### Test Cases *These are only possible outputs, your outputs need not match all of these as long as they are valid.* ``` 0 0 0 1 0 0 0 0 0 0 0 0 -> 0 1 0 0 0 0 0 0 0 0 0 1 , 0 0 0 1 0 0 1 0 0 1 0 0 0 1 0 -> 0 1 0 0 1 0 0 0 1 0 0 1 , 0 0 1 1 2 3 1 0 0 1 2 3 0 3 1 -> 0 1 0 0 3 1 0 0 8 0 0 1 , 0 0 8 0 0 1 0 0 1 1 1 1 0 1 0 -> 0 1 0 0 1 0 1 1 1 1 0 0 , 0 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 1 0 0 -> 0 0 1 0 0 0 0 1 0 0 0 1 1 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 0 0 0 0 , 0 0 0 0 1 ``` [Answer] # Julia, 2 bytes ``` qr ``` The function `qr` accepts a square matrix and returns a `Tuple` of matrices: **Q** and **R**. [Try it online!](https://tio.run/##yyrNyUw0@/8/Lb9IoSS1uEQhM09Boyq1KL9YwzOvREfBGIg0dRRSK1NR@NGGCkYKxtYKBgrGCoYgykDBIlaHSwEZRINEwZKGCgbWQAIIY4FagRoVTEB8I5CspYIpDq1w7QYwI6AMCBNsHsRgqJJYTbApBUWZeSU5eRqFRRogH2lqcqXmpfz/DwA) [Answer] # [Octave](https://www.gnu.org/software/octave/), 19 bytes ``` @(x)[[q,r]=qr(x),r] ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzOrpQpyjWtrAIyAYy/qdpREcb6hjpGMdaRxvoGOsYgmkDHYvYWM3/AA "Octave – Try It Online") My first Octave answer \o/ Octave’s `qr` has quite a few alternatives in other languages that return both **Q** and **R**: `QRDecomposition` (Mathematica), `matqr` (PARI/GP), `128!:0` - if I recall correctly - (J), `qr` (R)... [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes ``` QRDecomposition ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Yb8z8wyCU1OT@3IL84syQzP@9/QFFmXkl0WnR1tYGOAhwZ1uooIAQMgSRCwBAiDBUwhCGwgCGKGbWxsf8B "Wolfram Language (Mathematica) – Try It Online") I mean... what can I say? [Answer] # [R](https://www.r-project.org/), ~~38~~ 37 bytes ``` pryr::f(list(qr.R(q<-qr(m)),qr.Q(q))) ``` [Try it online!](https://tio.run/##K/qfZvu/oKiyyMoqTSMns7hEo7BIL0ij0Ea3sEgjV1NTB8gN1CjU1NT8n2ubm1hSlFmhkaxhoGOgYwjGhhBaU8dYkysNqOE/AA "R – Try It Online") [Answer] # [SageMath](https://www.sagemath.org/), 27 bytes ``` lambda x:matrix(RDF,x).QR() ``` [Answer] # Python 2, ~~329~~ 324 bytes ``` import fractions I=lambda v,w:sum(a*b for a,b in zip(v,w)) def f(A): A,U=[map(fractions.Fraction,x)for x in zip(*A)],[] for a in A: u=a for v in U:u=[x-y*I(v,a)/I(v,v)for x,y in zip(u,v)] U.append(u) Q=[[a/I(u,u)**.5 for a in u]for u in U];return zip(*Q),[[I(e,a)*(i>=j)for i,a in enumerate(A)]for j,e in enumerate(Q)] ``` We must use fractions to ensure correct output, see <https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process#Numerical_stability> Indentation used: 1. 1 space 2. 1 tab [Answer] # Python with numpy, 28 bytes ``` import numpy numpy.linalg.qr ``` ]
[Question] [ You probably know the rhetorical question of whether [a glass is half full or half empty](https://en.wikipedia.org/wiki/Is_the_glass_half_empty_or_half_full%3F). I'm getting a little tired of the phrase, so I decided that it's time to eliminate this confusion about glass fullness or emptiness programmatically. Your task is to write a program that takes an ASCII art representation of an *ugly glass* and outputs an ASCII art of a corresponding *nice glass*. It also has to decide whether the glass is `full`, `mostly full`, `mostly empty` or `empty` and output this as well (any 4 constant, distinct output values do). ## TL;DR Input is an ASCII art of a glass (`#` characters) and liquid (`a-z`) distributed randomly inside and outside of the glass. Liquid within the glass falls down and accumulates at its bottom, liquid outside of it gets discarded. Output an ASCII art of the glass after the liquid has settled at the bottom. Determine how full the glass is and output that as well. ## Ugly and nice glasses A *glass* in general is a container made out of `#` characters with a bottom, two side walls and no top. * Valid glasses do not have holes in them. (All of the `#` characters have to be connected.) * There will either be at least two `#` characters in each line of the input ASCII art, or none. There won't be a line with exactly one `#`. * The top line of the input ASCII art will always have exactly two `#`. * Valid glasses have exactly one local minimum in their delimiting wall of `#` characters. This means that liquid can't get trapped somewhere. * The delimiting wall of a glass will not have local maxima. * There won't be any `#` below the bottom of the glass. * The interior of the glass will always be a [connected space](https://en.wikipedia.org/wiki/Connected_space). * There may be leading/trailing whitespace and newlines in the input. Examples of valid and invalid glasses: ``` VALID (possible input to your program): # # # # #### # # # # # # # # # # # # ## # # # # ### # # # #### # # # # # # # # # # ######## # # # # # ### # ### # ### ##### INVALID (you won't get one of those as input to your program): # # # Has a hole. #### # # # # This is also considered a hole. ## # # # # Less than two # on a line. # ## # # # More than two # on the first line. ### # # # Less than two # on the first line. ### # # # # # More than one local minimum. # # # # Liquid might get trapped. ### # # ### # # # # #### Interior is not a connected space. # # # # #### # # # ####### # ### # # ## # Has a local maximum. # # # # # # # ###### # # # # # # ##### # # <--- # below the bottom of the glass. # # # # # This is also a glass with a hole. The #'s aren't all connected. # # # # # ####### ``` An *ugly glass* is a glass with liquid just floating around in its interior. * Liquid is represented by the lowercase letters `a-z`. * There will be no liquid above the first line of `#` characters. This means that it's not required to allow for liquid to fall into the glass. * There may be liquid *outside of the glass*. This liquid will get discarded when converting the ugly glass into a nice glass. Examples of *ugly glasses*: ``` # y b # i x v#p q l# l a # a zj # p g g #ppcg c# u # r n # r ########## Discard Keep Discard <-- There will never be liquid above the glass # tz g# #y abc # d av z#ox s # l c#y abth# b #vg y rm# a ######## e a b c d <-- Discard this as well (not within interior) ``` A *nice glass* is a glass where all liquid has accumulated at the bottom. * From the bottom up, the interior of a nice glass consists of a number of lines that are completely filled with letters, followed by at most one line that's not completely filled with letters, and then a number of lines that are empty. * There may not be any liquid outside of the interior of a nice glass. ## Conversion of an ugly glass into a nice glass * The liquid inside the glass falls down and accumulates at the bottom. * Liquid outside of the glass gets discarded. * When converting an ugly glass into a nice glass, the exact letters in it have to be preserved. For example, if the ugly glass has three `a`'s in it, the nice glass has to have three `a`'s as well. (Soda doesn't suddenly turn into water.) * The letters within the nice glass do not have to be ordered. * The shape of the glass has to be preserved. No `#` characters may be added or removed. * Any amount of leading/trailing whitespace and newlines is allowed. ## Determining glass fullness * A glass is `full` if its entire interior space is filled with letters. * It is `mostly full` if 50% or more of the interior space is filled. * It's `mostly empty` if less than 50% of the interior space is filled. * It's `empty` if there are no letters in the glass. * There may be any number of additional newlines and spaces between the ASCII art glass and the fullness output. * The program may output any distinct (but constant!) values for the 4 levels of glass fullness, it doesn't have to print the exact strings above. Please specify which value represents which fullness level. ## I/O examples ``` Example 1 input: # y b # i x v#p q l# l a # a zj # p g g #ppcg c# u # r n # r ########## Example 1 output: # # # # # # #ppcglqb # #yprazjnc# ########## mostly empty Example 2 input: # tz g# #y abc # d av z#ox s # l c#y abth# b #vg y rm# a ######## e a b c d Example 2 output: # # # bc # #oxysa# #ygabth# #vgtyzrm# ######## mostly full Example 3 input: # # # g # f ###ih # d a c # # e b #### Example 3 output: # # # # ### g# #hi# #### mostly empty Example 4 input: #ab# #cd# #### Example 4 output: #cb# #da# #### full Example 5 input: # # h # # a # # g b# # f c # # # # e d ## Example 5 output: # # # # # # # # # # # # ## empty Example 6 input: # b az# #y s ### ###### t l u Example 6 output: # z # #ybsa### ###### mostly full Example 7 input: # # g # b #f # c### #da ### i # e### ##### h Example 7 output: # # # # # ### #de ### #abc### ##### mostly empty ``` # Misc * This is code golf so the shortest answer wins. * If possible, please provide a link to an online interpreter that can be used to run your program on the provided example inputs, for example [tio.run](http://tio.run) [Answer] ## [Retina](https://github.com/m-ender/retina), 56 bytes ``` T%` l`!`^.*?#|[^#]+$ O` |\w *`! T`#!¶ *M` \w +` \w + ``` [Try it online!](https://tio.run/##TVBBTsMwELzvKyZaKqE24gu8AHGgN0plJw1JUCglhNBGfRcP4GNh1rYKluPd7M7OjN1XQ7v382YvuTy4PJfFNcO8Xjh0LnPbm@Wtnh@3@rS6knuH8@ZLli4TyNpp9vMtyzsH1lbhFKzmGWkpThYKJmG1wuPIb9QD8M6ks07Hsk8DFqcXJgSgllCt2TgcSgaUaqXPiEXPsA/kvVw0L0skooaJFGEOeoIvShZ3Aj9i0rcjPgxjFkhu7aFRFGF0rOm/fzV@L/@5BRWC5QIlyCXpfmpJHVSfxdBtY@Q78TBR7ko4g@hOfcGBcscjudW/h2uS@UhrYhob4U2K9GMyZcLFG0YZ06GuKZk5SvqJMie7rEY9VQwEdXzNXw "Retina – Try It Online") The output encoding is `0\n0` for full, `0\n1` for empty, `1\n0` for mostly full and `1\n1` for mostly empty (in other words, the first bit indicates "mostly" and the second bit indicates "empty"). ### Explanation ``` T%` l`!`^.*?#|[^#]+$ ``` We start by turning all spaces and letters outside the glass into `!`. This is done by matching either a line-beginning up to the first `#` or by matching a line-ending that doesn't contain a `#` and transliterating all spaces and letters in those matches. ``` O` |\w ``` Sort all spaces and letters. Since letters have higher code points than spaces, this sorts all the letters to the end, which means to the bottom of the glass. This also happens to sort the letters among themselves, but the order of the letters in the result is irrelevant. ``` *`! ``` Dry run: print the result of replacing all `!` with spaces, but don't actually apply this change to the working string. This prints the nice glass. ``` T`#!¶ ``` Discard all `#`, `!` and linefeeds, so that we're only left with the spaces and letters inside the glass (still sorted). ``` *M` \w ``` Dry run: print the number of matches of a space followed by a letter. This will find at most one match, and that only if the there were both spaces and letters inside the glass, i.e. the glass is *mostly* (full/empty). ``` +` \w ``` Repeatedly remove a space followed by a letter. This "cancels" letters and spaces, so that we end up with only that type of character which appears more often inside the glass. ``` + ``` Count the number of matches of this regex, which gives `1` if there are any spaces left (i.e. the glass was [mostly] empty) and `0` if there are non left (i.e. the glass was at exactly 50% or more and therefore [mostly] full). [Answer] # C, 190 bytes *Thanks to @l4m2 for saving 17 bytes!* ``` i,k,t,s;f(char*g){char*p=g,l[strlen(g)];for(s=t=0;*p;*p>35&&(t?l[i++]=*p:1)?*p=32:0,~*p++&t&&++s)t^=*p==35;for(k=i;i;t&*p==32?*p=l[--i]:0)t^=*--p==35;printf("%s\n%d",g,k?k-s?k*2<s?1:2:3:0);} ``` Outputs 0 for empty glass, 1 for mostly empty, 2 for mostly full, and 3 for full. First loops through the input string counting the space inside the glass, marking down letters that are inside the glass, and changing all letters to spaces. Then loops through the string backwards placing all the letters that were in the glass at the bottom of the glass. [Try it online!](https://tio.run/##nVLbjpswEH3PV4ywFnGVEtjsA5TyIUkqgROIC8tS7I02WW1/PZ2xnZRKfcqIZOyZ8Zwzx@Zxy/n1KqIuUpHMG48fqylo/U/tx6KN@o1UU38YvNbf5c3b5MlCFcs8GPH7nq5d11NlvxFhuCuCMVv5JZ5Kk2wZ/Q7GMHSV64ah9NUPzBZFutYtukLkIleuDiV0ot/EsdhlS10Yx6Z0nMSgGs95ktvhae9EbdSVXSzLLki@yXKVJVmKJ/KvK5bBayUGz198LgCN2APyXm12UIAD1hicydW40Ca2A/5/4O/ERoBfuOgp1VO8skfIX37iAiug1SfQY2YceUtYTMfeTTVM6AYNMNlait/NyTXBxiN2fj6@K@k52yH@v20Hx88X/4yU3EdCDHVBKgYf2BmqmmN0j/vqBBf29gGSqvQ4yJMK1JFBrffs1KIc0ytRrWwLa7g7gFagBg6wn5NOHiGdGtJWduzPtIRIrkEsRBRHIorMK6AR8DtgojaU5vDpI/DPFr6qCZrvGaBDg3nn50c6r2@3wf6@saOR9z4rCclMyjyf2u708BxuSbDvRY@v50dFSIE5y/UjLF9u8qOg1YU0ONPLoIs2Fw6K0Hp8xXOsF@zzdf0D) **Unrolled:** ``` i,k,t,s; f(char*g) { char l[strlen(g)], *p=g; for (s=t=0; *p; *p>35&&(t?l[i++]=*p:1)?*p=32:0, ~*p++&t&&++s) t ^= *p==35; for (k=i; i; t&*p==32?*p=l[--i]:0) t ^= *--p==35; printf("%s\n%d", g, k?k-s?k*2<s?1:2:3:0); } ``` [Answer] # [Python 2](https://docs.python.org/2/), 342 bytes ``` import re def f(g): g=[l for l in g if'#'in l];s,w,l,W=zip(*[re.findall(r'([^#]*)(#+)'*2,l)[0] for l in g[:-1]]);a=sorted(''.join(l));R=len(a);r=a.count(' ');L=[] for x in l:L+=[''.join(a[:len(x)])];a=a[len(x):] for l in zip([' '*len(x)for x in s],w,L,W)+[re.sub('[^#]',' ',g[-1]),'mostly '*(0<r<R)+['full','empty'][r>R/2]]:print''.join(l) ``` [Try it online!](https://tio.run/##hVJNj9sgEL3zK0bhACRuus3RWfcX5JTLHiiV8LdXxHaxk8b58@kMcbIrrdQgDAwz8@a9wf001l27uV6bQ9/5EXzB8qKEUlYqZlAl2kHZeXDQtFBBUwou8OTMdoj@Ri56Sy5NL5faF@uyaXPrnPRC6t/cLJXkKyWWm8gp/WI@oej42w9j1NYmA1YscinE@r1rWumU2u4TV7TSqq1P7Drrju0oBQi13SXasAByJhAX71aJvidaHVPWWRllENbqmxXPGaEs8dQItbz5HkiDQSG76E2tSMRwTKUg@iLC2KjSSFVF4tANo5swWb68@tc9xory6BwGFYd@nITR/uf@@8aYuPdNO34IupZysVjAPDhMtKV4CKNhuJzxO/Ee4A8eHHkcXts5gfbLOx4wACoWbit09H2GG2Scro63WPC4tQHcs0fNx0Ai66F3DXb0VyuUYiyQZezOERPHC8IHTOAT2DTDy5yBPcGFd2cYKIboYWFyjzWHlEx@qlCbP1Btyz7XZVBAkJNCBpD/n8TcF854UInVSkZITU2Fc2aBCOEsGOLBc1XcphwYz3JaccCzJvCPt6oZPGwenoTfHOEZ0tkghhncXcDmZJoFGTnRfKYatdgLqp6ow9izW@tgRACHz/u8aUSKYHhJrcsCRm4JC38yovJAhfor2vUf "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 197 bytes ``` map{/#([^#]+)#/;$l.=$1;y/#/ /c}@a=grep/#/,<>;$f=length$l;$_=$l=~y/ //d/$f;$a[--$i]=~s/#( +)#/'#'.(substr$l,0,($q=length$1),"").$"x($q-$p).'#'/e while$p=length$l;say for@a;say'm'x($_!=int),$_>.5?e:f ``` [Try it online!](https://tio.run/##RY3BjoIwEIbv@xRdOgk0lhYOXKxVX2CfwCipWISkQKUYJZv10beWw2bn8OefyZdvrB5N4X2n7DfHyeGEjyuCuQDDJORi5pgjXv3slbyO2oaNbrYCaml0f50aMAJKCUa@5oDxC4dagDqkKbRH@XJBiBZbjGOWuPvZTSMYmtEEbn@CnNAoIgyiZzimYAkLMNfo0bRGg/3/49SM6mHcq6XFXRz48lO2/UQolFtW7PS69h6jM0YfuLosGQb9DnZqh9759KtgWZ69AQ "Perl 5 – Try It Online") Outputs: ``` e empty me mostly empty mf mostly full f full ``` ]
[Question] [ As you all know, today is election day! Your task today is to print out a ballot, given an input. If the input is `Hillary Clinton`, print: ``` Hillary Clinton ===-----===> Donald Trump === ===> ____________ === ===> ``` However, if the input is `Donald Trump`, print: ``` Hillary Clinton === ===> Donald Trump ===-----===> ____________ === ===> ``` If it is something else, write it on the third line: ``` Hillary Clinton === ===> Donald Trump === ===> Oliver Ni ===-----===> ``` (Technically, I'm not 18 yet...) Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins. [Answer] # Jelly, ~~55~~ 53 bytes ``` ³ẇị⁾- x5⁾ =,”=x3¤j;”>ṭ ṭ“Gụ©l⁴“%eŻƤ(»”_x12¤ṭQḣ3z⁶ZÇ€Y ``` [Try it online!](http://jelly.tryitonline.net/#code=wrPhuofhu4vigb4tIHg14oG-ID0s4oCdPXgzwqRqO-KAnT7hua0K4bmt4oCcR-G7pcKpbOKBtOKAnCVlxbvGpCjCu-KAnV94MTLCpOG5rVHhuKMzeuKBtlrDh-KCrFk&input=&args=IkpvaG4gTWNBZmVlIg) ### Explanation ``` ³ẇị⁾- x5⁾ =,”=x3¤j;”>ṭ Helper link. Argument: row ³ẇ Check if the user's vote is in this row ị⁾- Take "-" if it was, " " otherwise x5 Take five of that character ⁾ =,”= Take the array [" =", "="] x3 Turn it into [" ===", "==="] ¤ Combine the two previous steps into a nilad j Join the list by the five character string ;”> Add ">" ṭ Prepend the original row ṭ“Gụ©l⁴“%eŻƤ(»”_x12¤ṭQḣ3z⁶ZÇ€Y Main link. Argument: vote “Gụ©l⁴“%eŻƤ(» Take the array ["Hillary Clinton", "Donald Trump"] ṭ Add the user's vote to the list ”_ Take "_" x12 Take twelve times that ¤ Combine the two previous steps into a nilad ṭ Add that string to the list Q Remove duplicates ḣ3 Take the three first items z⁶ Transpose, padding with spaces Z Transpose back Ç€ Apply the helper to each row Y Join with newlines ``` [Answer] ## Python 2, 127 bytes ``` X=['Hillary Clinton','Donald Trump'] i=input() X+=[[i],['_'*12]][i in X] for x in X:print x.ljust(18)+'==='+' -'[i==x]*5+'===>' ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~74~~ ~~59~~ 57 bytes Uses [CP-1252](http://www.cp1252.com) encoding. ``` ”ŽÏaryµÍ””¹Ñ Trump”I'_12×)Ù3£vyð18yg-ׄ -¹yQè5×'=3×.ø'>J, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCdxb3Dj2FyecK1w43igJ3igJ3CucORIFRydW1w4oCdSSdfMTLDlynDmTPCo3Z5w7AxOHlnLcOX4oCeIC3CuXlRw6g1w5cnPTPDly7DuCc-Siw&input=QmVybmllIFNhbmRlcnM) [Answer] # Java 7, ~~390~~ ~~339~~ 335 bytes ``` String c(String s){String h="Hillary Clinton",d="Donald Trump",r=h+" ===Q===>\n"+d+" ===X===>\nZ===J===>";boolean H=h.equals(s),D=d.equals(s);for(int i=s.length();i++<18;s+=" ");return r.replace(H?"Q":D?"X":"J","-----").replace(H|D?"Z":"~","____________ ").replaceAll(H?"X|J":D?"Q|J":"Q|X"," ").replace(H|D?"~":"Z",s);} ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/KdHHEl) ``` class M{ static String c(String s){ String h = "Hillary Clinton", d = "Donald Trump", r = h+" ===Q===>\n"+d+" ===X===>\nZ===J===>"; boolean H = h.equals(s), D = d.equals(s); for(int i = s.length(); i++ < 18; s += " "); return r.replace(H?"Q":D?"X":"J", "-----") .replace(H|D?"Z":"~", "____________ ") .replaceAll(H?"X|J":D?"Q|J":"Q|X", " ") .replace(H|D?"~":"Z", s); } public static void main(String[] a){ System.out.println(c("Hillary Clinton")); System.out.println(); System.out.println(c("Donald Trump")); System.out.println(); System.out.println(c("Anyone else?..")); System.out.println(); System.out.println(c("S")); System.out.println(); System.out.println(c("Anyone who is willing to take the job")); } } ``` **Output:** ``` Hillary Clinton ===-----===> Donald Trump === ===> ____________ === ===> Hillary Clinton === ===> Donald Trump ===-----===> ____________ === ===> Hillary Clinton === ===> Donald Trump === ===> Anyone else?.. ===-----===> Hillary Clinton === ===> Donald Trump === ===> S ===-----===> Hillary Clinton === ===> Donald Trump === ===> Anyone who is willing to take the job===-----===> ``` [Answer] ## JavaScript (ES6), 149 bytes ``` s=>['Hillary Clinton','Donald Trump',0].map(S=>((S?S:s||'____________')+p+p+p+p+p).slice(0,18)+`===${!S^S==s?(s=0,'-----'):p}===>`,p=' ').join` ` ``` ### Demo ``` let f = s=>['Hillary Clinton','Donald Trump',0].map(S=>((S?S:s||'____________')+p+p+p+p+p).slice(0,18)+`===${!S^S==s?(s=0,'-----'):p}===>`,p=' ').join` ` console.log(f('Hillary Clinton')) console.log(f('Donald Trump')) console.log(f('Obi-Wan Kenobi')) ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 104 bytes ``` OHillary Clinton³ ³=µ ³=>YpRDonald Trump p15r_ñ/^¨á« ᫾©.*î¨.*î©*\1 22|5r-Gdññ3GjéRDk@"Í_/ 22|5r- ``` [Try it online!](http://v.tryitonline.net/#code=T0hpbGxhcnkgQ2xpbnRvbsKzIMKzPcK1IMKzPT4bWXBSRG9uYWxkIFRydW1wICAgG3AxNXJfw7EvXsKow6HCqyDDocKrwr7CqS4qw67CqC4qw67CqSpcMQoyMnw1ci1HZMOxw7EzR2rDqVJEa0AiG8ONXy8gCjIyfDVyLQ&input=SGlsbGFyeSBDbGludG9u) This answer is way too hacky, and way too long. I guess that's what you get when you design a golfing-language off of a text-editor. `¯\_(ツ)_/¯` [Answer] ## Batch, 210 bytes ``` @set s=%1 @call:l %1 "Hillary Clinton" @call:l %1 "Donald Trump" @call:l %1 %s% @exit/b :l @set v= @if %1==%2 set v=-----&set s=____________ @set t=%~2 @echo %t:~0,18%===%v%===^> ``` Note: the line `@set v=` has 5 trailing spaces, and the line `@set t=%~2` has 18. Accepts input as a quoted command-line parameter. [Answer] # C#, 266 Bytes Golfed: ``` string B(string s){var h="Hilary Clinton".PadRight(17);var d="Donald Trump".PadRight(17);var r="=== ===>\n";var c=r.Replace(" ", "-");var b="____________".PadRight(17);return s==h.Trim()?s.PadRight(17)+c+d+r+b+r:s==d.Trim()?h+r+d+c+b+r:h+r+d+r+s.PadRight(17)+c;} ``` Ungolfed: ``` public string B(string s) { var h = "Hilary Clinton".PadRight(17); var d = "Donald Trump".PadRight(17); var r = "=== ===>\n"; var c = r.Replace(" ", "-"); var b = "____________".PadRight(17); return s == h.Trim() ? s.PadRight(17) + c + d + r + b + r : s == d.Trim() ? h + r + d + c + b + r : h + r + d + r + s.PadRight(17) + c; } ``` *Tried to create a Func for all those PadRights...Exactly the same byte count...* Testing: ``` var printABallot = new PrintABallot(); Console.WriteLine(printABallot.B("Hilary Clinton")); Hilary Clinton ===-----===> Donald Trump === ===> ____________ === ===> Console.WriteLine(printABallot.B("Donald Trump")); Hilary Clinton === ===> Donald Trump ===-----===> ____________ === ===> Console.WriteLine(printABallot.B("Kanye West")); Hilary Clinton === ===> Donald Trump === ===> Kanye West ===-----===> ``` [Answer] # Python 3.6, 132 bytes ``` i=input() s=['Hillary Clinton','Donald Trump','_'*12] if x not in s:s[2]=i for k in s:print(f'{k:18}==={" -"[k==i]*5}===>') ``` Uses [3.6's new f-strings](https://www.python.org/dev/peps/pep-0498/). [Answer] # Pyth, 76 bytes ``` V{+_tW!}zJ[*\_12"Donald Trump""Hillary Clinton")Jzs[.[Nd18K*\=3*?qzN\-d5K\> ``` ]
[Question] [ Given a positive integer `k > 1` and a non-negative integer `i`, generate a `k`-tuple (or `k`-dimensional vector) of non-negative integers. For every `k`, the map from ℕ to ℕk, **must be bijective**. That is, every input `i` should produce a different tuple, and every possible tuple must be produced by some input `i`. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. You may use any convenient, unambiguous, flat list format for the output. Your solution should impose no artificial limits on `k` and `i` but you may assume that they fit into your language's native integer size. At the very least, you must support values up to `255`, though, even your native integer size is smaller than that. For any `1 < k < 32`, `i < 231`, your code should produce a result in a matter of seconds (of course, if your answer doesn't support `i` that large due to the previous rule, the limit is adjusted accordingly). This should be no issue: it's possible to solve this challenge such that it works up to 2128 in a few seconds, but the limit is there to avoid answers which actually iterate from `0` to `i` to find the result. Please include in your answer a description of your chosen mapping and a justification for why it's bijective (this doesn't need to be a formal proof). This is code golf, the shortest answer (in bytes) wins. ### Related Challenges * [Generate a pair of integers from a non-negative one](https://codegolf.stackexchange.com/q/48705/8478) * [Output a list of all rational numbers](https://codegolf.stackexchange.com/q/5809/8478) [Answer] # Pyth, ~~15~~ 12 bytes ``` ms+0_%Q>_zdQ ``` [Test suite](https://pyth.herokuapp.com/?code=ms%2B0_%25Q%3E_zdQ&input=12351253%0A3&test_suite=1&test_suite_input=1%0A3%0A10%0A3%0A100%0A3%0A1243123%0A3%0A21003034%0A3&debug=0&input_size=2) My transformation is similar to one of xnor's, but in base 10. It works by unzipping the input into k separate numbers: ``` n = 21003034 k = 3 21003034 1 3 4 134 2 0 3 203 0 0 0 ``` The numbers are ordered in decreasing position of the rightmost digit, so that all orderings of any group of numbers are possible. The way the code works is we reverse the input, then slice off the last `0, 1, ... k-1` digits, then take every `k`th digit, reverse again, stick a `0` at the begining, and convert to int. [Answer] # CJam, 20 bytes ``` q~({4b2fmd2/z2fb~p}* ``` The mapping is bijective since it applies the mapping from [this answer](https://codegolf.stackexchange.com/a/48717) **k - 1** times. The program reads the input as `i k`. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~(%7B4b2fmd2%2Fz2fb~p%7D*&input=9%205). ### Idea We can construct a bijective mapping **f : N → N2** by defining **f(i)** as follows: * Convert **i** into the array of its binary digits. * Prepend a **0** to this array if there is an odd number of digits. * Deinterleave the resulting array, forming to new ones in the process. * Convert those arrays from base 2 to integer. Define **f1(i)** and **f2(i)** as the results. To obtain a bijective mapping **g : N → N3**, we can define **g(n) := (f1(i), f1(f2(i)), f2(f2(i)))**. To obtain a bijective mapping **h : N → N4**, we can define **h(i) := (g1(i), g2(i), f1(g3(i)), f2(g3(i)))**. Continuing the above process, we eventually arrive at a bijective map **N → Nk**. ### Code ``` q~ e# Read and evaluate all input. This pushes i and k. ({ e# Do k-1 times: 4b e# Convert the integer on the stack (initially i) to base 4. 2fmd e# Replace each base-4 digit d by d/2 and d%2. 2/ e# Split into the chunks [d/2 d%2]. z e# Transpose. This collects all quotients in one array and all e# residues in another one. 2fb e# Convert each array from base 2 to integer. ~ e# Dump both integers on the stack. p e# Print the topmost one. }* e# ``` [Answer] # CJam, 18 bytes ``` q~({)2bW%_1#p))b}* ``` It uses a more stupid formula. [Try it here](http://cjam.aditsu.net/#code=q%7E%28%7B%292bW%25_1%23p%29%29b%7D*&input=65535743%205). ### Explanation ``` q~ e# Read input. ({ e# Repeat k-1 times: ) e# Increment the current integer (initially i), to make it positive. 2b e# Convert to binary. W% e# Reverse the binary. e# The result can be any non-empty binary string without trailing 0s. _1# e# Find the position of the first 1, or the number of initial 0s. p e# Print. ) e# Extract the final bit, which is always 1. e# An array that can be any binary string is left in the stack. ) e# Increment the 1 to make it 2. b e# Convert the binary string to a number using base 2. e# Only the number of initial 0s doesn't affect the result, e# which is exactly what is printed before. }* e# The final integer is printed automatically when the program ends. ``` In summary, it maps a positive integer to: 1. The number of trailing zeros. 2. The original integer with trailing zeros removed, reversed, and the trailing (originally initial) 1 removed. [Answer] ## Python 2, 62 ``` lambda z,k:[int('0'+bin(z)[~i:1:-k][::-1],2)for i in range(k)] ``` This code is ugly and golfable, but the idea is very simple. Pack `k` binary expansions into one by reading every `k`th digit with different offsets. For example, with `k=3`, the input `357` maps to `(3,0,7)`: ``` 101100101 <- 357 1 0 1 -> 5 0 0 0 -> 0 1 1 1 -> 7 ``` Zipping the numbers back together reverses it, so it's a bijection. In doing so, think of the binary expansions as having an infinite number of leading zeroes. [Answer] # J, ~~38~~ ~~28~~ 27 bytes ``` (({.,g^:_1@}.)g=:_ q:>:)~<: ``` This is a tacit, dyadic verb that takes **i** and **k** as left and right arguments. Try it online with [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=1595%20(%20((%7B.%2Cg%5E%3A_1%40%7D.)g%3D%3A_%20q%3A%3E%3A)~%3C%3A%20)%205). ### Idea We define a map **f : N → Nk** by **f(i) := (α1, … αk-1, p1αk…p2αk+1… - 1)**, where **⟨pn⟩** is the sequence of prime numbers and **i + 1 = p1α1p2α2…**. By the Fundamental Arithmetic Theorem, the map **g : N → Nω** defined by **g(i) := (α1, α2, …)** (exponents of the prime factorization of **i + 1**) is bijective. Since **f(i) = (g1(i), … gk-1(i), g-1(gk(i), gk+1(i), …))**, the map **f** is bijective as well. ### Code ``` Left argument: i -- Right argument: k <: Decerement k. ( )~ Reverse the order of the arguments and apply the dyadic verb inside the parentheses to k-1 and i. g=: Define a monadic helper verb g: >: Increment its right argument. _ q: Calculate the exponents of the prime factorization. (implicit) Apply g to i. ( ) Apply the dyadic verb inside the parentheses to k-1 and (g i). }. Drop the first k-1 elements of (g i)... @ and... g^:_1 apply the inverse of g to the result. {. Take the first k-1 elements of (g i). , Append the rightmost result to the leftmost one. ``` [Answer] ## Python 2, 72 ``` q=lambda z:z and z%2+2*q(z/4) g=lambda z,k:1/k*[z]or[q(z)]+g(q(z/2),k-1) ``` The function `q` acts on binary numbers by taking every second bit starting from the end. As a result `q(z), q(z>>1)` gives two numbers whose binary digits intersperse to give `z`. For example, 594 splits into 12 and 17. ``` 1001010010 <- 594 0 1 1 0 0 -> 12 1 0 0 0 1 -> 17 ``` This is a bijection because we can zip the numbers back together to recover the original number. The function `g` applies this bijection `k-1` times, expanding from a single element to a pair to a triple ... to a `k`-tuple. Each time, the last element is expanded to two elements. This is done recursively by mapping the input to a pair via the bijection, taking the first element of the pair for the first entry of the output, and applying the function recursively with `k-1` to the second element to produce the remaining entries. ]
[Question] [ Write a [*GOLF*](https://github.com/orlp/golf-cpu) assembly program that given a 64-bit unsigned integer in register `n` puts a non-zero value into register `s` if `n` is a square, otherwise `0` into `s`. **Your *GOLF* binary (after assembling) must fit in 4096 bytes.** --- Your program will be scored using the following Python3 program (which must be put inside the *GOLF* directory): ``` import random, sys, assemble, golf, decimal def is_square(n): nd = decimal.Decimal(n) with decimal.localcontext() as ctx: ctx.prec = n.bit_length() + 1 i = int(nd.sqrt()) return i*i == n with open(sys.argv[1]) as in_file: binary, debug = assemble.assemble(in_file) score = 0 random.seed(0) for i in range(1000): cpu = golf.GolfCPU(binary) if random.randrange(16) == 0: n = random.randrange(2**32)**2 else: n = random.randrange(2**64) cpu.regs["n"] = n cpu.run() if bool(cpu.regs["s"]) != is_square(n): raise RuntimeError("Incorrect result for: {}".format(n)) score += cpu.cycle_count print("Score so far ({}/1000): {}".format(i+1, score)) print("Score: ", score) ``` Make sure to update *GOLF* to the latest version with `git pull`. Run the score program using `python3 score.py your_source.golf`. It uses a static seed to generate a set of numbers of which roughly 1/16 is square. Optimization towards this set of numbers is against the spirit of the question, I may change the seed at any point. Your program must work for any non-negative 64-bit input number, not just these. ### Lowest score wins. --- Because *GOLF* is very new I'll include some pointers here. You should read [the *GOLF* specification with all instructions and cycle costs](https://github.com/orlp/golf-cpu/blob/master/specification.md). In the Github repository example programs can be found. For manual testing, compile your program to a binary by running `python3 assemble.py your_source.golf`. Then run your program using `python3 golf.py -p s your_source.bin n=42`, this should start the program with `n` set to 42, and prints register `s` and the cycle count after exiting. See all the values of the register contents at program exit with the `-d` flag - use `--help` to see all flags. [Answer] # Score: 27462 About time I'd compete in a *GOLF* challenge :D ``` # First we look at the last 6 bits of the number. These bits must be # one of the following: # # 0x00, 0x01, 0x04, 0x09, 0x10, 0x11, # 0x19, 0x21, 0x24, 0x29, 0x31, 0x39 # # That's 12/64, or a ~80% reduction in composites! # # Conveniently, a 64 bit number can hold 2**6 binary values. So we can # use a single integer as a lookup table, by shifting. After shifting # we check if the top bit is set by doing a signed comparison to 0. and b, n, 0b111111 shl v, 0xc840c04048404040, b le q, v, 0 jz no, q jz yes, n # Hacker's Delight algorithm - Newton-Raphson. mov c, 1 sub x, n, 1 geu q, x, 2**32-1 jz skip32, q add c, c, 16 shr x, x, 32 skip32: geu q, x, 2**16-1 jz skip16, q add c, c, 8 shr x, x, 16 skip16: geu q, x, 2**8-1 jz skip8, q add c, c, 4 shr x, x, 8 skip8: geu q, x, 2**4-1 jz skip4, q add c, c, 2 shr x, x, 4 skip4: geu q, x, 2**2-1 add c, c, q shl g, 1, c shr t, n, c add t, t, g shr h, t, 1 leu q, h, g jz newton_loop_done, q newton_loop: mov g, h divu t, r, n, g add t, t, g shr h, t, 1 leu q, h, g jnz newton_loop, q newton_loop_done: mulu u, h, g, g cmp s, u, n halt 0 yes: mov s, 1 no: halt 0 ``` [Answer] ## Score: 161558 ~~227038~~ ~~259038~~ ~~260038~~ ~~263068~~ I took the fastest integer square root algorithm I could find and return whether its remainder is zero. ``` # based on http://www.cc.utah.edu/~nahaj/factoring/isqrt.c.html # converted to GOLF assembly for http://codegolf.stackexchange.com/questions/49356/testing-if-a-number-is-a-square # unrolled for speed, original source commented out at bottom start: or u, t, 1 << 62 shr t, t, 1 gequ v, n, u jz nope62, v sub n, n, u or t, t, 1 << 62 nope62: or u, t, 1 << 60 shr t, t, 1 gequ v, n, u jz nope60, v sub n, n, u or t, t, 1 << 60 nope60: or u, t, 1 << 58 shr t, t, 1 gequ v, n, u jz nope58, v sub n, n, u or t, t, 1 << 58 nope58: or u, t, 1 << 56 shr t, t, 1 gequ v, n, u jz nope56, v sub n, n, u or t, t, 1 << 56 nope56: or u, t, 1 << 54 shr t, t, 1 gequ v, n, u jz nope54, v sub n, n, u or t, t, 1 << 54 nope54: or u, t, 1 << 52 shr t, t, 1 gequ v, n, u jz nope52, v sub n, n, u or t, t, 1 << 52 nope52: or u, t, 1 << 50 shr t, t, 1 gequ v, n, u jz nope50, v sub n, n, u or t, t, 1 << 50 nope50: or u, t, 1 << 48 shr t, t, 1 gequ v, n, u jz nope48, v sub n, n, u or t, t, 1 << 48 nope48: or u, t, 1 << 46 shr t, t, 1 gequ v, n, u jz nope46, v sub n, n, u or t, t, 1 << 46 nope46: or u, t, 1 << 44 shr t, t, 1 gequ v, n, u jz nope44, v sub n, n, u or t, t, 1 << 44 nope44: or u, t, 1 << 42 shr t, t, 1 gequ v, n, u jz nope42, v sub n, n, u or t, t, 1 << 42 nope42: or u, t, 1 << 40 shr t, t, 1 gequ v, n, u jz nope40, v sub n, n, u or t, t, 1 << 40 nope40: or u, t, 1 << 38 shr t, t, 1 gequ v, n, u jz nope38, v sub n, n, u or t, t, 1 << 38 nope38: or u, t, 1 << 36 shr t, t, 1 gequ v, n, u jz nope36, v sub n, n, u or t, t, 1 << 36 nope36: or u, t, 1 << 34 shr t, t, 1 gequ v, n, u jz nope34, v sub n, n, u or t, t, 1 << 34 nope34: or u, t, 1 << 32 shr t, t, 1 gequ v, n, u jz nope32, v sub n, n, u or t, t, 1 << 32 nope32: or u, t, 1 << 30 shr t, t, 1 gequ v, n, u jz nope30, v sub n, n, u or t, t, 1 << 30 nope30: or u, t, 1 << 28 shr t, t, 1 gequ v, n, u jz nope28, v sub n, n, u or t, t, 1 << 28 nope28: or u, t, 1 << 26 shr t, t, 1 gequ v, n, u jz nope26, v sub n, n, u or t, t, 1 << 26 nope26: or u, t, 1 << 24 shr t, t, 1 gequ v, n, u jz nope24, v sub n, n, u or t, t, 1 << 24 nope24: or u, t, 1 << 22 shr t, t, 1 gequ v, n, u jz nope22, v sub n, n, u or t, t, 1 << 22 nope22: or u, t, 1 << 20 shr t, t, 1 gequ v, n, u jz nope20, v sub n, n, u or t, t, 1 << 20 nope20: or u, t, 1 << 18 shr t, t, 1 gequ v, n, u jz nope18, v sub n, n, u or t, t, 1 << 18 nope18: or u, t, 1 << 16 shr t, t, 1 gequ v, n, u jz nope16, v sub n, n, u or t, t, 1 << 16 nope16: or u, t, 1 << 14 shr t, t, 1 gequ v, n, u jz nope14, v sub n, n, u or t, t, 1 << 14 nope14: or u, t, 1 << 12 shr t, t, 1 gequ v, n, u jz nope12, v sub n, n, u or t, t, 1 << 12 nope12: or u, t, 1 << 10 shr t, t, 1 gequ v, n, u jz nope10, v sub n, n, u or t, t, 1 << 10 nope10: or u, t, 1 << 8 shr t, t, 1 gequ v, n, u jz nope8, v sub n, n, u or t, t, 1 << 8 nope8: or u, t, 1 << 6 shr t, t, 1 gequ v, n, u jz nope6, v sub n, n, u or t, t, 1 << 6 nope6: or u, t, 1 << 4 shr t, t, 1 gequ v, n, u jz nope4, v sub n, n, u or t, t, 1 << 4 nope4: or u, t, 1 << 2 shr t, t, 1 gequ v, n, u jz nope2, v sub n, n, u or t, t, 1 << 2 nope2: or u, t, 1 << 0 shr t, t, 1 gequ v, n, u jz nope0, v sub n, n, u nope0: end: not s, n # return !remainder halt 0 # before unrolling... # # start: # mov b, 1 << 62 # squaredbit = 01000000... # loop: # do { # or u, b, t # u = squaredbit | root # shr t, t, 1 # root >>= 1 # gequ v, n, u # if remainder >= u: # jz nope, v # sub n, n, u # remainder = remainder - u # or t, t, b # root = root | squaredbit # nope: # shr b, b, 2 # squaredbit >>= 2 # jnz loop, b # } while (squaredbit > 0) # end: # not s, n # return !remainder # halt 0 ``` EDIT 1: removed squaring test, return !remainder directly, save 3 ops per test EDIT 2: use n as the remainder directly, save 1 op per test EDIT 3: simplified the loop condition, save 32 ops per test EDIT 4: unrolled the loop, save about 65 ops per test [Answer] # Score: 344493 Does a simple binary search within the interval `[1, 4294967296)` to approximate `sqrt(n)`, then checks if `n` is a perfect square. ``` mov b, 4294967296 mov c, -1 lesser: add a, c, 1 start: leu k, a, b jz end, k add c, a, b shr c, c, 1 mulu d, e, c, c leu e, d, n jnz lesser, e mov b, c jmp start end: mulu d, e, b, b cmp s, d, n halt 0 ``` [Answer] # Score: 22120 (3414 bytes) My solution uses a 3kB lookup table to seed a Newton's method solver that runs for zero to three iterations depending on the result's size. ``` lookup_table = bytes(int((16*n)**0.5) for n in range(2**10, 2**12)) # use orlp's mod-64 trick and b, n, 0b111111 shl v, 0xc840c04048404040, b le q, v, 0 jz not_square, q jz is_square, n # x will be a shifted copy of n used to index the lookup table. # We want it shifted (by a multiple of two) so that the two most # significant bits are not both zero and no overflow occurs. # The size of n in bit *pairs* (minus 8) is stored in b. mov b, 24 mov x, n and c, x, 0xFFFFFFFF00000000 jnz skip32, c shl x, x, 32 sub b, b, 16 skip32: and c, x, 0xFFFF000000000000 jnz skip16, c shl x, x, 16 sub b, b, 8 skip16: and c, x, 0xFF00000000000000 jnz skip8, c shl x, x, 8 sub b, b, 4 skip8: and c, x, 0xF000000000000000 jnz skip4, c shl x, x, 4 sub b, b, 2 skip4: and c, x, 0xC000000000000000 jnz skip2, c shl x, x, 2 sub b, b, 1 skip2: # now we shift x so it's only 12 bits long (the size of our lookup table) shr x, x, 52 # and we store the lookup table value in x add x, x, data(lookup_table) sub x, x, 2**10 lbu x, x # now we shift x back to the proper size shl x, x, b # x is now an intial estimate for Newton's method. # Since our lookup table is 12 bits, x has at least 6 bits of accuracy # So if b <= -2, we're done; else do an iteration of newton leq c, b, -2 jnz end_newton, c divu q, r, n, x add x, x, q shr x, x, 1 # We now have 12 bits of accuracy; compare b <= 4 leq c, b, 4 jnz end_newton, c divu q, r, n, x add x, x, q shr x, x, 1 # 24 bits, b <= 16 leq c, b, 16 jnz end_newton, c divu q, r, n, x add x, x, q shr x, x, 1 # 48 bits, we're done! end_newton: # x is the (integer) square root of n: test x*x == n mulu x, h, x, x cmp s, n, x halt 0 is_square: mov s, 1 not_square: halt 0 ``` ]
[Question] [ # Background Many moons ago, in a galaxy much like our own, a young BrainSteel attempted to invent a board game. He believed that he, too, could find an amazingly simple set of rules that would generate wonderfully strategic gameplay. He drew up the first set of rules--it looked promising. He played with his thoughts, and noticed a minor inconsistency here, or a slight balance issue there. One by one, the rules started piling up, until they were at best arbitrary. Try as he might, the beautiful simplicity of Checkers or Go failed to shine through. His final creation, one bad enough he would only refer to it when speaking in the 3rd person, was given the *temporary* name "Quagmire." While perhaps not a brilliant board game, it ought to be a fun code golf! # The Rules of Quagmire The game is played on an 8x8 board, and each player has 10 identical pieces. If player one has `O` pieces, and player 2 has `X` pieces, here is a portrayal of the game at the start (where `.` indicates a blank space): ``` a b c d e f g h +-+-+-+-+-+-+-+-+ |.|.|.|.|X|X|X|X| 8 +-+-+-+-+-+-+-+-+ |.|.|.|.|.|X|X|X| 7 +-+-+-+-+-+-+-+-+ |.|.|.|.|.|.|X|X| 6 +-+-+-+-+-+-+-+-+ |.|.|.|.|.|.|.|X| 5 +-+-+-+-+-+-+-+-+ |O|.|.|.|.|.|.|.| 4 +-+-+-+-+-+-+-+-+ |O|O|.|.|.|.|.|.| 3 +-+-+-+-+-+-+-+-+ |O|O|O|.|.|.|.|.| 2 +-+-+-+-+-+-+-+-+ |O|O|O|O|.|.|.|.| 1 +-+-+-+-+-+-+-+-+ ``` Note that every space on the grid can be named with a letter and number, e.g. there is an `O` character on `c2`. Players take turns in an alternating fashion. On a player's turn, they may move in two ways: * The player may move any piece in a straight line vertically, horizontally, or diagonally at most until they meet either another wall or piece. e.g. `|X|.|.|O|.| => |.|.|X|O|.|` for one move of length 2 horizontally. Note that the `X` piece cannot move any farther right, because there is a piece in the way. * The player may use a piece to jump over a **single, adjacent, and friendly** piece. Jumps, like ordinary moves, may be horizontal, vertical, or diagonal. Under *normal circumstances* an enemy piece may not be jumped. e.g. `|X|X|.| => |.|X|X|` If a piece cannot move to any of its surrounding spaces, and at least one of those adjacent spaces is occupied by an enemy piece, that piece is said to be in a state of *Quagmire*. If a player ends his turn with a piece in Quagmire, they lose the game. Now for the more arbitrary rules: * The bottom left player goes first. * Each player must make exactly one move per turn. (No pass!) * A piece may not be moved twice in a row, **ever**. e.g. if, on the first turn, player one moves the piece on `c2`, he may not move the same piece on his following turn. * If the player to move has one or more pieces in Quagmire which may move, they must move one of those pieces. * A piece may jump an enemy piece in the same way that it jumps a friendly piece if and only if that enemy piece is part of a closed loop (which may or may not start and end at a wall) of pieces of one color, and that loop is impenetrable by normal moves. If a piece jumps in this way, it must jump from inside the loop to the outside, or vice versa. Since this rule is weird, here is an example board: ``` a b c d e f g h +-+-+-+-+-+-+-+-+ |.|.|.|O|X|.|.|X| 8 +-+-+-+-+-+-+-+-+ |.|.|.|.|X|.|.|X| 7 +-+-+-+-+-+-+-+-+ |.|.|.|.|X|.|.|.| 6 +-+-+-+-+-+-+-+-+ |X|.|.|.|.|X|X|X| 5 +-+-+-+-+-+-+-+-+ |O|O|O|O|.|.|.|.| 4 +-+-+-+-+-+-+-+-+ |.|.|.|O|X|.|.|.| 3 +-+-+-+-+-+-+-+-+ |.|.|.|O|.|.|O|.| 2 +-+-+-+-+-+-+-+-+ |O|O|O|O|.|.|.|.| 1 +-+-+-+-+-+-+-+-+ ``` In this position, the `X` on `a5` may legally jump to `a3`. In contrast, the `O` on `d8` may NOT jump to `f8`, since the loop of `X` pieces is not fully closed -- the inside is accessible through the `e5` - `g7` diagonal. Also, note that the 'X' on `e3` may not jump to `c5` because this jump does not cross from outside the loop to the inside. # The Challenge Your challenge is to allow two players at the same computer to play a game of Quagmire, adhering perfectly to the rules, against each other. At every point in the game, your program should output the board as shown in the first example board, reflecting the current positions of all pieces on the board. You may choose any characters for the `O`, `X`, and `.` values, but the rest of the characters must be exactly as shown. **You should also display, in a reasonable manner, whose turn it is!** # Input On a players' turn, you should accept a string of at least 5 bytes in the form `X#<seperator>Y#`. You may make **reasonable** adjustment to this format to suit your programming language. You may also assume that the input, while not necessarily a legal move, will be formatted correctly (no numbers greater than 8, etc). Your program should evaluate whether or not a move from `X#` on the board to `Y#` is legal for this player. If it is legal, your program should make the move and output the next board accordingly. If it is not legal, your program should output some falsy value (`0` is perfectly reasonable--you do not need an explanation) and receive another input. # Winning A player wins when the other player fails to relieve one of his pieces from Quagmire. Alternatively, a player wins when it is their opponent's turn and their opponent has no legal moves. Note that the first win condition takes precedence over the second. If I leave a piece in Quagmire at the end of the turn and simultaneously leave my opponent with no legal moves, I still lose the game. If the game is over after a player's move, you should output the winning board, the winning player's piece character (e.g. 'X') and some truthy value (Again, `1` is sufficient). At this point, your program may either terminate or restart the game. # Challenge Rules * This is **code-golf**. Smallest code, in bytes, wins. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are disallowed. [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), ~~695...618~~ 610 bytes ``` i=*0..7 t,*b={} "?>=<765/.'".bytes{b[_1],b[~_1]=A=?X,E=?O} loop{puts' '+[*?a..?h]*' ',a='+-'*8+?+,i.map{|j|"|#{b[8*~j,8].map{_1||?.}*?|}| #{8-j} "+a} eval"M,*m=->u,w=p,*s{Q=(0..8).map{c,r=u;z=c+8*r #{$f='(v=c+=_1/3-1,r+=_1%3-1)-i==[]&&'}(k=#{$g='b[c+8*r]'} w ?b[z]==A&&(t[A]!=z&&(#$f!#$g&&(k==A||k&&N[u]&N[v]==[])&&s<<u+v c,r=u;s<<u+v while#$f!#$g);k):k!=E&&s<<v)};s} N,*q=->o,n=M[o]{n==n|=n.flat_map{M[_1]}||redo;n} i.product(i){#{h='M[_1,1];A,E=E,A;([p,A]&Q)[0]&&'}(p A;Z);m+=e=#{h}q+=e} A,E=E,A ($><<A+?>;c,r,_,x,y=gets.bytes.map{~-_1%8})until[[c,r,x,y]]-(m[0]?q[0]?q:m:(p E;Z))==[] #$g,b[t[A]=x+8*y]=p,A"} ``` [Try it online!](https://tio.run/##dVTbcuI4EH1efUUHGHxBOENIgI1RXOxW9i0zNW9T6/HO2Fg2Aiw7lg0J2Pn1bJvLbrIXu0rVUh@dPt0tKS@D59c2qCIXGQgZclmAL0OYp0mCtoIoTxN0ZGVBfhNrbm1zUXBdExqFH3O/AOvgswqR/rBiVQb65R/flHlJQdOM0wLO29Z5ST2WnO@43vomW4ZBOqoIhbRynmZcNrTGq2DmR8sak4KaAdvXpOXcsel4dHNpaS0reC642lfLKnCXHg3cl6XHZsz5Su@Z87km6zTN9qhHaQS0nms6vmU5C8/UQKM@03p9zZz0nB4VVuJnDU2rau8Dd2K@LOnEOy6u8K8cqzadqq6gvZ/0lyii59eEb/x164GaCevflXTLMmqq/Remo9yJcWac05yV9o7NexMzJ@19J2KavsEpW14O@wOao/EBDaMvGHO9bler9RVDXMy0wD3s8rSabMEJ3J3H2Kzb1Qt35l2wHVrtTnTR7sRordBVVatu95NbejhsvIbO6HbVdFr2NuSo4ziB7QJ7d9pr2CvjdnXB7g/QjVHbqiafqPmIWaVUsgc39faSMVkxaUVrv/h@yGxXPaCeuqpyHqa2rImwsjwNy3mhC6Nxt/cLpiGGDjx7hv24pzNbdzM687pfDPfjMdMMZvbvhp30GMecF/UjGjU5wYneuZtOZz3nzkb19Dt9os8s5oU6tv1c4Zf@8sOkNkpZiLXrNkjEeV5fTzCK83gYbpNbjHWPsYymLATzxtPS1JE9YYmfPWzerFW/vgKEA5gPoPnaMPelVsC6uQGphHQrIRN8zskBtbj5TxSXPHl@i@PDE06meJmau@WLeIEbhDwhwp9/OiJCrgohfbw9GA2PrQg5BKmfh0fc6WuY3kLR@XQ1guF49suv6Az8EKI0T/wCHXwC/H02Sbrh/xCJCD7@m/qwDHiZ@YAEVxCNEBKPID7nG49BKHgs/TgR2P3DA5GU6kjdYMfA39dmWSYZKCHj9fvQiIxvcEc0gujm3yqVn/CTmmIrcBQSC5inW@IPYT4k0QSCa@Jfgz8kqC68Iu1gCCj5RCUiKOXp6eIhbfrKZaigKHPZcJ1TsOErbIVUpOkq5nz9FweSHLQLWaQYer5OFSbcPCuQRm9TUXaz53/YPx/Y/wQ "Ruby – Try It Online") (620 bytes because the older Ruby on TIO doesn't support numbered block parameters.) A simple example game is included that illustrates most of Quagmire's rules. Just for clarity, the input is commented and invalid moves are indented. Input is in the format `x# y#`, terminated either by newline or EOF. Any single byte is accepted as the separator. The input prompt is `O>` for player 1 and `X>` for player 2. (In an interactive terminal the input appears as it is typed, after the prompt.) The prompt is repeated until a valid move is entered, then the updated board is printed. When the game ends, the winning player's symbol is printed in double quotes; I like to imagine it is raising its arms in victory. # Explanation > > While perhaps not a brilliant board game, it ought to be a fun code golf! > > > #### Steel your Brain The first 3 lines perform initialisation. `i` is a fixed list of row/column numbers. The value of each square on the board (`O`, `X`, or `nil`) is stored in the (1D) array `b`. Empty squares, stored as `nil`, are replaced by `.` on output. The starting configuration is encoded by the 10-byte string `?>=<765/.'`, whose codepoints give the indices of squares containing X's. `t` is a hash that stores the index of the piece moved on each player's previous turn (this piece cannot be moved on the next turn). `A` and `E` store the 'active' and 'enemy' piece symbols and are interchanged each turn. Being *constants* (uppercase names), `A` and `E` have global scope. Constants are abused throughout the program to avoid scoping issues that would arise with ordinary local variables. A side effect is that whenever a constant is reassigned, warnings are emitted to STDERR. (These warnings may be suppressed by calling Ruby with the `-W0` option.) Now the main `loop` begins, running until one player wins. Following the 3 lines that display the board, the remainder of the program is enclosed in an `eval` string, which allows a few chunks of code (stored in the strings `$f`, `$g`, and `h`) to be recycled. The first 5 lines of this string contain the real meat of the program: the lambdas `M` and `N`. #### Mary had a little lambda Let's start with `N`. `N` finds the set of all squares that are *connected* to the square at co-ordinates `o` (co-ordinates are pairs of 0-indexed column and row numbers). Here, connected means that there is a path between all the squares that is not blocked by enemy pieces. Source and destination squares must be unconnected as a prerequisite for jumping an enemy piece. `N` fans out from the current square, adding its non-enemy neighbours (`n=M[o]`) and their neighbours (`n|=n.flat_map{M[_1]`) to the set `n` by calling `M` (see below). We `redo` this process, adding more neighbours of neighbours, until `n` no longer changes (i.e. until all connected squares have been found). `M` probes the board around the square at co-ordinates `u`. Its exact behaviour is determined by the switch `w`, which takes a value of either `nil` (a.k.a. `p`) or `1`: * When `w` is `nil`, `M` returns an array `s` of the co-ordinates of all neighbours (8-neighbourhood) of the square at `u` that do not contain enemy pieces (`k!=E`). Lambda `N` uses this information to find the set of all squares that are connected to the current square, as described above. The co-ordinates of each neighbour (column `c` and row `r`, stored as the pair `v`) are obtained by independently advancing `c` and `r` by -1, 0, or 1 (`(0..8).map...(v=c+=_1/3-1,r+=_1%3-1)`), ensuring that `c` and `r` both lie within the board (`(v=...)-i==[]`). This code for finding adjacent squares is required again later, so to save bytes it is stored as a string in `$f` and interpolated into the `eval` string. Similarly, the code that returns the value of the square at `v` is saved in `$g` (`$g='b[c+8*r]'`). * When `w` equals `1` and the square at `u` contains one of the active player's pieces (`b[z]==A`), `M` does two things: 1. It returns an array `s` containing all possible moves for the active player originating from this square. 2. It saves the values of all neighbouring squares in `Q`, which is used later to test for quagmire.Moves are only allowed if the piece was not moved on the previous turn (`t[A]!=z`). For jumps, the destination square is found by advancing `c` and `r` in the same directions a second time (by interpolating `$f`) and testing whether this square is empty (`!#$g`). For a jump to be possible, there must either be an active piece to jump over (`k==A`) or, if an enemy piece is being jumped, the source and destination squares must be unconnected (`k&&N[u]&N[v]==[]`). For ordinary moves, `c` and `r` are reset (`c,r=u`) and then both variables are advanced in the same directions as before, one square at a time, until no further move along that path is possible (`while#$f!#$g`). Moves are saved (`s<<u+v`) in the format `[c,r,x,y]`, that is, the column and row numbers of the source square followed by the column and row numbers of the destination. #### Into the quagmire The last four lines of the program run the game according to the following steps: 1. Loop over all squares of the board by forming pairs of column and row numbers (`i.product(i)`). 2. For the current square, complete the following steps, all saved in `h`: * Call `M` in move-finding mode (`M[_1,1]`). If the square contains an *enemy* piece, update `Q` with the values of the neighbouring squares. (Any possible moves for that piece are also returned, but we immediately discard them: it's not the opponent's turn to move, after all!) * Interchange the active and enemy pieces (`A,E=E,A`). The reason for interchanging players is that quagmire checks are performed twice per square, once (here in step 2) to find whether the opponent has left a piece in quagmire and again (in step 4) to find whether the active player has been quagmired by the opponent's previous move. * Test whether the current square contains a quagmired enemy piece (`([p,A]&Q)[0]`). `([p,A]&Q)[0]` is truthy only if there are no empty neighbours and at least one neighbour is an active piece. 3. If the current square contains a quagmired enemy piece then the game is won. Print the active player's symbol (`p A`) and terminate by throwing a tantrum (`Z` is not defined). 4. Repeat step 2, reading 'active' for 'enemy' and vice versa, but this time add all possible moves (neglecting quagmire for the moment) for the active player to `m` and keep a copy in `e` (`m+=e=#{h}`). If the current square contains a quagmired active piece then add `e` to `q` as well (`q+=e`). 5. Outside the loop, interchange the active/enemy pieces to advance the turn (`A,E=E,A`). 6. Finally it's time for some input! * We now have two lists of moves for the active player: `m` contains all possible moves (neglecting quagmire) whereas `q` (a subset of `m`) contains possible moves by any quagmired pieces. `(m[0]?q[0]?q:m:(p E;Z))` decides which move list should be used. If `m` is empty (i.e. the active player has no possible moves) then the game is lost; print the opponent's symbol and terminate (`m[0]?...:(p E;Z)`). If `q` is nonempty it takes precedence over `m` (`q[0]?q:m`). * Until a valid move is entered correctly (`until[[c,r,x,y]]-(...)==[]`), display the prompt (`$><<A+?>`) and convert the input to 0-indexed column/row numbers (`gets.bytes.map{~-_1%8}`). 7. Update the source and destination squares, saving the destination index in `t` (`#$g,b[t[A]=x+8*y]=p,A`). ]
[Question] [ It's the ending of another well played chess game. You're the white player, and you still have a rook and your king. Your opponent only has his king left. Since you're white, it's your turn. Create a program to play this chess match. Its output can be a sequence of moves, a gif animation, ASCII art or whatever you like. It seems quite obvious, but I'll state it explicitly: you have to win the game (in a finite number of moves). It's always possible to win from this position. DO NOT LOSE THAT ROOK. DO NOT STALEMATE. Your program may or may not accept a human input for the starting position and for each black move (you can safely assume this is a legal position, i.e. the kings are not touching each other). If it doesn't, a random starting position and random movements for the black king will suffice. ## Score Your score will be length in byte of your code + bonus. Any language is allowed, lowest score wins. ### Bonus -50 if your program allows both a human defined starting position and a random one. Humans can enter it via stdin, file, GUI... -100 if your program allows both a human and a random player to move the black king +12345 if you rely on an external chess solver or a built-in chess library Good luck! # Update! Extra rule: The match must be played until checkmate. Black does not resign, doesn't jump outside the chessboard and doesn't get kidnapped by aliens. ## Hint You can probably get help from [this question](https://chess.stackexchange.com/questions/4886/how-do-you-checkmate-with-a-rook) on [chess.se](http://chess.stackexchange.com). [Answer] # Haskell 1463-100=1363 Just getting an answer in. This finds the solution the retrograde way, working back from checkmate to the position we're in. It differs from the description of retrograde analysis on [chessprogramming](https://chessprogramming.wikispaces.com/Retrograde+Analysis) - instead of starting with an initial set and expanding it with backwards moves until no squares moved to haven't been seen, it starts with all unused squares and reduces that set by trying forward moves. This is going to be less time-efficient than the traditional way, but the memory usage exploded for me when I tried it. Compile with `ghc -O2` for acceptable performance for the endgame table calculation; play is instant after the first move. Supply white king, rook, black king squares as arguments. For a move, it just wants a square, and will pick one for you if you press return. Example session: ``` $ time printf "\n\n\n\n\n\n\n\n"|./rook8 e1 a1 e8 ("e1","a7","e8")[d8]? ("d2","a7","d8")[c8]? ("d2","h7","c8")[b8]? ("c3","h7","b8")[a8]? ("b4","h7","a8")[b8]? ("c5","h7","b8")[a8]? ("b6","h7","a8")[b8]? ("b6","h8","b8") mate real 0m8.885s user 0m8.817s sys 0m0.067s ``` Code: ``` import System.Environment import qualified Data.Set as S sp=S.partition sf=S.fromList fl=['a'..'h'] rk=[0..7] lf=filter m=map ln=notElem lh=head pl=putStrLn pa[a,b]=(lh[i|(i,x)<-zip[0..]fl,a==x],read[b]-1) pr(r,c)=fl!!r:show(c+1) t f(w,r,b)=(f w,f r,f b) km(a,b)=[(c,d)|c<-[a-1..a+1],d<-[b-1..b+1],0<=c,c<=7,0<=d,d<=7] vd (w,r,b)=b`ln`km w&&w/=r&&b/=w&&b/=r vw p@(_,r,b)=vd p&&r`ln`km b&&(ck p||[]/=bm p) vb p=vd p&&(not.ck)p rm (w@(c,d),(j,k),b@(u,x))=[(w,(j,z),b)|z<-rk,z/=k,j/=c||(k<d&&z<d)||(d<k&&d<z),j/=u||(k<x&&z<x)||(x<k&&x<z)] kw(w,r,b)=m(\q->(q,r,b))$km w xb(w,r,_)b=(w,r,b) wm p=lf(\q->q/=p&&vw q)$rm p++(m(t f)$rm$t f p)++kw p bm p@(_,_,b)=lf(\q->q/=p&&vb q)$m(xb p)$km b c1((c,d),(j,k),(u,x))=j==u&&(c/=j||(k<x&&d<k)||(k>x&&d>k)) ck p=c1 p||(c1$t f p) mt p=ck p&&[]==bm p h(x,y)=(7-x,y) v=f.h.f f(x,y)=(y,x) n p@((c,d),_,_)|c>3=n$t h p|d>3=n$t v p|c>d=n$t f p|True=p ap=[((c,d),(j,k),(u,x))|c<-[0..3],d<-[c..3],j<-rk,k<-rk,u<-rk,x<-rk] fr s p=S.member(n p)s eg p=ef(sp mt$sf$lf vw ap)(sf$lf vb ap) ps w mv b0=sp(\r->any(fr b0)$mv r)w ef(b0,b1)w=let(w1,w2)=ps w wm b0 in(w1,b0):(if S.null w2 then[]else ef(f$ps b1 bm w2)w2) lu((w1,b0):xs)p=if fr w1 p then lh$lf(fr b0)$wm p else lu xs p th(_,_,b)=b cd tb q=do{let{p=lu tb q};putStr$show$t pr p;if mt p then do{pl" mate";return()}else do{let{b1=pr$th$lh$bm p};pl("["++b1++"]?");mv<-getLine;cd tb$xb p (pa$if""==mv then b1 else mv)}} main=do{p1<-getArgs;let{p2=m pa p1;p=(p2!!0,p2!!1,p2!!2)};cd(eg p)p} ``` Edited: Fixed code to remember endgame table and use arguments, so much less painful to test repeatedly. [Answer] # C, Currently 2552 noncomment nonwhitespace characters The count indicates to me that I could golf it down below 2552 total chars, but given there is already a smaller answer (which will be tough to beat) I will consider that carefully before bothering to do it. It's true there's about 200 chars for displaying the board and another 200 each for checking user input of both start position and move (which i need for testing, but could eliminate.) No game tree here, just hardcoded algorithm, so it moves instantly. Start positions are entered as row (1-8) column (1-8) numbered from top right and the program works on the same scheme. So if you turned your screen 90 degrees anticlockwise, it would follow the standard Correspondence Chess numeric square notation. Positions where the black king is already in check are rejected as illegal. Black moves are entered as a number from 0 to 7, with 0 being a move to the north, 1 to the northeast and so on in a clockwise sense. It doesn't follow the commonly known algorithm that exclusively uses the rook under the protection of the white king to restrict the black king. The rook only restricts the black king in a vertical sense (and will run away horizontally if chased.) The white king restricts the black king in horizontal movement. This means the two white pieces do not get in each others' way. I seem to have ironed out most of the bugs and possible infinite loops, it's running pretty well now. I will play with it again tomorrow and see if there is anything else that needs fixing. ``` #include "stdafx.h" #include "stdlib.h" #include "string.h" int b[2], w[2], r[2], n[2],s,t,i,nomate; int v[2][8] = { {-1,-1,0,1,1,1,0,-1}, {0,1,1,1,0,-1,-1,-1} }; int u[5] = { 0, 1, -1, 2, -2 }; char empty[82] = " \n--------\n--------\n--------\n--------\n--------\n--------\n--------\n--------\n"; char board[82]; int distance(int p[2], int q[2]){ return __max(abs(p[0]-q[0]),abs(p[1]-q[1])); } int sign(int n){ return (n>0)-(0>n); } // from parameters p for white king and q for rook, determines if rook is/will be safe int rsafe(int p[2],int q[2]){ return distance(p, q)<2 | distance(q,b)>1; } void umove(){ t=0; while (t != 100){ printf("Enter number 0 to 7 \n"); scanf_s("%d", &t); t %= 8; n[0] = b[0] + v[0][t]; n[1] = b[1] + v[1][t]; if (distance(w, n) < 2 | (n[0] == r[0] & (n[1]-w[1])*(r[1]-w[1])>0) | ((n[1] == r[1]) & (n[0]-w[0])*(r[0]-w[0])>0) | n[0] % 9 == 0 | n[1] % 9 == 0) printf("illegal move"); else{ b[0] = n[0]; b[1] = n[1]; t = 100; }; } } void imove(){ t=0; // mate if possible if (distance(b, w) == 2 & b[0] == w[0] & (b[1] == 1 | b[1] == 8) & r[0]!=w[0]){ n[0] = r[0]; n[1] = b[1]; if (rsafe(w, n)){ r[1] = n[1]; printf("R to %d %d mate!\n", r[0], r[1]); nomate=0; return; } } //avoid stalemate if ((b[0] == 1 | b[0] == 8) & (b[1] == 1 | b[1] == 8) & abs(b[0] - r[0]) < 2 & abs(b[0]-w[0])<2){ r[0] = b[0]==1? 3:6; printf("R to %d %d \n", r[0], r[1]); return; } // dont let the rook be captured. if(!rsafe(w,r)) { if (w[0] == r[0]) r[1] = w[1] + sign(r[1]-w[1]); else r[1] = r[1]>3? 2:7; printf("R to %d %d \n", r[0], r[1]); return; } // if there's a gap between the kings and the rook, move rook towards them. we only want to do this when kings on same side of rook, and not if the black king is already on last row. if (abs(w[0]-r[0])>1 & abs(b[0] - r[0]) > 1 & (b[0]-r[0])*(w[0]-r[0])>0 & b[0]!=1 & b[0]!=8){ n[0] = r[0] + sign(b[0] - r[0]); n[1] = r[1]; if (rsafe(w, n)) r[0] = n[0]; else r[1] = r[1]>3? 2:7; printf("R to %d %d \n", r[0], r[1]); return; } // if kings are far apart, or if they not on the same row (except if b 1 row from r and w 2 rows from r), move king if ((w[0]-r[0])!=2*(b[0]-r[0]) | abs(b[0]-w[0])>1 | distance(w,b)>2){ for (i = 0; i<8; i++) if (v[0][i] == sign(b[0] - w[0]) & v[1][i] == sign(b[1] - w[1])) t = i; s = 1 - 2 * (w[0]>3 ^ w[1] > 3); for (i = 0; i < 5; i++){ n[0] = w[0] + v[0][(t + s*u[i] + 8) % 8]; n[1] = w[1] + v[1][(t + s*u[i] + 8) % 8] *(1-2*(abs(w[0]-b[0])==2)); if (distance (n,b)>1 & distance(n, r)>0 & rsafe(n,r) & n[0]%9!=0 & n[1]%9!=0 & !(n[0]==r[0] & (w[0]-r[0])*(b[0]-r[0])>0)) i = 5; } if (i == 6) { w[0] = n[0]; w[1] = n[1]; printf("K to %d %d \n", w[0], w[1]); return; } } //if nothing else to do, perform a waiting move with the rook. Black is forced to move his king. t = r[1]>3? -1:1; for (i = 1; i < 5; i++){ n[0] = r[0]; n[1] = r[1] + t*i; if (rsafe(w, n)){ r[1] = n[1]; i=5; } } printf("R to %d %d \n", r[0], r[1]); } int _tmain(){ do{ t=0; printf("enter the row and col of the black king "); scanf_s("%d%d", &b[0], &b[1]); printf("enter the row and col of the white king "); scanf_s("%d%d", &w[0], &w[1]); printf("enter the row and col of the rook"); scanf_s("%d%d", &r[0], &r[1]); for (i = 0; i < 2; i++) if (b[i]<1 | b[i]>8 | w[i]<1 | w[i]>8 | w[i]<1 | w[i]>8)t=1; if (distance(b,w)<2)t+=2; if ((b[0] == r[0] & (b[1]-w[1])*(r[1]-w[1])>0) | ((b[1] == r[1]) & (b[0]-w[0])*(r[0]-w[0])>0)) t+=4; printf("error code (0 if OK) %d \n",t); } while(t); nomate=1; while (nomate){ imove(); strncpy_s(board, empty, 82); board[b[0] * 9 + b[1] - 1] = 'B'; board[w[0] * 9 + w[1] - 1] = 'W'; board[r[0] * 9 + r[1] - 1] = 'R'; printf("%s", board); if(nomate)umove(); } getchar(); getchar(); } ``` Here's a typical finish (mate can sometimes occur anywhere on the right or left edge of the board.) ![enter image description here](https://i.stack.imgur.com/U4cZi.png) ]
[Question] [ Simplified version of ["Signpost"](https://www.chiark.greenend.org.uk/%7Esgtatham/puzzles/js/signpost.html) puzzle from [Simon Tatham's Portable Puzzle Collection](https://www.chiark.greenend.org.uk/%7Esgtatham/puzzles/). ### How the puzzle is created We pick up randomly positive integer `N` and one of permutations of `1…N` *with `1` at the first position:* N = 12 [![enter image description here](https://i.stack.imgur.com/sklQh.jpg)](https://i.stack.imgur.com/sklQh.jpg) Numbers `1` and `N` always stay open, and `2` is always on the right of `1`. So we look at numbers `2` and `3`. `3` is on the left from `2`, so we mark `2` with left arrow: [![enter image description here](https://i.stack.imgur.com/3RQVt.jpg)](https://i.stack.imgur.com/3RQVt.jpg) Next we look at `3` and `4`. `4` is on the right from `3`, so we mark `3` with right arrow: [![enter image description here](https://i.stack.imgur.com/fKfuP.jpg)](https://i.stack.imgur.com/fKfuP.jpg) And so on so that every arrow above the number points towards the number that follows it (though the next number can be any distance away in that direction): [![enter image description here](https://i.stack.imgur.com/Wr2BF.jpg)](https://i.stack.imgur.com/Wr2BF.jpg) After all we hide initial sequence except `1` and `N`: [![enter image description here](https://i.stack.imgur.com/iSyZf.jpg)](https://i.stack.imgur.com/iSyZf.jpg) and write down puzzle in form of array: ``` ["1", "→", "→", "→", "→", "←", "→", "←", "12", "←", "←", "←"] ``` ### Task Given by an array of directions and two key positions, restore the initial sequence of numbers. ### Input List of directions and keys in any form, suitable for your language: array, json, string etc. Let for example `"→"` be `"r"` and `"←"` be `"l"`: ``` ["1", "r", "r", "r", "l", "r", "l", "12", "l", "l", "l"] ``` You may take `N` as a separate input or calculate it as length of list. You may assume that key points are given not as numbers, but as symbols (for example `"1"` = `"b"`(egin) and `N` = `"e"`(nd) ) Input always valid: non-empty, no typos, errors and necessarily corresponds to some valid sequence. ### Output Encrypted sequence as array, echo-print or as you like. You may only use test cases that are composed of existing sequences and therefore have at least one solution. But if there may be several, you can print any or all of them. ### Test cases ``` In "r" / "l" / "1" / "N" form: ["1", "2"] → [1, 2] ["1", "3", "l"] → [1, 3, 2] ["1", "r", "5", "l", "l"] → [1, 3, 5, 2, 4] or [1, 2, 5, 4, 3] ["1", "r", "6", "r", "r", "l"] → [1, 2, 6, 3, 4, 5] ["1", "r", "r", "r", "r", "l", "r", "l", "12", "l", "l", "l"] → [1, 3, 11, 5, 9, 10, 6, 8, 12, 4, 2, 7] ["1", "7", "l", "l", "l", "l", "l"] → [1, 7, 6, 5, 4, 3, 2] ["1", "r", "r", "l", "7", "l", "l"] → [1, 5, 3, 4, 7, 2, 6] or [1, 6, 4, 5, 7, 3, 2] ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 147 bits1, 18.375 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` 2€÷ṘN"ƛż*⇧⇧›;÷ṘȮL+?LpJ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwiMuKCrMO34bmYTlwixpvFvCrih6fih6figLo7w7fhuZjIrkwrP0xwSiIsIiIsIlsxLCAxLCAxLCAxLCAtMSwgMSwgLTEsIDIsIC0xLCAtMSwgLTFdIl0=) Takes input as single list without the starting symbol where `1` is an arrow to the right, `-1` is an arrow to the left and `2` is the end. Doesn't output the first `1`. ## How? Suppose that we have an input like this: `> < > < e < > <` We split the input on the end symbol and in the first part start assigning numbers to the left arrows from right to left. ``` > < > < e < > < 1 > < > < e < > < 2 1 ``` Then assign numbers to the right arrows from left to right. ``` > < > < e < > < 3 2 4 1 ``` This way the last number in the first part points to the right. Similarly we can assign numbers to the second part in a way that the last number points to the left. ## Code explanation ``` 2€÷ṘN"ƛż*⇧⇧›;÷ṘȮL+?LpJ 2€ # split on 2 ÷ # push each element Ṙ # reverse N # times -1 " # pair ƛ # map: ż* # multiply each by it's 1-based index ⇧ # grade up (sort indices by their value) ⇧ # grade up › # increment ; # end map ÷ # push each element Ṙ # reverse Ȯ # copy the second to last element on the stack to the top of the stack L # length + # add ?L # input length p # prepend J # join ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` ≔⌕A…θ⌕θILθrηEθ⎇№βιI⁺²⌕⁺⁺⁻⌕Aθrη⮌⌕Aθlηκι ``` [Try it online!](https://tio.run/##ZY0xC4MwEIX3/oqQ6YR00NVJAp0qSOkmDqkNJvSImqjgr09jsBTbG75794531yph216g94VzujNw0eZZIAJfW5Rc9QOMjGzm1rlwE1yl6SYFYxKKEWppoEryU2W1maAUMXGX1gi7Au/nYD4Y0cker3B2kO034xBRahP4@T5@DzNyk4u0Th6WSOP3bf2KSgfm3tc1TWkM/wOPKs1@zabx5wXf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⌕A…θ⌕θILθrη ``` Find the indices of all of the `r`s that appear to the left of the ending position. ``` Eθ⎇№βιI⁺²⌕⁺⁺⁻⌕Aθrη⮌⌕Aθlηκι ``` Find the indices of all the right `r`s, concatenate with the reversed indices of all the `l`s and with the indices of the left `r`s. Replace each lowercase letter with the index of its index in the list of indices, plus `2`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ẹⱮØ<ṚNƭ€F>ÞMA;MŻỤ ``` A monadic Link that accepts the signpost array as a list of characters with no leading `1` and with one `N` mixed with `<` for left and `>` for right and yields a possible input permutation. **[Try it online!](https://tio.run/##y0rNyan8///hrp2PNq47PMPm4c5ZfsfWPmpa42Z3eJ6vo7Xv0d0Pdy/5//@/up0NENr5gQgbdQA "Jelly – Try It Online")** ### How? ``` ẹⱮØ<ṚNƭ€F>ÞMA;MŻỤ - Link: signpost list, S Ø< - "<>" Ɱ - map across (c in "<>") with: ẹ - indices of (c) in (S) € - for each: ƭ - alternate between: Ṛ - a) reverse; and N - b) negate F - flatten M - maximum indices (of S) -> [index of 'N' in S] Þ - sort (the flattened list) by: > - is greater than (maximum indices)? (vectorises) A - absolute values M - maximum indices (of S) -> [index of 'N' in S] ; - (absolute values) concatenate (maximum indices) Ż - prepend a zero Ụ - sort the indices (of that) by their values ``` ### Example Using `S` with the leading `1` will also work so long as `N>1`, it just increases the results of `ẹⱮؽ` by one with no effect on the final result. ``` S "><><>>N><>><": > < > < > > N > < > > < M [7] ẹⱮØ< [[2, 4, 9, 12], [ 1, 3, 5, 6, 8, 10, 11]] ṚNƭ€ [[12, 9, 4, 2], [-1,-3,-5,-6,-8,-10,-11]] F [12, 9, 4, 2, -1, -3, -5, -6, -8,-10,-11] >ÞM [ 4, 2, -1, -3, -5, -6, -8,-10,-11, 12, 9] A [ 4, 2, 1, 3, 5, 6, 8, 10, 11, 12, 9] ;MŻ [0, 4, 2, 1, 3, 5, 6, 8, 10, 11, 12, 9, 7] (ie 1st, 5th, 3rd, 2nd, ...) Ụ [1, 4, 3, 5, 2, 6, 7, 13, 8, 12, 9, 10, 11] 1 > < > < > > N > < > > < ``` [Answer] # [Python](https://www.python.org), 154 bytes ``` lambda x:(z:=len(x))and next(i for i in permutations(range(z))if all(x[j]==i[j]or("RL"[j>i.index(i[j]+1)]==x[j])for j in range(z))) from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bY5NTsMwEIX3nGLk1RgC6o-EqkrhBF11m3ZhFBsmcsaRO5VMz8GKbrJp78RtcCgCFHXzRvO9p6d3PHdv8hq4PzkoYXPai7tffH540z7XBtISD8vSW8akteEa2CZBAhciEBBDZ2O7FyMUeIfR8IvFg9bkwHiPqWq2ZUlZQ0S1XqmqeaIH4tomHOjdVGd_SOmhsBkKfzv0jYuhBRIbJQS_A2q7EOX2Z-F7F4kFHVaTYrrN6X-_WqtiNmKzQq3Uldz8Cod5AZl-y9h6_LNGkpOXbX1_uV8) 0-indexed. I imagine in 5 minutes someone will post a answer in half this number of bytes [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 207 bits1, 25.875 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` żṖ'£Lɾḣṫ$⟑›"¥vḟƒ>‛rli;pJn‹İ?⁼ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwixbzhuZYnwqNMyb7huKPhuask4p+R4oC6XCLCpXbhuJ/Gkj7igJtybGk7cEpu4oC5xLA/4oG8IiwiIiwiWzEsIFwiclwiLCA1LCBcImxcIiwgXCJsXCJdIl0=) Probably times out online for anything larger than a 5 item list. Signpost is my favourite puzzle in the pack btw - the 5x5 grids are what I main. I sometimes do 6x6s for fun, or 4x4s when I want to see how fast I can solve one. It's especially fun when there's no extra hints, just the start, end, and a whole bunch of arrows. Non-fixed start/end positions are fun too :p ## Explained This boils down to "find the first permutation where applying the algorithm gives the input" ``` żṖ'£Lɾḣṫ$⟑›"¥vḟƒ>‛rli;pJn‹İ?⁼ żṖ' # All permutations (P) of the range [1, input.length] where: £Lɾḣṫ$ # The range [2, P.length) ⟑›"¥vḟƒ>‛rli; # With the following applied to each item (eagerly evaluated): ›" # [item, item + 1] ¥vḟ # 0-indexed positions in P ƒ> # reduced by greater than ‛rli # indexed into the string "rl" # (This determines which way a number points in P) pJ # With 1 prepended and P.length appended n‹İ # In the original of order of P ?⁼ # Equals the input ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 144 bytes ``` (m=Max@#;r[a_,i_,n_]:=(If[n >0,MapThread[If[#1<2&&#1(#2-i)<0,r[w=ReplacePart[a,#2->n-1],#2,n-1]]&,{a,Range@m}]];w);r[#,Position[#,m][[1,1]],m])& ``` [Try it online!](https://tio.run/##TY3BCsIwDIbvPoVQKBtksO7gQa3s6mEwhrdSRtDOFWwdtTBB9uw14mWQn@/nSyAO42gcRnvFNMiUOdngu2aHoLAH24Pv9V5m50H57amEBqfLGAzeFBkmjhXnTGSsKmx@LCGoWXZmeuDVtBiiQqDNyRdCU4EfNYcPQof@bmq3aH2Yc/rEoH2@bLRPT9VppQTQKbWcpzZYH@uh/pRAFnaUQiybld6K1RQrVH/@s6Qv "Wolfram Language (Mathematica) – Try It Online") Recursive approach. It seems that no one has used it yet. I’m sure it can be made shorter and better, but so far so. Take input with: * First position `0` * Max number `N` as it is * Left direction `-1` * Right direction `1` Ungolfed explained: ``` mainRec[arr_, currentInd_, current_] := (If[current > 0, MapThread[ If[#1 < 2 && #1*(#2 - currentInd) < 0, (*Recursive call for items that could be predecessors of \ current*) mainRec[currentArr = ReplacePart[arr, #2 -> current - 1], #2, current - 1] ] &, {arr, Range@Length@arr}] ]; currentArr); init = {0, 1, 1, 6, 1, -1}; (*First call with initial puzzle, N and index of N*) mainRec[init, Position[init, Max@init][[1, 1]], Max@init] ``` ]
[Question] [ A [super prime](https://en.wikipedia.org/wiki/Super-prime) is a prime whose index in the list of primes is also a prime: ``` 3, 5, 11, 17, 31, 41, 59, 67, 83, 109, 127, 157, 179, 191, 211, 241, 277, 283, 331, 353, 367, 401, 431, 461, 509, 547, 563, 587, 599, 617, 709, 739, 773, 797, 859, 877, 919, 967, 991, ... ``` For this challenge, an "order 2" super prime is defined as a super prime whose index in the list of super primes is a super prime: ``` 11, 31, 127, 277, 709, 1063, 1787, 2221, 3001, 4397, ... ``` An "order 3" super prime is an order 2 super prime whose index in the list of order 2 super primes is an order 2 super prime: ``` 5381, 52711, 648391, ... ``` And so on. ## Task Your task is to write a program or function, which, when given a prime, outputs/returns the highest order of super primes that the prime is a part of. In other words, how "super" is the prime? ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the solution with the lowest byte count wins * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden * The index of each prime in the list of primes, super primes, and so on, is assumed to be 1-indexed * You must output: + 0 for primes which are not super primes + 1 for super primes which are not order 2 super primes + 2 for order 2 super primes which are not order 3 super primes + And so on * You can assume inputs will always be prime numbers ## Test Cases ``` 2 -> 0 3 -> 1 11 -> 2 211 -> 1 277 -> 2 823 -> 0 4397 -> 2 5381 -> 3 171697 -> 2 499403 -> 2 648391 -> 3 ``` Your program must in theory be able to handle any order of super prime from 0 to infinity, even if it can only do the first few in a reasonable time. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12 11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆRJfịƊƬḊẎċ ``` A monadic Link that accepts a prime integer and yields the level. **[Try it online!](https://tio.run/##y0rNyan8//9wW5BX2sPd3ce6jq15uKPr4a6@I93/D7c/alrz/3@0kY6CsY6CoaGOghGYMDfXUbAwAgqZGFsCmabGFkBRQ3NDMxDPxNLSxAAoZ2ZiYWxpGAsA "Jelly – Try It Online")** ### How? ``` ÆRJfịƊƬḊẎċ - Link: prime number, P e.g ÆR - get all primes in [2..P] in ascending order Ƭ - start with L=that and collect up while distinct applying: Ɗ - last three links as a monad - f(L): J - indices of L -> [1..length(L] f - filter keep if in (L) ị - index into (L) -> next level, less than or equal to P -> new L Ḋ - dequeue - remove the initial list of primes Ẏ - tighten - to a flat list of all of the numbers found at all levels ċ - count occurrences of (P) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes ``` If[PrimeQ@#,1+#0@PrimePi@#,0]&/*Log2/*Floor ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zMtOqAoMzc10EFZx1Bb2cABzAvIBHINYtX0tXzy0430tdxy8vOL/geWZqaWgJTnlUQr69qlOSjHxqrVBScn5tVVcxnpcBnrcBka6nAZgQlzcx0uCyOgkImxJZBpamwBFDU0NzQD8UwsLU0MgHJmJhbGloZctf8B "Wolfram Language (Mathematica) – Try It Online") Primes of order \$n\$ are those that are a result of applying `Prime` (with `Prime[x]` the `x`th prime) on an integer \$2^n\$ times. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes ``` Þp¥(¨₂›æ;)ḟ›&›)⁽æ$ŀL‹ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJ+IiwiIiwiw55wwqUowqjigoLigLrDpjsp4bif4oC6JuKAuinigb3DpiTFgEzigLkiLCIiLCIyIC0+IDBcbjMgLT4gMVxuMTEgLT4gMlxuMjExIC0+IDFcbjI3NyAtPiAyXG44MjMgLT4gMFxuNDM5NyAtPiAyXG41MzgxIC0+IDNcbjE3MTY5NyAtPiAyXG40OTk0MDMgLT4gMlxuNjQ4MzkxIC0+IDMiXQ==) ## Explained ``` Þp¥(¨₂›æ;)ḟ›&›)⁽æ$ŀL‹ )⁽ $ŀ # While applying function ⁽ on the result of function ) is true, collect results. ⁽æ # Function ⁽: Is argument prime? Þp¥(¨₂›æ;)ḟ›&›) # Function ): Þp # The list of all primes ¥( ) # #register times (starts at 0): ¨₂ ; # Filter the top of the stack by: › # item index + 1 æ # is prime # This gets the (register)th order super primes ḟ› # Find the index of the function argument in that list &› # Increment the register for the next iteration L‹ # Length of that - 1 ``` [Answer] # JavaScript (ES6), 84 bytes ``` n=>~~Math.log2((g=n=>{for(i=k=0;k<n;i+=!d)for(d=k++;k%d--;);return!d*n&&1+g(i)})(n)) ``` [Try it online!](https://tio.run/##dc5BDoIwEAXQvaeAhaRjg9BWA6bWG3gIQgFrSWsKujFy9SpBV8Is/8ufmWvxKLrSqVsfGysrXwtvxGkYzkV/2ba2oQg14pM8a@uQElqkXB8NV1iEEsZMCo0x12sZxxy4q/q7M6HcmCgiuEEKXoAMgC@t6WxbjStRjYJxKECQJEG6mjE2GZkxQiaj/0Z/NtOjWbbYyylb@mXHDou9Pcu/95h/Aw "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~106~~ ~~98~~ 66 bytes ``` (a=Prime@Range@PrimePi@#;0)//.c_/;!FreeQ[a=0&@@a[[#]]&/@a,#]:>c+1& ``` [Try it online!](https://tio.run/##HctNC0AwGADg36LVIjIi@Wh6T864rqW39WKHOWh@/8TtuTwO/UkOvTUYdhlilPNtHcGK10Hwe7bAhiIRIjebGKLpJloUyoIDoFJMay4AM6b70aQlD8tjyX/z8rBDU7dVV4YX "Wolfram Language (Mathematica) [Dash] Try It Online") Thanks to @att! Old less golfed version for such noobs as I am: ``` (a=Table[Prime@k,{k,PrimePi@#}]; c=0; While[ MemberQ[a=If[#<=Length@a,a[[#]],Nothing] /@a,#], c++]; c)& ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÅP.ΓDāåÏ}˜I¢ ``` Very slow for larger inputs due to the `āåÏ`. The test suite below uses the legacy version with a slightly modified (1 byte longer) version to speed it up significally - although it'll still time out for the largest two test cases. [Try it online](https://tio.run/##AR8A4P9vc2FiaWX//8OFUC7Ok0TEgcOlw499y5xJwqL//zMx) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfaXS/8OtAeemHJ5wuu1I4@Glh/trD62vPLTI5r@SXpjOoS3/o410jHUMDXWMQNjcXMfCyFjHxNjSXMfU2MJQx9Dc0MzSPBYA). **Explanation:** ``` ÅP # Push a list of all primes <= the (implicit) input-prime .Γ # Loop until the result no longer changes, retaining any intermediate results: D # Duplicate the current list ā # Push a list in the range [1,length] (without popping) å # Check for each index whether it's in the list Ï # Only keep the values at the truthy indices }˜ # After the changes-loop: flatten the list of lists I¢ # Count the input in this flattened list # (after which the result is output implicitly) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 354 bytes [Try it online!](https://tio.run/##ZZFRS8MwFIXf/Rci7MFGZtq6rWaBqiAIbk4RfAhXyVy6BW1SshQLo7@9S9cOMiQPuefcnO8mJOd2I3Ju5TdvmvmMV3QUT6IEkxezEqbVMVkYmYuFXOg/YeZia@mDzgu9lVZqlabvfPkrWH8G7cLPixoGpKIHh71xtRbpZd9O2wlAjNjSXVUTRTH52EgXV1N6HIgq2iErxiQA2knkKvLvFkwBO@AA6g55VxRCrZgrkRuiggBIxlSZf8EtnelV6ZgOpktblLbud3qFyaM2TFKM5PRZqLXdtARAMgjQU8ZmIl8K89p63X0cEAaD81M/wH3niJWOe28E/2FA2tXZ0GQshOHQvUXZs4xFXo2xJ8JTNR57ahL6sThK/OZNNPGTeIxHJ/04SeJrP99999Fo9g) ``` NMax=648391;OrderMax=4;PrimePiPowerNest=Composition@@Table[PrimePi,{2^#}]&;x=Prime[Range@*PrimePi@NMax];res={x};n=1;While[n<=OrderMax,x=Table[x[[i]],{i,x[[;;PrimePiPowerNest[n][NMax]]]}];res=Append[res,x];n++];f[num_]:=Module[{i,output},output=-1;For[i=1,i<Length[res],i++,If[MemberQ[res[[i]],num]&&!MemberQ[res[[i+1]],num],output=i-1;Break[];];];output] ``` --- How does it work? Or Ungolfed version: ``` ClearAll["Global`*"]; NMax = 648391; OrderMax = 4; PrimePiPowerNest[n_] := Composition @@ Table[PrimePi, {2^n}]; PrimePowerNest[n_] := Composition @@ Table[Prime, {2^n}]; x = Prime[Range[1, PrimePi[NMax], 1]]; res = {x}; n = 1; While[n <= OrderMax, x = Table[x[[i]], {i, x[[;; PrimePiPowerNest[n][NMax]]]}]; Print[x[[;; 5]]]; res = Append[res, x]; n++] f[num_] := Module[{i, output}, output = -1; For[i = 1, i < Length[res], i++, If[MemberQ[res[[i]], num] && ! MemberQ[res[[i + 1]], num], output = i - 1; Break[];];]; output] (*input 648391 output 3, 648391 is 3 order super prime*) f[2]//Print f[3]//Print f[11]//Print f[211]//Print f[277]//Print f[823]//Print f[4397]//Print f[5381]//Print f[171697]//Print f[499403]//Print f[648391]//Print ``` the \$k\$-th element of \$n\$-order super prime is just `PrimePowerNest[n][k]` ]
[Question] [ One thing that is constantly frustrating when golfing ARM Thumb-2 code is generating constants. Since Thumb only has 16-bit and 32-bit instructions, it is impossible to encode every immediate 32-bit value into a single instruction. Additionally, since it is a variable length instruction set, some methods of generating a constant are smaller than others. **I hate that.** Write a program or function that does this work for me so I don't have to think about it. (\*shudder\*) There are four different variants of the `mov` instruction as well as a pseudo instruction which loads from a constant pool. They are either 2 bytes, 4 bytes, or 6 bytes long. These are the following: 1. `movs`: **2 bytes**. Generates any 8-bit **unsigned** value from `0x00` to `0xFF` in the low 8 bits, setting the other bits to `0`. 2. `mov`: **4 bytes**. Generates any 8-bit unsigned value **bitwise rotated any number of bits,**† filling the rest with `0` bits. 3. `mvn`: **4 bytes**. The same as `mov`, but generates the **one's complement** of that rotated 8-bit value, filling the rest with `1` bits. 4. `movw`: **4 bytes**. Can set the low 16 bits to any 16-bit **unsigned** value from `0x0000`-`0xFFFF`, and the high 16 bits to 0. 5. `ldr`: **6 bytes**. The last resort. Can generate **any** 32-bit value, but is slow and larger than the other options. †: Note that this is dramatically oversimplified, [the real encoding would make this challenge quite frustrating](https://developer.arm.com/documentation/ddi0308/d/Thumb-Instructions/Immediate-constants/Operation?lang=en). The input will be a 32-bit integer, either by string (base 10 signed/unsigned or hex), `stdin`, or value. **Every value from `0x00000000` to `0xFFFFFFFF` must be handled.** It is a critical part of the challenge. Watch out for signed shift issues. However, you can safely assume all inputs will fit into 32 bits, since ARM is a 32-bit architecture. The output will be the **shortest** instruction to encode this constant. The output format is whatever is easiest, as long as the values are distinct and you indicate which instruction corresponds to each output. There will be a few cases where multiple answers are correct. You may either output one of the correct answers, or all of them. However, you must only display the **shortest** answers. So, for example, you must only output `ldr` when none of the other instructions can generate it. Test cases (values are in hex to show the bit patterns) ``` 0x00000000 -> movs 0x00000013 -> movs 0x000000ff -> movs 0x12345678 -> ldr 0x02300000 -> mov 0xffffffff -> mvn 0x00ffffff -> mvn 0x00001200 -> mov or movw 0x11800000 -> mov 0x80000000 -> mov 0x00000100 -> mov or movw 0x0000f00d -> movw 0xfff3dfff -> mvn 0x03dc0000 -> mov 0xf000000f -> mov 0x00003dc0 -> mov or movw 0x0021f300 -> ldr 0x00100010 -> ldr 0xffff0000 -> ldr ``` Standard loopholes apply. Note that `as` and `objdump` will not help; they will use the real encoding which is wrong. 😏 Being [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest answer in bytes per language wins. [Answer] # JavaScript (ES6), 57 bytes Returns **false** for "mov", **true** for "movs", **2** for "ldr", **3** for "mvn" or **4** for "movw". ``` f=(n,r)=>n>>8?~n>>8?r>31?n>>16?2:4:f(n>>>31|n*2,-~r):3:!r ``` [Try it online!](https://tio.run/##dVDBboMwDL33KzwuTTbakoQxhASc9hXTDqgh0yYWqsBg0rb@OnNaSksLkZLY78l@z/7ImqzamvddvdKlzLtOxUS7hsaJTpIw3R9ekwiWYsSClEd@pAjGCP3qe@6u9oZGIrozXZ1XNcSgIU5gW@qqLPJ1Ub4RQkxeIYFllMIDLJd0vcvks5YksLlDHHzJD6isqPIInM@ycVyozVefVJhxDAtpMBIWbDRG/pFuHfijL6jxaptRhy4W1grxvr3@UNhswDYaE0zMEErdEIwL/zF4Cg8EGhkKuBhJnHDVnyPe6LPAHI5@@LkPlMZ@7aDPwkmd8GrE0SBsvt9hTM@TJ769MC7klEEht5OD9iubMmBL5g1wpkTf73Kh1jXea9wubdBHvPsH "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input r // r = rotation counter, initially undefined ) => // n >> 8 ? // if some of the upper 24 bits of n are not 0's: ~n >> 8 ? // if some of the upper 24 bits of n are not 1's: r > 31 ? // if the input was rotated 32 times (which means // that we've tried all possible rotations and we // are back to the original value): n >> 16 ? // if some of the upper 16 bits of n are not 0's: 2 // return 2 for "ldr" : // else: 4 // return 4 for "movw" : // else: f( // do a recursive call: n >>> 31 // rotate n by 1 position to the left | n * 2, // -~r // increment r ) // end of recursive call : // else: 3 // return 3 for "mvn" : // else: !r // return true for "movs" if r is zero'ish // or false for "mov" if r is greater than 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes ``` +Ø%BḊ¹¬ƭṙJ$Ḅ<⁹Ẹ ⁹²>;Ç;Ç;<⁹$TṀ ``` [Try it online!](https://tio.run/##y0rNyan8/1/78AxVp4c7ug7tPLTm2NqHO2d6qTzc0WLzqHHnw107uIDUoU121ofbQQgkqBLycGfD/8Ptj5rWPNzd/ahhTm5@WTmEApFleRB2MZDKSSl61DA38v//aC6DCgMo0IGzDY0R7LQ0ENvQyNjE1MzcAixuZAxXnwYFEPXIbKApRhA1hoYWcPUW6HYZIthpBgYpUDONU2DmGKckw@2COgimHiQFYRsZphnDzDEEGwpzG0RvLAA "Jelly – Try It Online") Returns 0, 1, 2, 3, 4 respectively for `ldr`, `movw`, `mov`, `mvn` and `movs`. Probably could be improved. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~105~~ \$\cdots\$~~73~~ 72 bytes Saved 15 bytes thanks to [EasyasPi](https://codegolf.stackexchange.com/users/94093/easyaspi)!!! Saved ~~3~~ 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` i;z;f(n){for(i=0;z=n>>8,i++<32&&z&&~z;)n=n*2|n<0;i=z?~z?z>>8?4:3:2:i>1;} ``` [Try it online!](https://tio.run/##bVJRb8IgEH7fryBNbKrWjBbdOrH6sOxt/8A2i6F0kk00pVNSV/@6A0q1biPhjvvu4447jozeCTmfGa5w7vH@Md8WHoshrmI@n0c@Gw5nKHTdynVPFe7zmA/Cbz6DmMXV4lQtKkVajKdoGk7ZPMD1ebNi3Osf74BajJdgs90LEAOIuwhQSNBB9lwj4Q3noBB0RT6zQnPGDULWq2KgcFEWX6RkWy6WqfIeHZ3O8YHWRu25tQ5aqyBOfY1ZUlG@8WUavzoJTGSAEpnnSodoPHl4jBIZIqiXhpvVnjRJ40EQWUajDWYuQJgZMsoMHWXERmpoFlIpghzZW4FNpP3O9ZVU7igpadZUqAv0QVeqoszR131shTH/iMP/bhOhFXWnw2RNyQctbG8T@RIm8ulZ7YnuZsdGbVvN@KhHM55RqcbI6JlgFd3ml0ruG3vQ2ng4NDw7NpfvUVntFxl3im/ceqxyr@zfolShl479vrYrFCX3HCh7MJJgNAe90ViAnkj0mJT@7USJ1AdtB0Qc09Smqu/q8w8 "C (gcc) – Try It Online") Returns \$0,1,2,3,4\$ for `movs`, `mov`, `mvn`, `movw`, `ldr`. ### Explanation (before some golfs) ``` i;f(n){ // function taking a 32 bit parameter n for(i=0;i++<32 // loop for maximum of 32 times &&n>>8 // while there's set bits in the 24 msb &&~n>>8;) // and in the 24 msb of n's 1s compliment n=n*2|n<0; // rotate n 1 bit to the left i= // return: n>>8?~n>>8? // if these are still truth values then we // must have rotated n 32 times n>>16? // does the original n have set bits in the // 16 msb? 4: // ldr if it does 3: // movw if it doesn't. // the ones below are because we stopped // looping when we found no/all 1 bits in // the 24 msb 2: // mvn if all 24 msb are set in the // current of a rotation of n i>1; // mov if there's no set bits in the 24 msb // of the current rotation of n // movs if there's no set bit in the 24 msb } // of n at the start. ``` [Answer] # MMIX, 96 bytes (24 instrs) Returns 8 for `movs`, else is a bitfield (1 for `mov`, 2 for `mvn`, 4 for `movw`). 0 is thus for `ldr`. I'm fairly certain that this can never return 6 or 7. ``` 00000000: 3fff0008 4aff0003 e3010008 f8020000 ?”¡®J”¡¤ẉ¢¡®ẏ£¡¡ 00000010: 3fffff08 7301ff04 cf040000 e3050000 ?””®s¢”¥Ẇ¥¡¡ẉ¦¡¡ 00000020: fe020004 f2030003 f6040002 28010301 “£¡¥ṗ¤¡¤ẇ¥¡£(¢¤¢ 00000030: 3b030020 e3020000 e3040020 27040401 ;¤¡ ẉ£¡¡ẉ¥¡ '¥¥¢ 00000040: 3fff0338 6302ff01 3bff031f 3f030301 ?”¤8c£”¢;”¤þ?¤¤¢ 00000050: c00303ff 5b04fffa c0010102 f8020000 Ċ¤¤”[¥”«Ċ¢¢£ẏ£¡¡ ``` ``` gt2 SRU $255,$0,8 BNZ $255,0F // if(!(n >> 8)) SET $1,8 POP 2,0 // return 8; (movs) 0H SRU $255,$255,8 ZSZ $1,$255,4 // rv = !(n >> 16) << 2 NXOR $4,$0,0 // y = ~n SET $5,0 GET $2,rJ PUSHJ $3,0F // q = f(y, 0) PUT rJ,$2 2ADDU $1,$3,$1 // rv = rv + q * 2 0H SLU $3,$0,32 // f(n, rv): y = n << 32 SET $2,0 // q = 0 SET $4,32 // i = 32 0H SUBU $4,$4,1 // loop: i-- SRU $255,$3,56 CSZ $2,$255,1 // if(!(y >> 56)) q = 1 SLU $255,$3,31 SRU $3,$3,1 OR $3,$3,$255 // y = (y >> 1) | (y << 31) PBNZ $4,0B // if(i) goto loop OR $1,$1,$2 // rv |= q POP 2,0 // return(rv) ``` To also support the weird versions of `mov` and `movn`, replace `SET $2,0` (`E3020000`, `ṭ£¡¡`) with the following, at a cost of 40 bytes/10 instructions: ``` SRU $255,$0,16 // ?”¡Ñ t = n >> 16 XOR $255,$255,$0 // İ””¡ t ^= n SLU $255,$255,48 // ;””0 t <<= 48 ZSZ $4,$255,1 // s¥”¢ i = !t (test for top-equals-bottom) SLU $255,$3,24 // ;”¤ð t = y << 24 ZSZ $1,$255,$4 // r¢”¥ q = t? 0 : i (test for low-bytes-zero) XOR $255,$255,$3 // İ””¤ t ^= y SRU $255,$255,56 // ?””8 t >>= 56 CSZ $1,$255,$4 // b¢”¥ if(!t) q = i (test for all-bytes-equal) SRU $255,$3,56 // ?”¤8 t = y >> 56 CSZ $1,$255,$4 // b¢”¥ if(!t) q = i (test for high-bytes-zero) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes ``` ≔⍘×⊕X²¦³²N²θ¿‹Lθ⁴¹movs¿‹Lθ⁴⁹movw¿№θ×0²⁴mov¿№θ×1²⁴mvn¦ldr ``` [Try it online!](https://tio.run/##fY5NC8IwDIbv/oqyUwsT9nURT@ppIDLQm3iYW9wKXeeabvPf1wxFGIqBBPrwvEmLOjdFmyvnNoiy0nybIxytkbriJ9kA8lQXBhrQFkqetSMYHvksjoTwWarvvT30zZXg9I6oO7FeyBvje0CkoStb8454EgrBMtprude0A3rkgUJgP@XVTB5n8q7tiXc@e/3PCzy6nIhZ4m8g/AoM@hN4I1UaQs6dg0cUJ8FUF7cc1BM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⍘×⊕X²¦³²N²θ ``` Input the integer, multiply it by 2³²+1, and convert to binary. ``` ¿‹Lθ⁴¹movs ``` If the length is less than 41, then the original number had 8 bits or fewer, so a `movs` instruction will work. ``` ¿‹Lθ⁴⁹movw ``` Otherwise if the length is less than 49, then the original number had 16 bits or fewer, so a `movw` instruction will work. ``` ¿№θ×0²⁴mov ``` Otherwise if the binary contains a string of 24 `0`s, then they can be rotated to the beginning of the original number, so a `mov` instruction will work. ``` ¿№θ×1²⁴mvn ``` Otherwise if the binary contains a string of 24 `1`s, then they can be rotated to the beginning of the original number, so a `mvn` instruction will work. ``` ¦ldr ``` Otherwise give up and use `ldr`. This challenge reminds me of the difficulty of loading immediate values using original ARM instructions, so I wrote a 32-byte program that identifies values that can be loaded into a register via `mov` or `mvn`: ``` ≔⍘×⊕X²¦³²N⁴θ¿№θ×0¹²mov¿№θ×3¹²mvn ``` [Try it online!](https://tio.run/##bYwxC8IwFIR3f8Uj0wtEiK2bkwpCFynoJg61PjXQvNgkrf77GHXUgxvuuO/aW@Nb13QpLUMwV8ZVE2gXveEr7o2lgBW3nixxpDPW7kEeCwVlIaWCiu9D3A72lMt3nmf3cjExF8C1Gzhir@D7IrRQMMuUhDqfRxTWjSJvqQsE/4DyBxg5Aykd9FNvPtLHNB27Fw "Charcoal – Try It Online") Link is to verbose version of code. Outputs `mov` if the value can be used directly as an immediate operand, or `mvn` if you can at least load it into a register. [Answer] # Z80, ~~59~~ 55 bytes Input value in `dehl`. Output in `c`, 0, 1, 2, 3, 4 for `ldr`, `mvn`, `mov`, `movw`, `movs` respectively. Trashes `b` and `a`. This is indeed rather silly. ``` 0E 03 7C B7 20 01 0C 7B B2 C8 AF 4F 3C F5 7A 2F 57 7B 2F 5F 7C 2F 67 7D 2F 6F 06 20 7A 17 CB 15 CB 14 CB 13 CB 12 7C B3 B2 20 03 F1 4F F5 10 EC F1 D8 37 3C F5 18 D7 ``` ``` foo: ld c,3 // 0E 03 we might want to return 3 ld a,h // 7C is h zero? or a // B7 the test jr nz,hnz // 20 01 if so, inc c // 0C increment c hnz: // in any case, ld a,e // 7B load e or d // B2 or in d ret z // C8 if both zero return xor a // AF clear a and carry ld c,a // 4F and c inc a // 3C actually, set a to 1 push af // F5 store a and carry subr: ld a,d // 7A complement dehl cpl // 2F ld d,a // 57 ld a,e // 7B cpl // 2F ld e,a // 5F ld a,h // 7C cpl // 2F ld h,a // 67 ld a,l // 7D cpl // 2F ld l,a // 6F ld b,32 // 06 20 do the following 32 times: loop: ld a,d // 7A load D into A rla // 17 move top bit of A into C flag rl l // CB 15 do the rest of rl h // CB 14 the left rotation rl e // CB 13 rl d // CB 12 ld a,h // 7C or together or e // B3 the top three or d // B2 bytes; jr nz,nofit // 20 03 if all zero, pop af // F1 reload old af ld c,a // 4F load c push af // F5 push it back nofit: // in any case djnz loop // 10 EC end loop pop af // F1 reload old af ret c // D8 return if second time scf // 37 marker for second time inc a // 3C and increment a push af // F5 push those back jr subr // 18 D7 and try again with complement ``` Bonus: another version that also checks for the weird constants, in 75 bytes. (Inserted region between »German guillemets«, changed byte in \*stars\*). ``` 0E 03 7C B7 20 01 0C 7B B2 C8 AF 4F 3C F5 7A 2F 57 7B 2F 5F 7C 2F 67 7D 2F 6F»AB 20 11 7C AA 20 0D AC 28 07 AD 28 04 7D B7 20 03 F1 4F F5«06 20 7A 17 CB 15 CB 14 CB 13 CB 12 7C B3 B2 20 03 F1 4F F5 10 EC F1 D8 37 3C F5 18*C3* ``` ``` foo: ld c,3 // 0E 03 we might want to return 3 ld a,h // 7C is h zero? or a // B7 the test jr nz,hnz // 20 01 if so, inc c // 0C increment c hnz: // in any case, ld a,e // 7B load e or d // B2 or in d ret z // C8 if both zero return xor a // AF clear a and carry ld c,a // 4F and c inc a // 3C actually, set a to 1 push af // F5 store a and carry subr: ld a,d // 7A complement dehl cpl // 2F ld d,a // 57 ld a,e // 7B cpl // 2F ld e,a // 5F ld a,h // 7C cpl // 2F ld h,a // 67 ld a,l // 7D cpl // 2F ld l,a // 6F // begin insert xor e // AB check for e=l jr nz,stlp // 20 11 if not, skip to loop ld a,h // 7C xor d // AA check for d=h jr nz,stlp // 20 0D if not, skip to loop xor h // AC check for h=0 (a 0 already) jr z,succ // 28 07 if so, skip to succ xor l // AD check for h=l jr z,succ // 28 04 if so, skip to succ ld a,l // 7D or a // B7 check for l=0 jr nz,stlp // 20 03 if not, skip to loop succ: pop af // F1 reload old af ld c,a // 4F load c push af // F5 push it back stlp: // end insert ld b,32 // 06 20 do the following 32 times: loop: ld a,d // 7A load D into A rla // 17 move top bit of A into C flag rl l // CB 15 do the rest of rl h // CB 14 the left rotation rl e // CB 13 rl d // CB 12 ld a,h // 7C or together or e // B3 the top three or d // B2 bytes; jr nz,nofit // 20 03 if all zero, pop af // F1 reload old af ld c,a // 4F load c push af // F5 push it back nofit: // in any case djnz loop // 10 EC end loop pop af // F1 reload old af ret c // D8 return if second time scf // 37 marker for second time inc a // 3C and increment a push af // F5 push those back jr subr // 18 C3 and try again with complement ``` ]
[Question] [ *NOTE: Since I'm Dutch myself, all dates are in the Dutch `dd-MM-yyyy` format in the challenge description and test cases.* ## Challenge: **Inputs:** Start date \$s\$; End date \$e\$; Digit \$n\$ **Outputs:** All dates within the range \$[s,e]\$ (including on both sides), which contain \$n\$ amount of unique digits in their date. **Example:** *Inputs:* Start date: `12-11-1991`; End date: `02-02-1992`; Digit: `4` *Outputs:* With leading 0s for days/months: ``` [20-11-1991, 23-11-1991, 24-11-1991, 25-11-1991, 26-11-1991, 27-11-1991, 28-11-1991, 30-11-1991, 01-12-1991, 02-12-1991, 09-12-1991, 10-12-1991, 13-12-1991, 14-12-1991, 15-12-1991, 16-12-1991, 17-12-1991, 18-12-1991, 20-12-1991, 23-12-1991, 24-12-1991, 25-12-1991, 26-12-1991, 27-12-1991, 28-12-1991, 31-12-1991, 01-01-1992, 02-01-1992, 09-01-1992, 10-01-1992, 11-01-1992, 12-01-1992, 19-01-1992, 20-01-1992, 21-01-1992, 22-01-1992, 29-01-1992, 01-02-1992, 02-02-1992] ``` Without leading 0s for days/months: ``` [20-11-1991, 23-11-1991, 24-11-1991, 25-11-1991, 26-11-1991, 27-11-1991, 28-11-1991, 30-11-1991, 3-12-1991, 4-12-1991, 5-12-1991, 6-12-1991, 7-12-1991, 8-12-1991, 10-12-1991, 13-12-1991, 14-12-1991, 15-12-1991, 16-12-1991, 17-12-1991, 18-12-1991, 20-12-1991, 23-12-1991, 24-12-1991, 25-12-1991, 26-12-1991, 27-12-1991, 28-12-1991, 31-12-1991, 3-1-1992, 4-1-1992, 5-1-1992, 6-1-1992, 7-1-1992, 8-1-1992, 10-1-1992, 13-1-1992, 14-1-1992, 15-1-1992, 16-1-1992, 17-1-1992, 18-1-1992, 20-1-1992, 23-1-1992, 24-1-1992, 25-1-1992, 26-1-1992, 27-1-1992, 28-1-1992, 31-1-1992] ``` ## Challenge rules: * The input and output dates may be in any reasonable (date-)format. Can be as a string in any `dMy` format (including optional separators), list of three integers, your language's native Date-object, etc. Output may be a list/array/stream, printed to STDOUT, a single delimited String, etc. * You are allowed to include or exclude leading 0s for days/months in your outputs. **Please specify which of the two you use in your answer**, since it will cause different results. I.e. `1-1-1991` has 2 unique digits, but `01-01-1991` as 3 unique digits. * You don't have to deal with leap years and differences of Gregorian vs Julian calendars. You can assume the date-ranges given in the test cases will never go over February 28th/March 1st for years divisible by 4. * The input-digit \$n\$ is guaranteed to be in the range \$[1,8]\$, so dealing with \$n=0\$ is unspecified (returning an empty list would be most reasonable, but giving an error or incorrect result is fine as well; you won't have to deal with that input). ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Inputs: [12-11-1991, 02-02-1992], 4 Outputs with leading 0s: [20-11-1991, 23-11-1991, 24-11-1991, 25-11-1991, 26-11-1991, 27-11-1991, 28-11-1991, 30-11-1991, 01-12-1991, 02-12-1991, 09-12-1991, 10-12-1991, 13-12-1991, 14-12-1991, 15-12-1991, 16-12-1991, 17-12-1991, 18-12-1991, 20-12-1991, 23-12-1991, 24-12-1991, 25-12-1991, 26-12-1991, 27-12-1991, 28-12-1991, 31-12-1991, 01-01-1992, 02-01-1992, 09-01-1992, 10-01-1992, 11-01-1992, 12-01-1992, 19-01-1992, 20-01-1992, 21-01-1992, 22-01-1992, 29-01-1992, 01-02-1992, 02-02-1992] Outputs without leading 0s: [20-11-1991, 23-11-1991, 24-11-1991, 25-11-1991, 26-11-1991, 27-11-1991, 28-11-1991, 30-11-1991, 3-12-1991, 4-12-1991, 5-12-1991, 6-12-1991, 7-12-1991, 8-12-1991, 10-12-1991, 13-12-1991, 14-12-1991, 15-12-1991, 16-12-1991, 17-12-1991, 18-12-1991, 20-12-1991, 23-12-1991, 24-12-1991, 25-12-1991, 26-12-1991, 27-12-1991, 28-12-1991, 31-12-1991, 3-1-1992, 4-1-1992, 5-1-1992, 6-1-1992, 7-1-1992, 8-1-1992, 10-1-1992, 13-1-1992, 14-1-1992, 15-1-1992, 16-1-1992, 17-1-1992, 18-1-1992, 20-1-1992, 23-1-1992, 24-1-1992, 25-1-1992, 26-1-1992, 27-1-1992, 28-1-1992, 31-1-1992] Inputs: [19-09-2019, 30-09-2019], 5 Outputs (same with and without leading 0s): [23-09-2019, 24-09-2019, 25-09-2019, 26-09-2019, 27-09-2019, 28-09-2019, 30-09-2019] Inputs: [19-09-2019, 30-09-2019], 8 Output (same with and without leading 0s): [] Inputs: [20-06-1749, 30-06-1749], 8 Outputs with leading 0s: [23-06-1749, 25-06-1749, 28-06-1749] Outputs without leading 0s: [] Inputs: [10-12-1969, 12-01-1970], 6 Outputs (same with and without leading 0s): [30-12-1969] Inputs: [10-12-1969, 12-01-1970], 5 Outputs with leading 0s: [10-12-1969, 13-12-1969, 14-12-1969, 15-12-1969, 17-12-1969, 18-12-1969, 20-12-1969, 23-12-1969, 24-12-1969, 25-12-1969, 27-12-1969, 28-12-1969, 31-12-1969, 02-01-1970, 03-01-1970, 04-01-1970, 05-01-1970, 06-01-1970, 08-01-1970, 12-01-1970] Outputs without leading 0s: [10-12-1969, 13-12-1969, 14-12-1969, 15-12-1969, 17-12-1969, 18-12-1969, 20-12-1969, 23-12-1969, 24-12-1969, 25-12-1969, 27-12-1969, 28-12-1969, 31-12-1969, 2-1-1970, 3-1-1970, 4-1-1970, 5-1-1970, 6-1-1970, 8-1-1970, 12-1-1970] Inputs: [11-11-1111, 11-11-1111], 1 Output (same with and without leading 0s): [11-11-1111] ``` [Answer] # [R](https://www.r-project.org/), 81 bytes ``` function(s,e,n,x=seq(s,e,1))x[lengths(sapply(strsplit(paste(x),""),unique))==n+1] ``` [Try it online!](https://tio.run/##TYoxCgIxEEXvkmoGs2IWmy3SeQuxCMtEA2HM7kwgnj5mrYRXfN77e4@@x8qrpjeDWLJsmxfaftshtnsmfupLQEIp@QOiu5ScFEoQJWhojUFbOW2VEL3nk3v0CEHOtzC6ccviJjeYx@3fztPlYNgr9i8 "R – Try It Online") Uses R’s native date format and has leading zeros on day and month. [Answer] # [Red](http://www.red-lang.org), 93 bytes ``` func[a b n][until[if n = length? exclude d: rejoin[a/4"-"a/3"-"a/2]"-"[print d]b < a: a + 1]] ``` [Try it online!](https://tio.run/##jYxBCsIwFET3PcWQrXyapLWSongHtyGL2CQaKVFKC94@pgouXAmf@bN48ybv8sk7barQI4clDdrijGT0kuY46hiQcMDo02W@HuGfw7g4D9dj8rd7TNrWLSNm6@ad0pSnH1NMM5w5Yw/bw2IDYUwOEJKEIKGUAJdUrlSJFp8BIyJWFUoRVyS5UGj4t3a/FKdVpzq1avmq3fE/KWzzCw "Red – Try It Online") Without leading 0s for days/months. Too bad that [Red](http://www.red-lang.org) converts internally `09-10-2019` to `9-Oct-2019` - that's why I need to extract the day/month/year individually. [Answer] # [Japt](https://github.com/ETHproductions/japt), 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes the date inputs as Unix timestamps, outputs an array of strings with formatting and leading `0`s dependent on your locale. Would be 1 byte shorter in Japt v2 but there seems to be a bug when converting `Date` objects to strings. ``` òV864e5@ÐX s7Ãf_¬â ʶWÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=0FVxLSB3KW4K0FZxLSB3KW4&code=8lY4NjRlNUDQWCBzN8NmX6ziIMq2V8Q&input=IjEyLTExLTE5OTEiCiIwMi0wMi0xOTkyIgo0Ci1S) ``` òV864e5@ÐX s7Ãf_¬â ʶWÄ :Implicit input of integers U=s,V=e & W=n òV :Range [U,V] 864e5 : With step 86,400,000 (24*60*60*1000) @ :Map each X ÐX : Convert to Date object s7 : Convert to locale date string à :End map f :Filter _ :By passing each through the following function ¬ : Split â : Deduplicate Ê : Length ¶ : Is equal to WÄ : W+1, to account for the inclusion of the delimiting "/" or "-" ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 84 bytes -6 bytes thanks to Gloweye ``` lambda s,e,n:[d for i in range((e-s).days+1)if-len(set(d:=str(s+type(e-s)(i))))==~n] ``` An unnamed function which returns a list of strings (counting/including leading zeros) that accepts three arguments: * `s`, the *start* - a `datetime.date` object; * `e`, the *end* - a `datetime.date` object; and * `n`, the number of days - an `int` object. **[Try it online!](https://tio.run/##VY07DsIwEAV7TrHlWnEQIQhCJJ8EKIy8BkvxR/Y2bri6IemY7o2eNKnyO4ZxSrnZHD0YzcTOEzifYuZt76y6t0X7p9FQJMkw3wzYmMGBC5B1eBEi9UXsja6lG4Sz/UIBCzGaWRXOWDquibYTOvFDqU94tJRdYLS4VnC4nK4SzhKOByHhX42rmoRoXw "Python 3.8 (pre-release) – Try It Online")** Note: As the function accepts `datetime.date` objects I have not counted the import code for that (and have worked around importing the `datetime.timedelta` object as it is indirectly accessible via subtraction of these input objects). [Answer] # [Ruby](https://www.ruby-lang.org/) `-rdate`, 54 bytes Takes 2 [Date](https://ruby-doc.org/stdlib-2.6.1/libdoc/date/rdoc/Date.html) objects and a number as input, and returns a list of Date objects as output. Handles leap years and uses leading zeroes. ``` ->a,b,n{(a..b).select{|d|d.to_s.chars.uniq.size==n+1}} ``` [Try it online!](https://tio.run/##jZBBbsMgEEX3OQXyKlEZxLipUxbuqrewrApsoliKsGvwoo1z9dIxTZuoq3zN5qEH88U4mY@4LyO8aG64O621EGYjvD3aJpzmdm5F6N@8aA569GJy3bvw3actS/eA53OsVoxSZagUAuaAmHG2UA5yGaJtzS9SLlGBVIBqkX7pURI93SM9/0m429JxAblM6y70X1KFSp1@JLWTIJeSRMU90rUTUiBNkm4JSaqF1c2BtT2bNWeGMzeni8MUPNtXrzpYMdD32bXecHaDhtDV9CRck62sa@NXP4Sudz7C2JL/DQ "Ruby – Try It Online") [Answer] # JavaScript (ES6), 91 bytes Takes input as `(n)(end)(start)`, where the dates are expected as Unix timestamps in milliseconds. Returns a space-separated list of dates in format `yyyy-mm-dd`. Leading 0s are included. ``` n=>b=>g=a=>a>b?'':(new Set(d=new Date(a).toJSON().split`T`[0]).size+~n?'':d+' ')+g(a+864e5) ``` [Try it online!](https://tio.run/##rZFBS8MwGIbv/orckhC@kq923SIku@zkQQ/zJsKyNSsdJRlr2MCDf7226MRWNgSF75Dw8D7ke7OzR9tsDtU@gg@Fa7e69dqstSm11caa9ZzSO@bdiSxdZIXuTwsbHbM8ieF@@fjAeNLs6yqunlbP8qW7VK9OvPk@VwhKKBcls2KWZ27C203wTahdUoeSUQBDKBFkyzLOxJeZolIpyH4oHwME7KYH/OaCbDLIpBIVSAW3ciQ7A1TXZOo/ZbPhNtOsy@Q/ZWeQymuyfFTNVIL8rGYI8u5ZKaD8fWd/lOEwg/jxaTiWfQe8fQc "JavaScript (Node.js) – Try It Online") [Answer] # [PHP](https://php.net/), 90 bytes ``` for([,$s,$e,$n]=$argv;$s<=$e;)$n-count(count_chars($d=date(Ymd,86400*$s++),1))||print$d._; ``` [Try it online!](https://tio.run/##jZHPT4MwFMfv/BUvS5OBa2eLDKiMePbk2TCyEKgysxVCixfn346lw22JHta8NO/bfN7PtnU7rJ/aunUcpIXSClLIHDAnmzOfMEYY52yOYU59Yswo36ggx78QJ5QTnzI@Qg/0Sq1ugfgZ8s1zSFgUnKGzii@ZKBnb4qGFjEvHDiNqVHgLdNUTs9OZY6FrxQyUJ47z1nSiKGtwp9UUCqznwZdNIsq6gdmzbHv9CDNYwkezk@4Mg7EJXMJsI196fUISG4aULjptFq10pxu9O4hTgYzmHtxDHAaUTqSQ1T8c@8MV3fvn@HOy3@/xVADb8KmTzM/zZDADuRlGCiOBkcxTG5cgtU6RSDwkSdn0Urv23pZ10SkXVWlVaOG@HipsK94htVh4mHne8dh2O6lRtdwmw2UfG7mRZtLvYYh4vBpiGkZD8AM "PHP – Try It Online") This is with leading 0s. Inputs are command arguments (`$argv`) and dates are Unix timestamps in days (basically standard seconds / 86400), I used this format as we don't need the time in this challenge and it allowed me to golf 1 more byte. Keeps adding a day to start until it reaches the end and prints any dates with `$n` unique digits in it, separated by `_` in `Ymd` format. Also have a [89 bytes alternative](https://tio.run/##jZHPb4MgFMfv/hUvhqS6QgfOqsw2O@@082JNY5TNLi0awV3W/e0OqWubbIe@EHhf8nm8H7R1O6ye2rp1HKSF0grWkDlgLJuxgDBGGOdshmFGA2KWUYFRYY5/IU4oJwFlfIQe6JVa3gLxMxSY64iwODxDZ5VcXqJkLItHFjIuHSuMqVHRLdBVTcx2Z8xC14oZKE8d563pRFHW4E2jKRRYz4cv@4go6wbcZ9n2@hFcWMBHs5Oei8GsCVyAu5EvvT4hqQ1DShedNoNWutON3h3EKUFGcx/uIYlCSidSyOofjv3hiu79c/w52e/3eEqAbfhUSRbkeTqYhrwMI4WRwEjmaxuXIrVaI2GO@dxHkpRNL7Vn921ZF53yqkIL7/VQYZvyDikfM98/HttuJzVSi206XMaxkRtpGv0ehpgnyyGhUTyEPw) which prints dates to output in same format as input (Unix timestamps in days). [Answer] # [Java (JDK)](http://jdk.java.net/), 86 bytes ``` (s,e,n)->s.datesUntil(e.plusDays(1)).filter(d->(""+d).chars().distinct().count()==n+1) ``` [Try it online!](https://tio.run/##jVRtb5swEP6eX3FCjWRWbGHapSMZ@dRWmrRIk7p9mKp88MAkZGAQNt2qKr89O5u8NttUg4yfu@defD6zEk@CrrKfm6Jq6tbACjEzRSXZ5zoV5a0wcjI40@V1WwnDrPYr4nsHjWxPqZ0pSqZNK0XF3k0Gg7QUWsNMFApeBgCFQotcpBLuHQZ4cNyP@8hTyMkegA7gAGRg7UH5E7RcD3Bquh9lkYI2wuDnqS4yqDAUQaeFWjzOQbQL7YNZtvUvDXe/U9mYolbb0PeQQ7IhOpCB8ulUswyj6G8Kt0Aka8pO34pnTbjvs7woMXGS0SnxvMvMZ@lStJr4LCu0KVRqcJnWncJvkqhL7m8mu925RDAVdG00JNvYdrx4PKKcUx7H3AvACyOKL6LIomtvHRxTYxrGNAp5bJVX4TF6/3bqh1NqhMoR5TfXe@oBvaLykNp045FT4jK0md@EFo3eTn2dK3cVwOGop2hHXffFPGs9yM4kyTmL1fkXt1DEyzI6m9EOh@f3TrGt4dAv9pBg3J@Vvz@qo37EAHvEGuwBSSz5MZwH59lsQxw7kP9ywP/rwPU9mn7C@7PALTlDBL1tNEfilvnwrI2sWN0Z1uCmTE48nQz5hcmonSs3fw9AJsPICSMnjJxQJcOri2yosPp48/C@qX0GOcvJTmb/BXciXZJDsPHYRSsPBn9JZKj6Z1f7dX@P15s/ "Java (JDK) – Try It Online") I chose to use leading `0`s. ## Credits * -24 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) who didn't know he could golf away that much :p [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) # Without leading 0s, ~~104~~, 103 bytes ``` (s,e,n)=>new int[(e-s).Days+1].Select((x,i)=>s.AddDays(i)).Where(x=>$"{x:yyyMd}".Distinct().Count()>=n) ``` [Try it online!](https://tio.run/##xdLPS8MwFAfwu39FCB4S@hqaOn/U2YJYBcWeFHaYO9T2TQNbBk2KLbK/vaZqh2wXPQxJICHf98gHksL4hVHdTa2LizS3@KiWCJuN0hZur3W9xCp/XuCmIknInMQdM4CgeZxofCOudsrQN1ykeWs8ORMPuMDCMtaAcjVGXJZlHzHFuZi8YoWsIXFySN@b87Zts3JNRaqMVdo1cXG1qrVbk1jzbkwOJpWyeK80MjqlxCPGVkq/iLuV0owCBTJnvWIQMhlFEqSbIQeynYTghjsf8QHZS8gnpSz9LPMdqF1Tzj06I0@a8vGfAWEgIwgikNE2YEiOApcc/z/hbI8EeTpyF51AGOw8w3eyf4KUXz9B7hB@JvL3hO4D "C# (Visual C# Interactive Compiler) – Try It Online") # With leading 0s, ~~106~~ 105 bytes ``` (s,e,n)=>new int[(e-s).Days+1].Select((x,i)=>s.AddDays(i)).Where(x=>$"{x:yyyMMdd}".Distinct().Count()>=n) ``` [Try it online!](https://tio.run/##xdLPS8MwFAfwu39FCB4S@hqaOn/U2YJYBcWeFHaYO9T2TQNbBk2KLbK/vaZqh2wXPQxJICHf98gHksL4hVHdTa2LizS3@KiWCJuN0hZur3W9xCp/XuCmIknInMQdM4CgeZxofCOudsrQN1ykeWs8ORMPuMDCMtaAcjVGXJZlHzHFuZi8YoWsIXFySN@b87Zts6ws11SkylilXRsXV6tauzWJNe/G5GBSKYv3SiOjU0o8Ymyl9Iu4WynNKFAgc9Y7BiOTUSRBuhlyINtJCG648xEfmL2FfGLK0s8y35HaNeXcozPypCkf/xkQBjKCIAIZbQOG5ChwyfH/E872SJCnI3fRCYTBzjN8J/snSPn1E@QO4Wcif0/oPgA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # Kotlin, 119 bytes ``` fun f(a:LocalDate,b:LocalDate,c:Long)=a.datesUntil(b.plusDays(1)).filter{it.toString().chars().distinct().count()==c+1} ``` Without leading 0s, takes in two `java.time.LocalDate` and a `Long`, returns a `Stream` of `LocalDate`s ]
[Question] [ ## Introduction *(may be ignored)* Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers. This is the fifth challenge in this series (links to the [first](https://codegolf.stackexchange.com/questions/181268), [second](https://codegolf.stackexchange.com/questions/181825), [third](https://codegolf.stackexchange.com/questions/182348) and [fourth](https://codegolf.stackexchange.com/questions/182810) challenge). In this challenge, we will meet the Wythoff array, which is a intertwined [avalanche](https://www.youtube.com/watch?v=gynbtKFMwVE) of Fibonacci sequences and Beatty sequences! The [Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number) are probably for most of you a well known sequence. Given two starting numbers \$F\_0\$ and \$F\_1\$, the following \$F\_n\$ are given by: \$F\_n = F\_{(n-1)} + F\_{(n-2)}\$ for \$n>2\$. The [Beatty sequence](https://en.wikipedia.org/wiki/Beatty_sequence), given a parameter \$r\$ is: \$B^r\_n = \lfloor rn \rfloor\$ for \$n \ge 1\$. One of the properties of the Beatty sequence is that for every parameter \$r\$, there is exactly one parameter \$s=r/(r-1)\$, such that the Beatty sequences for those parameters are disjunct *and* joined together, they span all natural numbers excluding 0 (e.g.: \$B^r \cup B^{r/(r-1)} = \Bbb{N} \setminus \{0\}\$). Now here comes the mindblowing part: you can create an array, where each row is a Fibonacci sequence ***and*** each column is a Beatty sequence. This array is the [Wythoff array](https://en.wikipedia.org/wiki/Wythoff_array). The best part is: every positive number appears exactly once in this array! The array looks like this: ``` 1 2 3 5 8 13 21 34 55 89 144 ... 4 7 11 18 29 47 76 123 199 322 521 ... 6 10 16 26 42 68 110 178 288 466 754 ... 9 15 24 39 63 102 165 267 432 699 1131 ... 12 20 32 52 84 136 220 356 576 932 1508 ... 14 23 37 60 97 157 254 411 665 1076 1741 ... 17 28 45 73 118 191 309 500 809 1309 2118 ... 19 31 50 81 131 212 343 555 898 1453 2351 ... 22 36 58 94 152 246 398 644 1042 1686 2728 ... 25 41 66 107 173 280 453 733 1186 1919 3105 ... 27 44 71 115 186 301 487 788 1275 2063 3338 ... ... ``` An element at row \$m\$ and column \$n\$ is defined as: \$A\_{m,n} = \begin{cases} \left\lfloor \lfloor m\varphi \rfloor \varphi \right\rfloor & \text{ if } n=1\\ \left\lfloor \lfloor m\varphi \rfloor \varphi^2 \right\rfloor & \text{ if } n=2\\ A\_{m,n-2}+A\_{m,n-1} & \text{ if }n > 2 \end{cases}\$ where \$\varphi\$ is the golden ratio: \$\varphi=\frac{1+\sqrt{5}}{2}\$. If we follow the anti-diagonals of this array, we get [A035513](https://oeis.org/A035513), which is the target sequence for this challenge (note that this sequence is added to the OEIS by [Neil Sloane](https://oeis.org/wiki/User:N._J._A._Sloane) himself!). Since this is a "pure sequence" challenge, the task is to output \$a(n)\$ for a given \$n\$ as input, where \$a(n)\$ is [A035513](https://oeis.org/A035513). There are different strategies you can follow to get to \$a(n)\$, which makes this challenge (in my opinion) really interesting. ## Task Given an integer input \$n\$, output \$a(n)\$ in integer format, where \$a(n)\$ is [A035513](https://oeis.org/A035513). *Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 2\$, etc. Please mention this in your answer if you choose to use this.* ## Test cases ``` Input | Output --------------- 1 | 1 5 | 7 20 | 20 50 | 136 78 | 30 123 | 3194 1234 | 8212236486 3000 | 814 9999 | 108240 29890 | 637 ``` It might be fun to know that the largest \$a(n)\$ for \$1\le n\le32767\$ is \$a(32642) = 512653048485188394162163283930413917147479973138989971 = F(256) \lfloor 2 \varphi\rfloor + F(255).\$ ## Rules * Input and output are integers * Your program should at least support input in the range of 1 up to 32767). Note that \$a(n)\$ goes up to 30 digit numbers in this range... * Invalid input (0, floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour. * Default [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply. * [Default 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 the shortest answers in bytes wins [Answer] # [R](https://www.r-project.org/), ~~143~~ ~~130~~ ~~124~~ 123 bytes ``` function(n){k=0:n+1 `~`=rbind m=k-1~(k*(1+5^.5)/2)%/%1 for(i in k)m=m~m[i,]+m[i+1,] m=m[-1:-2,] m[order(row(m)+col(m))][n]} ``` [Try it online!](https://tio.run/##FYtBDoIwEADvvIILya6lwpJwIfYlTQ0KNmlKt6RqjDHy9YqXmblMyrY8yWyfPD1cZGD8eNUOLKgYt1Glq@O5CMpL2sAfgER/PvbYdFg1FRU2JnCl49JjUGEL2tVG7BRUm/0KWtIgu3/rmOZbghRfEFBMcdmFRrP55vtlXZc30EBtbTH/AA "R – Try It Online") Uses the formula \$T(n,-1)=n-1; T(n,0)=\lfloor n\cdot\phi\rfloor;T(n,k)=T(n,k-1)+T(n,k-2)\$ to construct the array (transposed), then `splits` the array along antidiagonals. `k` merely exists to prevent forcing a `drop=F` argument in `m[-1:-2,]` for the case `n=1`. *Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for pointing out a 1 byte golf.* # [R](https://www.r-project.org/), ~~150~~ ~~138~~ 132 bytes ``` function(n){T[2]=1 for(j in 2:n-1)T=c(T,T[j]+T[j+1]) m=T[-1]%o%((1:n*(.5+5^.5/2))%/%1)+T[-1-n]%o%(1:n-1) m[order(row(m)+col(m))][n]} ``` [Try it online!](https://tio.run/##HYxBCsIwEEX3PUU2gRnTtE6hm2JukV2IINVASzspURERzx5jN/8t3uOnHMRJ5/Dk8TFFBsaPdZ03VIWYYBYTi25gTWjNCLa2bvaqjCKP1Wqs0@RllAA08AGaXvXnpm87RNlKQvX3mveC9pdqdTFdbwlSfMGKaoxLAXrH/pvvl21b3qWkYx0w/wA "R – Try It Online") Implements the formula \$T(n,k)=Fib(k+1)\cdot\lfloor n\cdot\phi\rfloor+Fib(k)\cdot(n-1)\$ to get generate the array, then `splits` along the antidiagonals and extracts the `nth` element. Thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder) for the `T[2]=1` trick for generating the Fibonacci sequence. --- Both solutions are highly inefficient, creating an `nxn` matrix of (most likely) `double`s, as R promotes `integer` (32-bit signed) to `double` automatically when overflowing, but the second one should be quite a lot faster. Taking `n` as a bignum should work automatically, using the call `gmp::as.bigz(n)`, should loss of precision under `double`s be worrisome, and then the language would be `R + gmp`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 24 bytes ``` p`SÞ⁸ịð’;רpḞ¥×⁹r‘ÆḞ¤Sð/ ``` [Try it online!](https://tio.run/##AT0Awv9qZWxsef//cGBTw57igbjhu4vDsOKAmTvDl8OYcOG4nsKlw5figbly4oCYw4bhuJ7CpFPDsC////8xMjM0 "Jelly – Try It Online") Monadic link using 1-based indexing. Thanks to @JonathanAllan for a better way of getting the row and columns from `n` and saving 3 bytes. In its shortest form it’s too slow for larger n on TIO, so the following [Try it online!](https://tio.run/##y0rNyan8///hjiWH9h7pKkgIPjzvUeOOh7u7D2941DDT@vD0wzMKHu6Yd2jp4emPGncWPWqYcbgNxF8SfHiD/n@dRw1zFHTtFB41zNU53M51uP1R05rI/0EPdzY@3LkGyD46ORPTnIe7FgKN0T48Qw9s1KluoFEO@v8NdUx1jAx0TA10zC10DI2MQdhEx9jAwEDHEgh0jCwtLA0A "Jelly – Try It Online") reduces the size of the initial list of rows and columns at the cost of three bytes. ### Explanation ``` p` | Cartesian product of the range from 1..input with itself SÞ | Sort by sum ⁸ị | Find the tuple at the position indicated by the input - this is the row and column ð ð/ | Start a new dyadic chain using the row as the left and column as the right argument ’ | Increase the row by 1 ; ¥ | Concatenate to: רp | row × φ Ḟ | rounded down × ¤ | Multiply this pair by ÆḞ | the Fibonacci numbers at positions ⁹ | column index and r‘ | column index plus one S | sum ``` Note this is based on the description of the Python code on the OEIS page. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 90 bytes ``` Flatten[Table[(F=Fibonacci)[a+1]⌊(b-a+1)GoldenRatio⌋+(b-a)F@a,{b,#},{a,b,1,-1}]][[#]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773y0nsaQkNS86JDEpJzVaw83WLTMpPy8xOTlTMzpR2zD2UU@XRpIukKXpnp@TkpoXBNSZ/6inWxskqunmkKhTnaSjXKtTnaiTpGOoo2tYGxsbHa0cG6v2P6AoM69EwSE92tDI2CT2/38A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` p`SÞ⁸ịð;Øp,²;\¤×Ḟ¥/;+ƝQƊ⁹¡ị@ð/ ``` **[Try it online!](https://tio.run/##AT8AwP9qZWxsef//cGBTw57igbjhu4vDsDvDmHAswrI7XMKkw5fhuJ7CpS87K8adUcaK4oG5wqHhu4tAw7Av////MjA "Jelly – Try It Online")** This is a little slow, but a huge improvement is made with a prefix of `Ḥ½Ċ` (double, square-root, ceiling) like in this [test-suite](https://tio.run/##y0rNyan8///hjiWH9h7pKkgIPjzvUeOOh7u7D2@wPjyjQOfQJuuYQ0sOT3@4Y96hpfrW2sfmBh7retS489BCoBqHwxv0/x/dc7j9UdMa9///DXVMdYwMdEwNdMwtdAyNjEHYRMfYwMBAxxIIdIwsLSwNAA "Jelly – Try It Online"). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes ``` Nθ≔⁰ηW‹ηθ«≦⊕η≧⁻ηθ»⊞υ¹Fθ⊞υ⁻⁺³ι§υ⊖§υι⊞υθF⁺²⁻θη⊞υΣ…⮌υ²I⊟υ ``` [Try it online!](https://tio.run/##TY69jsIwEITry1NsuZZ8EgcFRSoUmkhwiuAJQliwJcdJ/MMdQjy7sYEALiztzOw324jaNF2tQih1792vb3dkcGB5trBWHjVOOIg4/QmpCHBF1qLgMDAGl@xrXffPWKkbQy1pR/vHwtvbyKNwuJba22il3Ty7ZpW3Aj2HnzgdOgOxE0btnsVKxW/GQTIOC1fqPf0nc0mvJvyQJUsvf3GHkXvHTEfokK5j76qtb7E4N4oK0fW4oRMZS@hj5fSBM1I7LGrrsIoBn8QQ5vPwfVI3 "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Uses only integer arithmetic so works for arbitrary large values. Explanation: ``` Nθ ``` Input `q`. ``` ≔⁰ηW‹ηθ«≦⊕η≧⁻ηθ» ``` Calculate the antidiagonal by subtracting ever increasing numbers from `q`, which ends up with the target row number `m`. ``` ⊞υ¹Fθ⊞υ⁻⁺³ι§υ⊖§υι ``` Calculate the first `m+1` terms of [A019446](https://oeis.org/A019446), although we're only interested in the `m`th. ``` ⊞υθF⁺²⁻θη⊞υΣ…⮌υ² ``` Calculate the first `n+4` terms of the generalised Fibonacci series that starts with `[a(m), m]`. The terms of this sequence are the `m`th terms of [A019446](https://oeis.org/A019446), [A001477](https://oeis.org/A001477), [A000201](https://oeis.org/A000201), [A003622](https://oeis.org/A003622), [A035336](https://oeis.org/A035336); these last two are the first two columns of the Wythoff array, and so this sequence continues with the rest of the `m`th row of the array. ``` I⊟υ ``` Output the desired term. ]
[Question] [ # Goal In light of the World Series being around the corner, I need a program that can read the box scores and tell me what inning it is. This is complicated slightly because baseball uses an odd method to record the score. They don't write down the at-bat team's score for the inning until they've scored a run (and are still going) or have finished their at-bat. Thus a 0 on the scoreboard always means a finished at-bat. For example: ``` Example A: Inning| 1| 2| 3| 4| 5| 6| 7| 8| 9| Them| 0| 0| 0| 0| 0| 2| | | | Us| 0| 0| 2| 0| 0| 0| | | | Example B: Inning| 1| 2| 3| 4| 5| 6| 7| 8| 9| Them| 0| 0| 0| 0| 0| 2| | | | Us| 0| 0| 2| 0| 0| 1| | | | Example C: Inning| 1| 2| 3| 4| 5| 6| 7| 8| 9| Them| 0| 0| 0| 0| 0| 2| | | | Us| 0| 0| 2| 0| 0| | | | | #Them is the Away Team, Us is the Home Team (who are the guys you root for) ``` * Example A: We know we're at the top of the 7th because Us has a recorded 0 in the Bottom of the 6th and the Top of the 7th is blank. * Example B: It can either be the Bottom of the 6th or the Top of the 7th. * Example C: It can either be the Top or Bottom of the 6th. Your task is to return which inning(s) it could be. # Input Two lists of non-negative integers. Lists will be assumed jagged with the Away team's list being either the same size or one element larger in comparison to the Home team's. You can take the scores in either order but state in your answer if you do not use the default. I.e., Away Team then Home team (the default), or Home team then Away team (reversed). They can also be padded with dummy data if you want, state in your answer if you do so. # Output A string or something equivalent which identifies the inning number and whether it's the top or bottom. E.g. `7B 8T`, `B7 T8`, `['7B','8T']` are all fine. If there are two answers, you must output both. The format is pretty flexible though. # Rules * Input will always be valid * Games can go into indefinite extra innings. Your program should be able to support up to 255 innings. * Standard Loopholes are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins # Test Cases ``` #Input: [[], []] #Output: 1T #Input: [[0], []] #Output: 1B #Input: [[0,0,0,1], [0,0,0,0]] #Output: 5T #Input: [[0,0,0,1], [0,0,0,1]] #Output: 4B, 5T #Input: [[0,0,0,1,0,0,1,0,0,1], [0,0,0,0,1,0,0,1,0,1]] #Output: 10B, 11T #Input: [[0,0,0,1], [0,0,0]] #Output: 4T, 4B #Input: [[0,0,0,0], [0,0,0]] #Output: 4B ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 50 bytes Takes input as a pointer to an interleaved list (i.e. `{them#1, us#1, them#2,...}`). Returns one option via modification, and the other via return value. Negative values indicate bottom of the inning, positive values indicate top of the inning. Zeroes are "empty". The absolute value of the output is the number of the inning. So, `-4,5` indicates the possibilities being top of the fifth and bottom of the fourth, and `1,0` indicates the only possibility being the top of the first. The return value of the macro can be used to determine whether there's one or two possible innings; the return value is `0` if there's no other inning. Otherwise, it is the number of the inning. Zero bytes of source code. Use the following as a preprocessor flag: ``` -Df(o,n,l)=({o=n%2?~n/2:n/2+1;l[n-1]?-o-~n%2:0;}) ``` [Try it online!](https://tio.run/##nZFBCoMwEEXXeoogCAmd0MRNi2Ld9BbWhUYUwcbSFroI8ehNs1MsUZAwgZnP@/NhBG2FMMbcy05igpTvdfKNSqgS3/O9Km1wCQwwttO8IEoTYoXH07YNDpRG9IJUWENY65sMwIKoIjOUTyhbsGwTPs9gmB6HP6uFutuYrxrzTeOIOSM7/vWNbmoryckRZG3dXtO1cziPoc1XNH3Zvgz9GHpt8AASepJiNaQyjLJRHqPY1oEnfS4pLzI60NEqMUs0@QE "C (gcc) – Try It Online") ## Degolf ``` -Df(o,n,l)=({ // Define a function-like macro f(o,n,l) // o is the output variable, n is the size of the list, // l is a pointer to the first element of the list. o=n%2?~n/2:n/2+1; // If there's an odd number of elements, first possible inning is -(n+1)/2. // Else, it is (n/2)+1. l[n-1]?-o-~n%2:0}) // If the score from the last inning is non-zero, the other possible inning // needs to be determined; flip the sign of first output value then deduct // 1 from it if the number of elements is even. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~52 48~~ 45 bytes *-3 bytes thanks to some restructuring from nwellnhof!* ``` ->\a,\b{(+a,a==b if (b,a)[a>b].tail;b+1,a>b)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJauYKvwX9cuJlEnJqlaQztRJ9HWNkkhM01BI0knUTM60S4pVq8kMTPHOknbUAfI06z9X5xYqZCuER2ro8ClAAbRsZrWXFBRAxzCOiBoiCQJETHAVINMxuqgKUeSNoRrVUAYj6I8Fk3eAEP@PwA "Perl 6 – Try It Online") Anonymous code block that takes input as two lists, top then bottom. Output is a list of tuples, where the first element is the inning number and the second element is True or False, corresponding to Bottom or Top. ### Explanation: ``` { } # Anonymous code block ->\a,\b # That takes input lists a and b ( ) # Return a list of b+1,a>b # A list of # The length of the second list plus 1 # And top/bottom +a,a==b # And the length of the first list # And the other of top/bottom if # Only if: (b,a)[a>b] # The current of top/bottom's .tail # Last element exists and is not 0 ``` [Answer] # [R](https://www.r-project.org/), ~~103~~ 96 bytes ``` function(a,b,l=sum(a|1),k=sum(b|1))I(l,I(l-k,I(a[l],c(l,-l),-l),I(b[l],c(-l,l+1),l+1)),1) I=`if` ``` [Try it online!](https://tio.run/##dYxNCoQwDEb3c5IEU2gO4ElEsC0UxKig42pmzt7pzyYuJCR5vI/kSCn28drCe943cORJ@vNawX0ZaanoM@JnmuMEQm2ZpYEbZKSQtRGsXa1v1ghJl7@UgcT4SxECYE4QXwWtZirFxTS0TwHfAz3VtQr44dNNW6XTHw "R – Try It Online") *@digEmAll saved 7 bytes!* Takes two ~~lists~~ vectors as input, and outputs one or two integers representing the possible innings. Positive integers are the top of the inning, and negative integers are the bottom of the inning. In R, positive integers are truthy, so I can use the difference in lengths as the first argument to `if()`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 75 bytes ``` f=(a,c=1,p=0,z=0)=>1/(t=a[p][c-1])?f(a,c+p,1-p,t):[c,p]+(z?[,c+p-1,1-p]:'') ``` [Try it online!](https://tio.run/##hZFPS8MwGIfv@RSBHZa4t38CemmJg9704A7uFqILMd0qXRvaTGXiZ6/t1mmLkxEI5H2f5/eG5FW9qVpXmXVeUb6Ypkk5UaA5A8tD2POQ8lsWEMeVsFJoj0k6TztiZoF5FhyNhAYrZ2Q/F13VY11dRtMpbZypnVa1qTHHKzS5K@zORUgICRhhISVGk8XOdUXMlmgAhOeIZERAt9iROx7CEX6zvICzEX6dwHlluEv4HTbojJNY2EYxdmH8ePgS2gv8FcJ/hQStYrRVTm9M1T5u0JtEPE3kFT1x/TFYx@h9k@UGE9fCveabD6PJzxdRij8RxuIZcNZlAS4PIbI1XNx2dFnUZW78vFyTlNw/Lh58q6rakANO6UnwXZVtCaUx@mq@AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ZẎṖṠṪ$СẈd2 ``` [Try it online!](https://tio.run/##y0rNyan8/z/q4a6@hzunPdy54OHOVSqHJxxa@HBXR4rR/8PtRyc93Dnj///oaAMdEDREJmN1uBSg4sgyhrGxCgA "Jelly – Try It Online") First element: 0-based index of column. Second element: `0` for top, `1` for bottom. Output is a list of one or two pairs as specified above (prettified to show it better). The output innings are in reverse order. [Answer] # [Python 2](https://docs.python.org/2/), ~~135~~ ~~129~~ ~~126~~ ~~125~~ ~~123~~ 119 bytes ``` a,b=input() c=len(a) e,f=`c+1`+"T",`c`+"B" print((f+e,e)[b[-1]<1],(`c`+"T"+f,f)[a[-1]<1])[len(b)<c]if b else"1"+"TB"[c] ``` [Try it online!](https://tio.run/##bY7BCoMwDIbvfYqSUzs7sLvsYi8@g7dQ0HYpE6STzcH29F0VmR4kkPx8Sf5k/E73R7wk/7gRNxwAUqec6eP4noRk3gwURScZqWBaX@i2gAZU63OtgY3PPk5ChIIUSXR41rbSVoml30ARVJDYrVji7OVk5W0fuOM0vAg05MEa0NuUbzP6kOfLLyd@TYhWobUMsfwLNUe@sarykOqZrnKft7Ud1wcOO9dyYz8 "Python 2 – Try It Online") -1 with thanks to @ovs -4 thanks again to @ovs [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` a,b=input() exec"a,b=[0]+b,a;print[len(b)][a[-1]<len(a+b)%2:];"*2 ``` [Try it online!](https://tio.run/##bYxBCsMgEEX3nkKEQkwsqJtC05xkmIWmQgPFSLHQnt6qbYmLMDD8/5h54R1vq9dpXq@OTpQxloyw0@LDM3acuJebWQEgcbDCjOGx@Ah35zvLEQwcFV5KM4PlB33GkfU61SOSXfWfVndPTwkABSASyLZ/EGVUrt8kd6kq9Bfbvb01XO0YGqvc2Ac "Python 2 – Try It Online") Prints two lines, first the bottom inning possibility then the top one, as a singleton list. If either one is not possible, that list is empty. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~84~~ 75 bytes ``` import StdEnv $ =length ?v|last[0:v]>0= $v=0 @a b| $b< $a=(?a,$a)=($a+1,?b) ``` [Try it online!](https://tio.run/##dY0xC8IwEIXn5lfckEExQrqKsQ46CG6OMcO1xlpIophYEfztxlQHqyAHx3vf495VRqOL9ri7GA0WGxcbezqeA2zCbulaQkEY7epwIEV7N@iD5JNWzbgA2gpO5gjlHWg5BYpiUCCjOBQDiqOcFeUwbgKmKgFyDuGgLVw8bLcgO82SUTAdQ9A@eEWuTfqRvUx3QLJMSsWkUuwleV@zbvJE3or/C/KfoL8/1z2e/2n6xvyDE1XxUe0N1j6OV@u4uDm0TeWf "Clean – Try It Online") Defines the function `@ :: [Int] [Int] -> (Int, Int)` and some helpers. Gives output in the form `(Top, Bottom)` where a zero signifies a null possibility. ]
[Question] [ *(Despite 60+ questions tagged [chess](/questions/tagged/chess "show questions tagged 'chess'"), we don't have a simple n-queens challenge.)* In chess, the [N-Queens Puzzle](https://en.wikipedia.org/wiki/Eight_queens_puzzle) is described as follows: Given an `n x n` chessboard and `n` queens, arrange the queens onto the chessboard so that no two queens are threatening each other. Below is an example solution for `n = 8`, borrowed from Wikipedia. [![8-queens example solution from Wikipedia](https://i.stack.imgur.com/D32OV.png)](https://i.stack.imgur.com/D32OV.png) Or, in ASCII rendering: ``` xxxQxxxx xxxxxxQx xxQxxxxx xxxxxxxQ xQxxxxxx xxxxQxxx Qxxxxxxx xxxxxQxx ``` The challenge here will be to take input `n` and output an ASCII representation of a solution to the `n`-Queens puzzle. Since there are more than one possible solution (e.g., at the least, a rotation or reflection), your code only needs to output any valid solution. ## Input A single positive integer `n` with `n >= 4` [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). (n=2 and n=3 have no solutions, and n=1 is trivial, so those are excluded) ## Output The resulting ASCII representation of a solution to the N-queens puzzle, as outlined above. You may choose any two distinct ASCII values to represent blank spaces and queens. Again, this can be output in any suitable format (single string, a list of strings, a character array, etc.). ## Rules * Leading or trailing newlines or whitespace are all optional, as well as whitespace between characters, so long as the characters themselves line up correctly. * You can either use an algorithm to calculate the possible positions, or use the explicit "stair-step" style of solution, whichever is golfier for your code. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other people can try out your code! * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ## Examples ``` n=4 xQxx xxxQ Qxxx xxQx n=7 xxQxxxx xxxxxxQ xQxxxxx xxxQxxx xxxxxQx Qxxxxxx xxxxQxx n=10 xxxxQxxxxx xxxxxxxxxQ xxxQxxxxxx xxxxxxxxQx xxQxxxxxxx xxxxxxxQxx xQxxxxxxxx xxxxxxQxxx Qxxxxxxxxx xxxxxQxxxx ``` [Answer] # C, 114 bytes ``` Q(n,o,y){o=n%2;n-=o;for(y=0;y<n+o;++y)printf("%*c\n",y<n?o+n-(n+y%(n/2)*2+(n%6?y<n/2?n/2-1:2-n/2:y<n/2))%n:0,81);} ``` Directly prints a solution in O(1) time. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~33~~ ~~32~~ 27 bytes ``` `x,GZ@]1Z?tt!P!,w&TXds]h1>a ``` [**Try it online!**](https://tio.run/##y00syfn/P6FCxz3KIdYwyr6kRDFAUadcLSQipTg2w9Au8f9/QwMA "MATL – Try It Online") Semi-brute force, non-determistic approach: 1. Generate a random permutation of row positions 2. Generate a random permutation of column positions 3. Check that no queens share a diagonal or anti-diagonal 4. Repeat if necessary. The obtained solution is random. If you run the code again you may get a different valid configuration. Running time is also random, but the longest test case (`n = 10`) finishes in about 30 seconds in TIO most of the time. [Answer] # Mathematica, 103 ~~108~~ ~~110~~ ~~117~~ bytes -5 bytes for `DuplicateFreeQ` -> `E!=##&@@@` -7 bytes for `ReplacePart[Array[],]` -> `SparseArray[]` ``` SparseArray[Thread@#&@@Select[Permutations@Range@#~Tuples~2,And@@(E!=##&@@@{#-#2,+##})&@@#&]->1,{#,#}]& ``` Return a 2D-array. It takes 2.76s to calculate `f[6]` and 135s for `f[7]`. (In the current version, `-` becomes `0` and `Q` to `1`. [![output](https://i.stack.imgur.com/kNzgW.png)](https://i.stack.imgur.com/kNzgW.png) The algorithm is similar to MATL answer but here the code is completely brute-force. [Answer] # C - 222 bytes ``` v,i,j,k,l,s,a[99];main(){for(scanf("%d",&s);*a-s;v=a[j*=v]-a[i],k=i<s,j+=(v=j<s&&(!k&&!!printf(2+"\n\n%c"-(!l<<!j)," #Q"[l^v?(l^j)&1:2])&&++l||a[i]<s&&v&&v-i+j&&v+i-j))&&!(l%=s),v||(i==j?a[i+=k]=0:++a[i])>=s*k&&++a[--i]);} ``` The code is not mine, but from the [IOCCC](http://www.ioccc.org/1990/baruch/). I hope I'm not breaking any rules. Also, this displays all solutions for N between 4 and 99. I'll try to get a TIO link later. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 21 bytes ``` ,JŒc€IF€An/PC ẊÇ¿=þRG ``` [Try it online!](https://tio.run/##y0rNyan8/1/H6@ik5EdNazzdgIRjnn6AM9fDXV2H2w/ttz28L8j9////FgA "Jelly – Try It Online") Assuming each queen are placed on separate rows, we only need to find the column indices to place each queen at to avoid conflicts, which can be found by generating a random permutation of `[1, 2, ..., n]` and testing it. ## Explanation ``` ,JŒc€IF€An/PC Helper. Input: permutation of [1, 2, ..., n] J Enumerate indices, obtains [1, 2, ..., n] , Join Œc€ Find all pairs in each I Calculate the difference of each pair F€ Flatten each A Absolute value (We now have the distance in column between each queen and the distance in rows between each queen. If they are unequal, the queens do not conflict with each other) n/ Reduce using not-equals P Product, returns 1 only if they are all unequal C Complement Returns 1 when there is a conflict, else 0 ẊÇ¿=þRG Main. Input: n Ẋ Shuffle (When given an integer, it will shuffle [1, 2, ..., n]) Ç¿ While the helper returns 1, continue shuffling R Range, gets [1, 2, ..., n] =þ Equality table (Generates the board as a matrix) G Pretty-print the matrix ``` [Answer] ## Python 3, ~~204~~ 189 bytes ``` import itertools as p n=int(input()) r=range(n) b='.'*(n-1)+'Q' for c in p.permutations(r): if len(set((x*z+c[x],z)for x in r for z in[1,-1]))==n+n:[print(*(b[x:]+b[:x]))for x in c];break ``` Brute force search through all permutations. I could remove the \* and print the list comprehensions, but they look awful. Output: ``` 10 Q . . . . . . . . . . . Q . . . . . . . . . . . . Q . . . . . . . . . . . Q . . . . . . . . . . . Q . . . . Q . . . . . . . . . . . . . Q . . Q . . . . . . . . . . . Q . . . . . . . . . . . . Q . . . ``` Slightly ungolfed: ``` import itertools as p n=int(input()) r=range(n) b='.'*(n-1)+'Q' for c in p.permutations(r): if len(set( (x*z+c[x],z) for x in r for z in[1,-1] )) == n+n: [print(*(b[x:] + b[:x])) for x in c] break ``` [Answer] # Befunge, 122 bytes ``` &::2%-v>2*00g++00g%00g\-\00g\`*4>8#4*#<,#-:#1_$55+"Q",,:#v_@ /2p00:<^%g01\+*+1*!!%6g00-2g01\**!!%6g00-g012!:`\g01:::-1<p01 ``` [Try it online!](http://befunge.tryitonline.net/#code=Jjo6MiUtdj4yKjAwZysrMDBnJTAwZ1wtXDAwZ1xgKjQ+OCM0KiM8LCMtOiMxXyQ1NSsiUSIsLDojdl9ACi8ycDAwOjxeJWcwMVwrKisxKiEhJTZnMDAtMmcwMVwqKiEhJTZnMDAtZzAxMiE6YFxnMDE6OjotMTxwMDE&input=OA) This is more or less based on the [C solution](/a/133862/62101) by [orlp](/users/4162/orlp). **Explanation** ![Source code with execution paths highlighted](https://i.stack.imgur.com/kybAI.png) ![*](https://i.stack.imgur.com/jmV4j.png) Read the number of queens, *q*, from stdin and calculate two variables for later use: `n = q - q%2`, and `hn = n/2` ![*](https://i.stack.imgur.com/z4eIY.png) Start the main loop, iterating *r*, the row number, from *q* down to 0, decrementing at the start of the loop, so the first *r* is *q* minus 1. ![*](https://i.stack.imgur.com/RFUim.png) Calculate the offset of the queen in each row with the following formula: ``` offset = (n - ( (hn <= r) * (2 - hn) * !!(n % 6) + (hn > r) * ((hn - 2) * !!(n % 6) + 1) + (y % hn * 2) + n ) % n) * (n > r) ``` ![*](https://i.stack.imgur.com/BX1CZ.png) Output *offset* space characters to indent the queen's position for the current row, plus one additional space just because it makes the output loop easier. ![*](https://i.stack.imgur.com/aZli8.png) Output the `Q` for the queen, followed by a newline to move to the next row. ![*](https://i.stack.imgur.com/SetfX.png) Test if *r* is zero, in which case we've reached the end of the board and can exit, otherwise we repeat the main loop again. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 bytesSBCS Full program prompting for `n` from stdin. Prints space-separated solution to stdout using `·` for empty squares and `⍟` for Queens. ``` ⎕CY'dfns' ⊃queens⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jvqnOkeopaXnF6lyPupoLS1NT84qBgiDZ/wpgkMZlwgVjmcNZhgYA "APL (Dyalog Unicode) – Try It Online") `⎕CY'dfns'` **C**op**y** the "dfns" library `⎕` get input from stdin `queens` find all truly unique Queens' solutions (no reflections or rotations) `⊃` pick the first solution [Answer] # [Haskell](https://www.haskell.org/), 145 bytes The obvious brute force approach: ``` b=1>0 t[]=b t(q:r)=all(/=q)r&&foldr(\(a,b)->(abs(q-b)/=a&&))b(zip[1..]r)&&t r q n|y<-[1..n]=(\q->(' '<$[1..q])++"Q")<$>[x|x<-mapM(\_->y)y,t x]!!0 ``` [Try it online!](https://tio.run/##TcvRasIwGIbh817FbygxPzVVYQciTa7AHQwP2yAJTizGtEkja4f3XtsNxk6f73uvurt9WjuORmzlJomlEiaJzO8DCm0tWwuPgdJLY8@BVUyvDHLJtOmY5wbXQlOKaNh33ZbbPFcBKY0QEg/uORR8NqcEq/wULWFZpLN4hVlGPggWqSz7Z1/wu27fWXXicsBhFaFXi8VmvOvagYCLrVuYDyco3/J8pyCFygGXcG4SgPYRjzEc3KTE7YFAlkF3bb7ATeNv9u/if/gPCBlf "Haskell – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 136 bytes ``` .+ $* $_;$`Q¶ ( +)\1( ?); :$1; :( +);\1\1 $1$1 :(( )+);( *) $1$1% $3$3 : ( +);( \1)?( *) $1 $1%$#2$* $#2$* $#2$* $1$3$3 ( +)%\1? ``` [Try it online!](https://tio.run/##VY0xCkJBDET7nGLALCT/gzD@Rv4Wewb7gFpY2FiIZ/MAXmzNfrAQwkDezDDP2@v@uPa@n0UnCETPVS@nz1sMswcNzausypRBajAoSmX@BsCTGSYXDFigiy6yYssagt5@bl7R3SFn/pRbY@RLsEnvxy8 "Retina – Try It Online") Port of @orlp's excellent C answer. Explanation: ``` .+ $* ``` Convert to unary, using spaces (there is a space after the `*`). ``` $_;$`Q¶ ``` Create `N` rows with `N` spaces, a `;`, then `0..N-1` spaces, then a `Q`. The remaining stages apply to all rows. ``` ( +)\1( ?); :$1; ``` Integer divide `N` by 2. (Also wrap the result in `:;` to make it easier to anchor patterns.) ``` :( +);\1\1 $1$1 ``` If the loop index equals `N/2*2`, then just leave that many spaces. ``` :(( )+);( *) $1$1% $3$3 ``` If `N/2` is a multiple of 3, then take double the loop index plus one, modulo `N/2*2+1`. ``` : ( +);( \1)?( *) $1 $1%$#2$* $#2$* $#2$* $1$3$3 ``` Otherwise, take double the loop index plus `(N/2-1)` plus an extra 3 in the bottom half of the board, modulo `N/2*2`. ``` ( +)%\1? ``` Actually perform the modulo operation. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes ``` Nθ≔÷θ²ηEθ◧Q⊕⎇⁼ι⊗ηι⎇﹪η³﹪⁺⁺⊗ι⊖η׳¬‹ιη⊗η﹪⊕⊗ι⊕⊗η ``` [Try it online!](https://tio.run/##VY5NCoMwEIX3PUVwNUK6aTcFVwW7ELRY6AWiTmsgJpqfQk@fRquosxiY@Wbee3XLdK2Y8D6TvbN311WoYYiTw9UY/paQSZvyD28QBkpOMSVtYKXm0kLB@nFZsibHl4XoEVGSyVpjh9JiA0/Ukukv3AbHhAFOSapcJQJp4yAU5uWiUI0TClpKzgHMUymc@bfljQeY4mowyTx5hwbOlNyVhRzNZBTIyHZ@s@w24Soc76NvHv@VeH/xx4/4AQ "Charcoal – Try It Online") Link is to verbose version of code. Another port of @orlp's excellent C answer. [Answer] # [J](http://jsoftware.com/), 49 bytes ``` i.=/0({(1-.@e.,)@(([:(=#\){.|@-}.)\."1)#])!A.&i.] ``` [Try it online!](https://tio.run/##FcyxDkAwFAXQvV9xkfBewsUmTZrUd2ASDRaDEd9eDGc9ewwnnEWDT9zo6kYuaSv6haV6kcGKy0a9ePvqoY5MW80mTXrmG6eoJiWK8BcFSjwW4TRmmdcDAV18AQ "J – Try It Online") Brute force by testing all permutations of length *n*. ]
[Question] [ # Find the outcome of a game of War When I was in elementary school, there was a "Rock-Paper-Scissors"-ish game we'd play during assemblies, when waiting for our teacher, at recess etc. We called it "War". After some searching however, it turns out this is a much simpler variant of the ["Shotgun Game" (according to WikiHow)](https://www.google.ca/amp/m.wikihow.com/Play-the-Shotgun-Game%3Famp%3D1). I'm going to call it "War" since the rules are slightly different: 2 people sit across from each other. The goal of the game is to "kill" the other player. Each turn, you can play one of 3 moves: * **Reload**: You have a gun that holds a single shot. It must be reloaded before it can be fired each time. Reloading when you already have ammo is legal, but does nothing. A reload was symbolized by tapping your temples with both hands. Each player starts with 0 ammo. * **Guard**: The only safe move. If you're shot while guarding, you don't die. Guarding was symbolized by crossing your arms over your chest. * **Fire**: Fire your gun. To successfully fire, you must have reloaded since the last shot. If your opponent is reloading, you win. If they also fire, and you both have ammo, it's a draw. If they're guarding, you wasted the ammo. While firing without ammo is a legal move, it does nothing and leaves you vulnerable like reloading. Firing was symbolized by pointing at the other player. It was played similar to RPS, in that each player simultaneously throws down their choice (we tapped our legs twice in between turns to keep in rhythm with each other, but that's not important to the challenge). # The Challenge: Your task is to find the outcome of a game of War. It can be a function or full program. # Input * The option each player chose each turn will be represented by a character/string: + **r**: reload + **g**: guard + **f**: fire * Input will be a list of pairs, a delimited/undelimited string, or anything else along these lines. An example input in Python could be `[("r", "g"), ("f", "r")]`, meaning on the first turn the first player reloaded, and the second player guarded. On the second turn, the first player fires, while the second player reloads. Player one wins this game. The same input could optionally be represented as `"r g f r"`, `"rgfr"`, `"rg fr"` `"rg-fr"`... You can assume the following: * Input will match your chosen format, and that it will only contain valid characters. * Someone will die within 100 turns. You cannot however assume that the turns end when someone dies. # Output A value indicating who won (or, who won first`*`). You can chose what to output for each scenario, but must account for the following: * Player 1 wins * Player 2 wins * They kill each other (draw) Each outcome must have a district value, and must always be the same for each scenario. As an example: you could output `1` when player 1 wins, `2` when player 2 wins, and `0` in the event of a draw. You must then **always** output `1` when player 1 wins, `2` when player 2 wins, and `0` in the event of a draw. It can be returned, or printed to the stdout. Trailing whitespace is fine. Just so it's clear, the only scenario that leads to a draw is if both players fire, and both have ammo. `*` Since in this challenge, turns may continue after someone dies, it's possible more than 1 player may win eventually. You need to find who won first according to the input. # Test Cases (assuming `1` when P1 wins, `2` when P2 wins, and `0` for a draw): ``` "rg fr" => 1 (P1 shot P2 while they were reloading) "rg ff" => 1 (They both shot, but only P1 had ammo) "rr ff" => 0 (Both had ammo and shot each other) "rr ff rr fg" => 0 (Both had ammo and shot each other. Everything after the first win is ignored) "rr fg rf" => 2 (P2 shot P1 while they were reloading) "rf gg rr fg rr fr" => 1 (P2 tried to shoot but didn't have any ammo, then they both guarded, then they both reloaded, then P2 blocked a shot, then they both reloaded again [but P2 still only has 1 ammo!], then P1 shoots P2 while they're reloading. "rr gf fr rf gg rg ff" => 1 ^ Player 1 wins here. The rest to the right has no effect on the output ``` This is code golf, so the smallest number of bytes wins! Note, as the test cases show, you must handle "dumb" moves. It's perfectly valid for a player to try to shoot when they don't have ammo, or reload 2 turns in a row (and only accumulate a single ammo). [Answer] # Python, 139 Bytes ``` c=d=0 for i in input(): b=(c&(i=='fr'))-(d&(i=='rf'));p,q=i if b|(i=='ff')&c&d:print b;break c,d=(p=='r',i!='fg')[c],(q=='r',i!='gf')[d] ``` Takes input on stdin in the form of a list of 2-character strings (eg. ['rf','rr','rg','ff']). Outputs 1 if player 1 wins, -1 if player 2 wins, and 0 for a draw. **Explanation:** First checks if anyone fired a bullet, if so the game ends. Then we determine if the players have either reloaded their guns or wasted their ammo. This is my first codegolf post :) [Answer] ## JavaScript (ES6), ~~108~~ ~~107~~ ~~93~~ ~~91~~ ~~89~~ 85 bytes *Saved 4 bytes with the help of Titus* Takes input as an array of 2-character strings describing the moves played by each player. ``` b=>b.map(c=>w=w||b&'312'[b=(s='0210231')[m='ffrfgrrggf'.search(c)]|s[m-2]&b,m],w=0)|w ``` Returns: * `1` if player 1 wins * `2` if player 2 wins * `3` for a draw --- ### How it works We maintain a bitmask `b` describing who has a loaded bullet: * bit #0: player 1 has a bullet * bit #1: player 2 has a bullet We use the [De Bruijn sequence](https://en.wikipedia.org/wiki/De_Bruijn_sequence) `'ffrfgrrggf'` to identify all 9 possible combinations of moves. We use OR and AND bitmasks to update `b` according to the move combination. We use a 3rd set of bitmasks which are AND'ed with `b` to determine the winner `w`. (The only three winning combinations being `ff`, `fr` and `rf`.) It's worth noting that the OR and AND masks can be stored with the same pattern, shifted by two positions. ``` Index in | Combination | Bullet | Bullet | Winner sequence | | AND mask | OR mask | mask ----------+-------------+----------+---------+-------- 0 | ff | 0 | 0 | 3 1 | fr | 0 | 2 | 1 2 | rf | 0 | 1 | 2 3 | fg | 2 | 0 | 0 4 | gr | 1 | 2 | 0 5 | rr | 0 | 3 | 0 6 | rg | 2 | 1 | 0 7 | gg | 3 | 0 | 0 8 | gf | 1 | 0 | 0 ``` --- ### Test cases ``` let f = b=>b.map(c=>w=w||b&'312'[b=(s='0210231')[m='ffrfgrrggf'.search(c)]|s[m-2]&b,m],w=0)|w console.log(f(["rg","fr"])); // 1 console.log(f(["rg","ff"])); // 1 console.log(f(["rr","ff"])); // 3 console.log(f(["rr","ff","rr","fg"])); // 3 console.log(f(["rr","fg","rf"])); // 2 console.log(f(["rf","gg","rr","fg","rr","fr"])); // 1 console.log(f(["rr","gf","fr","rf","gg","rg","ff"])); // 1 ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 36 bytes ``` s`(?<=r..([^f]..)*)f ! A`g G1`! \w _ ``` The input format should be linefeed separated pairs, e.g. ``` rr fr ``` Output is `!_` is player 1 wins, `_!` if player 2 wins and `!!` if there's a draw. [Try it online!](https://tio.run/nexus/retina#PYw9CoAwDIX3nCIOQusQcFfEyQM4WjVTsqeDx69tKV0@3g/vje7kEFNkty2rEbnrkZvIT15ggJ0VjpkHCB@8KZmiGBQKmHVioVataDkUVMVmrU4MVbLAVvUHLbbmPw "Retina – TIO Nexus") (A test suite that uses space-separation for convenience.) I must have completely overlooked this challenge. I'm sure I would have tried this in Retina earlier otherwise. :) ### Explanation ``` s`(?<=r..([^f]..)*)f ! ``` We start by marking "valid" shots by turning the first `f` after each `r` into `!`. We do this by matching each `f` from which can find an `r` on the same player without crossing over another `f`. Limiting the search to `r`s on the same player is easy by always going three characters at a time. ``` A`g ``` Now we discard all turns in which someone guarded themselves, because the ending turn cannot be one of those. ``` G1`! ``` Now we keep *only* the first turn which contains an `!`. If a valid shot happens (and we know that no one guarded) the game ends. ``` \w _ ``` Finally, we need to consolidate the string to give consistent outputs, and we simply do this by turning the non-`!` characters (either `r` or `f`) into `_`. [Answer] # [Perl 6](http://perl6.org/), ~~71~~ 62 bytes ``` {&[<=>](|map {m/r[..[r|g]]*.$^f/.to//∞},/[r|f]f/,/.f[r|f]/)} ``` Regex-based solution. Takes input as a string in the form `"rg fr"`. The three possible outputs are the enum values `More` (player 1 won), `Less` ( player 2 won), `Same` (draw) – which turn into those words when printed, or into `1`, `-1`, `0` when coerced to numbers. [Try it online!](https://tio.run/nexus/perl6#Ky1OVSgzs@bKrVRQS1Ow/V@tFm1jaxerUZObWKBQnatfFK2nF11Ukx4bq6WnEpemr1eSr6//qGNerY4@UDgtNk1fR18vDczU16z9X5xYqZCmoFSUrpBWpGTNhcRNQ@IWYXIVQGQ6qmC6QhGysjSF9HQFqHgRqvlFCulpQBEFqBqIdf8B "Perl 6 – TIO Nexus") ### How it works * ``` map { m/r[..[r|g]]*.$^f/.to // ∞ }, /[r|f]f/, /.f[r|f]/ ``` Performs two regex matches on the input. After interpolation, the two regexes are: + `r[..[r|g]]*.[r|f]f` – Matches the first successful shot by player 2. + `r[..[r|g]]*..f[r|f]` – Matches the first successful shot by player 1.In each case, it returns the end position of the match (`.to`), or infinity if there was no match. * ``` &[<=>](| ) ``` Applies the `<=>` operator to the two match end positions. It returns a value from the `Order` enum (`More`, `Less`, or `Same`), depending on whether the first argument is greater, less, or equal to the second. [Answer] # [Haskell](https://www.haskell.org/), ~~101 91~~ 87 bytes ``` n!(c:r)|'g'>c=n:1!r|'g'<c=1:0!r|1<3=2:n!r _!r=[] a#b=[x|x@(y,z)<-zip(1!a)$1!b,2>y+z]!!0 ``` [Try it online!](https://tio.run/nexus/haskell#XY7BasMwEETv/oqVU4hMZbDcm7FCP6F3Y4oiR0KHqmFtSGLy764cLcZUpzczuztaAuOmweJ5dMeTUaGRDFdujZJNFVm2H6puAsPsm6Hq@kwfzqq7P@@f/CHmoi1nf@WS6eJNsrOoT4/3uWesWn60D6Bg@IUM4ruiDxN0Odr8kDvMBRDaDZGQBDqSq6IxR6l1EdMRZ1c3bVgX53ooS5gu42T0eBn35QC8ErIAEPAfK8JNkOQyqZRtW7Cz9h68ypPhw@CNjh@BLwk3H0ZB13ZB/QpAh4F6fRQwoL4tfw "Haskell – TIO Nexus") The infix function `#` takes two strings representing the actions of each of the two players and returns `(0,1)` if player 1 wins, `(1,0)` for player 2 and `(0,0)` for a draw. **Example usage:** ``` Prelude> "rgrfrf" # "fgrgrr" (0,1) ``` **Explanation:** The infix function `!` translates a sequence of actions `'r'` (reload), `'f'` (fire) and `'g'` (guard) to a sequence of observable actions `0` (actual fire), `1` (no action) and `2` (guard), where a *fire* action is only counted as *actual fire* action if a bullet is loaded, and as *no action* otherwise. To achieve this the first argument `n` is `0` if a bullet is loaded and `1` if the gun is not loaded. This way each `'f'` can simply be replaced with the current `n`. (`n=0` -> loaded -> *actual fire* -> `0`, `n=1` -> unloaded -> *no action* -> `1`) ``` n ! (c:r) -- n is 0 or 1, c is 'f', 'g' or 'r' and r the rest of the string |'g'>c = n : (1 ! r) -- c is smaller 'g', so it must be 'f'. append n to the list -- and set load status to 1 (unloaded) |'g'<c = 1 : (0 ! r) -- c is larger 'g', so it must be 'r'. append 1 (no action) -- and set load status to 0 (loaded) |1<3 = 2 : (n ! r) -- c must be equal to 'g'. append 2 (guard) -- and leave the load status unchanged _ ! r = [] -- base case for recursion ``` The nine resulting possibilities are then * `(0,0)`: Both players shoot and die, game ends. * `(0,1)` or `(1,0)`: One player shoots the other, game ends. * `(0,2)` or `(2,0)`: One player shoots but the other guards, game continues. * `(1,1)`, `(1,2)`, `(2,1)` or `(2,2)`: No player shoots, game continues. By design the sum of the game ending options is smaller then 2 and the sum of each game continuing possibility is larger or equal 2. The outcome of the game is then the first tuple with sum less then 2. ``` a#b=[x| -- build the list of all x x@(y,z) <- -- where x is an alias for the tuple (y,z) which is drawn from the list zip (1!a) -- of tuples where the first component is from 1!a = eg. [1,2,1,0,1,0] (1!b) -- and the second from 1!b = eg. [1,2,1,2,1,1] , 2 > y+z] -- and y+z are smaller 2. !!0 -- return the first element of this list ``` [Answer] ## Batch, 249 bytes ``` @echo off set g=goto gg set/ax=y=0 :gg shift&goto %1 :fg set x=0 %g% :gf set y=0 %g% :rr set/ax=y=1 %g% :fr if %x%==1 exit/b1 :gr set y=1 %g% :rf if %y%==1 exit/b2 :rg set x=1 %g% :ff set/az=3-x-x-y if %z%==3 %g% exit/b%z% ``` Input is in the form of pairs of characters for each turn and outputs by error level (0 = draw, 1 = player 1, 2 = player 2). `x` and `y` keep track of whether the player has ammo, so when both fire, the result is `3-x-x-y`, unless that is 3, in which case we keep going. On line 5 I abuse Batch's parser - `%1` (which is the current move) is substituted before the `shift` statement executes and removes it, so we still go to the correct label. [Answer] ## Clojure, 168 bytes ``` #(reduce(fn[[l L r R][a A]](if(and l L)(let[M(fn[r a A](if(and(= a \f)r)[nil(= A \g)][(or(= a \r)r)1]))[r L](M r a A)[R l](M R A a)][l L r R])[l L r R]))[1 1 nil nil]%) ``` Less golfed (if both persons are alive we use `M` to update their ammo and enemy's life state, otherwise we return the current status): ``` (def f (fn[A] (reduce (fn [[l1 l2 r1 r2] [a1 a2]] (if (and l1 l2) (let[M (fn [r1 a1 a2] (if (and(= a1 \f)r1) [false (= a2 \g)] ; we lost the ammo, a2 lives if he was guarding [(or(= a1 \r)r1) true])) ; we might gain or keep ammo, a2 lives no matter what [r1 l2] (M r1 a1 a2) [r2 l1] (M r2 a2 a1)] [l1 l2 r1 r2]) [l1 l2 r1 r2])) [true true false false] A))) ``` Example usage (first element tells if Player 1 is alive at the game end, second element tells if Player 2 is alive, 3rd and 4th tell the ammo status which isn't relevant when determining the winner): ``` (-> (for[[a b s] (partition 3 "rr fg rf fr ")][a b]) f (subvec 0 2)) ``` Update: Well look at that, this `loop` has identical length! I find `reduce` version easier to develop as you can easily inspect intermediate states if you use `reductions`. ``` #(loop[l 1 L 1 r nil R nil[[a A]& I]%](if(and l L)(let[M(fn[r a A](if(and(= a \f)r)[nil(= A \g)][(or(= a \r)r)1]))[r L](M r a A)[R l](M R A a)](recur l L r R I))[l L])) ``` [Answer] # PHP, ~~107~~ ~~101~~ 90 bytes using a bit mask $d for the loading status and a DeBruijn sequence for the firing moves. ``` for(;!$x=$d&strpos(_frff,$m=$argv[++$i]);)$d=$d&g<$m|h<$m|2*($d/2&f<$m[1]|g<$m[1]);echo$x; ``` takes input as 2-character command line arguments, run with `-nr`. > > 1 = Player 1 wins > > 2 = Player 2 wins > > > > **breakdown** ``` for(;!$x=$d&strpos(_frff, // 1. $x=someone dies, loop while not $m=$argv[++$i] // loop throug moves );) $d= $d&g<$m|h<$m // 2. unload/reload Player 1 = bit 0 |2*( $d/2&f<$m[1]|g<$m[1] // 3. unload/reload Player 2 = bit 1 ); echo$x; ``` * DeBruijn Sequence: `fr`:position=1=P1 fires; `rf`=position 2=P2 fires, `ff`=position 3=both fire * `g<$m` <=> `f<$m[0]` (`f<$m` is always true, because there is a second character). [Answer] # Python, 200 bytes ``` def war_game(turns): turn=0 player1=True player2=True ammo1=False ammo2=False while turn<len(turns): if turns[turn][0]=='f' and ammo1==True and turns[turn][1]!='g': player2=False elif turns[turn][0]=='f' and turns[turn][1]=='g': ammo1=False elif turns[turn][0]=='r': ammo1=True if turns[turn][1]=='f' and ammo1==True and turns[turn][0]!='g': player1=False elif turns[turn][1]=='f' and turns[turn][0]=='g': ammo2=False elif turns[turn][1]=='r': ammo2=True if player2==False or player1==False: break turn+=1 if player1==True and player2==False: print('Player 1 wins') return 1 elif player1==False and player2==True: print('Player 2 wins') return 2 print('Draw') return 0 ``` [Answer] # Clojure, ~~180~~ 173 bytes ``` (fn[t](loop[z nil x nil[[c v]& r]t](let[k #(and %3(= %\f)(not= %2\g))h #(and(not= %\f)(or %2(= %\r)))q(k v c x)w(k c v z)](cond(and q w)0 q 2 w 1 1(recur(h c z)(h v x)r))))) ``` -7 bytes by changing the function to a full function instead of using a macro. That let me make the inner functions macros, which saves a bit. This is a very literal solution. I'm kind of mind-locked since I just wrote a full version of the game, and this is basically a greatly stripped down version of the algorithm I used. There are probably many optimizations I could do, but I'm fairly happy with it. See pregolfed code for explanation. ``` (defn outcome [turns] ; Take input as ["rr" "ff"] (loop [p1-ammo? false ; Keep track of if each player has ammo p2-ammo? false [[p1-move p2-move] & rest-turns] turns] ; Deconstruct the turns out (let [killed? (fn [m m2 a] (and a (= m \f) (not= m2 \g))) ; Function that checks if one player killed the other has-ammo? (fn [m a] (and (not= m \f) (or a (= m \r)))) ; Function that decides if a player has ammo in the ; next turn p1-killed? (killed? p2-move p1-move p2-ammo?) ; Check if each player was killed. p2-killed? (killed? p1-move p2-move p1-ammo?)] (cond ; Check who (if any) died. If no one died, recur to next turn. (and p1-killed? p2-killed?) 0 p1-killed? 2 p2-killed? 1 :else (recur (has-ammo? p1-move p1-ammo?) (has-ammo? p2-move p2-ammo?) rest-turns))))) ``` ]
[Question] [ Given an integer `n`, output the first `n` sloping binary numbers, either 0- or 1-indexed. They are called this because of how they are generated: Write numbers in binary under each other (right-justified): ``` ........0 ........1 .......10 .......11 ......100 ......101 ......110 ......111 .....1000 ......... ``` Then, you need to take each diagonal from bottom-left to top-right, such that each final digit is the final digit of a diagonal. Here's the fourth diagonal (zero-indexed) marked with `x`'s, which is `100`: ``` ........0 ........1 .......10 .......11 ......10x ......1x1 ......x10 ......111 .....1000 ......... ``` The upward-sloping diagonals in order are: ``` 0 11 110 101 100 1111 1010 ....... ``` Then, convert to decimal, giving `0, 3, 6, 5, 4, 15, 10, ...` [**OEIS A102370**](http://oeis.org/A102370) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes wins.** [Answer] ## JavaScript (ES6), 53 bytes ``` n=>[...Array(n)].map(g=(j=1,i)=>j>i?0:j&i|g(j+j,i+1)) ``` 0-indexed. It's not often I get to use a recursive function as a parameter to `map`. [Answer] # Mathematica, 46 bytes ``` Plus@@@Table[BitAnd[n+k,2^k],{n,0,#},{k,0,n}]& ``` Unnamed function taking a nonnegative integer `#` as input and returning the 0-index sequence up to the `#`th term. Constructs the sloping binary numbers using `BitAnd` (bitwise "and") with appropriate powers of 2. [Answer] # Jelly, 11 bytes ``` ḤḶBUz0ŒDUḄḣ ``` [Try it online!](https://tio.run/nexus/jelly#ARoA5f//4bik4bi2QlV6MMWSRFXhuIThuKP///82OA) ### Explanation ``` ḤḶBUz0ŒDUḄḣ Main link. Argument: n Ḥ Double the argument. This ensures there are enough rows, since n + log2(n) <= 2n. Ḷ Get range [0 .. 2n-1]. B Convert each number to binary. U Reverse each list of digits. z0 Transpose, padding with zeroes to a rectangle. ŒD Get the diagonals of the rectangle, starting from the main diagonal. This gets the desired numbers, reversed, in binary, with some extras that'll get dropped. U Reverse each diagonal. Ḅ Convert each diagonal from binary to a number. ḣ Take the first n numbers. ``` The transpose is the simplest way to pad the array for the diagonals builtin to work. Then the reverses are added to get everything in the correct order. [Answer] # Python3, ~~63~~ 61 bytes ``` lambda i:[sum(n+k&2**k for k in range(n+1))for n in range(i)] ``` Uses the formula from OEIS. -2 bytes thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)! `i+1` --> `i` [Answer] # PHP, 68 bytes ``` for(;$n++<$argv[1];print$s._)for($s=$i=0;$i<$n;)$s|=$n+$i-1&1<<$i++; ``` takes input from command line argument, prints numbers separated by underscores. Run with `-r`. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~18~~ 17 bytes ``` :q"@tt:+5MW\~fWs+ ``` [Try it online!](https://tio.run/nexus/matl#@29VqORQUmKlbeobHlOXFl6s/f@/kQEA "MATL – TIO Nexus") This uses the formula from OEIS: ``` a(n) = n + Sum_{ k in [1 2... n] such that n + k == 0 mod 2^k } 2^k ``` Code: ``` :q" % For k in [0 1 2 ...n-1], where n is implicit input @ % Push k tt % Push two copies : % Range [1 2 ... k] + % Add. Gives [n+1 n+2 ... n+k] 5M % Push [1 2... k] again W % 2 raised to that \ % Modulo ~f % Indices of zero entries W % 2 raised to that s % Sum of array + % Add % End implicitly. Display implicitly ``` [Answer] # [Perl 6](http://perl6.org/), ~~59~~ 43 bytes ``` {map ->\n{n+sum map {2**$_ if 0==(n+$_)%(2**$_)},1..n},^$_} ``` ``` {map {sum map {($_+$^k)+&2**$k},0..$_},^$_} ``` Uses the formula from the OESIS page. Update: Switched to the bitwise-and based formula from [TuukkaX's Python answer](https://codegolf.stackexchange.com/a/104260/14880). # [Perl 6](http://perl6.org/), 67 bytes ``` {map {:2(flip [~] map {.base(2).flip.comb[$++]//""},$_..2*$_)},^$_} ``` Naive solution. Converts the numbers that are part of the diagonal to base 2, takes the correct digit of each, and converts the result back to base 10. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` 2*ḍ+ ḶçЀḶUḄ+Ḷ’ ``` This would be shorter than the other Jelly answer if we had to print only the **n**th term. [Try it online!](https://tio.run/nexus/jelly#@2@k9XBHrzbXwx3bDi8/POFR0xogK/ThjhZtIP2oYeb////NAQ "Jelly – TIO Nexus") [Answer] ## R, 66 bytes ``` function(n,k=0:length(miscFuncs::bin(n-1)))sum(bitwAnd(k+n-1,2^k)) ``` Unnamed function which uses the `bin` function from the `miscFuncs` package to calculate the length of `n` represented in binary and then using one of the OEIS formulas. ]
[Question] [ [Inspired by this CR question](https://codereview.stackexchange.com/questions/121708/randomly-generate-spelling-mistake-in-string) (please don't kill me for browsing CR) ## Spec The probabilities of misspelling a word are: * 1/3 of the time don't change the output * 1/3 of the time remove a random character * 1/3 of the time duplicate a random character The chance for removing/duplicating a given character in the input should be the same for all chars. If two consecutive characters are the same (case-sensitive), the probability of one of them being modified should be the same as if they are one character. I.e. the outputs for `AA` (which are `AA` or `A` or `AAA`) should all have the same probability. --- The input will only contain of letters for simplicity. ## Examples First line is input, following lines are all possible misspellings. Each line should have the same probability of being output, the input is excluded in the examples but it should still have a 1/3 probability of output. ``` foo fo oo ffoo fooo ``` ``` PPCG PPC PPG PCG PPPCG PPCCG PPCGG ``` [Answer] ## [Pip](http://github.com/dloscutoff/pip), ~~38~~ 27 bytes ``` a@:`(.)\1*`YRR#aa@y@0X:RR3a ``` This was fun--got to use Pip's regex and mutable string capabilities, which I hadn't pulled out in a while. Takes input via command-line argument. Explanation: ``` a@:`(.)\1*` Split a into runs of identical chars using regex match YRR#a Yank randrange(len(a)) into y (randomly choosing one such run) a@y@0 Take the first character of that run X:RR3 Modify in place, string-multiplying by randrange(3): If RR3 is 0, character is deleted If RR3 is 1, no change If RR3 is 2, character is duplicated a Output the modified a ``` [Try it online!](http://pip.tryitonline.net/#code=YUA6YCguKVwxKmBZUlIjYWFAeUAwWDpSUjNh&input=&args=UFBDRw) [Answer] # Ruby, ~~64~~ 55 + 1 (`p` flag) = 56 bytes Input is a line of STDIN piped in without trailing newline. ``` a=[] gsub(/(.)\1*/){a<<$&} a.sample[-1]*=rand 3 $_=a*'' ``` [Answer] ## CJam (21 bytes) ``` re`_,mr_2$=3mr(a.+te~ ``` [Online demo](http://cjam.aditsu.net/#code=re%60_%2Cmr_2%24%3D3mr(a.%2Bte~&input=foo) ### Dissection ``` r e# Read a line of input from stdin e` e# Run-length encode it _,mr e# Select a random index in the RLE array _ e# Hang on to a copy of that index 2$= e# Copy the [run-length char] pair from that index 3mr( e# Select a uniformly random integer from {-1, 0, 1} a.+ e# Add it to the run-length t e# Replace the pair at that index e~ e# Run-length decode ``` [Answer] # JavaScript (ES6), 107 ``` w=>(r=x=>Math.random()*x|0,a=w.match(/(.)\1*/g),a[p=r(a.length)]=[b=a[p],b+b[0],b.slice(1)][r(3)],a.join``) ``` *Less golfed* ``` w=>( a = w.match(/(.)\1*/g), r = x => Math.random()*x | 0, p = r(a.length), b = a[p], a[p] = [b, b+b[0], b.slice(1)][r(3)], a.join`` ) ``` **Test** ``` f=w=>(r=x=>Math.random()*x|0,a=w.match(/(.)\1*/g),a[p=r(a.length)]=[b=a[p],b+b[0],b.slice(1)][r(3)],a.join``) function update() { O.innerHTML = Array(99) .fill(I.value) .map(x=>( r=f(x), r==x?r:r.length<x.length?'<b>'+r+'</b>':'<i>'+r+'</i>' ) ).join` ` } update() ``` ``` #O { width:90%; overflow: auto; white-space: pre-wrap} ``` ``` <input id=I oninput='update()' value='trolley'><pre id=O></pre> ``` [Answer] # Java 7, ~~189~~ ~~180~~ 178 bytes ``` import java.util.*;String c(String i){Random r=new Random();int x=r.nextInt(2),j=r.nextInt(i.length());return x<1?i:i.substring(0,j-(x%2^1))+(x<2?i.charAt(j):"")+i.substring(j);} ``` **Ungolfed & test cases:** [Try it here.](https://ideone.com/VVSE5i) ``` import java.util.*; class M{ static String c(String i){ Random r = new Random(); int x = r.nextInt(2), j = r.nextInt(i.length()); return x < 1 ? i : i.substring(0, j - (x%2 ^ 1)) + (x<2?i.charAt(j):"") + i.substring(j); } public static void main(String[] a){ for(int i = 0; i < 5; i++){ System.out.println(c("foo")); } System.out.println(); for(int i = 0; i < 5; i++){ System.out.println(c("PPCG")); } } } ``` **Possible output:** ``` foo fooo foo foo ffoo PPCCG PPCG PPCCG PPPCG PPCG ``` [Answer] # Python 2, 134 bytes ``` from random import* def f(s): p=c=0;M,L=[],list(s) for t in L: if t!=p:M+=c,;p=t c+=1 L[choice(M)]*=randint(0,2);return''.join(L) ``` White spaces in for loop are tabs. [Try it on Ideone](http://ideone.com/ow3Koc) [Answer] # Pyth - 17 bytes This one actually handles the special cases with consecutive char correctly. ``` XZOKrz8Or_1 2r9K ``` [Test Suite](http://pyth.herokuapp.com/?code=+XZOKrz8Or_1+2r9K&test_suite=1&test_suite_input=downgoat%0APPCG&debug=0). [Answer] # JavaScript (ES6), 103 ``` w=>{w=w.split(''),r=Math.random,x=r(),i=r()*w.length|0;w.splice(i,x<.6,x>.3?w[i]:'');alert(w.join(''))} ``` [Answer] ## APL, 21 ``` {⍵/⍨3|1+(?3)×(⍳=?)⍴⍵} ``` This starts by creating a vector of zeros with a 1 in random position. Then multiplies it by a random number between 1 and 3. +1 and mod 3 obtains a vector with all 1s and one random positioned 0,1 or 2. Finally, ⍵/⍨ says that each letter should be written n times, where n are the numbers in the vector. Try it on [tryapl.org](http://tryapl.org/?a=%7B%u2375/%u23683%7C1+%28%3F3%29%D7%28%u2373%3D%3F%29%u2374%u2375%7D%20%27PPCG%27&run) [Answer] # Python 2, 123 bytes ``` from random import* R=randint s=input() m=n=R(0,len(s)-1) c=R(0,2) m=[m,1+[-len(s),m][m>0]][c==1] n+=c==2 print s[:m]+s[n:] ``` [Answer] # APL, 27 bytes ``` {⍵/⍨(?3)⌷1⍪2 0∘.|1+(⍳=?)⍴⍵} ``` Explanation: ``` ⍴⍵ ⍝ length of ⍵ (⍳=?) ⍝ bit vector with one random bit on 1+ ⍝ add one to each value (duplicate one character) 2 0∘.| ⍝ mod by 2 and 0 (remove instead of duplicate) 1⍪ ⍝ add a line of just ones (do nothing) (?3)⌷ ⍝ select a random line from that matrix ⍵/⍨ ⍝ replicate characters in ⍵ ``` Test: ``` {⍵/⍨(?3)⌷1⍪2 0∘.|1+(⍳=?)⍴⍵} ¨ 10/⊂'foo' fooo foo oo foo fo fo oo fo oo fooo ``` ]
[Question] [ The [split-complex numbers](https://en.wikipedia.org/wiki/Split-complex_number), also known as "perplex numbers" are similar to the complex numbers. Instead of `i^2 = -1`, however, we have **`j^2 = 1; j != +/-1`**. Each number takes the form of `z = x + j*y`. In one attempt to limit the complexity of this challenge, I will use the symbol `-` to represent negation, as there will not be any subtraction. Here are some examples for your viewing pleasure: ``` 6 * 9 = 54 // real numbers still act normally 5 + -7 = -2 j*1 + j*1 = j*2 // two `j`s added together make a j*2 7 * j*1 = j*7 // multiplication is commutative & associative j*1 + 2 = 2+j*1 // like oil and water, "combine" to form a split-complex number j*1 + j*-3 = j*-2 // seems okay so far j*j*1 = j*-1*j*-1 = 1 // kinda sketchy, but such is its inherent nature j*j*-1 = j*-1*j*1 = -1 (2+j*3)+(4+j*7) = 6+j*10 // combine like terms 7 * (2+j*3) = 14+j*21 // distributive property j * (2+j*3) = (j*2) + (j*j*3) = 3+j*2 // since j^2 = 1, multiplying my j "swaps" the coefficients (2+j*3)*(4+j*7) = (2*4)+(2*j*7)+(j*3*4)+(j*3*j*7) = 8+j*14+j*12+21 = 29+j*26 // a complete multiplication ``` ## Challenge The goal of this challenge is to evaluate an expression with split-complex numbers. This is **code-golf,** the fewest bytes wins. **Input** Input will be a single line containing only the symbols `+*()-`, the digits `0123456789`, and the letter `j`, with an optional newline. This string represents an expression, using infix notation and operator precedence (multiplication before addition, with parenthesis grouping). * The symbol `-` will always represent negation, never subtraction. **If you so desire, you can replace `-` with either `_` or `~`** for ease of I/O. * Parenthesis can be nested up to three times to denote grouping: `(1+(1+(1)))` * The letter `j` will never be directly prefixed with negation, and will always be followed by `*`. * Parentheses will not be preceded by negation `-(7)`, but instead like `-1*(j*5+2)` * There will never be implicit operations. All multiplication will be expressed as `(7)*7` instead of `(7)7`, and as `j*5` instead of `j5`. * No leading zeros. **Output** Output will be in the form of `X+j*Y`, where X and Y can be any integer. If an integer is negative, it should be prefixed with the negation sign. ## Additional Restrictions Although I am not aware of any language with native support, built-ins that deal with split-complex numbers are forbidden. Regular complex numbers are fair game. ## Test Cases Similar to the above examples, but tidied up. Input on one line and output the line beneath. ``` (2+j*3)+(4+j*7) 6+j*10 (2+j*3)*(4+j*7) 29+j*26 (-5+j*1+j*2+2)*(4+j*7) 9+j*-9 (1+j*-1)*(1+j*1) 0+j*0 // this is why division does not exist. j*((j*-1)+2) -1+j*2 (2+(5+-1*(j*1))+2) 9+j*-1 ``` [Answer] ## Python 2, 62 bytes ``` def f(s):b,a=[eval(s)/2.for j in-1,1];print'%d+j*%d'%(a+b,a-b) ``` We simply evaluate the expression `s` with `j=1` and `j=-1`, and output half their sum and half their difference as the coefficients of `1` and `j`. This works because both `j=1` and `j=-1` satisfy the defining equation defining equation `j*j==1`. So, the original and simplified expressions must be equal for both these values. The simplified expression is linear, so this gives two linear equations in two unknowns: ``` x + 1*y = s(1) = 2*a x - 1*y = s(-1) = 2*b ``` which is solved by `x=a+b, y=a-b`. [Answer] # Python 2, 258 ``` class c(complex):__mul__=lambda s,o:c(s.real*o.real+s.imag*o.imag,s.real*o.imag+s.imag*o.real);__add__=lambda s,o:c(sum(map(complex,[s,o]))) import re r=eval(re.sub("j","c(0,1)",re.sub(r"(-?\d+)",r"c(\1)",raw_input()))) print`int(r.real)`+"+j*"+`int(r.imag)` ``` This is probably not the best approach, but it was the first time that OOP looked like a passable idea in Python for code golf, so why not? Creates a class `c` that inherits from complex but has a different `mul` operation. The `add` operation is also changed so that it returns an object of type `c` and not `complex`, this behaviour is necessary to prevent the case of `(a + b) * (c + d)` doing complex multiplication instead of this special kind. The input string is then converted into a string that can be evaluated naturally by python. It does this by changing every number into `c(number)` and then every `j` into `c(0,1)`. [Try it online](https://ideone.com/KCCNsv) or run a [Test Suite](https://ideone.com/khcGzZ) [Answer] ## [GAP](http://gap-system.org), 38 bytes ``` j:=X(Integers,"j");f:=t->t mod(j^2-1); ``` First `j` is defined to be an indeterminate, so we can create polynomials in `j`. To get the corresponding perplexing number, we reduce (i.e. take the remainder of polynomial division) by `j^2-1`. This gives a linear (or constant) term, and we can rely on GAP's ability to output polynomials. Examples: ``` gap> f((2+j*3)+(4+j*7)); 10*j+6 gap> f((1+j*-1)*(1+j*1)); 0 ``` Caveat: 1. This does not take a string as input, but a real term in GAP's language. To fix, I could use `EvalString`. 2. The output is nice and clear, but not exactly as specified: Order is changed, and unnecessary zeroes are suppressed. I think and hope this is still in the spirit of the challenge, otherwise I guess I'd be better off using @xnor's matrix approach. [Answer] # Axiom, ~~20~~ 42 bytes ``` f(x,n)==x^(n rem 2);m:=rule('j^n==f('j,n)) ``` the preceding solution have a problem if `n<0` in `j^n` but this it seems more solid, and advise well where there is something wrong, even if the perfection would be return example j^1.2 or j^sqrt(-1) the same expression not evaluate ``` (9) -> f(x,n)==x^(n rem 2);m:=rule('j^n==f('j,n)) n (9) j == 'f(j,n) Type: RewriteRule(Integer,Integer,Expression Integer) (10) -> [m((2+j*3)+(4+j*7)), m((2+j*3)*(4+j*7)), m((-5+j*1+j*2+2)*(4+j*7))] (10) [10j + 6,26j + 29,- 9j + 9] Type: List Expression Integer (11) -> [m((1+j*-1)*(1+j*1)), m(j*((j*-1)+2)), m(2+(5+-1*(j*1))+2)] (11) [0,2j - 1,- j + 9] Type: List Expression Integer (12) -> [m(j*j*j*j),m(j*j*j),m(j^200)] (12) [1,j,1] Type: List Expression Integer (13) -> [m(j^0),m(j^-1),m(j^-2), m(j^-3)] 1 1 (13) [1,-,1,-] j j Type: List Expression Integer (14) -> m(j^(3.4)) There are no library operations named m Use HyperDoc Browse or issue ``` if i not follow some law of the question: say me that and i add "not competitive". I mean it as one axiom for simplify formula [Answer] ## Batch, 52 bytes ``` @set/aj=1,a=%1,j=-1,a-=b=(a-(%1))/2 @echo %a%+j*%b% ``` After seeing @xnor's excellent answer nomination I felt compelled to port it. ]
[Question] [ What makes the ideal question? Perhaps it is merely the abstraction of a profound thought and the initialization of a dream, a hope, a thought, a (… *5,024.2 characters omitted*). Therefore, I propose that we find such a factor to quantify questions. I propose also that this factor be called ***Q****F*, or the Q-factor. I determine a question's Q-factor as thus: ![](https://latex.codecogs.com/gif.latex?%5Ctextbf%7B%5Ctextit%7BQ%7D%7D_F%3A%3Dr_F%5Cdfrac%7B%5Ctext%7Bviews%7D%5Ctimes%5Ctext%7Bnet%20votes%7D+%5Ctext%7Bedits%7D%7D%7B%5Ctext%7Banswers%7D%5E2-%5Ctext%7Bcomments%7D%7D) (Recall that ![](https://latex.codecogs.com/gif.latex?%5Cinline%20r_F%3D%5Cfrac%7B%5Ctext%7Bedits%7D%7D%7B%5Ctext%7BCharacters%20in%20original%20poster%27s%20name%7D%7D).) **Objective** Given a number ![](https://latex.codecogs.com/gif.latex?%5Cinline%20N) as input, determine the respective question's Q-factor on PPCG.SE. If the question does not exist, simply output `;-;` (the crying emote). Take, for example, ![](https://latex.codecogs.com/gif.latex?N%3D16327). ([this question](https://codegolf.stackexchange.com/questions/16327)): The net votes, in this case, means ![](https://latex.codecogs.com/gif.latex?%5Ctext%7Bpositive%20votes%7D+%5Ctext%7Bnegative%20votes%7D). ``` views = 23435 net votes = 33 edits = 6 answers = 30, answers^2 = 900 comments = 19 charsIOPN = "Joe Z.".length = 6 ``` So: ``` r_F = 6 / 6 = 1 Q_F = r_F * (23435 * 33 + 6) / (900 - 19) = 1 * 773361 / 881 ~ 877.821793 ``` Please provide at least 2 significant figures on ***Q****F*. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. --- Note: Please include three examples of your program running, one of which must be this question. The other two are yours to decide. (This is just a confirmation check.) Also report the time at which you entered the query. [Answer] # Julia, ~~411~~ ~~382~~ ~~367~~ ~~355~~ 353 bytes It's quite long but I'm very pleased that it works! ``` using Requests n->(R(t)=readall(get(t));G(t)=JSON.parse(R("http://api.stackexchange.com/2.2/questions/$t?site=codegolf"))["items"];j=G(n)[1];d=parse(Int,match(r"<span \S+n (\d+)",R("http://codegolf.xyz/posts/$n/revisions")).captures[1]);d/length(j["owner"]["display_name"])*(j["view_count"]*j["score"]+d)/(j["answer_count"]^2-length(G("$n/comments")))) ``` This creates an unnamed function that takes an integer as input and returns a float. It requires the `Requests` package, which can be installed using `Pkg.add("Requests")`. That package provides methods for `Base.get()` for submitting HTTP requests. It also imports the `JSON` package (on which it depends, so that doesn't need to be installed separately) which we use to parse the JSON output in the response. Ungolfed: ``` using Requests function f(n::Int) # Define a function to submit an HTTP request and read # the response, returning a string R(t) = readall(get(t)) # Define a function that submits a request, reads all text # as JSON, parses it, and extracts the items field G(t) = begin api = "http://api.stackexchange.com/questions" JSON.parse(R("$api/$t?site=codegolf"))["items"] end # Get the data for the question using the API j = G(n)[1] # Scrape the number of edits from the revision history HTML # using minxomat's handy shortened PPCG URL h = R("http://codegolf.xyz/posts/$n/revisions") d = parse(Int, match(r"<span \S+n (\d+)", h).captures[1]) # Compute the coefficient r_F r = d / length(j["owner"]["display_name"]) # Compute the Q-factor Q = r * (j["view_count"] * j["score"] + d) / (j["answer_count"]^2 - length(G("$n/comments"))) return Q end ``` Thanks to Dennis and Martin Büttner for golfing help! [Answer] # Mathematica 10, 381 bytes ``` f=(a=StringTemplate["http://api.stackexchange.com/``````?site=codegolf"];j=Import[a["questions/",#,""],"JSON"];c=Import[a["questions/",#,"/comments"],"JSON"];r=Import[a["posts/",#,"/revisions"],"JSON"];N[#5/#6*(#1*#2+#5)/(#3^2-#4)]&@@j[[3,2,1,{5,2,12},2]]~Join~{Length@c[[3,2]],Length@DeleteCases[r[[3,2]],_?(("revision_type"/.#)=="vote_based"&)],StringLength@j[[3,2,1,3,2,6,2]]})& ``` Just three API queries and a lot of indexing, really. Hardest part was trying to understand how to get `edits` from the available `revisions`, hopefully I got it right. [Answer] # Python 2, 392 Bytes Well, I gave it a shot. ``` from requests import*;from re import*;l=len def i(n): try:s,r="http://api.stackexchange.com/2.2/questions/%s?site=codegolf","http://codegolf.xyz/posts/%i/revisions"%n;q,c=s%n,s%('%i/comments'%n);i=get(q).json()['items'][0];m=float(l(findall("<span \S+n (\d+)",get(r).text)));r=m/l(i["owner"]["display_name"]);print r*(i["view_count"]*i["score"]+m)/(i["answer_count"]**2-m) except:print';-;' ``` Very similar logic to Alex's [Julia answer](https://codegolf.stackexchange.com/a/60586/34315). I'd like to loop through this to see which question is the most ideal but I'd rather not continually call the api for hours on end. [Answer] # Groovy, ~~459~~ 457 bytes Pretty much like the rest of the answers. ``` import groovy.json.JsonSlurper import java.util.zip.GZIPInputStream def f={n->def j,d,u={p->new JsonSlurper().parseText(new GZIPInputStream("http://api.stackexchange.com/2.2/questions/$p?site=codegolf".toURL().getContent()).getText()).items} j=u(n)[0] d=("http://codegolf.xyz/posts/$n/revisions".toURL().text=~/<span \S+n (\d+)/).getCount() println((d/j.owner.display_name.length())*(j.view_count*j.score+d)/(j.answer_count**2-u("$n/comments").size()))} ``` Saved 2 bytes thanks to Cᴏɴᴏʀ O'Bʀɪᴇɴ! Ungolfed: ``` import groovy.json.JsonSlurper import java.util.zip.GZIPInputStream def f = { n-> def stackApi = "http://api.stackexchange.com/2.2" // Fetch json from stackexchange rest api def getItems = { pathParam -> //Stackexchange compresses data, decompress before parsing json def httpData = "$stackApi/questions/$pathParam?site=codegolf".toURL().getContent() def deCompressedData = new GZIPInputStream(httpData).getText() def json = new JsonSlurper().parseText(deCompressedData) return json.items } // Get the edit count from the html page def htmlPage = "http://codegolf.xyz/posts/$n/revisions".toURL() def editCount = (htmlPage.text=~/<span \S+n (\d+)/).getCount() // apply formula def json = getItems(n)[0] def r = editCount/json.owner.display_name.length() def Q = r * ( json.view_count * json.score + editCount) / (json.answer_count**2 - getItems("$n/comments").size()) println(Q) } f(16327) ``` ]
[Question] [ Your goal is to write a perfect player for the game of [Wythoff's Nim](http://en.wikipedia.org/wiki/Wythoff's_game). ## Rules of Wythoff's Nim Wythoff's Nim is a deterministic two-player game played with two piles of identical counters. Players alternate turns, in which they do one of these: 1. Remove one or more counters from the first pile 2. Remove one or more counters from the second pile 3. Remove an equal number of counters (one or more), from both the first pile and the second pile. Of course, piles can't go negative, but they can to 0. Whichever player removes the last counter overall wins the game. For the more geometrically-minded, here is an equivalent formulation of the game that you can play on [this applet](http://www.cut-the-knot.org/pythagoras/withoff.shtml). A single queen starts on some square of a quarter-infinite chessboard whose corner is in the bottom-left. Players alternate moving the queen, which moves like a chess queen but restricted to three directions: 1. Down 2. Left 3. Diagonally down and left Whoever moves the queen to the corner wins. Associating the queen's coordinates (with corner `(0,0)`) to the sizes of the respective piles, it's easy to see both games are the same. ## Perfect play *(You can skip this if familiar with the notions of perfect play and winning moves.)* Since Wythoff's Nim is a finite and deterministic game, it has a notion of [perfect play](http://en.wikipedia.org/wiki/Perfect_play#Perfect_play). A perfect player is a strategy that will always win from a theoretically won position, meaning a position in which there exists a strategy that guarantees a win. To be a winning strategy, it suffices to move to always move to a theoretical winning position for the player who just moved, and thus the player not going next. The first of these winning positions (also called *cold positions*) are `(0,0), (1,2), (2,1), (3,5), (5,3)`. See the [Wikipedia article](http://en.wikipedia.org/wiki/Wythoff's_game) for an explanation of an algorithm to find a winning strategy for Wythoff's Nim, as well as a formula to generate win positions. ## Program requirements Write a [program or function](http://meta.codegolf.stackexchange.com/q/2447/20260) takes a position as input and outputs a winning move in the form of the position after that move. Fewest bytes wins. If no winning move exists, i.e., the position is a theoretical loss, your program should indicate so and forfeit. Your program must run within a reasonable amount of time. So, an exponential recursive game tree search will not suffice. If you want to precompute and hard-code a strategy, that's fine. **Input** A pair `(i,j)` of non-negative numbers representing pile sizes, each at most `99`. This can be two numbers, a tuple, a list, or whatever container you prefer. **Output** Print or output the position after your move, again as two numbers or a container thereof. This must be a legal move to a winning position. If there's multiple such moves, any one is fine, but only one. If there's no winning move, you must indicate this in the output. Any output like `False`, `None`, 0, or `(-1,-1)` will do, as long as it's not a legal position, and is the same for every losing input. **Example runs** ``` f(5,0) = (0,0) f(2,2) = (1,2) # Or (2,1) or (0,0) f(1,2) = False f(13,9) = (13,8) # Or (10,6) f(10,6) = False f(5,10) = (5,3) f(25,30) = (8,13) ``` [Answer] # Haskell, ~~167~~ 165 characters ``` c p=o p:c(o p:p) o p=[(a,b)|a<-[0..],b<-[0..a],(a,b)?p==[]]!!0 (a,b)?p=[y|y@(c,d)<-p,c==a||c==b||d==b||a+d==b+c] f x@(a,b)|a<b=f(b,a)|x?c[]!!0==x=(0,-1)|1>0=x?c[]!!0 ``` The algorithm is inefficient, but it still runs within a second (though not in the interactive console) for inputs < 100. ### Explanation: ``` c p=o p:c(o p:p) ``` The list of cold positions given a set of previous cold positions is one cold position followed by the list of cold positions given this position and the previous ones (Inefficiency: this position is generated twice) ``` o p=[(a,b)|a<-[0..],b<-[0..a],(a,b)?p==[]]!!0 ``` One cold position is the first pair such that there are no cold positions reachable from that pair (Inefficiency: we should search from the previous pair instead) ``` (a,b)?p=[y|y@(c,d)<-p,c==a||c==b||d==b||a+d==b+c] ``` Positions reachable from a pair are those such that their first elements match, their second elements match, their difference matches, or the smaller heap before removal is the larger heap after removal. ``` f x@(a,b)|a<b=f(b,a) |x?c[]!!0==x=(0,-1) |1>0=x?c[]!!0 ``` (main method) If the heaps are in the wrong order, swap them. Else, if the first cold position reachable from a position is the position itself, indicate failure (ideally, one would return `Maybe (Int,Int)` instead). Else return that cold position (Inefficiency: said pair is looked up twice. Worse, the list of cold positions is generated twice) [Answer] ## GolfScript (63 57 bytes) ``` {\]zip{~-}%0|$(!*,1=}+1,4*{..,,^[(.@,2/+.2$]+}38*2/?0]0=` ``` Expects input from stdin in the form `[a b]`, and leaves output on stdout in that form or `0` if it's a losing position. [Online demo](http://golfscript.apphb.com/?c=OydbNSAwXQpbMiAyXQpbMSAyXQpbMTMgOV0KWzEwIDZdCls1IDEwXQpbMjUgMzBdJ24vewojIyBFbmQgdGVzdCBmcmFtZXdvcmsgcHJlZml4Cgp7XF16aXB7fi19JTB8JCghKiwxPX0rMSw0KnsuLiwsXlsoLkAsMi8rLjIkXSt9MzgqMi8%2FMF0wPWAKCiMjIFN0YXJ0IHRlc3QgZnJhbWV3b3JrIHN1ZmZpeApwdXRzfS8%3D) ### Overview ``` ,4*{..,,^[(.@,2/+.2$]+}38*2/ ``` computes a list of cold positions (including the flipped version `[b a]` for each cold position `[a b]`) using the [Beatty sequence](http://en.wikipedia.org/wiki/Beatty_sequence) property. Then `?` searches for the first cold position satisfying the block created by ``` {\]zip{~-}%0|$(!*,1=}+ ``` which basically checks that the position is reachable from the input position by computing the vector difference and then verifying that it's either `[0 x]`, `[x 0]`, or `[x x]` for some `x > 0`. IMO that test is the cleverest bit: `0|$` forces any array in one of those formats into the form `[0 x]` while mapping `[0 0]` to `[0]`, `[a b]` where neither `a` nor `b` is `0` to a three-element array, and `[-x 0]` or `[-x -x]` to `[-x 0]`. Then `(!*,1=` checks that we have `[0 x]`. Finally `0]0=`` does the fallback case and formatting for output. [Answer] ## [Pyth](https://github.com/isaacg1/pyth) 57 ~~58 61 62~~ ``` K1.618Jm,s*dKs*d*KKU39M<smf|}TJ}_TJm,-Ghb-Hebt^,0hk2U99 1 ``` [Try it online.](http://isaacg.scripts.mit.edu/pyth/index.py) Pretty similar to other answers, but that wikipedia page didn't give much else to go on ;) The magic number `39` is the number of cold positions with values < `99`. Defines a function `g` that you can call like `g 30 25`. Returns `[]` for failure, `[(13,8)]` on success. Explanation ``` K1.618 : K=phi (close enough for first 39 values) Jm,s*dKs*d*KKU39 : J=cold positions with the form (small,big) M<s 1: Define g(G,H) to return this slice: [:1] of the list below mf|}TJ}_TJ : map(filter: T or reversed(T) in J, where T is each member of.. m,-Ghb-Hebt^,0hk2 : [(G H) - (0 x+1),(x+1 0) and (x+1 x+1)] U99 : for each x from 0 - 98 ``` [Answer] # Javascript ES6 - 280 bytes Minified ``` r=x=>~~(x*1.618);g=(y,x)=>y(x)?g(y,x+1):x;s=A=>A?[A[1],A[0]]:A;f=(a,b)=>j([a,b])||j([a,b],1);j=(A,F)=>l(A,F)||s(l(s(A),F));l=(A,F)=>([a,b]=A,c=(F&&a+b>=r(b)&&(e=g(x=>a+b-2*x-r(b-x),0))?[a-e,b-e]:(e=g(x=>r(a+x)-2*a-x,0))+a<b?[a,a+e]:(e=r(b)-b)<a?[e,b]:0),c&&r(c[1]-c[0])==c[0]?c:0) ``` Expanded ``` r = x => ~~(x*1.618); g = (y,x) => y(x) ? g(y,x+1) : x; s = A =>A ? [A[1],A[0]] : A; f = (a,b) => j([a,b]) || j([a,b],1); j = (A,F) => l(A,F) || s(l(s(A),F)); l = (A,F) => ( [a,b] = A, c = ( F && a+b >= r(b) && (e = g( x => a+b - 2*x - r(b - x), 0 )) ? [a-e,b-e] : (e = g( x => r(a+x) - 2*a - x, 0)) + a < b ? [a,a+e] : (e = r(b) - b) < a ? [e,b] : 0 ), c && r(c[1] - c[0]) == c[0] ? c : 0 ); ``` Nice and quick algorithm. Runs in O(n), but would run in constant time if not for a byte-saving loop. The loop is implemented as a recursive incrementer, hence the script will eventually fail with a recursion error for *n* in the hundreds or thousands. Uses the same Beatty sequence property that Mr. Taylor mentions, but rather than computing the sequence, it simply steps up to the correct term(s). Runs properly on all of the test inputs and many dozens besides that I tested. The function to invoke is `f`. It returns an array on success and a `0` upon giving up. [Answer] # Perl 5 - 109 (with 2 flags) ``` #!perl -pl for$a(@v=0..99){for$b(@v){$c=$a;$d=$b;${$:="$a $b"}|| map{$$_||=$:for++$c.$".++$d,"$a $d","$c $b"}@v}}$_=$$_ ``` Usage: ``` $ perl wyt.pl <<<'3 5' $ perl wyt.pl <<<'4 5' 1 2 ``` Simply calculates solution for each possible input then just does a single lookup. ]
[Question] [ # Your task .. is to do what Brian Fantana apparently couldn't do, and solve the 2x2x2 Rubik's Cube. ![pocket cube - anchorman](https://i.stack.imgur.com/F0XXz.jpg) ## The Layout ``` - - A B - - - - - - C D - - - - E F G H I J K L M N O P Q R S T - - U V - - - - - - W X - - - - ``` And will be given to you via stdin or the command line (your choice - please specify in your answer) in the format: ``` ABCDEFGHIJKLMNOPQRSTUVWX ``` Note that A-D make up the U-face(up), EFMN make up the L-face(left), GHOP make up the F-face(front), IJQR make up the R-face(right), KLST make up the B-face(back), and U-X make up the D-face(down). There will be six unique characters representing each color, but they may vary, so prepare for any combination of 6 ascii characters to be used for each color. ## Specifications * Your code should output a solution using only the Right (R), Upper (U), and Front(F) faces, and should use the standard notation: R , R' , R2 , U , U' , U2 , F , F' , F2. You can find more info [here](http://astro.berkeley.edu/%7Econverse/rubiks.php?id1=basics&id2=notation). The restriction to the RUF subset is standard for the 2x2 cube (Hint: treat the bottom-back-left corner as a fixed base to work from). * Your code must be capable of solving all possible permutations of the pocket cube. * Each solution should take less than 30 seconds to complete. * Each solution should be less than 30 moves. * A bonus of -20% will be given for solutions always providing answers less than 20 moves (please advertise it in your answer so I can do a thorough check for it) * A bonus of -50% will be given for code which always provides an optimal solution. - Again, please advertise in your answer * Solutions must not contain two consecutive moves on the same face, because they can be easily combined into one move. * Solutions can optionally contain a single space - and *only* a single space - between each move. * The whole solution sequence, if necessary, may be contained in a pair of parentheses, quotation marks, braces, brackets, or carets, but no other extraneous output is allowed. * Please provide either a briefly commented version of your code or a thorough explanation of your code. * No use of external files. This includes internet, data tables, and libraries/packages made for this sort of problem. * Shortest code by byte count wins. * Winner chosen Wednesday (July 30, 2014). [Answer] # Python 2.7: 544 bytes -50% = 272 bytes\*\* ``` import sys;o=''.join;r=range;a=sys.argv[1];a=o([(' ',x)[x in a[12]+a[19]+a[22]] for x in a]);v={a:''};w={' '*4+(a[12]*2+' '*4+a[19]*2)*2+a[22]*4:''} m=lambda a,k:o([a[([0x55a5498531bb9ac58d10a98a4788e0,0xbdab49ca307b9ac2916a4a0e608c02,0xbd9109ca233beac5a92233a842b420][k]>>5*i)%32] for i in r(24)]) def z(d,h): t={} for s in d[0]: if s in d[1]:print d[h][s]+d[1-h][s];exit() n=[d[0][s],''] for k in r(3): for j in r(3):s=m(s,k);t[s]=n[h]+'RUF'[k]+" 2'"[(j,2-j)[h]]+n[1-h] s=m(s,k) d[0]=t;return d while 1:v,w=z([v,w],0);w,v=z([w,v],1) ``` Stackexchange replaces tabs with multiple whitespaces. So technical this version has 549 bytes. Just replace the first two spaces in the lines 6-10 with a tabulator. Idea behind my program: My first idea was a breath first search. But this took too long. Around 2 minutes for a hard (11 move optimal) scramble. So I decided to approach the problem from both sides. I use two sets. I generate sequentially all states with distance 1,2,3,... to the scramble and save them in set1, and at the same time all states with distance 1,2,3,... to the solved state and save them in set2. The first time a state is in both sets, we found the solution. For this I need the colors of the solved cube, which are not known. The characters 13, 20 and 23 define the left, back and down color. But these 3 colors are sufficient to represent the cube. I simply replace the other 3 colors with whitespaces and I can represent my solved state as '\_\_\_\_ll\_\_\_\_bbll\_\_\_\_dddd'. Oh, and for shortening the permutations I used an idea from <https://codegolf.stackexchange.com/a/34651/29577> Ungolfed version: ``` import sys #define permutations for R,U,F permutation = [[0,7,2,15,4,5,6,21,16,8,3,11,12,13,14,23,17,9,1,19,20,18,22,10], [2,0,3,1,6,7,8,9,10,11,4,5,12,13,14,15,16,17,18,19,20,21,22,23], [0,1,13,5,4,20,14,6,2,9,10,11,12,21,15,7,3,17,18,19,16,8,22,23]] def applyMove(state, move): return ''.join([state[i] for i in permutation[move]]) scramble = sys.argv[1] #remove up,front,rigth colors scramble = ''.join([(' ', x)[x in scramble[12]+scramble[19]+scramble[22]] for x in scramble]) solved = ' '*4+scramble[12]*2+' '*4+scramble[19]*2+scramble[12]*2+' '*4+scramble[19]*2+scramble[22]*4 dict1 = {scramble: ''} #stores states with dist 0,1,2,... from the scramble dict2 = {solved: ''} #stores states with dist 0,1,2,... from the solved state moveName = 'RUF' turnName = " 2'" for i in range(6): tmp = {} for state in dict1: if state in dict2: #solution found print dict1[state] + dict2[state] exit() moveString = dict1[state] #do all 9 moves for move in range(3): for turn in range(3): state = applyMove(state, move) tmp[state] = moveString + moveName[move] + turnName[turn] state = applyMove(state, move) dict1 = tmp tmp = {} for state in dict2: if state in dict1: #solution found print dict1[state] + dict2[state] exit() moveString = dict2[state] #do all 9 moves for move in range(3): for turn in range(3): state = applyMove(state, move) tmp[state] = moveName[move] + turnName[2 - turn] + moveString state = applyMove(state, move) dict2 = tmp ``` I'm pretty happy with the result, because I'm quite new to Python. This is one of my first python programs. ## edit: half a year later: 427 - 50% = 213.5 Got a little bit more experience in Python and in golfing. So I revised my original code and could save more than 100 character. ``` import sys;o=''.join;a=sys.argv[1];d=[{o((' ',x)[x in a[12]+a[19]+a[22]]for x in a):[]},{' '*4+(a[12]*2+' '*4+a[19]*2)*2+a[22]*4:[]}] for h in[0,1]*6: for s,x in d[h].items(): for y in range(12): d[h][s]=x+[y-[1,-1,1,3][h*y%4]]; if s in d[1-h]:print o('RUF'[x/4]+" 2'"[x%4]for x in d[0][s]+d[1][s][::-1]);exit() s=o(s[ord(c)-97]for c in'acahabcdnpbfegefhugiovjgqkciljdeklflmmmnnvoopxphrqdjrrbsstttuuqsviwwwkxx'[y/4::3]) ``` I basically use the exact same approach. The biggest change is, that I don't define a function anymore. Instead of ``` def z(d,h): for s in d[0]: if s in d[1]:... while 1:v,w=z([v,w],0);w,v=z([w,v],1) ``` I can do ``` for h in[0,1]*6: for s in d[h]: if s in d[1-h]:... ``` Also I changed the move lamda a little bit. First shortend, and then integrated the code directly, since the function call only appears once. I keep for each state a list of numbers between 0 and 11, to represent the moves, instead of a string containing the moves. The numbers are converted at the very end. Also I combined the two for-loops `'for k in r(3):for j in r(3):` into one `for y in r(12)`. Therefore I also have to do the moves `U4, R4, F4`. Of course such a move doesn't appear in the shortest solution, so `" 2'"[x%4]` works. (If `x % 4 == 3`, there would be a index out of range exception) It's also a little bit faster, since I look for the entry in the second set earlier. About 0.5 second for a 11 move solution. [Answer] # C, 366 - 50% optimal bonus = 183 ``` char c[99],t[3][26]={"ZGONFZCPTEZBHUMZ","ZIQPHZRUGAZJWOCZ","ZACB@ZJHFDZKIGEZ"};r=20;f(int m,int n){int e,i,j;for(i=4;i--;){for(j=15;j--;)c[t[n][j+1]]=c[t[n][j]];c[m]="FRU"[n],c[m+1]="4'2 "[i],c[m+2]=0;for(e=0,j=68;j<76;j++) e+= (c[j]!=c[j+8]) + (c[j]!=c[j^1]);i&&e&&e<45-m*2&m<r?f(m+2,(n+1)%3),f(m+2,(n+2)%3):e||(puts(c),r=m);}}main(){scanf("%s",c+64);f(0,2),f(0,1),f(0,0);} ``` **Using recursion, the program searches** through a tree of up to 11 moves deep (the max length of an optimal soluton according to <http://en.wikipedia.org/wiki/Pocket_Cube> and the page mentioned below) and when it finds a solution it prints it (up to 22 characters long, tracked by function argument `m`.) The order used is a kind of dictionary order, where all routes begining U,U2,U' are searched before any routes beginning R or F are searched. Thus it does not necessarily find the optimal solution first. When a solution is printed, `r` is made equal to `m` which ensures that only equal or shorter solutions will be printed afterwards. Putting `r=m-2` costs an extra 2 characters but ensures only one solution of each length found (down to optimal) is printed. If you want it to ONLY show the optimal solution, the best solution found so far must be stored to a variable, and the optimal solution printed at the end of the program (this would cost about an extra 15 characters.) the input is read into the array `c[]` from index 64 onwards. This is necessary in order to use alphabet characters in the movetable. The symbols `@` through `W` are used instead of A through X per the question, because it is necessary to start on an even number to make the test for solutions work. `c['Z']` is also used for temporary storage, because in order to perform 4-fold rotation a total of 5 assignments are needed. Because the first part of `c[]` is unused, it is available to store the solution (which is terminated with a zero byte, like all C strings.) `for(i..)` goes through a sequence of 4 quarterturns of the face specified by `n`. The first `for(j..)` performs the actual swapping according to table `t[]`. To test if the cube is solved, **it is only necessary to check the four side faces.** The pieces URF and DFR can be distinguised even with the U and D stickers removed, because one piece reads XRF in the clockwise direction and the other XFR. If the two pieces are interchanged so that U shows on the down face and vice versa, the F colour will show on the right face and vice versa. The second `for(j..)` counts the number of mismatches on the four side faces. For example for the front face it compares G & O, H & P, and G & H (twice.) If `e`==0, the cube is solved. If `e`<9 or `e`<13, it might be possible to solve the cube in the next one move or 2 moves respectively. Otherwise it definitely not possible to solve the cube in this number of moves. In order to save time, **this heuristic is used to prune the search tree** and avoid wasting time on many of those branches of depth 10 or 11 which will be unsuccesful. Expressed as a formula, this becomes `e<45-m*2`. **Ungolfed Code** ``` char c[99],t[3][26]={"ZGONFZCPTEZBHUMZ","ZIQPHZRUGAZJWOCZ","ZACB@ZJHFDZKIGEZ"}; r=20; //All moves are output as 2 characters. The index of the last move of the longest solution (11 moves) shall be 20. f(int m,int n){ //perform a cycle through four 1/4 turns of the face specified in n. The index of the move reported in the solution is m. int e,i,j; //e is for counting mismatches. i loops through the four 1/4 turns. j performs other functions. for(i=4;i--;){ for(j=15;j--;)c[t[n][j+1]]=c[t[n][j]]; //A 1/4 turn is performed as three 4-sticker rotations of the type z=a;a=b;b=c;c=d;d=z using the data in the movetable t[][] c[m]="FRU"[n],c[m+1]="4'2 "[i],c[m+2]=0; //Write to the output in c[] the face to be turned and the number of 1/4 turns. Terminate with a zero byte to overwrite any longer solution that may have been found before. for(e=0,j=68;j<76;j++)e+=(c[j]!=c[j+8])+(c[j]!=c[j^1]); //Compare each sticker of the top row of the side faces (64+4 through 64+11) with the stickers below and beside it. Count the number of mismatches. i && e && e<45-m*2 & m<r? //if the number of 1/4turns is not 4 AND the cube is not solved AND the heuristic (as described in the text) is good AND a shorter solution has not already been found, f(m+2,(n+1)%3), f(m+2,(n+2)%3): //deepen the search to another faceturn of the other two faces. e||(puts(c),r=m); //otherwise, if a solution has been found, print the solution and reduce the value of r to the new max solution length. } } main(){ scanf("%s",c+64); //scan in the current cube state to c[] at index 64. f(0,2),f(0,1),f(0,0); //call f() three times to search for solutions beginning with U R and F. } ``` **Performance** The program was tested with patterns 1 to 13 at <http://www.jaapsch.net/puzzles/cube2.htm> Results as follows give the timing on my machine to find ALL optimal solutions (for the curious-minded.) Also for the more complex positions, the timing is given for the 2-byte modification mentioned above which finds just one optimal solution. For this timings are given both to find the first solution and for the program to terminate. The solutions given (which are generally different to the solutions obtained by reversing the generators on the linked page) have been verified with an online cube simulator. ``` U 4 (1 move) horizontal flags (not mirror symmetric) 1 solution 1 sec U2 (1 move) 4 horizontal flags (mirror symmetric) 1 solution 1 sec F2 R2 F2 (3 moves) 4 vertical flags UUUULRBFRLFBLRBFRLFBDDDD 2 solutions 1 sec U2 F2 R2 U2 (4 moves) Supertwist; 6 flags DDUURRBFRRFBLLBFLLFBUUDD 3 solutions 1 sec U F2 U2 R2 U (5 moves) 4 vertical flags, 2 checkerboards UDDULBRFRFLBLBRFRFLBUDDU 2 solutions 1 sec R2 F2 R2 U2 (4 moves) 4 checkerboards UUUURLFBLRBFLRBFRLFBDDDD 4 solutions 1 sec R U2 R' F2 R U' R2 U F2 U' (10 moves) Cube in cube FFFUDDRFRULLLDRRUULBBBDB 18 solutions 26 sec; 1 solution U F2U'R2U R'F2R U2R' 1,13 sec R F U' R2 U F' R U F2 R2 (10 moves) Cube in cube 2 DDDUFFLFRBRRLFLLBBRBUUDU 8 solutions 28 sec; 1 solution R F U'R2U F'R U F2R2 12,21 sec U R F2 U R F2 R U F' R (10 moves)3-Cycle UFFULDRFRULBLLFRURBBDBDD 45 solutions 26 sec; 1 solution U R'F U'F'R'F2U R F2 8,14 sec U R U' R2 U' R' F' U F2 R F' (11 moves) Column turn UUUDLLFRFRBBLLFRFRBBDUDD many solutions 29 sec; 1 solution U R U'F U2R F'R'F'U2F' 3,27 sec F' U R' F2 U' R F U R2 U R' (11 moves)Corner swap UUUURLFBLRBFLLFFRRBBDDDD 29 sec 24 solutions; 1 solution R U'F R U'R2U'F'R'U F2 12,28 sec U F2 U' (3 moves) Zig-zag UDUDLLFRFFLBLBRRFRBBUUDD 1 solution 1 sec U' F2 U2 R2 U' F2 U2 R2 U' (9 moves) 2 Checkerboards, 4 L DUUDLLFBRRBFLRFFRLBBUDDU 8 solutions 13 sec; 1 solution U F2U2R2U R2U2F2U' 1,5 sec ``` ]
[Question] [ ## Background For the purposes of this challenge, we'll define a "perfect nontransitive set" to be a set \$A\$ with some [irreflexive](https://en.wikipedia.org/wiki/Irreflexive_relation), [antisymmetric](https://en.wikipedia.org/wiki/Antisymmetric_relation) relation \$<\$, such that for all \$a \in A\$ we have that \$|\{x \in A|x<a\}|=|\{x \in A|x>a\}|\$. Okay, now in layperson's terms: \$A\$ is a set of elements with no duplicates. \$<\$ is a comparison on the elements of \$A\$ which is true in exactly one direction unless comparing two equal elements (in which case it is false both ways). For every element \$a\$ of \$A\$ there must be an equal number of elements in \$A\$ greater than and less than \$a\$ (neither of these lists include \$a\$ itself). ## The Challenge Given an input \$n\$ your job is to output one (or many) perfect nontransitive set(s) of size \$n\$ where the elements are tuples of 3 integers. You may assume that \$n>0\$ will be odd. The comparison operation you must use is "majority rules", so in comparing two tuples we'll compare them element-wise and whichever there's more of "less-thans" or "greater-thans" will determine the overall result. All pairs of elements in your set must be comparable, that is, one must be "less than" the other. Note that while this allows you to have tuples where some elements are equal, it will likely be easier to exclude such pairs. Here are some more worked out example comparisons for reference: ``` 0<1 0<1 1>0 -> (0, 0, 1) < (1, 1, 0) 1>0 3>2 5<99 -> (1, 3, 5) > (0, 2, 99) 0<1 1=1 1=1 -> (0, 1, 1) < (1, 1, 1) 1<2 2<3 3>1 -> (1, 2, 3) < (2, 3, 1) ``` And some examples of ambiguous tuples that are not valid comparisons (and so should not coexist in the same set) ``` 1=1 1>0 1<2 -> (1, 1, 1) ? (1, 0, 2) 1>0 3=3 5<99 -> (1, 3, 5) ? (0, 3, 99) ``` Standard i/o rules apply, your output may be in any format so long as it's clear what the tuples are. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. ## Test Cases Some possible valid outputs. ``` 1 -> (0, 0, 0) 3 -> (1, 2, 3) (2, 3, 1) (3, 1, 2) 5 -> (0, 3, 3) (1, 4, 1) (2, 0, 4) (3, 1, 2) (4, 2, 0) ``` Invalid outputs with the reason they are invalid ``` 3 -> (0, 0, 0) # this contains ambiguous tuple comparisons (-1, 0, 1) (-2, 0, 2) 5 -> (0, 3, 1) # the first element here is less than 3 others but only greater than 1 (1, 4, 3) (2, 0, 4) (3, 1, 2) (4, 2, 0) ``` [Answer] # JavaScript (ES6), 50 bytes -5 bytes by porting the formulas used in [G B's answer](https://codegolf.stackexchange.com/a/254578/58563), as suggested by G B. ``` n=>[...Array(i=n)].map(_=>[i+=n+~n/2,-i-(i%=n),i]) ``` [Try it online!](https://tio.run/##ZU9LTsMwEN33FLOhsZXENJXYUBzEgg0SsOiyipDrOolpmESOG6lC5QRIbFjCPThPL8ARgpOAskAeeT7vzZuZR9GIWhpd2RDLjWpT3iKPV4yxK2PEnmiONGFPoiIPrqx9jv4Lns6DUIdEnzgw0Alt09IQBA7RAhAunD/rAp/DnMLzBMCo2qEpQbpwmSyxLgvFijIjyGy5tEZjRiirxGZphbHEtfnguefDzfL@jtU9Q6d74pRGjMhcye1QuwTv@@vt@PHufg/OwTt@vnrUzTtMJukOpdUlwsAXf0vZnUEQTDXK7MkaeNzXAQplodZZd9EKZkFvkCx6TDB37LWQOZFjA/T01a2wOesismZGbXZSEVIF0ASwpR25cjuPnAZCkKttQp067Y6KEt8fhhzo4H9X7MVnCXDuxhcKM5tDHEME0@mART025vP/3E6wkz20Pw "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 55 bytes *-1 thanks to [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)* Returns one perfect non-transitive set, built in a specific way. ``` n=>[...Array(i=n)].map(_=>[i,(i+~n/2)%n,(4*n-i-++i)%n]) ``` [Try it online!](https://tio.run/##ZU9LTsMwEN33FLOhsXFimgo2FAexYIMELLqMIuS6TmIanMhxI1WonACJDUu4B@fpBThCcBJQFsgjz@e9eTPzyBteC6MqG@hyLduUtZpFMaX0yhi@Q4ppnNAnXqEHV1Y@UuRFn8zxkfbR6bEOVECIclmC27Q0SAODcAEaLpw/6wLCYI7heQJgZO3QFGm8cJkodV0WkhZlhjS15dIapTOEacXXS8uNRa6NgOcegZvl/R2te4ZKd8gpjRgSuRSboXYJ3vfX2@Hj3f0enIN3@Hz1sJu3n0zSrRZWlRoGPv9bym6NBk5lI80OrYBFfR2gkBZqlXUXxTDze4Nk0WOcumOvuciRGBugp8e33Oa0i9CKGrneColQ5UPjwwZ35MrtPHIaCEDEmwQ7ddwdFSaEDEP2ePC/K/biswQYc@MLqTObQxRBCNPpgIU9Nubz/9xOsJPdtz8 "JavaScript (Node.js) – Try It Online") ### How? The tuples are built as follows: * First entry: \$n\$ to \$2n-1\$. It would be more obvious to use \$0\$ to \$n-1\$, but it's golfier that way. * Second entry: \$\lfloor n/2\rfloor\$ to \$n-1\$, then \$0\$ to \$\lfloor n/2\rfloor-1\$. * Third entry: \$n-1\$, \$n-3\$, ..., \$0\$, \$n-2\$, \$n-4\$, ..., \$1\$. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly) ``` rCm2ĖṠÞĖF€%o ``` A monadic Link that accepts an odd, positive integer and yields a list of triples. **[Try it online!](https://tio.run/##AR4A4f9qZWxsef//ckNtMsSW4bmgw57Elkbigqwlb////zU "Jelly – Try It Online")** Or see a [check of the first 21](https://tio.run/##y0rNyan8/7/IOdfoyLSHOxccnndkmtujpjWq@f8Pt8cf3pcAFDu0HEgc6T68z1BH9@GOJY8aZtg@atxxYtnD3d2PGuaEJeZkpgBpz7wyCGsuV1Cu0dFJD3fO0DncfqwLaJj7//8mRgA "Jelly – Try It Online") (checks that there are exactly \$\frac{n-1}{2}\$ others that are greater and exactly \$\frac{n-1}{2}\$ that are less for each triple in the result.). ### How? ``` rCm2ĖṠÞĖF€%o - Link: (odd, positive) integer, n C - complement (n) -> 1-n r - (n) inclusive range (that) -> [n,n-1,n-2,...,1,0,-1,...,3-n,2-n,1-n] m2 - modulo two slice -> [n, n-2,...,1, -1,...,3-n, 1-n] Ė - enumerate -> [[1,n],[2,n-2],...,[(n+1)/2,1],[(n+3)/2,-1],...,[n-1,3-n],[n,1-n]] Þ - sort by: Ṡ - sign (vectorises) ...rotates that list left by (n+1)/2 such that the [(n+3)/2,-1] entry is first Ė - enumerate F€ - flatten each % - modulo (n) (vectorises) o - logical OR (n) (vectorises) ...replaces zeros with n. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` NθI﹪Eθ⟦ι⁺ι⊘⊕θ±⊗⊕ι⟧θ ``` [Try it online!](https://tio.run/##XcqhDoMwEIBhv6eovCadQCM3MQQEv0wc5bI1OVparrz@rbNT/y8@/8HiE7LqEPcqU90WKpBtf5lLiAI3PATGtFZOMOIO2ZlncGbmekDrA/mkFYboC20UpX221joz0RuF4J7qwn8gNPBq5Ad71a7T68lf "Charcoal – Try It Online") Link is to verbose version of code. Outputs the triples @JonathanAllan's answer does (except decremented because Charcoal is 0-indexed), but using a different approach to generating the triples. Explanation: ``` Nθ Input `n` as an integer θ Input `n` E Map over implicit range ⟦ List of ι Current index θ Input `n` ⊕ Incremented ⊘ Halved ⁺ Plus ι Current index ι Current index ⊕ Incremented ⊗ Doubled ± Negated ⟧ End of list ﹪ Vectorised modulo by θ Input `n` I Cast to string Implicitly print ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~43 ...~~ 37 bytes ``` ->n{(1..x=n).map{[x+=n/2,-x-x%=n,x]}} ``` [Try it online!](https://tio.run/##PY6xDoJAEER7vsLG5IjcKmeMoVh@ZLOFGqFyJSeEI@x9@wmS2MzLFPMyfrhPqcFka5lNCRBQcnjdupnCAeXoChts2KMUgWNM3a6hC2crzhuuG0rOshZXifzWOqoRSyPn8HgP0s86qTkBuH/3OpLneloiIroY4yIq4dM/O1NVhdteqGhLDQmzEsf0BQ "Ruby – Try It Online") ### How? I wish you didn't ask. Just trial and error. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) -5 bytes porting [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/254470/52210) (which in turn is based on [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/254462/52210) - so make sure to upvote both of them as well). ``` Lε<DI>;+y·()I% ``` [Try it online](https://tio.run/##yy9OTMpM/f/f59xWGxdPO2vtykPbNTQ9Vf8fXv/fGAA) or [verify all odd inputs up to 15](https://tio.run/##yy9OTMpM/W9oerj1cGdZpb2SwqO2SQpK9pUuof99zm21cYmws9auPLRdQzNC9X/t4fU6/wE). **Explanation:** ``` L # Push a list in the range [1, (implicit) input-integer] ε # Map over each integer `y`: < # Decrease the integer to make it 0-based D # Duplicate it I> # Push the input+1 ; # Halve it + # Add it to the `y-1` y # Push `y` again · # Double it ( # Negate it ) # Wrap all three values on the stack into a list I% # Modulo each by the input # (after which the list of triplets is output implicitly as result) ``` **Original 19 (18†) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) brute-force approach:** ``` Ý3ãIã.ΔDδ.SOεD_«O}P ``` Very slow and will already time out for \$n\geq5\$.. [Try it online.](https://tio.run/##ASUA2v9vc2FiaWX//8OdM8OjScOjLs6URM60LlNPzrVEX8KrT31Q//8z) or [verify 1 and 3..](https://tio.run/##ATcAyP9vc2FiaWX/NcOFw4l2eT8iIOKGkiAiP3n/w50zw6N5w6MuzpREzrQuU0/OtURfwqtPfVD/fSz/). † If we're allowed to output all possible results for a certain range (e.g. all valid results using integers in the range \$[0,n]\$), it could be 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) less by changing the `.Δ` (find\_first) to `ʒ` (filter), although it'll then become even slower and already times out for \$n=3\$.. [try it online](https://tio.run/##ASQA2/9vc2FiaWX//8OdM8OjScOjypJEzrQuU0/OtURfwqtPfVD//zM). **Explanation:** ``` Ý # Push a list in the range [0, (implicit) input] 3ã # Get a list of all triplets using these values Iã # Get all input-sized lists using these triplets .Δ # Find the first list of triplets which is truthy for: D # Duplicate the current list of triplets δ # Apply double-vectorized: .S # Vectorize-compare the triplets # (e.g. [a,b,c] and [d,e,f] → [C(a,d),C(b,e),C(c,f)], where C(A,B) is a # compare resulting in -1 if A<B; 0 if A==B; and 1 if A>B) O # Get the sum of each inner-most triplet comparison ε # Map over each inner list: D # Duplicate the list _ # Check which values are equal to 0 (1 if 0; 0 otherwise) « # Merge the two lists together O # Sum the list }P # After the map: take the product of this list of sums # (only 1 is truthy in 05AB1E, so I basically check for each triplet- # comparison [x,y,z] whether x+y+z+(x==0)+(y==0)+(z==0)==1 - meaning there # is exactly one 0 and an equal amount of 1s and -1s) # (after which the result is output implicitly) ``` [See here for a step-by-step output.](https://tio.run/##XZHBahsxFEX3/orHbNKCZ0gTsikYU2xaDG0TcLIKpSgzLx5RWU/oSQ4JBPoR3XZl6KLdZNHkA@y9P6I/MpU0SiAZZjW6517dO8TiQmLXFTNtvHsLxXC0eRgPignpFVoH0oEjEHC@P5RR8aW0Qi@wASU5ybc/e@ADOhBKgSFmeaEQnJVGoWPwLPUCXIuMsBLKI0fucLt@Dib7kuVNNn8OPrm9Iq2uwVipXT6FS2nZwcHR6@g7266nB0eb9b/vv6qq2vweppC5E6GMIjIRolAtkJJTEPhgpeAK91bBi7xuQt9wUdmARfYq1ax2PwYFTLy1qF2PhV2SSjhMQ9yN@0IwoaURFqEhH4YoV1g7srFXlk13f6t51sb2sQP7JdAloKjbx65QJx/JpDN4nKFPaBeYsHSRK@na3kQs86elMCbsKBhGo32oW6y/cTbZ3U@/bv7cZqt5yE2hIdy1xD3PLwIfb2ksNb52QxBhJHZkgHSN/ZThfZOxk4yVT08Rf8PtoHg/@/zuIxyfnZ6cnUbxuOsOu7LUVCpxc/0f) ]
[Question] [ The point of this challenge is to find the smallest positive integer that uses up *at least* all of the digits supplied in the input after it is squared and cubed. So, when provided an input such as `0123456789` (i.e. a number that finds the result): ``` 69² = 4761 69³ = 328509 ``` It means that `69` is the result of such an input. (Fun fact: 69 is the smallest number that uses up all of the decimal digits of 0 to 9 after squaring and cubing.) ## Specification The input doesn't have to be unique. For example, the input can be `1466` and here's the result: ``` 4² = 16 4³ = 64 ``` That means we can't just fulfill this input by just doing a number that only uses 1 digit of `6`, it has to have 2 digits of 6 in the output. ## Test cases Here's an [exhaustive list](https://pastebin.com/6f7PGC2W) of all numbers from 1 to 10000. ``` 1333 (or 3133/3313/3331) -> 111 ``` ## Input specification * You may take input as a list of digits. * Since the test cases (somehow) have a bug in it, here's an extra rule: the `0`'s in the input will be ignored. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~12~~ 13 bytes *-2 bytes thanks to @KevinCruijssen* *+1 byte thanks to @Grimmy* ``` ∞.Δ23SmJœIÅ?Z ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTjIyDc72OTvY83Gof9f@/oZmZiSUA "05AB1E – Try It Online") --- ### Explanation ``` ∞.Δ - First number that... 23Sm - Power of 2 and 3 [n^2, n^3] J - Concatenated œ - Permutations of this number IÅ?Z - any of these start with the number ``` By the way it's quite slow... [Answer] # [Python 3](https://docs.python.org/3/), 78 bytes ``` f=lambda s,n=1:n*all(f'{n*n}{n**3}'.count(i)>=s.count(i)for i in s)or f(s,n+1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRoVgnz9bQKk8rMSdHI029Ok8rrxZIaBnXqusl55fmlWhkatrZFsPZaflFCpkKmXkKxZpAVpoGULu2oeb/gqJMoHSahrqBoZGxiamZuYWluqYmF1zY0MTMDFXA2NgYKPAfAA "Python 3 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-æ`](https://codegolf.meta.stackexchange.com/a/14339/), ~~17~~ ~~16~~ ~~15~~ ~~14~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ~~*Still* very not happy with this!~~ ~~A little happier!~~ *Now* I'm happy! Takes input as an integer. ``` ²+U³s)á dèN ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LeY&code=sitVs3Mp4SBk6E4&input=Mzg) ``` ²+U³s)á dèN :Implicit map of each U in the range [0,input) ² :U squared + :Concatenate U³ : U cubed s : Converted to a string (preventing the + from adding the 2 numbers) ) :End concatenate á :All permutations d :Any truthy (not 0) when è : Counting the occurrences of N : The array of inputs, which is implicitly cast to a string :Implicit output of first U to return true ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~82~~ \$\cdots\$~~78~~ 77 bytes Added 2 bytes to fix an error kindly pointed out by [S.S. Anne](https://codegolf.stackexchange.com/users/89298/s-s-anne). Switched to Python 2 thanks to [Grimmy](https://codegolf.stackexchange.com/users/6484/grimmy). Saved a byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` f=lambda s,i=1:i*all((`i*i`+`i**3`).count(c)/s.count(c)for c in s)or f(s,i+1) ``` [Try it online!](https://tio.run/##PY3NDoIwEITvPMWmpxbqTymiktSjT@DNmFChxCZYSFsTjfHZcfHgZTPf7M7s@Iq3weXT1Kle36@thsCtEpVNdd9TWtvU1hnOVNZs2QwPF2nDVuEvu8FDA9ZBYKg6iulMsMmr91H3wVTEDRF0IBxO/oGI8pPMocDNHKMJJaIoSzwoGJ9BSokghPjhWuSy2JTb3R7Nco8eqxLQCj@xBEZvXcQqsjjgWnPwZ62UuXAg5jmaJpqWTF8 "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` 1*2,3DFœ&Ƒ@ʋ1# ``` [Try it online!](https://tio.run/##y0rNyan8/99Qy0jH2MXt6GS1YxMdTnUbKv@3ftQwR0HXTuFRw1zrw@1ch9sfNa2J/P8/2lDHRMdMxyxWJ9pAx1AHqAvINwWKmOtY6FgCRQ2BIkAYCwA "Jelly – Try It Online") A monadic link taking a list of digits and returning an integer in a single element list. ``` 1 ʋ1# | Start with 1 and find the first integer where the following is true, using the input digit list as the right argument: *2,3 | - To the power of 2 and 3 D | - Convert to lists of decimal digits F | - Flatten œ&Ƒ@ | - Check whether the inout digit list is invariant when intersected with this list of digits ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 89 bytes ``` 1//.t_/;ContainsNone[Subsets[Join@@IntegerDigits[t^{2,3}],Length@#],Permutations@#]:>t+1& ``` [Try it online!](https://tio.run/##RcyxCsIwEIDh3acQBBcPQ6x0UJSALopIwbFUSeVIb8gFkutU@uwxm@P/Db@3MqC3Ql@b3SlrpbbyUcdLYLHE6RkY29fYJ5TU3gOxMTcWdBiv5KiYvKcdVHMHD2Qng1l10GD0o5Rl4FT6cJaNXucmEsvSODNp2EMN9bz4UwUaqrLJ@Qc "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES7), ~~77~~ 72 bytes Takes input as a list of digits. ``` f=(a,k)=>([...[k*k]+k**3].sort()+'').match(a.sort().join`.*`)?k:f(a,-~k) ``` [Try it online!](https://tio.run/##bctBCsIwEIXhvRdpJk0HpFqwUD1ICDTERtupGWmCS68eW3Cn/Lv38Sb7stEt4zNVga9Dzr4TVhF0Z6ERUZMkU5KUtcHISxJQFgXgwyZ3F/Y74cRj6FH2cKHWr/fqTZAdh8jzgDPfhBd6rw6qUY0B2P1IvfVHTmrruEr@AA "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: a, // a[] = input k // k = counter, initially undefined ) => // ( [...[k * k] + k ** 3] // concatenate k² and k³ and split the resulting string .sort() // sort from lowest to highest digit + '' // coerce back to a string (this puts commas between the // digits, but they are harmless) ).match( // test whether it matches: a.sort() // the input list sorted the same way .join`.*` // joined with .* patterns, so that unused digits and // commas are ignored ) ? // if it does: k // stop recursion and return k : // else: f(a, -~k) // try again with k + 1 ``` [Answer] # [R](https://www.r-project.org/), ~~142~~ ~~134~~ 121 bytes ``` i=1;x=table(scan());l=function(t)x>table(strsplit(paste0(t^2,t^3),"")[[1]])[names(x)];while(any(l(i),is.na(l(i))))i=i+1;i ``` [Try it online!](https://tio.run/##LYvRCsIwDEV/RfaUYBHrHkv9kdJBHBUDNY4lYv36OsV7Xg4c7to7Rx9aNLrUAjqTAGKo8fqU2fghYNjO/2irLpUNFlIrR7Dp5Gwa0Q0DpuRzxiR0LwoNc3jdeLuQvKECo2M9CP10G0fe@8Dd78Yv/QM "R – Try It Online") # [R](https://www.r-project.org/), ~~152~~ ~~146~~ ~~144~~ 130 bytes (This is only if we have to be wrong like your test cases) ``` i=1;x=scan();x=table(x[x>0]);l=function(t)x>table(strsplit(paste0(t^2,t^3),"")[[1]])[names(x)];while(any(l(i),is.na(l(i))))i=i+1;i ``` [Try it online!](https://tio.run/##JYtBCsIwEAC/Ij3tYpFEvYX0IyGFWCIuxLV0txhfH4POaWCYrTXy1lUvS2LALppuJUMNdTIRXfH3nRelF4Ninf5RdJO1kMKaRLMBnc@jzhcchwFDsDFi4PTMAhWjez@oL4k/UIBwJDlx@mmHPB2to3Y9mPYF "R – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 67 bytes Uses Arnauld's regex. Takes a list of digits. If that isn't allowed, add 6 bytes to change `d.sort` to `d.chars.sort`. ``` ->d,i=0{i+=1until"#{i*i}#{i**3}".chars.sort*''=~/#{d.sort*'.*'}/;i} ``` [Try it online!](https://tio.run/##LcvdCoIwGIDh813F0Gi1av7M/lk3UiKWmh@oE7cRIevWV4EnL7wHz2Dub1eJm9tcijWIcISViEynofH8ESjYfym3HnvU@aCYkoOmhIhP4I/FdIwSG5zBulcNTYmfpVYI495ohavrLPtJ2faTb/N@MT9pmcEyRWVXuDCKebLd7Q9HFHHOURKHXw "Ruby – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 28 bytes ``` r0{{2 3}?^im}]mj{j\\z?}j+]fi ``` [Try it online!](https://tio.run/##TZBLDoIwFEXnroK5k36gr2/kDlwBODDBBAImQoiJDVMX4BLdSO2HyO3o9Obdnpdel2lo58fS@uHunFjnp5@Ec6rQ6@nSjWsz9q6v69dp7Y/NrfMhWM6e2Yji@/4UUh8CS2AFrBMrilwmNimvgM02z/FCULZQ5sRaBiYQE4gJxARiyuIy5VmsExuYJ5gBL4HXbt6YWwmsgDVwCQxea/b3LQFnrxTxI2wWc2QW@xIsgRVwFnN8iLPYpm61LRHNbKBAwBZkf7EU4eT2Dw "Burlesque – Try It Online") ``` r0 # Range from [0,inf] { {2 3}?^ # {squared, cubed} im # Concatenate }]m # Map over each and parse to string j # Swap stack { j # Swap \\ # List difference z? # Is null } j+] # Prepend input to make {input j \\ z?} fi # Find index s.t. ``` [Answer] # [Perl 5](https://www.perl.org/) `-pF`, 70 bytes ``` $p=join'.*',sort@F;1while(join'',sort((++$\**2 .$\**3)=~/./g))!~/$p/}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lwDYrPzNPXU9LXac4v6jEwc3asDwjMydVAywMEdTQ0NZWidHSMlLQA1HGmrZ1@nr66ZqainX6KgX6tdX//xsaGxv/yy8oyczPK/6v62uqZ2Bo8F@3wA0A "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` ≔⁰ηWΦχ›№θIκ№⁺IXη³×ηηIκ≦⊕ηIη ``` [Try it online!](https://tio.run/##LY3BDsIgEETvfgXHJcHEhmNPponGgwkHf4DgRogULFD7@bhg9zT7dmbHWJ1M1L7Wc87uFeAkmOXjYbPOI4OL8wUTDESvCXXTU1xDgUWwSecCb85JdaT8mqFDFTcyWsFkuz7cjLlttnv3FA2768/eegsm4Yyh4PPfr5Kjl91MsbHWQUpZj1//Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁰η ``` Start at zero. ``` WΦχ ``` Repeat until none of the 10 digits satisfies... ``` ›№θIκ№⁺IXη³×ηηIκ ``` ... the count of that digit in the input is greater than the count in the cube and the square... ``` ≦⊕η ``` ... increment the result. ``` Iη ``` Output the result. [Answer] # [Haskell](https://www.haskell.org/), 62 bytes ``` import Data.List f l=[n|n<-[0..],[]==l\\(show=<<[n^2,n^3])]!!0 ``` [Try it online!](https://tio.run/##FcUxDsIgFADQ3VP8EgdNkEBpURPYHL0BpQmDTYnwSwqJi3fH@Ja3@vJ@xdhaSHnbKzx89ewZSj0sEI3FL@qL5Yw5ap0xcZpOZd0@RmuLc09xlu7suo635AOCgbwHrHCE5DMsYImQUhIKRAxK/eeil8Oorrc7ce0H "Haskell – Try It Online") Even with the import, Haskell's list difference function `\\` is quite powerful. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~93~~ 92 bytes -1 Byte thanks to ceilingcat ``` D;I;C(N){N=N?C(N/10)+(N%10==D):0;}F(N){for(D=I=0;D<10;C(N)>C(I*I)+C(I*I*I)?D=!++I:++D);I=I;} ``` [Try it online!](https://tio.run/##XcuxDoIwEAbgnaeoJCQ9q7G1WIVaGWhIuvQJWAwEwyAYYlwIz14Lk3jL/fnvu2r/qCrntDQyxxZGq2zmw4FRINhGjCqlIaVyKuZr0w9YK6Oo1FdGl49bjs3WAFmWD5lWG0JMSogGaZSRk2u7N3re2w5/@raGYAyQn9fg6waHIkEpiuqyC3eowOzI45M4XxIKIFcuRisXC/EvGGO/gnM@i8l9AQ "C (gcc) – Try It Online") ungolfed: ``` int D; int I; int CNT(N) // count occurrences of digit D in number N { if (N) return CNT(N / 10) + (N % 10 == D); return 0; } int F(N) { for (D = I = 0; D < 10; ++I) { for (D = 0; D < 10; ++D) if (CNT(N) > CNT(I * I) + CNT(I * I * I)) break; } return I-1; } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 134 bytes ``` s,c,i,m;f(n){for(c=s=i=m=1;m;c=(s=++i*i)*i){int a[10]={};for(;c;s/=10)a[c%10]++,s&&a[s%10]++,c/=10;for(m=n;m*a[m%10]--;m/=10);}n=--i;} ``` [Try it online!](https://tio.run/##dYxBCoMwEEX3nkIEJTEJ1cbalmFOYrsII5YsEosp3Yhnt0a6dZjN/Pfmk3oRrWuQJK10MDDP52GcGGFAiw5rcEDIAgphS8u3na3/pKarqyfOC0QXCMIJ64qbjvItF0KGojBd@B8U4W469OBK07lIlAK3v8HiUSkLyxqrnbGefUfb82RO0m3e0xYPLMv7h89kOrD6rJtLe73dK87hQGna9hhqrSNc1h8 "C (gcc) – Try It Online") Ungolfed and with better variable names: ``` int square, cube, result, input_copy; int f(int input) { for(cube = square = result = input_copy = 1; input_copy; cube = (square = ++result * result) * result) { int digits[10] = { }; for(; cube; square /= 10) { digits[cube % 10]++; if(square) digits[square % 10]++; cube /= 10; } for(input_copy = input; input_copy && digits[input_copy % 10]--; input_copy /= 10); } return result-1; } ``` ]
[Question] [ ## Introduction *(may be ignored)* Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers. This is the third challenge in this series (links to the [first](https://codegolf.stackexchange.com/questions/181268) and [second](https://codegolf.stackexchange.com/questions/181825/) challenges). In this challenge, we will arrange the natural numbers in rows of increasing length in such a way that the sum of each row is a prime. What I find really amazing about this, is that every natural number has a place in this arrangement. No numbers are skipped! This visualisation of this arrangement looks like this: ``` row numbers sum 1 1 1 2 2 3 5 3 4 5 8 17 4 6 7 9 15 37 5 10 11 12 13 21 67 6 14 16 17 18 19 23 107 etc. ``` We can read the elements from the rows in this triangle. The first 20 elements are: 1, 2, 3, 4, [***5, 8, 6***](https://www.youtube.com/watch?v=wXl3Qej1tjM), 7, 9, 15, 10, 11, 12, 13, 21, 14, 16, 17, 18, 19 (*yes, there is a New Order song hidden in this sequence*). Since this is a "pure sequence" challenge, the task is to output \$a(n)\$ for a given \$n\$ as input, where \$a(n)\$ is [A162371](http://oeis.org/A162371). ## Task Given an integer input \$n\$, output \$a(n)\$ in integer format. \$a(n)\$ is defined as the \$n\$th element of the lexicographically earliest permutation of the natural numbers such that, when seen as a triangle read by rows, for n>1 the sums of rows are prime numbers. Since the first lexicographical permutation of natural numbers starts with 1, \$a(1)\$ is 1. Note that by this definition \$a(1) = 1\$ and \$a(1)\$ is ***not*** required to be prime. This is OEIS sequence [A162371](https://oeis.org/A162371). *Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 2\$, etc. Please mention this in your answer if you choose to use this.* ## Test cases ``` Input | Output --------------- 1 | 1 5 | 5 20 | 19 50 | 50 78 | 87 123 | 123 1234 | 1233 3000 | 3000 9999 | 9999 29890 | 29913 ``` ## Rules * Input and output are integers (your program should at least support input and output in the range of 1 up to 32767) * Invalid input (0, floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour. * Default [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply. * [Default 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 the shortest answers in bytes wins [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;®»ṀƊSÆn_S ẎṀ©+LRḟẎḣL;Ç$ṭ 1Ç¡Fị@ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/60LpDux/ubDjWFXy4LS8@mOvhrj4g99BKbZ@ghzvmg3g7FvtYH25XebhzLZfh4fZDC90e7u52@P//v7kFAA "Jelly – Try It Online")** - very slow as it builds n rows first, for a faster version which doesn't, at 37 bytes, [try this](https://tio.run/##y0rNyan8/9/60LpDux/ubDjWFXy4LS8@mOvhrj4g99BKbZ@ghzvmg3g7FvtYH25XebhzLZfh4XY3H5tDm49tOrTf7eHubof///8bWVpYGgAA "Jelly – Try It Online"). [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~80~~ 77 bytes ``` {({$!=@_;+(1...{$_∉$!&&(|$!,$_).rotor(1..*).one.sum.is-prime-1})}...*)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1qjWkXR1iHeWlvDUE9Pr1ol/lFHp4qimppGjYqijkq8pl5Rfkl@EUhSS1MvPy9Vr7g0Vy@zWLegKDM3VdewVrNWDyQVrRIfW/u/OLFSIU0jztDAQNP6PwA "Perl 6 – Try It Online") ### Explanation: ``` { } # Anonymous code block ( ...*)[$_] # Index into the infinite sequence { } # Where each element is $!=@_; # Save the list of previous elements into $! +(1...{ }) # Return the first number that $_∉$! # Has not appeared in the list so far && # And (|$!,$_) # The new sequence .rotor(1..*) # Split into rows of increasing length # And ignoring incomplete rows .one # Have exactly one row .sum # Where the sum .is-prime-1 # Is not prime (i.e. just the first row) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~122~~ 120 bytes ``` import Data.Numbers.Primes l%a|(p,q)<-splitAt l a,(s,k:t)<-span(not.isPrime.(+sum p))q=p++k:(l+1)%(s++t) ((1:1%[2..])!!) ``` [Try it online!](https://tio.run/##HYtBC4IwGIbv/YoJCd/Y59i0KEUPQdeiu0gsMBpua7p167@b@cLzHB54XyoMvTHzrK1/T5GcVVT8@rGPfgr8Nmnbh41J1Rc8jrTOgjc6niIxRCEEHKq4RuXAvSPXYX1wYOFjiad0bDxjQwWGSZpCYCzSzbMBkJVM25zzjiYJna3SjjTEKn@5Ez9pF0kLLpP43C6mX1dnrcQ95gL3Ag9HlHnxZ4eFEALLZZiXx1J03fwD "Haskell – Try It Online") (has an extra 2 bytes for `f=`) EDIT: Now uses 0-based indexing to save 2 bytes. Thanks @wastl for pointing that out, I must have missed it in the OP. This was very fun to write! The helper function `%` takes a length `l` and a list of values it can use `a`. It returns an infinite list of values for the sequence. The length is one less than the length of the current triangle row and the list is infinite and pre-sorted. First we just yield the first `l` values from `a` and then look through the rest of a until we find the first (smallest) value that makes the sum prime. We break up the list around that value using `span` and some pattern matching. Now all we have to do is yield that new value and recur with the next line length `l+1` and the remaining values in `a`. For the final result we prepend 1 (special case for n=0) and index into it with `!!`. [Answer] # [Husk](https://github.com/barbuz/Husk), 22 bytes ``` !¡§ḟ(ΛoṗΣtü¤≤LCN:)`-Nø ``` [Try it online!](https://tio.run/##AS4A0f9odXNr//8hwqHCp@G4nyjOm2/huZfOo3TDvMKk4omkTENOOilgLU7DuP///zc4 "Husk – Try It Online") I was honestly somewhat surprised that `CN` worked as intended here. Heavily inspired by [Jo King's answer](https://codegolf.stackexchange.com/a/182353/33208). ### Explanation ``` !¡λḟ(ΛoṗΣtü¤≤LCN:⁰)-⁰N)ø (Expanded; let X denote the argument.) ! Take element X of ¡ the list created by repeatedly applying this function to the prior list and appending its output, ø starting with an empty list: -⁰N Take the list of natural numbers not contained in the argument, ḟ and find the first element such that ΛoṗΣ all sums are prime of :⁰ the element appended to the argument, CN cut into lengths of 1, 2, 3, etc., ü¤≤L filtered for increasing length, t with its first element dropped. ``` [Answer] # JavaScript (ES6), ~~111~~ 110 bytes ``` n=>{for(g=n=>{for(d=n;n%--d;);},i=l=0;i--||(k=s=0,i=l++),n--;g[k]=s+=r=k)for(;g[++k]|g(!i*++s)|d>1;);return r} ``` [Try it online!](https://tio.run/##ZcxNDoIwEAXgvafAhUlrrRaQoGmGixgXxkKDkNa06MZydqT@xjqrl/flzelwPdijqc8dVVqUQwWDguJWaYMkvJMAxdWMUsEx7xc1tMB4TalzqAELzDeE4IWilMtdswdLwECD/XQsCGn2TqJpPSfEYieKeHxjyu5iVGT64aiV1W25bLVEFYoxjvytVlE8@aXsS1lACXuaX23D2dcyFli@@dgmDyxO0gf6n0n6j2uvTww1ZYy91MfhDg "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 46 bytes ``` S©‘æR®Ḥ‘¤_®ḟ;F¥Ṃ FLḤRḟFḣ0ịLƊ;祵W 1;Ç$⁸½Ḥ¤¡Fị@ ``` [Try it online!](https://tio.run/##y0rNyan8/z/40MpHDTMOLws6tO7hjiVA5qEl8SDmfGu3Q0sf7mzicvMBigcBBdwe7lhs8HB3t8@xLuvDyw8tPbQ1nMvQ@nC7yqPGHYf2AhUdWnJooRtQgcP///@NDQwMAA "Jelly – Try It Online") Times out for large n on tio, but works there for all but the last two examples. [Answer] # [Lua](https://www.lua.org), ~~242~~ ~~228~~ ~~226~~ 211 bytes ``` s={}u={}i=0 n=0+...while i<n do n=n-i x,S=1,0 for j=1,i do while u[x]do x=x+1 end s[j]=x S=S+x u[x]=0 end while u[x]or p do x=x+1 d=S+x p=F for c=2,d-1 do p=p or d%c<1 end end i=i+1 s[i]=x u[x]=0 end print(s[n]) ``` [Try it online!](https://tio.run/##TY3NCsIwEITv@xS5CEp/SLwJ7tUX6DH0IE3FLWUbGosB8dljNh50YWDZmfl23q4pBXy9tyxCrRh11bbt807zqOjMyi3AyA1BrDs0tYbbsqopbyTWN7fZ2LtFRYyVUSM7CHbqMUKHXRVBXNQg9188Q7wASgdcCXq8FPqAx9o1RmyPXuWL2w1nUwgiQsqdYEl@/NH9SvzYB8v9IaV0yvMB "Lua – Try It Online") ]
[Question] [ In the game of chess, there is piece called the queen that may attack any other piece that is on the same row, column or diagonal. In chess there are typically two sides, black and white, with each piece belonging to one of the teams. Pieces may not attack pieces belong to the same team. Your goal is to find out the largest peaceable coexisting armies for a square board. That is the largest number of black and white queens that can fit on the board such that no two queens can attack each other and the number of black queens is equal to the number of white queens. You will receive as input the side length of a square board, and should output the number of size of the largest peaceable coexisting armies that can fit on that board. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so standard rules for the tag apply. [OEIS A250000](http://oeis.org/A250000) These test cases encompass all known answers. Your solution should be a generalized answer that, given enough computing power and time, can compute the solution for any input value. ``` 1: 0 2: 0 3: 1 4: 2 5: 4 6: 5 7: 7 8: 9 9: 12 10: 14 11: 17 12: 21 13: 24 ``` [Answer] # C, 476 bytes, DFS iterating white queens, O(2n2) ``` #define R return #define Z(q)for(j=q;j<I;j++) #define Q(q)memset(q,0,4*J); #define U(q)S(w[k]/I q j,w[k]%I+j) int*c,*w,*Y,j,k,r,I,J,m;T(i,j){R i*I+j;}S(x,y){x>=0&&x<I&&y>=0&&y<I?Y[T(x,y)]=1:0;}g(l){int i;if(l==m){Q(Y)for(k=m;k--;){Z(0)Y[T(w[k]/I,j)]=Y[T(j,w[k]%I)]=1;Z(-I)U(+),U(-);}for(r=k=J;k--;)r-=Y[k];R r>=m;}for(i=!l?0:w[l-1]+1;i<J;i++){if(!c[i]){c[i]=1;w[l]=i;if(g(l+1))R 1;c[i]=0;}}R 0;}f(s){I=s;J=I*I;int C[J],W[J],y[J];c=C;w=W;Y=y;for(m=1;;m++){Q(c)if(!g(0))R m-1;}} ``` ## 518 bytes, DFS with pruning, O(2n) ``` #define R return #define Z(q)for(j=q;j<I;j++) #define Q(q)memset(q,0,4*J); #define V(Q)t=Q;if(!Y[t]){G-=Y[t]=1;b[B++]=t;} #define F(q)if(S(x q j,y+j)){V((x q j)*I+y+j)} int*c,*w,*Y,j,k,r,I,J,m;S(x,y){R x>=0&&x<I&&y>=0&&y<I;}D(l,H){int i,b[J],B,t,x,y,G;if(l==m)R 1;for(i=!l?0:w[l-1]+1;i<J;i++){if(!c[i]){c[i]=1;w[l]=i;x=i/I;y=i%I;G=H;Z(B=0){V(x*I+j)V(j*I+y)}Z(-I){F(+)F(-)}if(G>=m&&D(l+1,G))R 1;for(j=B;j--;)Y[b[j]]=0;c[i]=0;}}R 0;}f(s){I=s;J=I*I;int C[J],W[J],y[J];c=C;w=W;Y=y;for(m=1;;m++){Q(c)Q(Y)if(!D(0,J))R m-1;}} ``` ## 577 bytes, DFS iterating white and black queens, O(?) ``` #define R return #define U(V,r,q)S(V,r[i]/I q j,r[i]%I+j) #define W(q)for(j=q;j<I;j++) #define Z(r,q,t,v)for(i=0;i<r;i++){t[q[i]]=1;W(0)v[T(q[i]/I,j)]=v[T(j,q[i]%I)]=1;W(-I)U(v,q,+),U(v,q,-);}; #define P(K,L,M)memcpy(v,K,4*J);for(i=0;i<J;i++)if(!v[i]){L[M++]=i;if(g(E,N,!C))R 1;M--;}; int*w,*b,m,I,J;T(i,j){R i*I+j;}Q(int*q){memset(q,0,4*J);}S(V,x,y)int*V;{x>=0&&x<I&&y>=0&&y<I?V[T(x,y)]=1:0;}g(E,N,C){int i,j,v[J],X[J],Y[J];if(E==m&&N==m)R 1;Q(X);Q(Y);Z(E,w,X,Y)Z(N,b,Y,X)if(C){P(Y,b,N)}else{P(X,w,E)}R 0;}f(q){I=q,J=I*I;int W[J],B[J];w=W,b=B;for(m=1;;m++)if(!g(0,0,0))R m-1;} ``` Basically, the code iterates over possibilities of white queen and check whether black queen could be placed then. Speed reference table (in seconds): ``` +---+----------------------+---------------------+-----------------+--------+ | n | DFS w & b | DFS w | DFS w/ pruning | Clingo | +---+----------------------+---------------------+-----------------+--------+ | 3 | 0.00 | 0.00 | 0.00 | 0.01 | | 4 | 0.00 | 0.00 | 0.00 | 0.02 | | 5 | 0.47 | 0.16 | 0.00 | 0.04 | | 6 | 20.62 | 1.14 | 0.00 | 0.60 | | 7 | 1125.07 | 397.88 | 0.63 | 18.14 | | 8 | | | 1.28 | 979.35 | | 9 | | | 23.13 | | +---+----------------------+---------------------+-----------------+--------+ ``` [Answer] # [Clingo](https://potassco.org/), 90 bytes ``` {q(1..n,1..n)}.a(X+(-I;0;I),Y+(0;I)):-q(X,Y),I=-n..n.:~K={q(X,Y)},{a(1..n,1..n)}n*n-K.[-K] ``` ### Demo ``` $ clingo peaceable.lp -cn=6 clingo version 5.1.0 Reading from peaceable.lp Solving... Answer: 1 Optimization: 0 Answer: 2 q(6,1) a(7,1) a(7,2) a(8,1) a(8,3) a(9,1) a(9,4) a(10,1) a(10,5) a(11,1) a(11,6) a(12,1) a(6,1) a(6,2) a(6,3) a(6,4) a(6,5) a(6,6) a(5,1) a(5,2) a(4,1) a(4,3) a(3,1) a(3,4) a(2,1) a(2,5) a(1,1) a(1,6) a(0,1) a(7,0) a(8,-1) a(9,-2) a(10,-3) a(11,-4) a(12,-5) a(6,-4) a(6,-3) a(6,-2) a(6,-1) a(6,0) a(5,0) a(4,-1) a(0,7) a(1,-4) a(2,-3) a(3,-2) a(6,-5) a(6,7) a(0,-5) a(12,7) Optimization: -1 Answer: 3 q(1,6) q(6,1) a(7,1) a(7,2) a(7,6) a(8,1) a(8,3) a(9,1) a(9,4) a(10,1) a(10,5) a(11,1) a(11,6) a(12,1) a(6,1) a(6,2) a(6,3) a(6,4) a(6,5) a(6,6) a(5,1) a(5,2) a(5,6) a(4,1) a(4,3) a(4,6) a(3,1) a(3,4) a(3,6) a(2,1) a(2,5) a(2,6) a(1,1) a(1,2) a(1,3) a(1,4) a(1,5) a(1,6) a(0,1) a(0,5) a(0,6) a(-1,4) a(-1,6) a(-2,3) a(-2,6) a(-3,2) a(-3,6) a(-4,1) a(-4,6) a(-5,6) a(7,0) a(8,-1) a(9,-2) a(10,-3) a(11,-4) a(12,-5) a(6,-4) a(6,-3) a(6,-2) a(6,-1) a(6,0) a(5,0) a(4,-1) a(0,7) a(1,7) a(2,7) a(-1,8) a(1,8) a(3,8) a(-2,9) a(1,9) a(-3,10) a(1,10) a(-4,11) a(1,11) a(-5,12) a(1,-4) a(1,0) a(2,-3) a(3,-2) a(6,-5) a(6,7) a(4,9) a(5,10) a(6,11) a(1,12) a(-5,0) a(0,-5) a(7,12) a(12,7) Optimization: -2 Answer: 4 q(1,6) q(6,1) q(6,6) a(7,1) a(7,2) a(7,5) a(7,6) a(8,1) a(8,3) a(8,4) a(8,6) a(9,1) a(9,3) a(9,4) a(9,6) a(10,1) a(10,2) a(10,5) a(10,6) a(11,1) a(11,6) a(12,1) a(12,6) a(6,1) a(6,2) a(6,3) a(6,4) a(6,5) a(6,6) a(5,1) a(5,2) a(5,5) a(5,6) a(4,1) a(4,3) a(4,4) a(4,6) a(3,1) a(3,3) a(3,4) a(3,6) a(2,1) a(2,2) a(2,5) a(2,6) a(1,1) a(1,2) a(1,3) a(1,4) a(1,5) a(1,6) a(0,1) a(0,5) a(0,6) a(-1,4) a(-1,6) a(-2,3) a(-2,6) a(-3,2) a(-3,6) a(-4,1) a(-4,6) a(-5,6) a(7,0) a(8,-1) a(9,-2) a(10,-3) a(11,-4) a(12,-5) a(12,0) a(6,-4) a(6,-3) a(6,-2) a(6,-1) a(6,0) a(5,0) a(4,-1) a(0,7) a(1,7) a(2,7) a(5,7) a(-1,8) a(1,8) a(3,8) a(4,8) a(-2,9) a(1,9) a(3,9) a(-3,10) a(1,10) a(2,10) a(-4,11) a(1,11) a(-5,12) a(0,12) a(1,-4) a(1,0) a(2,-3) a(3,-2) a(6,-5) a(6,7) a(6,8) a(4,9) a(6,9) a(5,10) a(6,10) a(6,11) a(1,12) a(6,12) a(-5,0) a(0,-5) a(0,0) a(7,7) a(8,8) a(9,9) a(10,10) a(11,11) a(7,12) a(12,7) a(12,12) Optimization: -3 Answer: 5 q(1,1) q(1,6) q(6,1) q(6,6) a(7,1) a(7,2) a(7,5) a(7,6) a(8,1) a(8,3) a(8,4) a(8,6) a(9,1) a(9,3) a(9,4) a(9,6) a(10,1) a(10,2) a(10,5) a(10,6) a(11,1) a(11,6) a(12,1) a(12,6) a(6,1) a(6,2) a(6,3) a(6,4) a(6,5) a(6,6) a(5,1) a(5,2) a(5,5) a(5,6) a(4,1) a(4,3) a(4,4) a(4,6) a(3,1) a(3,3) a(3,4) a(3,6) a(2,1) a(2,2) a(2,5) a(2,6) a(1,1) a(1,2) a(1,3) a(1,4) a(1,5) a(1,6) a(0,1) a(0,2) a(0,5) a(0,6) a(-1,1) a(-1,3) a(-1,4) a(-1,6) a(-2,1) a(-2,3) a(-2,4) a(-2,6) a(-3,1) a(-3,2) a(-3,5) a(-3,6) a(-4,1) a(-4,6) a(-5,1) a(-5,6) a(7,-5) a(7,0) a(8,-1) a(9,-2) a(10,-3) a(11,-4) a(12,-5) a(12,0) a(6,-4) a(6,-3) a(6,-2) a(6,-1) a(6,0) a(5,-3) a(5,0) a(4,-2) a(4,-1) a(3,-1) a(2,0) a(0,7) a(1,7) a(2,7) a(5,7) a(-1,8) a(1,8) a(3,8) a(4,8) a(-2,9) a(1,9) a(3,9) a(-3,10) a(1,10) a(2,10) a(-4,11) a(1,11) a(-5,7) a(-5,12) a(0,12) a(1,-5) a(1,-4) a(1,-3) a(1,-2) a(1,-1) a(1,0) a(2,-3) a(3,-2) a(6,-5) a(6,7) a(6,8) a(4,9) a(6,9) a(5,10) a(6,10) a(6,11) a(1,12) a(6,12) a(-5,-5) a(-5,0) a(-4,-4) a(-3,-3) a(-2,-2) a(-1,-1) a(0,-5) a(0,0) a(7,7) a(8,8) a(9,9) a(10,10) a(11,11) a(7,12) a(12,7) a(12,12) Optimization: -4 Answer: 6 q(1,2) q(1,3) q(2,2) q(2,3) q(2,6) a(7,1) a(7,2) a(7,3) a(7,6) a(8,2) a(8,3) a(8,6) a(6,2) a(6,3) a(6,6) a(5,2) a(5,3) a(5,5) a(5,6) a(4,1) a(4,2) a(4,3) a(4,4) a(4,5) a(4,6) a(3,1) a(3,2) a(3,3) a(3,4) a(3,5) a(3,6) a(2,1) a(2,2) a(2,3) a(2,4) a(2,5) a(2,6) a(1,1) a(1,2) a(1,3) a(1,4) a(1,5) a(1,6) a(0,1) a(0,2) a(0,3) a(0,4) a(0,5) a(0,6) a(-1,1) a(-1,2) a(-1,3) a(-1,4) a(-1,5) a(-1,6) a(-2,2) a(-2,3) a(-2,5) a(-2,6) a(-3,1) a(-3,2) a(-3,3) a(-3,6) a(-4,2) a(-4,3) a(-4,6) a(-5,2) a(-5,3) a(7,-4) a(7,-3) a(7,-2) a(8,-4) a(8,-3) a(8,0) a(6,-3) a(6,-2) a(6,-1) a(5,-2) a(5,-1) a(5,0) a(4,-1) a(4,0) a(3,0) a(2,0) a(1,7) a(2,7) a(3,7) a(5,7) a(0,8) a(1,8) a(2,8) a(4,8) a(-2,7) a(-1,9) a(1,9) a(2,9) a(-3,7) a(-3,8) a(-2,10) a(2,10) a(-4,7) a(-4,8) a(-4,9) a(-3,11) a(-5,8) a(-5,9) a(-4,12) a(1,-4) a(1,-3) a(1,-2) a(1,-1) a(1,0) a(2,-4) a(2,-3) a(2,-2) a(2,-1) a(6,7) a(6,8) a(5,9) a(6,10) a(2,11) a(2,12) a(-5,-4) a(-5,-3) a(-4,-4) a(-4,-3) a(-4,-2) a(-4,0) a(-3,-3) a(-3,-2) a(-3,-1) a(-2,-2) a(-2,-1) a(-2,0) a(-1,-1) a(-1,0) a(0,0) a(7,7) a(7,8) a(8,8) a(7,9) a(8,9) a(7,11) a(8,12) Optimization: -5 OPTIMUM FOUND Models : 6 Optimum : yes Optimization : -5 Calls : 1 Time : 0.733s (Solving: 0.71s 1st Model: 0.00s Unsat: 0.71s) CPU Time : 0.730s ``` [Answer] # Python 2 | 325 284 217 bytes [Try it online!](https://tio.run/##ZVHBbtswDD3HX8GgKCBl7tKk2GHGPAwYsKN/YNhBlmlHiEy6kpwtX59RbhIU6E18fOR7j5rO6cC0vzzAbg/tOWGswI0Th@RogA2odDB0jCX8@Gm8nb1JHH6hd4RrXTzAy20GCAezzFimziXHFMFQB3PMoPEeHMWEpgPugTjBJ@AgG77eN4x8ytQOe0fLgszMlN3zjRPwSgqY5kDwDErMemddukEy0zBhNncPBFZCDHkuCyeGb7vc3n9Ymw4I/Uw2q5cwmmMGZbcRVBJMgYdgxlIGJm/sOyN/XTpAG9Acl9DoI34G/CejLgKTP4OVE2AHrl9E3qgSUWqPpAb9vabMJTxhgDCTGPxy9/92xGWf5Q5zhKvwyfgZL33gUXxiSMw@Xj9wUzS1o2lOShehDnIBVM2m0UXPAUSMIFQFDHUoICMxI5bH1pFZvk8NJemqWOXmlJuxGureeZFR3oxtZ@C1klTqt2mjen1snqbHRq/rpdpKtW10KfC6FrwURB7b5o8uB12s3ueulmsUq8VKPl2Vkyp62unL5eU/) ``` from itertools import* N=input() r=range(N*N) for n in r: g=r for s in combinations(g,n): for p in s:g=filter(lambda q:all([abs(q%N-p%N)!=abs(q/N-p/N),q%N!=p%N,q/N!=p/N]),g) if len(g)>=n:break g=r else:exit(n-1) ``` **Edit:** Replaced tuples with integers in g and other trivial edits. **Edit2:** Bytes down to 217 thanks to [musicman523](https://codegolf.stackexchange.com/users/69054/musicman523) and [CalculatorFeline](https://codegolf.stackexchange.com/users/51443/calculatorfeline)! ## How it works The program iterates over all possible positions of `n` queens and filters out non-peaceful points in `g` caused due to position of the queens. If the remaining points is greater than `n` then it means that it is possible to for `n` queen armies to stay peacefully. If for the next value of `n`, no peaceful situation is found, then the program exits with exit code : `n-1`, which is the answer. **In short, it is brute force** The program can be made faster by changing the last two lines to ``` for n in range(N**2): if not z(n,N):print n-1;break ``` [Answer] ## [Haskell](https://www.haskell.org/), ~~169 156 153~~ 152 bytes ``` k!(a:b)=k!b++[a:c|c<-(k-1)!b] k!x=[x|k==0] q&l|p<-q![[x,y,x-y,x+y]|x<-l,y<-l]=or[all and$zipWith(/=)<$>b<*>w|b<-p,w<-p] g n=last$filter(&[1..n])[0..n*n] ``` Defines a function `g`, may be further golfable. [Try it online!](https://tio.run/##DcW7DsIgGEDhvU8BCTGtLd7iZMBXcHQgDFB7IfxibUmkhmcXGc53RrXYDiAli0t10RW3WNe1UJc2toyWlh4rrGVhceAiRMv5QRbvDcSJ0TcWIjRrE2iuXmUMjEKzZiR/zUIBIOUe5Gumu/FjuecVI1fNttdP1IxOzScjiwE5DmrxpDfgu7nciONu52QlDnlbJ9NTGYc4mmbjPCJoQOf0a3tQw5Lo7fQH "Haskell – Try It Online") On TIO, when compiled with `-O2`, this takes about 36 seconds for **n = 4** and times out on **n = 5**. The time complexity should be **O(n24n2)**. ## Explanation We iterate over the possible values for the number of queens (**q**). For each **q**, we generate all pairs of size-**q** subsets of **[1..n]2**, one set of black queens (**b**) and one of white queens (**w**). Then, each element of **b** is checked against each element of **w** to see if they share a row, column, diagonal or anti-diagonal. This also takes care of two pieces sharing the same coordinate. The greatest value of **q** that admits a peaceable configuration is the final value. The first two lines of the program define the function `!`, which computes the length-`k` subsequences of a list `x`. The implementation is by a basic recursion: either choose the first element to be in the set or not and recurse to the tail, decrementing `k` if necessary. Then the empty list or reached, check that `k==0`. ``` k!(a:b)= -- ! on integer k and list with head a and tail b is k!b++ -- the concatenation of k!b and [a:c| -- the list of lists a:c where c<-(k-1)!b] -- c is drawn from (k-1)!b. k!x= -- If x doesn't have the form a:b (which means that it's empty), [x| -- the result is a list containing x k==0] -- but only if k==0. ``` The second auxiliary function `&` takes a number `q` (number of queens on either side) and a list `l` (the x-coordinates of the board, also used as the y-coordinates), and returns a Boolean value indicating if a peaceable configuration exists. We first compute `p`, the list of length-`q` subsequences of the list of values `[x,y,x-y,x+y]`, where `x` and `y` range over `l`. They represent the row, column, diagonal and anti-diagonal of a square `(x,y)` on the board. ``` q&l -- & on inputs q and l: |p<- -- define p as q! -- the q-subsequences of [[x,y,x-y,x+y] -- the list of these 4-lists |x<-l,y<-l] -- where x and y are drawn independently from l. ``` Next we have the result of `q&l`. We draw two subsequences `b` and `w` from `p`, pair the 4-lists of them together in all possible ways, and check that they always differ in all 4 coordinates. If some choices of `b` and `w` result in a truthy result, we return `True`. ``` =or -- Does the following list contain a True: [all and$ -- every list contains only truthy values zipWith(/=) -- if we zip with inequality <$>b<*>w -- all elements of b and w in all possible ways, |b<-p,w<-p] -- where b and w are drawn independently from p. ``` The last line is the main function. Given `n`, it simply finds the largest possible value of `q` for which `q&[1..n]` is true. ``` g n= -- g on input n is last$ -- the last of filter(&[1..n]) -- those values q for which q&[1..n] is true [0..n*n] -- in this list. ``` ]
[Question] [ The [treewidth](https://en.wikipedia.org/wiki/Treewidth) of an undirected graph is a very important concept in Graph Theory. Tons of graph algorithms have been invented which run fast if you have a decomposition of the graph with small treewidth. The treewidth is often defined in terms of tree decompositions. Here's a graph and a tree decomposition of that graph, courtesy of Wikipedia: [![enter image description here](https://i.stack.imgur.com/O7NYw.png)](https://i.stack.imgur.com/O7NYw.png) A tree decomposition is a tree where each vertex is associated with a subset of the vertices of the original graph, with the following properties: * Every vertex in the original graph is in at least one of the subsets. * Every edge in the original graph has both of its vertices in at least one of the subsets. * All of the vertices in the decomposition whose subsets contain a given original vertex are connected. You can check that the above decomposition follows these rules. The width of a tree decomposition is the size of its largest subset, minus one. Therefore, it is two for the above decomposition. The treewidth of a graph is the smallest width of any tree decomposition of that graph. --- In this challenge, you will be given a connected, undirected graph, and you must find its treewidth. While finding tree decompositions is hard, there are other ways to calculate the treewidth. The Wikipedia page has more info, but one method of calculating treewidth not mentioned there which is often used in algorithms to calculate the treewidth is the minimum elimination ordering width. See [here](http://www.callowbird.com/uploads/8/6/6/4/8664563/a_fast_parallel_branch_and_bound_algorithm_for_treewidth.pdf) for a paper using this fact. In an elimination ordering, one eliminates all of the vertices of a graph one at a time. When each vertex is eliminated, edges are added connecting all of that vertex's neighbors to each other. This is repeated until all of the vertices are gone. The elimination ordering width is the largest number of neighbors that any vertex which is being eliminated has during this process. The treewidth is equal to the minimum over all orderings of the elimination ordering width. Here is an example program using this fact to calculate the treewidth: ``` import itertools def elimination_width(graph): max_neighbors = 0 for i in sorted(set(itertools.chain.from_iterable(graph))): neighbors = set([a for (a, b) in graph if b == i] + [b for (a, b) in graph if a == i]) max_neighbors = max(len(neighbors), max_neighbors) graph = [edge for edge in graph if i not in edge] + [(a, b) for a in neighbors for b in neighbors if a < b] return max_neighbors def treewidth(graph): vertices = list(set(itertools.chain.from_iterable(graph))) min_width = len(vertices) for permutation in itertools.permutations(vertices): new_graph = [(permutation[vertices.index(a)], permutation[vertices.index(b)]) for (a, b) in graph] min_width = min(elimination_width(new_graph), min_width) return min_width if __name__ == '__main__': graph = [('a', 'b'), ('a', 'c'), ('b', 'c'), ('b', 'e'), ('b', 'f'), ('b', 'g'), ('c', 'd'), ('c', 'e'), ('d', 'e'), ('e', 'g'), ('e', 'h'), ('f', 'g'), ('g', 'h')] print(treewidth(graph)) ``` --- Examples: ``` [(0, 1), (0, 2), (0, 3), (2, 4), (3, 5)] 1 [(0, 1), (0, 2), (1, 2), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (3, 4), (4, 6), (4, 7), (5, 6), (6, 7)] 2 [(0, 1), (0, 3), (1, 2), (1, 4), (2, 5), (3, 4), (3, 6), (4, 5), (4, 7), (5, 8), (6, 7), (7, 8)] 3 [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] 4 ``` --- You will receive the graph as input, and you must return the treewidth as output. The input format is flexible. You may take a list of edges, an adjacency map, or an adjacency matrix as input. If you'd like to use another input format, ask in the comments. You may assume the input is connected, and you may build that assumption into your input format, e.g. by using a list of edges. EDIT: Built-in operations which calculate treewidth are not allowed. I apologize for not specifying this up front. Shortest code wins. [Answer] # Octave, 195 bytes ``` function x=F(a)r=rows(a);P=perms(s=1:r);x=r;for m=s;b=a;n=0;for z=P(m,:);(T=sum(b)(z))&&{b|=(k=accumarray(nchoosek(find(b(z,:)),2),1,[r r]))|k';n=max(T,n);b(z,:)=0;b(:,z)=0}{4};end;x=min(x,n);end ``` A function that takes as input an adjacency matrix. It consumes large amount of memory so it is useless if number of vertices is more than 10-12. * there is no need to `endfunction` however it should be added to tio. [Try it online!](https://tio.run/##TZA/b8IwEMX3fIqb4Cw8JPytON3amYENMThOECm1U9nQhgCfPb2kou3gp9@z7nz3XNuz@Sy77nDx9lzVHhp@RaMCh/orCtCGP8rgIkbO1kFRw4EOdQDHkXI25DkdfMsbdHqtCLccLw5zha1So9EtvzOe2Fh7cSYEc0Vvj3UdyxMeKl9gjq10KT1VOtO7AGGv1P00lnedaXCrvaKfEpmT41q3Ao/b/EGlL2QZV3ls@iKxnZxnjOS9imfepRoyAtEZQaZhOuicYKphQTAbWHRJMB9uRFcECw0vBMuBV8L7SUZJYoo3Y0tvr//D9GNk8X7XHlGiTHYppHtFfw13/sUxJfK9T6e6bw "Octave – Try It Online") Ungolfed: ``` function min_width = treewidth(graph_adj) Nvertices = rows(graph_adj) Permutations = perms(1:Nvertices); % do not try it for large number of vertices min_width = Nvertices; for v = 1:Nvertices; new_graph=graph_adj; max_neighbors=0; for p = Permutations(v,:) Nneighbors=sum(new_graph)(p); if(Nneighbors)>0 connection=accumarray(nchoosek(find(new_graph(p,:)),2),1,[Nvertices Nvertices]); % connect all neighbors new_graph|=connection|connection'; % make the adjacency matrix symmetric new_graph(p,:)=0;new_graph(:,p)=0; % eliminate the vertex max_neighbors=max(Nneighbors,max_neighbors); end end min_width=min(min_width,max_neighbors); end end ``` [Answer] # SageMath , ~~29 bytes~~ noncompeting\* ``` lambda L:Graph(L).treewidth() ``` \*This answer posted before OP's change of the question that "Builtins are banned", so I maked it noncompeting . [Online Demo!](https://sagecell.sagemath.org/?z=eJxLs81JzE1KSVTwsXIvSizI0PDR1CspSk0tz0wpydDQ5OVK04jWMNBRMNTUUQDRRiDaEEGbQGlTKG0Goo10FIyhNFjeGEqbQOWBtDmINoXyzUD8WE0ADQwczw==&lang=sage) [Answer] # [Haskell](https://www.haskell.org/) (Lambdabot), ~~329~~ ~~321~~ 245 bytes Here's my solution, thanks to the flexibility of the input it works on graphs with graphs containing any type that is an instance of `Eq`. ``` (&)=elem l=length t n g s=last$minimum[max(t n g b)$t(n++b)g$s\\b|b<-filterM(\_->[0>1,1>0])s,l b==div(l s)2]:[l[d|d<-fst g,not$d&n,d/=s!!0,(d&)$foldr(\x y->last$y:[x++y|any(&y)x])[s!!0]$join(>>)[e|e<-snd g,all(&(s!!0:d:n))e]]|1==l s] w=t[]<*>fst ``` [Try it online!](https://tio.run/##dVNNj5swEL3zK2YlhOzG0ADJbhWFXLZSVamrXnojVkXASegaO8LOl5T/no4hm3TT1pI1HjPvvRnPsC7Mq5DyXDcb3Vp41sq2WkYvWhWVd7n8XNgi@lYbeyYBzYQUjSczKdTKrj0LClZgMlkY6ze1qpttkzfFgfQfFtS3RA0GC7ryzXy@OC2m4bKWVrQvZP4znOXDWczi2ZBTwyQssqyqd0SCoQmf5DKvThXGGwsrprT1q0Cx6mNmHh6GjFQB9ZdaVi2ZH@AYzroMjpP8MBgcT4U6kuBID5zmLpr7v3StyGxGc3ES09CoCikLKUlA3PdJNVGUCs5PcZahPPf2mc359MMMxc9eGMIPgVmUhREGlq1uYNPqBT4EVMKUbb2xtVZerWLIIM@HDGLOnEl6k6JJGIzQpAzGnGNo8o/Q@GpGvRn35pF70K2O5j2bMyMX0pknNOPee3SeU0rvlNK/lJJeqWO7KqVX0vE77k9v3Cx/cp6TGP2/7uG1mItgepO4yd/XxD3P6i9tsVnDAblJPowinCo3XX6pVVlYOHB2oJ7rDQ6tse22tFDAUuxB4ba3fhXY7HarwK6xX1avBB5a2Nd27a5gVe@EAq2E8TqQQj13eO7AQdA7utlIYQV@fbs5lhJdrGWPdKKr6QbrVgZNsQGyjy6lUMhxRBj2HneKe8Qhw4eLWcJSdnn6O7V7juhVIU0aRarHJngK4z@gXVq4HBQHHAhJsoxGN4LySuB1qHcPWL4pB1B2TCuHMV3gq@pI83zLdhxOsIVpCK4xLgEGu87dDuL@ok@pvGCGzN1NHBYj7tCJa3dT1AomE/j6HQjtvQz/slpZ8PtuJuff "Haskell – Try It Online") ### Ungolfed version: ``` type Vertex a = a type Edge a = [Vertex a] type Graph a = ([Vertex a],[Edge a]) vertices = fst edges = snd -- This corresponds to the function w treeWidth :: (Eq a) => Graph a -> Int treeWidth g = recTreeWidth g [] (vertices g) -- This is the base case (length s == 1) of t recTreeWidth graph left [v] = length [ w | w <- vertices graph , w `notElem` left , w /= v , w `elem` reachable (subGraph w) ] where subGraph w = [ e | e <- edges graph, all (`elem` v:w:left) e ] reachable g = foldr accumulateReachable [v] (g>>g) accumulateReachable x y = if any (`elem` y) x then x++y else y -- This is the other case of t recTreeWidth graph left sub = minimum [ comp sub' | sub' <- filterM (const [False,True]) sub , length sub' == div (length sub) 2 ] where comp b = max (recTreeWidth graph left b) (recTreeWidth graph (left++b) (sub\\b)) ``` ]
[Question] [ ## Introduction: Let's take a look at a standard Calculator in Windows: [![enter image description here](https://i.stack.imgur.com/DLmi6.png)](https://i.stack.imgur.com/DLmi6.png) For this challenge, we'll only look at the following buttons, and ignore everything else: ``` 7 8 9 / 4 5 6 * 1 2 3 - 0 0 . + ``` ## Challenge: **Input:** You will receive two inputs: * One is something to indicate the rotation in increments of 90 degrees * The other is a list of coordinates representing the buttons pressed on the rotated calculator. Based on the first input, we rotate the layout mentioned above clockwise in increments of 90 degrees. So if the input is `0 degrees`, it remains as is; but if the input is `270 degrees`, it will be rotated three times clockwise (or once counterclockwise). Here are the four possible lay-outs: ``` Default / 0 degrees: 7 8 9 / 4 5 6 * 1 2 3 - 0 0 . + 90 degrees clockwise: 0 1 4 7 0 2 5 8 . 3 6 9 + - * / 180 degrees: + . 0 0 - 3 2 1 * 6 5 4 / 9 8 7 270 degrees clockwise / 90 degrees counterclockwise: / * - + 9 6 3 . 8 5 2 0 7 4 1 0 ``` The second input is a list of coordinates in any reasonable format *†*. For example (0-index 2D integer-array): ``` [[1,2],[2,3],[0,3],[1,0],[1,1]] ``` **Output:** We output both the sum, as well as the result (and an equal sign `=`). **Example:** So if the input is `270 degrees` and `[[1,2],[2,3],[0,3],[1,0],[1,1]]`, the output will become: ``` 517*6=3102 ``` ## Challenge rules: * *†* The inputs can be in any reasonable format. The first input can be `0-3`, `1-4`, `A-D`, `0,90,180,270`, etc. The second input can be a 0-indexed 2D array, 1-indexed 2D array, a String, list of Point-objects, etc. Your call. It's even possible to swap the x and y coordinates compared to the example inputs given. **Please state which input formats you've used in your answer!** * You are allowed to add spaces (i.e. `517 * 6 = 3102`) if you want to. * You are allowed to add trailing zeros after the comma, to a max of three (i.e. `3102.0`/`3102.00`/`3102.000` instead of `3102` or `0.430` instead of `0.43`). * You are not allowed to add parenthesis in the output, so `(((0.6+4)-0)/2)/4=0.575` is not a valid output. * You are allowed to use other operand-symbols for your language. So `×` or `·` instead of `*`; or `÷` instead of `/`; etc. * Since a calculator automatically calculates when inputting an operand, **you should ignore operator precedence!** So `10+5*3` will result in `45` (`(10+5)*3=45`), not `25` (`10+(5*3)=25`) (i.e. `10` → `+` → `5` → `*` (it now displays 15 in the display) → `3` → `=` (it now displays the answer `45`)). Keep this in mind when using `eval` and similar functions on the resulting sum. * There won't be any test cases for division by 0. * There won't be any test cases with more than three decimal digits as result, so no need for rounding the result. * There won't be any test cases where multiple operands follow each other, or where two dots follow each other. * There won't be any test cases for negative numbers. The minus-sign (`-`) will only be used as operand, not as negative. * There won't be any test cases for `.##` without a leading number before the comma (i.e. `2+.7` will not be a valid test case, but `2+0.7` could be). ## 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: ``` Input: 270 degrees & [[1,2],[2,3],[0,3],[1,0],[1,1]] Output: 517*6=3102 Input: 90 degrees & [[3,1],[0,0],[0,1],[3,3],[2,0],[0,3],[0,0],[0,2],[3,0],[2,1]] Output: 800/4+0.75=200.75 Input: 0 degrees & [[0,0],[1,0],[2,0],[3,0],[1,2],[2,1],[2,2]] Output: 789/263=3 Input: 180 degrees & [[3,0],[1,0],[1,2],[0,0],[3,2],[0,1],[2,0],[0,3],[2,1],[0,3],[3,2]] Output: 0.6+4-0/2/4=0.575 ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~70~~ ~~69~~ 67 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` i⅛⁸Νο;⌡░▼Y6γj±²‘1n4n.⌡Iø,→{_≤whwιh:"/*-+”;W? )Κ; (Κ;}+}:Ƨ)(čøŗoļ=→p ``` [Try it Here](https://dzaima.github.io/SOGLOnline/?code=aSV1MjE1QiV1MjA3OCV1MDM5RCV1MDNCRiUzQiV1MjMyMSV1MjU5MSV1MjVCQ1k2JXUwM0IzaiVCMSVCMiV1MjAxODFuNG4uJXUyMzIxSSVGOCUyQyV1MjE5MiU3Ql8ldTIyNjR3aHcldTAzQjloJTNBJTIyLyotKyV1MjAxRCUzQlclM0YlMjAlMjkldTAzOUElM0IlMjAlMjgldTAzOUElM0IlN0QrJTdEJTNBJXUwMUE3JTI5JTI4JXUwMTBEJUY4JXUwMTU3byV1MDEzQyUzRCV1MjE5MnA_,inputs=MiUwQSU1QiU1QjQlMkMxJTVEJTJDJTVCMiUyQzElNUQlMkMlNUIyJTJDMyU1RCUyQyU1QjElMkMxJTVEJTJDJTVCNCUyQzMlNUQlMkMlNUIxJTJDMiU1RCUyQyU1QjMlMkMxJTVEJTJDJTVCMSUyQzQlNUQlMkMlNUIzJTJDMiU1RCUyQyU1QjElMkM0JTVEJTJDJTVCNCUyQzMlNUQlNUQ_), or [try a version which takes inputs as given in the test-cases](https://dzaima.github.io/SOGLOnline/?code=aSV1MjE1QiV1MjA3OCV1MDM5RCV1MDNCRiUzQiV1MjMyMSV1MjU5MSV1MjVCQ1k2JXUwM0IzaiVCMSVCMiV1MjAxODFuNG4uJTI3Ry8ldTIzMjFJJUY4JTJDJXUyMTkyJTdCX0klM0JJJTNCJXUyMjY0d2h3JXUwM0I5aCUzQSUyMi8qLSsldTIwMUQlM0JXJTNGJTIwJTI5JXUwMzlBJTNCJTIwJTI4JXUwMzlBJTNCJTdEKyU3RCUzQSV1MDFBNyUyOSUyOCV1MDEwRCVGOCV1MDE1N28ldTAxM0MlM0QldTIxOTJw,inputs=MTgwJTBBJTVCJTVCMyUyQzAlNUQlMkMlNUIxJTJDMCU1RCUyQyU1QjElMkMyJTVEJTJDJTVCMCUyQzAlNUQlMkMlNUIzJTJDMiU1RCUyQyU1QjAlMkMxJTVEJTJDJTVCMiUyQzAlNUQlMkMlNUIwJTJDMyU1RCUyQyU1QjIlMkMxJTVEJTJDJTVCMCUyQzMlNUQlMkMlNUIzJTJDMiU1RCU1RA__) uses SOGLs `I` operator, which rotates the array. Then reads a string as a JavaScript array, and where an operation is used, encase previous result in parentheses, evaluates as JavaScript and then removes the parentheses. [Answer] # Dyalog APL, ~~94~~ ~~88~~ ~~86~~ 85 bytes ``` {o,'=',⍎('('\⍨+/'+-×÷'∊⍨o),'[×÷+-]'⎕R')&'⊢o←(((⌽∘⍉⍣⍺)4 4⍴'789÷456×123-00.+')⊃⍨⊂∘⊢)¨⍵} ``` [Try it online!](https://tio.run/##RY09bsJAEIV7TrEVsyvbwbuz/KTIJWhJCqQIGiTTIkQDEoJV1koTmZo0HCARUqQ0@CZzEbNjI2hG78187814PkveF@NZNq2qCW0/l1kMLxCTzyVIeCV/ijoQJWVRnoF2LvhMxTBiHyVvQPnXEFQbyB2zkJZS0sc/7Q7k9@S/yf8pKyz5H@gPnsuz7fbKQhtM0vQpAkVuE/rIrTngjupyIv@7qioUEyFRGCWtQB5aSc3WhNHSfDXC8k7zTjNS2wccBjbKMoKqlXJM36tquL5i04ysAmcazt44bOC6z96@PR6Zu@LrFQ) Takes the rotations as left argument, `0-3`, and the 1-based indices as right argument, as a list of `y x` coordinates, like `(1 1)(2 3)(4 5)` etc. This got quite messy because of the right-handed evaluation of expressions in APL. [Answer] # [C (gcc)](https://gcc.gnu.org/), 282 ~~294~~ ~~295~~ ~~296~~ ~~300~~ ~~304~~ ~~306 310~~ bytes All optimizations need to be turned off and only work on 32-bit GCC. ``` float r,s;k,p,l,i;g(d,x,y){int w[]={y,x,3-y,3-x,y};d=w[d+1]*4+w[d];}f(x,y,z)int**z;{for(i=0;i<=y;i++)putchar(k=i-y?"789/456*123-00.+"[g(x,z[i][0],z[i][1])]:61),57/k*k/48?p?r+=(k-48)*pow(10,p--):(r=10*r+k-48):k-46?s=l?l%2?l%5?l&4?s/r:s+r:s-r:s*r:r,r=p=0,l=k:(p=-1);printf("%.3f",s);} ``` 1 byte thanks to @Orion! [Try it online!](https://tio.run/##jVDbbqMwEH3nKxBSIl/B5h5ciw@JeMiS0AAOINOqCVV@fVlD0t1K@1JLx5o5M3PmUtLXspzn8nzQ6CydJN15YRQj7geUMRczHibMj1I3iHeYIg@7jNHA5yiOQm@XJh6ieBcHbhr5LAk5c8Sxf/@lTrYmo6i7N7slA1GkFhW4khuZoOEQmsTnGcsr4rGoeg1qyUT9Im@ixhgO72/LMKCVNb3l5/20r4s9K1CIV4sXRRZzSKLEa1HrhWk@5EBjCVoaphAN/QfgzCUDpRBmQEvOkMZrLDN/nINRqlxtfIMoV9swHz2djdiAGiCdaaLlIBlRsjUCg6QcikGbsSvgbNygcsgIxX1edrsc6g5A69OyzVuIK@lII1Z3LA/dUnHcHB2yvZJtBx@Br2SE7MmWNlhNeDko1ZegQ2M9nfpqZeH3iuVOjblT89KJxpxpJR@dlzftm0I@qp5S/jepL6X/B1vqzHWfBi@eiXfr0RQsG02G/MkMlT6dwKLzV@Qfa6j7zOzEYjYz4Aa@QWBx43Pjc9v/XVbq8DrOVF3@AA "C (gcc) – Try It Online") Function prototype: ``` f(<Direction 0-3>, <Number of entries>, <a int** typed array in [N][2]>) ``` Input format (as on TIO): ``` <Direction 0~3> <Number of entries> <Entries 0 Row> <Entries 0 Column> <Entries 1 Row> <Entries 1 Column> .... <Entries N Row> <Entries N Column> ``` Ungolfed version with comments: ``` float r, s; k, p, l, i; g(d, x, y) { int w[] = { y, x, 3 - y, 3 - x, y }; d = w[d + 1] * 4 + w[d]; } f(x, y, z) int **z; { for (i = 0; i <= y; i++) { putchar(k = i - y ? "789/456*123-00.+"[g(x, z[i][0], z[i][1])] : 61), // Print character, otherwise, '=' 57 / k * k / 48 ? // If the character is from '0'~'9' p ? // If it is after or before a dot r += (k - 48) * pow(10., p--) // +k*10^-p : (r = 10 * r + k - 48) // *10+k : k - 46 ? // If the character is not '.', that is, an operator, + - * / = s = l ? // Calculate the result of previous step (if exist) l % 2 ? // If + - / l % 5 ? // If + / l & 4 ? s / r : s + r : s - r : s * r : r, r = p = 0, l = k // Reset all bits : (p = -1); // Reverse the dot bit } printf("%.3f", s); } ``` The code can handle cases such as `1+.7` or `-8*4`. Very sad C doesn't have an `eval` 😭. [Answer] ## JavaScript (ES6), ~~162~~ ~~160~~ 157 bytes Takes input as orientation `o` and array of **(y,x)** coordinates `a` in currying syntax `(o)(a)`. The orientation is an integer in **[0..3]**: * **0** = 0° * **1** = 90° clockwise * **2** = 180° clockwise * **3** = 270° clockwise ``` o=>a=>(s=a.map(([y,x])=>'789/456*123-00.+'[[p=y*4+x,12+(y-=x*4),15-p,3-y][o]]).join``)+'='+eval([...x=`0)+${s}`.split(/(.[\d.]+)/)].fill`(`.join``+x.join`)`) ``` ### Test cases ``` let f = o=>a=>(s=a.map(([y,x])=>'789/456*123-00.+'[[p=y*4+x,12+(y-=x*4),15-p,3-y][o]]).join``)+'='+eval([...x=`0)+${s}`.split(/(.[\d.]+)/)].fill`(`.join``+x.join`)`) console.log(f(3)([[2,1],[3,2],[3,0],[0,1],[1,1]])) // 517*6=3102 console.log(f(1)([[1,3],[0,0],[1,0],[3,3],[0,2],[3,0],[0,0],[2,0],[0,3],[1,2]])) // 800/4+0.75=200.75 console.log(f(0)([[0,0],[0,1],[0,2],[0,3],[2,1],[1,2],[2,2]])) // 789/263=3 console.log(f(2)([[0,3],[0,1],[2,1],[0,0],[2,3],[1,0],[0,2],[3,0],[1,2],[3,0],[2,3]])) // 0.6+4-0/2/4=0.575 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~135 133~~ 132 bytes ``` ->r,c{a="";c.map{|x,y|a=((w="789/456*123-00.+"[[y*4+x,12-x*4+y,15-y*4-x,x*4+3-y][r]])=~/[0-9.]/?a:"#{eval a}")+w;w}*""+"=#{eval a}"} ``` [Try it online!](https://tio.run/##XU7RbsIwDHzfV6DsBVqndWxgYyjbh0R@yBA8bRIqY21Uul/v0ihi1V5O57vz2c31PYwnO@rXBg69t0rtD9WnP/e3DsLN2@WyterpeVevN9vCEGvEqlTOhWJddmBId5EEMBsdFd3BNLIO4hqRlf2pHepdJfWbf1GP/fHbfyz8oFZlu2@HQqlS2T91GM/Xr8vi5BicM0ACjoAjYkIDmNCIyENOmpjkqEwZTDhxTnnKCs9cSi4md96DsQdzP953OSuU8xPSbIvSdZz9RvdbnLn59wnlbzlnRMZf "Ruby – Try It Online") Orientation as integer: 0 for 0°, 1 for 90° and so on. [Answer] # Python 3, ~~235~~ ~~234~~ 230 bytes Bit ugly but it works for all the test cases except the first, which doesn't seem to match the example calculator. I take the rotation as 0-3 (0-270) and multiply by 16 to offset. `eval()` is a built-in which attempts to compile strings as code and handles converting the text symbols to operators. ``` import re def f(r,c,J=''.join): b='789/456*123-00.+01470258.369+-*/+.00-321*654/987/*-+963.85207410' s=t=J([b[r*16+x*4+y]for y,x in c]);t=re.split('([\+\-\/\*])',s) while len(t)>2:t=[str(eval(J(t[0:3])))]+t[3:] print(s+'='+t[0]) ``` Alternate method, it turned out a little bit longer but I really like [this SO tip](https://stackoverflow.com/a/9457923/3749967) for rotating the array. ``` import re def f(r,c): L=list;b=L(map(L,['789/','456*','123-','00.+'])) while r:b=L(zip(*b[::-1]));r-=1 s=''.join([b[x][y]for y,x in c]);t=re.split('([\+\-\/\*])',s) while len(t)>2:t=[str(eval(''.join(t[0:3])))]+t[3:] print(s+'='+t[0]) ``` [Answer] # Java 10, ~~418~~ ~~380~~ 378 bytes ``` d->a->{String r="",g=d>2?"/*-+963.85207410":d>1?"+.00-321*654/987":d>0?"01470258.369+-*/":"789/456*123-00.+",n[],o[];for(var i:a)r+=g.charAt(i[1]*4+i[0]);n=r.split("[-/\\+\\*]");o=r.split("[[0-9]\\.]");float s=new Float(n[0]),t;for(int i=1,O,j=0;++j<o.length;O=o[j].isEmpty()?99:o[j].charAt(0),s=O<43?s*t:O<44?s+t:O<46?s-t:O<48?s/t:s,i+=1-O/99)t=new Float(n[i]);return r+"="+s;} ``` Decided to answer my own question as well. I'm sure it can be golfed some more by using a different approach. Input as `int` (`0-3`) and `int[][]` (0-indexed / the same as in the challenge description). Output as `float` with leading `.0` if the result is an integer instead of decimal number. -2 bytes thanks to *@ceilingcat*. **Explanation:** [Try it here.](https://tio.run/##jVFLj5swGLznV1g@ATbGD/IghKAeulIPVQ57JBwoeaxTYhB2UkVRfnsK2XS7cMjmNjOfNd98nl12zNzd6vdV7quyNmDXcHIwsiCbg8qNLBV5uYNwkBeZ1uBnJtV5AIA2mZE5@Dee/VBmvV3X@EOQyiRpkuJXU0u1nc9BDqLryp1n7vz8roE6ghBvo9Wcx9BzXBSMBJkMOR37jMLpas5iiAilruDMGQ19L5iMW5nGkDJ/TPlwQsQoQK7jwSkcTwLPH44cxoVLKUEQq2Z7maThpqytY1YDOc3sGkVbkr9l9TdjyYSljo9kQlM7VFFNdFVIY8HE9ZZLtFw6KbTD8pOeUDdIl0vS6puizAzQkVr/AS8ttlTrg81tXXM8kBHDC7yLaIjQblaSYq225i1cRGWyS4nU3/eVOVl2HATTm3JPRW2so8XMF7F2zLQBfqzRDYxi7d7AJNaemWosUcTchRcEtunkkM099docagVqBCOIdHi5hoOmterwq2hau5d3LOUK7JtCrfdCkhRkdlsuAK8nbdZ7Uh4MqZqRKZSVk6yqipMl7DtoV95bPn/gM8P8gv9TjsVnSruUYdql7HKx7fCrCOxxBNHYdHbSLu1MRTcR7z8WD61414p2rZ67hj6@hvb/iD7IK/qPeT9Rh/KnAvKvvps@7JQ/@EHRn7Lny@D9mkXf@X7cZXC5/gU) ``` d->a->{ // Method with int & 2D int-array parameters and String return String r="", // Result-String, starting empty g=d>2? // If the input is 3: "/*-+963.85207410" // Use 270 degree rotated String :d>1? // Else if it's 2: "+.00-321*654/987" // Use 180 degree rotated String :d>0? // Else if it's 1: "01470258.369+-*/" // Use 90 degree rotated String : // Else (it's 0): "789/456*123-00.+", // Use default String n[],o[]; // Two temp String-arrays for(var i:a) // Loop over the coordinates: r+=g.charAt(i[1]*4+i[0]); // Append the result-String with the next char n=r.split("[-/\\+\\*]"); // String-array of all numbers o=r.split("[[0-9]\\.]"); // String-array of all operands (including empty values unfortunately) float s=new Float(n[0]), // Start the sum at the first number t; // A temp decimal for(int i=0, // Index-integer `i`, starting at 0 O, // A temp integer j=0;++j<o.length // Loop `j` over the operands ; // After every iteration: O=o[j].isEmpty()? // If the current operand is an empty String 99 // Set `O` to 99 : // Else: o[j].charAt(0), // Set it to the current operand character s=O<43? // If the operand is '*': s*t // Multiply the sum with the next number :O<44? // Else-if the operand is '+': s+t // Add the next number to the sum :O<46? // Else-if the operand is '-': s-t // Subtract the next number from the sum :O<48? // Else-if the operand is '/': s/t // Divide the sum by the next number : // Else (the operand is empty): s, // Leave the sum the same i+=1-O/99) // Increase `i` if we've encountered a non-empty operand t=new Float(n[i]); // Set `t` to the next number in line return r+"="+s;} // Return the sum + sum-result ``` [Answer] # [PHP](https://php.net/), ~~267~~ ~~235~~ ~~229~~ ~~225~~ ~~221~~ 213 bytes ``` <?php $t=[1,12,15,4,1];$j=$t[$k=$argv[1]];($o=$i=$t[$k+1])<5&&$o--;foreach(json_decode($argv[2])as$c){echo$s='/*-+963.85207410'[($c[0]*$i+$c[1]*$j+$o)%16];strpos(' /*-+',$s)&&$e="($e)";$e.=$s;}eval("echo'=',$e;"); ``` [Try it online!](https://tio.run/##PY9ha8MgGIT/Sgnvqjam8zVNt2FlP0RkBGuXpmWGGPpl7Lc7k4x9OR6OO44buiGl0/vQDRuYtEGOkmPDDxytgl7DZOCmoR0/HwatVRSChutql2jZqdluIVSVuoTRt66jfQxfH2fvwtnTtSYtayM49u1dFyBq8ryryrdjvX9tpHg5oCCGgjPC7uBaZsAMfQmBPeHRqjiNQ4iUbOYW4RBZHvS6oOBZocDvNUT14x/tnRbzANE55FXBVEpJJmNqLizPv1aVWcXC9R9jVrk4gtcL4z/PGfsL "PHP – Try It Online") 6 bytes thanks to @Kevin Cruijssen. Input directions are: 0 is 0, 1 is 90, 2 is 180 and 3 is 270 degrees. ## Ungolfed The rotation is tricky, my idea is to re-map the symbols depending on orientation. The re-mapping is done by multiplying the x and y coordinates by different amounts and offsetting the result. So, there is a triple per orientation (stored in $rot). There is probably a better way, but I can't think of it at the moment! ``` $coords = json_decode($argv[2]); $symbols = '789/456*123-00.+'; $r=$argv[1]; $rot = [1,4,0,12,1,12,15,12,15,4,15,3]; list($xs,$ys,$o)=array_slice($rot,$r*3,3); $expression=''; foreach($coords as $coord) { $symbol=$symbols[($coord[0]*$xs+$coord[1]*$ys+$o)%16]; if (!is_numeric($symbol) && $symbol!='.') { $expression = "($expression)"; } $expression .=$symbol; echo $symbol; } eval ("echo '='.($expression);"); ?> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~57~~ 54 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εžm3ôí…/*-ø"00.+"ª€SIFøí}yθèyнè}JD'=s.γžh'.«så}R2ôR».VJ ``` Uses 0-based coordinates similar as the challenge description, and `[0,1,2,3]` for `[0,90,180,270]` respectively as inputs. [Try it online](https://tio.run/##yy9OTMpM/f//3Naj@3KND285vPZRwzJ9Ld3DO5QMDPS0lQ6tetS0JtjT7fCOw2trK8/tOLyi8sLewytqvVzUbYv1zm0@ui/DUL/48NLaIKPDW4IO7dYL8/r/PzraWMcgVifaEEoaAUkDMNsYyjYEkkZgEQMdYzDbEM4GqYnlMgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/ipuSZV1BaUmyloGTv6WKvpJCYlwJiHp5gb2mgpaSgcXi/QkpqelFqarGmkg6Xkn9pCVA5SHXo/3Nbj@7LNT685fDaRw3L9LV0D@9QMjDQ01Y6tOpR05rgCLfDOw6vra08t@PwisoLew@vqPVyUbct1ju3@ei@DEP94sNLa4OMDm8JOrRbL8zrv86hbfb/o6MNdYxidaKNdIyBpAGYNNQxAJOGsbFcxlzR0cZAFkjOAEyC2MZgdUZQEWMkWSOwrAFYFqTfEKjfAGqeAVyPMVTECKoORBoBVRuAbTNAcoMR3GxjKNsQzWYjqOuMoWpiuYwA). **Explanation:** ``` ε # Map over each of the (implicit) input-coordinates: žm # Push builtin "9876543210" 3ô # Split it into parts of size 3: [987,654,321,0] í # Reverse each inner item: [789,456,123,0] …/*- # Push string "/*-" ø # Zip the lists together: [["789","/"],["456","*"],["123","-"]] "00.+"ª # Append string "00.+": [["789","/"],["456","*"],["123","-"],"00.+"] €S # Convert each inner item to a flattened list of characters # [[7,8,9,"/"],[4,5,6,"*"],[1,2,3,"-"],[0,0,".","+"]] IF # Loop the input-integer amount of times: ø # Zip/transpose the character-matrix; swapping rows/columns í # And then reverse each inner row } # Close the loop (we now have our rotated character matrix) yθèyнè # Index the current coordinate into this matrix to get the character }J # After the map: join all characters together to a single string D # Duplicate the string '= '# Push string "=" s # Swap to get the duplicated string again .γ # Group it by (without changing the order): žh # Push builtin "0123456789" 1/ # Divide it by 1, so it'll become a float with ".0": "0123456789.0" # (1 byte shorter than simply appending a "." with `'.«`) så # And check if this string contains the current character } # Close the group-by, which has separating the operators and numbers # i.e. "800/4+0.75" → ["800","/","4","+","0.75"] R # Reverse this list # i.e. ["0.75","+","4","/","800"] 2ô # Split it into parts of size 2 # i.e. [["0.75","+"],["4","/"],["800"]] R # Reverse the list again # i.e. [["800"],["4","/"],["0.75","+"]] » # Join each inner list by spaces, and then those strings by newlines # i.e. "800\n4 /\n0.75 +" .V # Execute this string as 05AB1E code J # Join this with the earlier string and "=" on the stack # (after which the result is output implicitly) ``` [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 122 bytes ``` pe'1'9r@3co{".-"".*""./"}z[)FL{'0'0'.".+"}+]j{{}{tp}{)<-<-}{tp)<-}}j!!e!<-Ppra{pPj<-d!}msJ'=_+j{><}gB3co{rtp^}mwpe?+'.;;++ ``` [Try it online!](https://tio.run/##HYy7CsIwGEZfxWQJNRcbO0njBQcHcegeongJQrAY0xbB8D97TMvHOZzpuw3hZbvPYFPylkiyCrvq/o5YcIzFPLPA8NPF4RRJmSewoBiocTFC7D3EQnHFx8wB4BCySPHGh2v0jVP8gaDtjmR9oS5uFDz343no/Rnar7dbSkRdU5oS1lqypWF6yarscrJk5WRpDJ5Vfw "Burlesque – Try It Online") Takes args as: `"[[1,2],[2,3],[0,3],[1,0],[1,1]]" 3` ``` pe # Push args to stack '1'9r@ # Range of characters [1,9] 3co # Split into chunks of 3 {".-" ".*" "./"}z[ # Zip in the operators )FL # Flatten the resulting list (giving us the first 3 rows) {'0 '0 '. ".+"}+] # Add the 4th row j # Swap rotation index to top of stack { {} # NOP {tp} # Transpose {)<- <-} # Reverse each column and row {tp )<-} # Transpose and reverse each row } j!!e! # Select which based on rotation spec and eval <- # Reverse the result Pp # Push to hidden stack ra # Read the coords as array { pP # Pop from hidden stack j<- # Reverse the coords (tp'd out) d! # Select this element }ms # For each coord and accumulate result as string J # Duplicate said string '=_+j # Put the equals at the end of the other string {><}gB # Group by whether digits 3co # Split into chunks of 3 { rt # rotate (putting op in post-fix position) p^ # Ungroup }mw # Map intercalating spaces pe # Evaluate the result ?+ # Combine the results '.;;++ # Change .* ./ etc to * / ``` ]
[Question] [ ## Challenge: Create a program that takes input of a positive non-zero integer and outputs the 4 next numbers in the sequence described below. *Note: Checking if the input is actually a positive non-zero integer is not necessary* ## Sequence: Every number in this sequence (apart from the first, which is the input) shall be composed of n digits, where n is an even number. If we split the number to n/2 pairs, for each pair, the first digit should be the amount of times the second digit appeared in the previous number **Visual explanation**: Consider this example "sequence starter" or input `6577` The next number in the sequence should look like this `161527` Because the input has 1 "6", 1 "5" and 2 "7"s. If input has too many digits (more than 9 of a single digit) you wouldnt be able to get a correct output Example: `111111111111` (12 1's) Next number in sequence has to describe 12 1's. Thus we split it into 9 1's and 3 1's (sum 9+3 = 12) Next number: `9131` *You should iterate 4 times for the input, and output it (either return a list/array of 4 integers, or output it by seperating them with a space, newlines are also acceptable)* **"The number can be written in a lot of ways, how do I write it?"**: If you think about it, the example input `6577` can also be written as 271516 (two 7's, one 5, one six). However this is non-valid output. You should iterate the number left to right. Thus 161527. If it was `7657` you would iterate the amount of 7's, then amount of 6's then amount of 5's, thus valid output would be `271615` ## Example I/O: Input:`75` Output:`1715 211715 12311715 4112131715` Input:`1` Output:`11 21 1211 3112` Input:`111111111111` (12 1's) Output:`9131 192113 31191213 23411912` --- This is unlike the "Say what you see" question, because the sequences are different: <https://oeis.org/A005150> <- This one returns numbers like this: Input: 1211 Output: 111221 While the sequence I'm asking for would do Input: 1211 Output: 3112 The two sequences are different and require different algorithms. My asked sequence: <https://oeis.org/A063850> "Possible duplicate" sequence: <https://oeis.org/A005150> --- **Important specification:** Since it wasnt clear enough for some people who tried to answer this question, the correct output for k chars where k > 9 is not "kc" (where c is char) but 9c(k-9)c etc. Thus correct output for 12 1's isn't `121` (12 1) but `9131`(9 1's, (12-9) 1's and so on) If in doubt, your code is wrong if it ever outputs a number with an odd amount of digits (like 121), it should have output of even digit numbers due to the nature of the sequence. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") thus code with least bytes wins. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~111~~ 104 bytes ``` $z=$args;1..4|%{($z=-join($z-split'\B'|group|%{for($c,$n=$_.Count,$_.Name;$c-gt9;$c-=9){"9$n"}"$c$n"}))} ``` [Try it online!](https://tio.run/nexus/powershell#@69SZauSWJRebG2op2dSo1qtARTQzcrPzAMydIsLcjJL1GOc1GvSi/JLC4DSaflFGirJOip5tirxes75pXklOkCGX2JuqrVKsm56iSWIsrXUrFayVMlTqlVSSQZRmpq1////N0QCAA "PowerShell – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 116 bytes ``` x=input() exec"x=''.join(x.count(n)/9*(`9`+n)+`x.count(n)%9`+n for i,n in enumerate(x)if n not in x[:i]);print x;"*4 ``` [Try it online!](https://tio.run/nexus/python2#TchBCoMwEAXQfU8xCJIZLZZCNyqeRAopEmEK/ZGQwNw@xVX7lq/aojhKZrkEC1tji3PDOyrYhi0WZIbcxo796HtI73/bnkN7TKRXkIICyiekVw5sojuBEPP5tk76lPlIikw2N92jVnf/474 "Python 2 – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ ~~23~~ 21 bytes ``` 4F©Ùv9y«®y¢9‰`U×XyJ}= ``` [Try it online!](https://tio.run/nexus/05ab1e#@2/idmjl4ZlllpWHVh9aV3lokeWjhg0JoYenR1R61dr@/2@ICQA "05AB1E – TIO Nexus") **Explanation** ``` 4F # 4 times do: © # store a copy of the current number in register Ùv # for each unique digit y in the number 9y« # concatenate 9 with y ®y¢ # count occurrences of y in current number 9‰ # divmod by 9 `U # store the result of modulus in X × # repeat the number "9y" result_of_div times X # push result of modulus y # push y J # join everything to one number } # end inner loop = # print the current number without popping ``` [Answer] # Mathematica, 117 bytes ``` Grid@{Rest@NestList[FromDigits[Join@@(Reverse/@Tally@IntegerDigits@#//.{a_,b_}/;a>9->{9,b}~Sequence~{a-9,b})]&,#,4]}& ``` Seems like it shouldn't need to be this long. [Answer] # C# 246 bytes ``` namespace System{using Linq;using f=String;class p{static void Main(f[] s){f p=s[0];for(int i=0,n;i++<4;Console.Write(p+" "))p=f.Concat(p.GroupBy(c=>c).SelectMany(g=>new int[(n=g.Count())/9].Select(_ =>"9"+g.Key).Concat(new[]{n%9+""+g.Key})));}}} ``` Ungolfed: ``` namespace System { using Linq; using f = String; class p { static void Main(f[] s) { f p = s[0]; for (int i = 0, n; i++ < 4; Console.Write(p + " ")) p = f.Concat(p.GroupBy(c => c).SelectMany(g => new int[(n = g.Count()) / 9].Select(_ => "9" + g.Key).Concat(new[] { n % 9 + "" + g.Key } ))); Console.ReadKey(); } } } ``` [Try it here](https://dotnetfiddle.net/1rxarw) (Type input into bottom frame once its compiled and hit ENTER) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` L,Ḣ D©®i$ÞŒgs9$€Ç€€FḌµ4µÐ¡Ḋ ``` [Try it online!](https://tio.run/nexus/jelly#@@@j83DHIi6XQysPrctUOTzv6KT0YkuVR01rDrcDCSBye7ij59BWk0NbD084tPDhjq7///8bIgEA "Jelly – TIO Nexus") The successive `€`s cannot be nested because chains cannot be nested. [Nesting with separate link: 27 bytes.](https://tio.run/nexus/jelly#@19seWirj87DHYsObX3UtIbL5dDKQ@syVQ7POzop/XA7UMTt4Y6ehztbDm01ObQQqKRx2////w2RAAA "Jelly – TIO Nexus") [Print instead of cumulation: 27 bytes.](https://tio.run/nexus/jelly#@19seWirj87DHYsObX3UtIbL5dDKQ@syVQ7POzop/XA7UMTt4Y6ehztbDm01ObQQqKRx2////w2RAAA "Jelly – TIO Nexus") **Explanation** ``` L,Ḣ - helper function, does the look-and-say. Input is a list of digits , - return 2-tuple of: L - length of input Ḣ - first element of input D©®i$ÞŒgs9$€Ç€€FḌµ4µÐ¡Ḋ - main link, takes input as integer µ4µÐ¡ - repeat 4 times, saving the results of each iteration: D - convert integer to list of digits © - save into register, for later use ®i$Þ - sort list's elements by first occurrence in list Œg - group runs of equal elements s9$€ - split each run into sets which are at most 9 elements long Ç€€ - do the look-and-say with helper function FḌ - flatten and convert back into integer for next iteration Ḋ - remove the first element from the list since it includes the initial element ``` [Answer] # PHP, 141 Bytes ``` for($a=$argn;$i++<4;$a=$o,print$a._,$o="")foreach(array_count_values(str_split($a))as$n=>$c)$o.=str_repeat("9$n",$c/9^0).($c%9?($c%9).$n:""); ``` [Try it online!](https://tio.run/nexus/php#HY1BCsMgFET3PYb8ghKxXbSUxNjcpPIR2wSCytcUenprshmYecPMOKU5nQDpEwx73Jmu70gc0ByRhqXrxpvefZSJllAAlZUQDWOiNT26mSMR/qyLWyj2i@vmM8@FbE7rUtqUEJghmCc4AVGZHZFPHgtnPQQmwV3611UoDu7cT4cKBWFoD7rWPw "PHP – TIO Nexus") ]
[Question] [ In this challenge you'll be building a program that grows as it traverses through the ages… Until it's 2017. ## Challenge Whenever this challenge description says “program”, you can also read “function”. Your submission, when executed, will output a program that is `THE LENGTH OF YOUR SUBMISSION` + `1` bytes long. When *that* program is executed, it will output a program that is `THE LENGTH OF YOUR SUBMISSION` + `2` bytes long… and so on. *However*, when your program has reached a length of 2017 bytes, it must instead output `2017` and exit. ## Rules * The output of the final program has to be `2017` and only `2017`. It can be a string or an integer, but it must read `2017` and not `2017.0` or `0x7E1` or other such nonsense. * No [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/13486). * ***Only*** your initial program is allowed to require input, which will be added to your bytecount. So if your initial program is 324 characters long and takes an input of 13 bytes, your total score will be *324 + 13 = 337* *and* the program outputted by it must be ***338*** bytes long. + Using command line flags (e.g. `perl -X`) is fine, however – as long as your initial program as well as all generated programs use the *same* flags. Also, they too count towards the total bytecount. Dashes, slashes etc. in front of a command line flag don't count towards the total, so e.g. `perl -X` counts as *one* additional byte. * If you return a function, it should be an actual function and not a string that, when evaluated, produces a function. * [Improper quines](https://codegolf.meta.stackexchange.com/q/4877/13486 "What counts as a proper quine?") (if your program is a quine) are disallowed. ## Example > > ### Pseudocode, 99 bytes > > > > ``` > IF (PROGRAM LENGTH == 2017) > PRINT 2017 > ELSE > PRINT (THE SOURCE OF THIS PROGRAM + 1 BYTE PADDING) > > ``` > > Your submission may work differently, as long as it complies with the rules above. [Answer] ## [\*><>](https://esolangs.org/wiki/Starfish), ~~29~~ ~~28~~ 30 bytes ``` " r::2+l'-':*7-(?ul1-n;Ol?!;ou ``` [Try it here!](https://starfish.000webhostapp.com/?script=EQAgTgXBBMDUA2ByAtIiAqA7MgFAfgFd4BGZAOwG4B5ePAQgoHsCg) (\*[try with 2017 bytes](https://starfish.000webhostapp.com/?script=EQAj4yunb+GKclq3o5r2e7-gwo4k0s8iyq6m2u+hxp5l1t9jzr7n3v-gYKHkATgC4xAJgDUAGwDkAWnliAVAHZFACgD8AV1kBGRQDsA3AHlZOgIRmA9nqA)) \*set delay to 0ms or you might have to wait a long time This adds an additional each subsquent run. If it has 2017 bytes and is run, it will output 2017 and stop execution with no other output. Update: Saved 1 byte by checking if the length is less than 2017 instead of equal Update 2: Fixed output for +2 bytes ### Explanation ``` " r: 2+ build quine : copy extra " " l push length to stack '-':*7- push "2018" to stack (?u O if not length < 2018: l1-n; output length-1 and exit Ol?!;ou output entire stack and exit ``` [Answer] # Python 2.7, 90 bytes Here's a relatively simple one: ``` p='q';s=r"p+='q';print('p=\''+p+'\';s=r\"'+s+'\";exec s')if len(p)<1929 else'2017'";exec s ``` [Try the first iteration here!](https://tio.run/nexus/python2#@19gq16obl1sW6RUoA1mFhRl5pVoqBfYxqiraxdoq8eAZWOU1LWLgRwl69SK1GSFYnXNzDSFnNQ8jQJNG0NLI0uF1JziVHUjA0NzdZiS//8B) [Try the penultimate iteration here!](https://tio.run/nexus/python2#@l9gq144CkbBKABsFIyCUTAKBgqoWxfbFikVaAMrZHXrgqLMvBIN9QLbGHV17QJt9RiwbIySunYxkKNknVqRmqxQrK6ZmaaQk5qnUaBpY2hpZKmQmlOcqm5kYGiuDlPy/z8A) [Try the final iteration here!](https://tio.run/nexus/python2#@l9gq144CkbBKABsFIyCUTAKBgyoWxfbFikVaANrZHXrgqLMvBIN9QLbGHV17QJt9RiwbIySunYxkKNknVqRmqxQrK6ZmaaQk5qnUaBpY2hpZKmQmlOcqm5kYGiuDlPy/z8A) Ungolfed: ``` p='q' # The length of string p is the number of iterations so far. s=r"p+='q';print('p=\''+p+'\';s=r\"'+s+'\";exec s')if len(p)<1928 else'2017'" exec s # s contains the source code, but also contains a line saying "p += 'q'", # which makes the byte count longer. When the length of p is 1928 (i.e. when the # entire program is 2017 bytes long), 2017 is printed instead. ``` [Answer] # Microscript II, 38 bytes ``` {v{h}sl+s""+vK#s2017=(2017ph)lp"~"ph}~ ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 34 bytes ``` ":l' '95**)b*f3++0.1-}'#'r>o<:ln;# ``` [Try it online!](https://tio.run/nexus/fish#@69klaOuoG5pqqWlmaSVZqytbaBnqFurrqxeZJdvY5WTZ638/z8A "><> – TIO Nexus") Note that, in order to test this for smaller values, your value (minus 1) must be able to be generated in 7 bytes. ## Explanation ``` ":l' '95**)b*f3++0.1-}'#'r>o<:ln;# "................................. push this string : duplicate l push length of stack ' '95** push 2016 ) 1, if length > 2016, 0 otherwise b* multiply by 11 f3++ add 18 0. jump to that character on this line if the length is sufficiently long, this skips the next 10 characters, to the 11th (`b` from earlier): :ln; (if length is > 2016) : duplicate l push length n output as number ; terminate 1-}'#'r>o< (if length <= 2016) 1- subtract 1 from the last char, `#`, to get `"`, } which is then moved to the bottom '#' pushes `#` (will be appended) r reverses the stack >o< output stack, until error (accepted by default) # This is never reached, but is used to generate `"` ``` [Answer] # Java, 251 Bytes (Eclipse IDE) ``` import java.io.*;class G{public static void main(String[]args) throws Exception{File x=new File("./src/G.java");if(x.length()==2017){System.out.print("2017");}else{PrintWriter y=new PrintWriter(new FileOutputStream(x,1>0));y.print("A");y.close();}}}// ``` This is assuming the project was made in Eclipse, using the convention of `.java` files in the SRC of the working dir. There are other ways to detect where the source is, but I don't think this is against the rules either. Basically opens the .java source-code, and appends As until 2017 (after a comment). When the file-size of the source reaches a total of 2017 bytes, it will instead print 2017. [Answer] # C, 197 Bytes ``` #define A "" char*s="#define A %c %s%c%cchar*s=%c%s%c;%cmain(){printf(sizeof A==1820?%c2017%c:s,34,A,34,10,34,s,34,10,34,34);}"; main(){printf(sizeof A==1820?"2017":s,34,A,34,10,34,s,34,10,34,34);} ``` [Answer] # Python 2, ~~217~~ ~~167~~ 78 bytes Note that there should be a trailing newline. I used similar concepts to what Calconym used, so thanks for the inspiration! ``` p='q';s='p+=p[0];print"p=%r;s=%r;exec s"%(p,s)if len(p)<1941else 2017';exec s ``` [**Try it online**](https://tio.run/nexus/python2#@19gq16obl1sq16gbVsQbRBrXVCUmVeiVGCrWgQUBRKpFanJCsVKqhoFOsWamWkKOal5GgWaNoaWJoapOcWpCkYGhubqUFVc//8DAA) [Try at 2016](https://tio.run/nexus/python2#@19gq144CkbBKBgFo2AUjIJBAdSti23VC7RtC6INYq0LijLzSpQKbFWLgKJAIrUiNVmhWElVo0CnWDMzTSEnNU@jQNPG0NLEKDWnOFXByMDQXB2q6v9/AA); [Try at 2017](https://tio.run/nexus/python2#@19gq144CkbBKBgFo2AUjILBAdSti23VC7RtC6INYq0LijLzSpQKbFWLgKJAIrUiNVmhWElVo0CnWDMzTSEnNU@jQNPG0NLEKDWnOFXByMDQXB2q6v9/AA) --- **Previous Version:** This program uses the `inspect` module to get the current line number. Then, it prints itself but with an extra line after the import, which changes the line number for the next program. There should also be a trailing newline here. ``` from inspect import* n=stack()[0][2];s='from inspect import*%sn=stack()[0][2];s=%r;print(s%%(chr(10)*n,s))if n<1852else 2017';print(s%(chr(10)*n,s))if n<1852else 2017 ``` [Try it online](https://tio.run/nexus/python2#hcqxCoAgEADQva9wETUaVIiC6kuiIURJqkvu/H/bWgp68ysBr5NFoORdZvFMF@a6gony6napZr3MdhloEl@P0ztyHBJGyJI4l25DabSqoSGlYmAwmr61/iDPrDadeOrfrEq5AQ) [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~39~~ ~~33~~ 30 bytes ``` 33q:X~ ``` with the input ``` 2017:N=N{33')X+`":X~"+}? ``` [Try it online!](https://tio.run/nexus/cjam#@29sXGgVUff/v5GBobmVn61ftbGxumaEdoISUFRJu9YeAA "CJam – TIO Nexus") This is functionally equivalent to my previous version, except that it avoids the need to write and escape the quotes. The previous version: ``` 33"2017:N=N{33')X+`\":X~\"+}?":X~ ``` Which outputs ``` 33")2017:N=N{33')X+`\":X~\"+}?":X~ ``` which outputs ``` 33"))2017:N=N{33')X+`\":X~\"+}?":X~ ``` and so on. Finally, the program ``` 33"))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))2017:N=N{33')X+`\":X~\"+}?":X~ ``` Outputs `2017`. **How it works** ``` 33 Push 33 q Read the input: 2017:N=N{33')X+`":X~"+}? :X Store it in variable X ~ Eval it ``` But what does the code in the input actually do? ``` 2017:N Push 2017 and store it in N = Check if the other number (33 on first run) equals 2017 N If it does, push 2017 { Else, execute this block: 33 Push 33 ') Push the ) character X Push X + Concatenate with ') ` String representation (wraps it in quotes, escapes quotes inside) ":X~" Push the string ":X~" + Concatenate }? (end of block) ``` If the first number of the program isn't equal to 2017, then it will output a program in which that number is incremented one more time than it was this time. If it does equal 2017 (i.e. it's been incremented 1984 times), then simply push 2017 and terminate. The first number starts out as 33 (the length of the code); every increment increases the code length by 1 AND that number by 1, so when 33 has been incremented enough to become 2017, the code will also be 2017 bytes long. [Answer] # JavaScript, ~~98~~ 83 bytes That was quite a challenge… Guess that's what I get for requiring actual functions to be returned and not just the function's source. ## Original function ``` function x(){return "3".length>1933?2017:Function(`return ${x}`.replace(/3/,33))()} ``` I'm using `function` instead of `=>` here because the latter doesn't support named functions, just assigning anonymous functions to a variable. ## First iteration Running the above in your browser console returns a function that, when cast to a string, looks like: ``` function x(){return "33".length>1933?2017:Function(`return ${x}`.replace(/3/,33))()} ``` ## Getting to 2017 Since every function returns a new function, you can call the original function / its result 1934 times to get *2017*. ``` console.log(( function x(){return "3".length>1933?2017:Function(`return ${x}`.replace(/3/,33))()} )()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()() ) ``` Tested with Firefox. ]
[Question] [ ## Introduction and credit Assume you're a bartender. You have many happy people in your bar at most times, but many only ever drink the very same drink and too few for your taste and you want to change that. So you introduce a system where the price of a drink is variable, depending on how many have already been sold, but never more or less expensive than certain thresholds. For some odd reason you always forget to keep proper track of all sold drinks and prices and thus you need to think of a short (= memorable!) piece of code that does the math for you given the amount of drinks consumed. This challenge has already appeared in the mid-term exam in 2012 at the functional programming course at my uni and I've got my professor's ok to post it here. We have been provided an example solution in the exam's language. ## Input Your input will be a list of strings which don't contain spaces - these are the names of the drinks sold. Take the input using your preferred, [generally accepted input method.](http://meta.codegolf.stackexchange.com/q/2447/55329) ## Output Your output will be a single number - this is the income you have generated this evening. Give the output using your preferred, [generally accepted output method.](http://meta.codegolf.stackexchange.com/q/2447/55329) ## What to do? This applies for each drink individually: * The starting price is 10. * Each time the drink is bought, it's price is bumped up by 1 for the next buyer. * The maximal price is 50. If the drink has been bought for 50 the new price will be 10 again. Your task is to find the overall income, generated by the input list of drinks given the above rules. --- In case you're wondering: "50 bucks is really damn expensive for a drink!", this is 50-deci Bucks, so 50 \* 0.1 \* Unit, but I've opted to go for 10-50 to not exclude languages without floating point arithmetic. ## Who wins? This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Standard rules apply.](http://meta.codegolf.stackexchange.com/q/1061/55329) ## Potential Corner Cases If the input list is empty, the output shall be 0. The input list icannot be assumed to be sorted by drink. ## Examples ``` [] -> 0 ["A"] -> 10 ["A","B"] -> 20 ["A","A","B"] -> 31 ["A","B","A"] -> 31 ["A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A"] -> 1240 ["A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","B","B","B","C","C","D"] -> 1304 ["D","A","A","C","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","B","B","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","B","C"] -> 1304 ["A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","B","B","B","C","C","D","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A"] -> 1304 ``` [Answer] # JavaScript (ES6), 50 bytes ``` a=>a.map(x=>t+=d[x]=d[x]<50?d[x]+1:10,t=0,d={})&&t ``` [Answer] # Python 2, ~~79~~ ~~74~~ ~~54~~ 48 Bytes Massive byte count increase by rethinking the problem. ~~I would like to get rid of the `int` cast but my brain isn't working~~. Making use of `l.pop()` to avoid trimming the list twice and some good old lambda recursion :) ``` f=lambda l:l and l.count(l.pop())%41+10+f(l)or 0 ``` *thanks to Jonathan Allan for saving 6 bytes :)* My old 54-byte version I was quite proud of :) ``` f=lambda l:int(l>[])and~-l.count(l[0])%41+10+f(l[1:]) ``` [Answer] # Pyth, 15 bytes ``` ssm<*lQ}T50/Qd{ ``` A program that takes input of a list and prints the result. [Test suite](http://pyth.tryitonline.net/#code=RlEuUQpzc208KmxRfVQ1MC9RZHs&input=IlRlc3RzIgpbXQpbIkEiXQpbIkEiLCJCIl0KWyJBIiwiQSIsIkIiXQpbIkEiLCJCIiwiQSJdClsiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIl0KWyJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJCIiwiQiIsIkIiLCJDIiwiQyIsIkQiXQpbIkQiLCJBIiwiQSIsIkMiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkIiLCJCIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJCIiwiQyJdClsiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJCIiwiQiIsIkIiLCJDIiwiQyIsIkQiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIl0) (First line to allow multiple input) **How it works** ``` ssm<*lQ}T50/Qd{ Program. Input: Q ssm<*lQ}T50/Qd{Q Implicit input fill {Q Deduplicate Q m Map over that with variable d: }T50 Yield [10, 11, 12, ..., 48, 49, 50] *lQ Repeat len(Q) times < /Qd First Q.count(d) elements of that s Flatten s Sum Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14 11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 50⁵rṁЀĠSS ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=NTDigbVy4bmBw5DigqzEoFNT&input=&args=WyJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkIiLCJCIiwiQiIsIkMiLCJDIiwiRCIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiXQ)** ### How? ``` 50⁵rṁЀĠSS - Main link: list of drink names e.g. ['d', 'a', 'b', 'a', 'c'] Ġ - group indices by values e.g. [[2, 4], [3], [5], [1]] ⁵ - 10 50 - 50 r - inclusive range, i.e. [10, 11, 12, ..., 48, 49, 50] ṁЀ - mould left (the range) like €ach of right(Ð) e.g. [[10, 11], [10], [10], [10]] note: moulding wraps, so 42 items becomes [10, 11, 12, ..., 48, 49, 50, 10] S - sum (vectorises) e.g. [40, 11] S - sum e.g. 51 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes Thanks to *Emigna* for saving a byte! ``` ÎÙv¹y¢L<41%T+OO ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w47DmXbCuXnCokw8NDElVCtPTw&input=WyJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkIiLCJCIiwiQiIsIkMiLCJDIiwiRCIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiLCJBIiwiQSIsIkEiXQ) [Answer] # Perl 41 Bytes Includes +1 for `-p` ``` $\+=$H{$_}+=$H{$_}?$H{$_}>49?-40:1:10;}{ ``` Takes input on newlines. Increments a hash value by: `10` if it's `undef`, `-40` if it's `> 49` i.e. `50`, or `1` otherwise. This is then added to `$\`, the output separator, which the `-p` prints. **Example:** ``` $ echo -e 'A\nB\nA' | perl -pe '$\+=$H{$_}+=$H{$_}?$H{$_}>49?-40:1:10;}{' 31 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes ``` {.¡€gL<41%T+O ``` **Explanation** `["A","B","A"]` used as example. ``` { # sort input # STACK: ["A","A","B"] .¡ # split on different # STACK: [["A","A"],["B"]] €g # length of each sublist # STACK: [2,1] L # range [1 ... x] (vectorized) # STACK: [1,2,1] < # decrease by 1 # STACK: [0,1,0] 41% # mod 41 # STACK: [0,1,0] T+ # add 10 # STACK: [10,11,10] O # sum # OUTPUT: 31 ``` [Answer] # C++14, 105 bytes As generic unnamed lambda returning via reference parameter. Requires input to be a container of `string` that has `push_back`, like `vector<string>`. Using the `%41+10` trick from Kade's [Python answer](https://codegolf.stackexchange.com/a/102735/53667). ``` [](auto X,int&r){r=0;decltype(X)P;for(auto x:X){int d=0;for(auto p:P)d+=x==p;r+=d%41+10;P.push_back(x);}} ``` Creates an empty container `P` as memory what has been served already. The price is calculated by counting the `x` in `P`. Ungolfed and usage: ``` #include<iostream> #include<vector> #include<string> using namespace std; auto f= [](auto X, int& r){ r = 0; decltype(X) P; for (auto x:X){ int d = 0; for (auto p:P) d += x==p; r += d % 41 + 10; P.push_back(x); } } ; int main(){ int r; vector<string> V; f(V,r);cout << r << endl; V={"A"}; f(V,r);cout << r << endl; V={"A","B"}; f(V,r);cout << r << endl; V={"A","B","C"}; f(V,r);cout << r << endl; V={"A","A"}; f(V,r);cout << r << endl; V={"A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A"}; f(V,r);cout << r << endl; V={"A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","B","B","B","C","C","D"}; f(V,r);cout << r << endl; V={"A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","B","C"}; f(V,r);cout << r << endl; } ``` [Answer] # Mathematica, 64 bytes Feels like it should be shorter. ``` Tr[(19+#)#/2&/@(Length/@Gather@#//.z_/;z>41:>Sequence[41,z-41])]& ``` `Length/@Gather@#` counts the repetitions of each drink. `//.z_/;z>41:>Sequence[41,z-41]` splits any integer `z` exceeding 41 in this into `41` and `z-41`, to reflect the price drop. Then each of the counts is plugged into the formula `(19+#)#/2`, which is the total cost of `#` drinks as long as `#` is at most 41. Finally, `Tr` sums up those costs. [Answer] # k, 22 bytes The argument can be any list - strings, numerics etc. ``` {+/,/10+(#:'=x)#\:!41} ``` The `q` translation is easier to read: ``` {sum raze 10+(count each group x)#\:til 41} ``` [Answer] # **C#, 193 bytes + 33** An extra 33 bytes for `using System.Collections.Generic;` ``` void m(string[]a){int t=0;Dictionary<string,int>v=new Dictionary<string,int>();foreach(string s in a){if(v.ContainsKey(s)){v[s]=v[s]==50?10:v[s]+1;}else{v.Add(s,10);}t+=v[s];}Console.WriteLine(t);} ``` I'm sure this can be golfed to oblivion, Dictionaries are definitely not the best way to do this and I could probably work a ternary into my if. Aside from that I think it's okay! Examples: ``` a = {"A", "A", "A", "B", "B", "C"}; //output = 64 a = {"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A",, "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A", "A" ,"A" "A" ,"A", "A" ,"A", "B", "B", "C"}; //output 727 ``` Ungolfed ``` void m(string[] a) { int t=0; Dictionary<string,int> v = new Dictionary<string,int>(); foreach(string s in a) { if(v.ContainsKey(s)) { v[s]=v[s]==50?10:v[s]+1; } else { v.Add(s,10); } t+=v[s]; } Console.Write(t); } ``` [Answer] ## Clojure, 79 bytes ``` #(apply +(mapcat(fn[l](for[i(range l)](+(mod i 41)10)))(vals(frequencies %))))) ``` Counts frequencies of drinks, then calculates the base price as `10 + (i % 41)`. `mapcat` concatenates them and `apply +` calculates the sum. [Answer] # PHP, 47 bytes ``` while($k=$argv[++$i])$s+=10+$p[$k]++%41;echo$s; ``` takes input from command line arguments; run with `-r`. ]
[Question] [ ## Challenge You've given a map to a friend that looks a bit like this: ``` | / | / | \ | \ D ``` A simple map that starts at the top and ends at the bottom. Sadly, your friend doesn't get it. Can you decode the map so that he can read it? ## Input The input is a string of characters consisting of `|`, `/`, `\`, `D`, `^`, `Y`, *(space)*, and newlines. * `|` tells to stay in the same column. * `\` tells to move to the column to the right and down 1. * `/` tells to move to the column to the left and down 1. * `D` marks the destination. + `^` (if present) tells of a split in the path. + `Y` (if present) tells of a rejoining of paths. Treat it like a `|`. The input will be arranged so that it makes a kind of path: ``` | | \ | ^ / \ / | D | ``` There will always be a space between two paths, and all paths will either rejoin or reach the last line of the input. There will only be one split per map. There is no limit to the length of the input map. There will never be more than two paths. ## Output The output should be a string of directions. * "**L**" should tell your friend to move **L**eft and take 1 step forward. * "**R**" should tell your friend to move **R**ight and take 1 step forward. * "**F**" should tell your friend to move 1 step forward. For the input example map, the output would be as follows: ``` F F L F R R R ``` Note that your friend is starting at the top of the map and facing down the map. Give the directions from his perspective. For an instance of "^", your program must be able to choose the path that leads to the destination (D). If the two paths recombine, your program must choose the straightest path (the one with the most `|`s) to follow. Directions must be separated by spaces, and must end *on* **D**. ## Examples **Input** ``` | | \ \ ^ / | | | \ | \ \ \ \ \ / Y D ``` **Output** ``` F F L L L F F F L L R F ``` Since the leftmost path contains only 1 `|`, we use the rightmost path that has 3. --- **Input** ``` \ | / | \ | / D ``` **Output** ``` L F R F L F R ``` --- **Input** ``` / \ / \ ^ \ \ D \ ``` **Output** ``` R L R L R L ``` ## Other details * This is code golf, so the person with the shortest code by next Wednesday, the 19th of August, wins. * Constructive feedback welcome and greatly appreciated. * Partially inspired by [A Map to Hidden Treasure](https://codegolf.stackexchange.com/q/54301/42768) * Feel free to change the title to something more creative. * If you find mistakes that I made, correct them. * And of course, have fun. ## Thank you! A bit late, maybe, but UndefinedFunction is the winner coding in JavaScript! Thanks to all who entered. No other entries will be accepted. [Answer] # PHP, 634 631 607 396 382 381 347 338 330 337 324 bytes My first ever golf so be gentle. Any tips are greatly appreciated. ``` <?php foreach(str_split(strtr(fgets(STDIN),[' '=>'']))as $i){if($i!=D){$z=$i=='^';$x=$i==Y;$s=!$z&&!$x?($i=='/'?R:($i=='|'?F:($i=='\\'?L:$s))):$s;$a.=$z?R:($x?F:(($c==1||!$c)?$s:''));$b.=$z?L:($x?F:(($c==2||!$c)?$s:''));$c=$z?1:($x?0:($c==1?2:($c==2?1:$c)));}else{echo(substr_count($a,F)<substr_count($b,F)&&$c==0||$c==2)?$b:$a;}} ``` **Short Explanation:** I have a count which is 0 if the Input has only one path. When the path splits the count is 1 for the left path and 2 for the right path. After defining both paths (or only one) I check which path has more "F's". **Ungolfed Version:** ``` <?php $input = fgets(STDIN); $inputArray = str_split($input); foreach ($inputArray as $currentChar) { if ($currentChar != 'D') { if ($i == '^') { $firstPath .= 'R'; $secondPath .= 'L'; $count = 1; } elseif ($i == 'Y') { $secondPath .= 'F'; $firstPath .= 'F'; $count = 0; } else { if ($i == ' ') { continue; } if ($i == '/') { $direction = 'R'; } else { if ($i == '|') { $direction = 'F'; } else { if ($i == '\\') { $direction = 'L'; } else { $direction = ''; } } } if ($count == 1) { $firstPath .= $direction; $count = 2; } elseif ($count == 2) { $secondPath .= $direction; $count = 1; } if (!$count) { $firstPath .= $direction; $secondPath .= $direction; } } } else { echo (substr_count($firstPath, 'F') < substr_count($secondPath, 'F')) || $count == 2 ? $secondPath : $firstPath; } }; ``` **Log:** Saved 36 Bytes thanks to Kamehameha. Saved many many bytes by changing the logic a bit. Saved 42 Bytes thanks to axiac. Replaced every if statment with ternary operators. [Answer] # Javascript (ES6), ~~261~~ ~~248~~ ~~252~~ ~~248~~ 212 bytes Since only one split has to be supported: ``` s=>(s=s.replace(/ /g,o="",d=0).split(` `)).map((v,j)=>{if(v=="^")for(v="/\\";(w=s[++j])&&(x=w[1]);d=x=="D"?1:w[0]=="D"?0:x>"{"?d+1:w[0]>"{"?d-1:d);o+=(p=v[d>0?1:0]||v[0])<"0"?"R ":p<"E"?"":p=="\\"?"L ":"F "})?o:o ``` However, ***240 bytes*** and we can deal with multiple splits: ``` s=>(s=s.replace(/ /g,o="").split(` `)).map((v,j)=>{if(!v[1])t=d=0 else if(!t){for(t=1;(w=s[++j])&&(x=w[1]);d=x=="D"?1:w[0]=="D"?0:x>"{"?d+1:w[0]>"{"?d-1:d);o+=d>0?"L ":"R "}o+=(p=v[d>0?1:0])<"0"?"R ":p<"E"||p=="^"?"":p=="\\"?"L ":"F "})?o:o ``` Both programs define anonymous functions. To use, give the function(s) a name by adding `f=` before the code. Afterwards, they can be called with ``` alert(f( ` | | \\ | ^ / \\ / | D |` )) ``` ### Explanation (outdated, but still the same concept. For the multiple split solution) ``` s=> //Remove all spaces from the input (s=s.replace(/ /g,o="", //Define function c, to convert symbols to directions c=p=>p<"0"?"R ":p<"E"||p=="^"?"":p=="\\"?"L ":"F " //Split input into an array by newlines ).split(` `)) //for each string v in the input array, at index j: .map((v,j)=>{ //if v is only one character long: if(!v[1]){ t=1 //assign t to 1 (true) - we need to test if multiple paths d=0 //assign d to 0 - reset the counter for determining shortest path } //if v is two characters long, and we have not tested which path is shorter yet: else if(t){ for( t=0; //assign t to 0 - we will have tested which path is longer //for each string left in the input, while the input still has two characters: (w=s[++j]) && w[1]; //assign d to determine which direction to go. This will be conveyed by if d>0 d= w[1]=="D"?1: //if the dest. is only on one side, choose that side. w[0]=="D"?0: w[1]=="|"?d+1: //otherwise add/subtract from d (like a tug of war) to determine which side has more "|" w[0]=="|"?d-1: d ); o+=d>0?"L ":"R " //append to the output which direction was taken } o+=c(v[d>0?1:0]) //append to the output the characters from the correct path in any case, determined by d calculated above //(or defaulting to 0, if path is not split, in which case the only character is appended) }) ? o : o //coerce the result, which will evaluate to an array of the input, to the output (o) and implicitly return ``` ### Notes * All backslashes (`\`) in the input are escaped as `\\`, so that javascript can recognize them. * Both outputs contain a trailing space. [Answer] # PHP, 281 bytes ``` $b=0;$p=['|'=>'$a[$b].="F ";$f[$b]++;','/'=>'$a[$b].="R ";','\\'=>'$a[$b].="L ";','^'=>'$d.=$a[0];$n=2;$a=["R ","L "];$f=[];$b=1;','Y'=>'$d.=$a[$f[0]<$f[$n=1]]."F ";$a=[];','D'=>'$d.=$a[$b];exit(rtrim($d));'];foreach(str_split($argv[$n=1])as$c){if($x=$p[$c]){eval($x);$b=++$b%$n;}} ``` It is the result of two golfing iterations. The ungolfed version is: ``` $a=$f=[]; // these assignments are not required (they were suppresed in v2) $n=1; // this assignment can be squeezed into $argv[$n=1] $b=0; // if this assignment is suppressed $b becomes '' and breaks the logic $code = [ '|' => '$a[$b].="F ";$f[$b]++;', '/' => '$a[$b].="R ";', '\\'=> '$a[$b].="L ";', '^' => '$d.=$a[0];$n=2;$a=["R ","L "];$f=[];$b=1;', 'Y' => '$d.=$a[$f[0]<$f[$n=1]]."F ";$a=[];', 'D' => '$d.=$a[$b];echo(rtrim($d));', ]; foreach (str_split($argv[1]) as $char) { // ignore input characters not in the keys of $code if ($x = $code[$char]) { eval($x); $b = ++ $b % $n; // cycles between 0 and 1 ($n == 2) or stays 0 ($n == 1) } } ``` It is pretty golfed itself and it emerged as an improvement of the following golfed program (312 bytes): ``` $b=0;foreach(str_split($argv[$n=1])as$c){if($c=='|'){$a[$b].='F ';$f[$b]++;}elseif($c=='/'){$a[$b].='R ';}elseif($c=='\\'){$a[$b].='L ';}elseif($c=='^'){$d.=$a[0];$n=2;$a=['R ','L '];$f=[];$b=1;}elseif($c==Y){$d.=$a[$f[0]<$f[$n=1]].'F ';$a=[];}elseif($c==D){$d.=$a[$b];exit(rtrim($d));}else continue;$b=++$b%$n;} ``` It is the golfed version of the original: ``` $map = $argv[1]; $dir = ''; // the already computed directions $nb = 1; // the number of branches $branches = [ '' ]; // the branches (2 while between '^' and 'Y', 1 otherwise) $nbF = [ 0, 0 ]; // the number of 'F's on the branches (used to select the branch) $curr = 0; // the current branch foreach (str_split($map) as $char) { if ($char == '|') { // go 'F'orward $branches[$curr] .= 'F '; // put it to the current branch $nbF[$curr] ++; // count it for the current branch } elseif ($char == '/') { // go 'R'ight $branches[$curr] .= 'R '; } elseif ($char == '\\') { // go 'L'eft $branches[$curr] .= 'L '; } elseif ($char == '^') { // fork; choose the path ('L' or 'R') that contains the most 'F'orward segments $dir .= $branches[0]; // flush the current path (it was stored as the first branch) $nb = 2; // start two branches $branches = [ 'R ', 'L ' ]; // put the correct directions on each branch $nbF = [ 0, 0 ]; // no 'F's on any branch yet $curr = 1; // need this to let it be 0 on the next loop } elseif ($char == 'Y') { // join $dir .= $branches[$nbF[0] < $nbF[1]]; // flush; choose the branch having the most 'F's $dir .= 'F '; // treat it like a "|" $branches = [ '' ]; // back to a single, empty branch $nb = 1; } elseif ($char == 'D') { // finish $dir .= $branches[$curr]; // flush break; // and exit; could use 'return' but it's one byte longer; use exit() in the final program and save 5 bytes } else { continue; } $curr = ++ $curr % $nb; } echo rtrim($dir); ``` Example execution: ``` $ php -d error_reporting=0 directions.php ' | | \ \ ^ / | | | \ | \ \ \ \ \ / Y D '; echo F F L L L F F F L L R F $ ``` It also handles multiple forks correctly (need to join before the next fork in order to have at most two branches any time). I asked about multiple forks in a comment but the code was already done when the answer ("not needed") came. The complete code with test suite and more comments can be found [on github](https://github.com/axiac/code-golf/blob/master/giving-directions.php). ]
[Question] [ There are 16 distinct [boolean functions](http://mathworld.wolfram.com/BooleanFunction.html) for two binary variables, A and B: ``` A B | F0 | F1 | F2 | F3 | F4 | F5 | F6 | F7 | F8 | F9 | F10 | F11 | F12 | F13 | F14 | F15 ----------------------------------------------------------------------------------------- 0 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 0 1 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 1 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 1 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 ``` The less than operator `<`, which normally isn't thought of as a logic operator like NOT, AND, or OR, is in fact one of these functions (F4) when applied to boolean values: ``` A B | A < B ----------- 0 0 | 0 0 1 | 1 1 0 | 0 1 1 | 0 ``` Interestingly, we can simulate *any* of the 15 other functions using expressions that only contain the symbols `()<AB10`. These expressions are read and evaluated just as they would be in many standard programming languages, e.g. parentheses must match and `<` must have arguments on either side of it. Specifically, these expressions must comply with the following grammar (given in [Backus-Naur form](http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form)): ``` element ::= A | B | 1 | 0 expression ::= element<element | (expression)<element | element<(expression) | (expression)<(expression) ``` This means that useless paretheses and expressions of the form `A<B<1` are not allowed. So the expression `A<B` matches the function F4, and `A<B<1` must be changed to `(A<B)<1` or `A<(B<1)`. To prove that all of the 15 other functions can be turned into expressions, it suffices to form a set of expressions that is [functionally complete](http://en.wikipedia.org/wiki/Functional_completeness), because then, by definition, they can be composed into expressions for any function. One such set of expressions is `x<1` (where `x` is `A` or `B`), which is [`¬x`](http://en.wikipedia.org/wiki/Negation), and `(((B<A)<1)<A)<1`, which is [`A → B`](http://en.wikipedia.org/wiki/Material_conditional). Negation (`¬`) and implication (`→`) are [known to be](https://proofwiki.org/wiki/Functionally_Complete_Logical_Connectives/Negation_and_Conditional) functionally complete. # Challenge Using the characters `()<AB10`, write 16 expressions in the form described above that are equivalent to each of the 16 distinct boolean functions. The goal is to make each of the expressions as short as possible. Your score is the sum of the number of characters in each of your 16 expressions. The lowest score wins. Tiebreaker goes to the earliest answer (provided they didn't edit their answer later with shorter expressions taken from someone else). You do not technically need to write any real code for this contest but if you did write any programs to help you generate the expressions, you are highly encouraged to post them. You can use this Stack Snippet to check if your expressions do what's expected: ``` function check() { var input = document.getElementById('input').value.split('\n'), output = '' if (input.length == 1 && input[0].length == 0) input = [] for (var i = 0; i < 16; i++) { var expected = [(i & 8) >> 3, (i & 4) >> 2, (i & 2) >> 1, i & 1] output += 'F' + i.toString() + '\nA B | expected | actual\n-----------------------\n' for (var j = 0; j < 4; j++) { var A = (j & 2) >> 1, B = j & 1, actual = '?' if (i < input.length) { try { actual = eval(input[i]) ? 1 : 0 } catch (e) {} } output += A.toString() + ' ' + B.toString() + ' | ' + expected[j] + ' | ' + actual.toString() + ' ' if (expected[j] != actual) output += ' <- MISMATCH' if (j != 3) output += '\n' } if (i != 15) output += '\n\n' } document.getElementById('output').value = output } ``` ``` <textarea id='input' rows='16' cols='64' placeholder='put all 16 expressions here in order, one per line...'></textarea><br><br> <button type='button' onclick='check()'>Check</button><br><br> <textarea id='output' rows='16' cols='64' placeholder='results...'></textarea><br> "?" means there was some sort of error ``` [Answer] There are a few options for some of these, so this 100-char set isn't identical to the previously posted ones. ``` 0 (B<A)<A B<A A A<B B ((A<B)<((B<A)<1))<1 (A<(B<1))<1 A<(B<1) (A<B)<((B<A)<1) B<1 (A<B)<1 A<1 (B<A)<1 ((B<A)<A)<1 1 ``` An easier proof that `<` is functionally complete would be that `A<(B<1)` gives NOR. The code which I used to find this is a heavy simplification of some Boolean optimisation code I've used on earlier challenges, with two small changes: 1. Make the score of an expression be the length of its string rather than the number of operations. 2. Make the string avoid unnecessary parentheses, to minimise the length. ``` import java.util.*; public class PPCG48193 { public static void main(String[] args) { Expr[] optimal = new Expr[16]; int unfound = 16; PriorityQueue<Expr> q = new PriorityQueue<Expr>(); q.offer(new Expr(0, "0")); q.offer(new Expr(15, "1")); q.offer(new Expr(3, "A")); q.offer(new Expr(5, "B")); while (unfound > 0) { Expr e = q.poll(); if (optimal[e.val] != null) continue; optimal[e.val] = e; unfound--; for (Expr e2 : optimal) { if (e2 != null) { Expr e3 = e.op(e2), e4 = e2.op(e); if (optimal[e3.val] == null) q.offer(e3); if (optimal[e4.val] == null) q.offer(e4); } } } for (Expr e : optimal) System.out.println(e.expr); } private static class Expr implements Comparable<Expr> { public final int val; public String expr; public Expr(int val, String expr) { this.val = val; this.expr = expr; } public Expr op(Expr e) { String l = expr.contains("<") ? String.format("(%s)", expr) : expr; String r = e.expr.contains("<") ? String.format("(%s)", e.expr) : e.expr; return new Expr((15 - val) & e.val, String.format("%s<%s", l, r)); } public int compareTo(Expr e) { int cmp = expr.length() - e.expr.length(); if (cmp == 0) cmp = val - e.val; return cmp; } } } ``` [Answer] # 100 characters ``` 0 (A<1)<B B<A A A<B B ((B<A)<((A<B)<1))<1 (A<(B<1))<1 A<(B<1) (B<A)<((A<B)<1) B<1 (A<B)<1 A<1 (B<A)<1 ((A<1)<B)<1 1 ``` [Answer] # 100 characters ``` 0 (A<B)<B B<A A A<B B ((A<B)<((B<A)<1))<1 (B<(A<1))<1 B<(A<1) (A<B)<((B<A)<1) B<1 (A<B)<1 A<1 (B<A)<1 ((A<B)<B)<1 1 ``` [Answer] ## 100 characters ``` 0 (A<1)<B B<A A A<B B ((A<B)<((B<A)<1))<1 ((B<1)<A)<1 (B<1)<A (A<B)<((B<A)<1) B<1 (A<B)<1 A<1 (B<A)<1 ((A<1)<B)<1 1 ``` Hey, it's not *exactly* the same as the other ones. I spent like 10 minutes on this so it's worth posting anyways, even if this is 2 years old. [Answer] # 100 characters ``` 0 (A<1)<B B<A A A<B B ((A<B)<((B<A)<1))<1 (A<(B<1))<1 A<(B<1) (A<B)<((B<A)<1) B<1 (A<B)<1 A<1 (B<A)<1 ((B<1)<A)<1 1 ``` ]
[Question] [ You work at a virtual, old-fashioned printing press. To help you arrange your monospace letters faster, you decide to make the shortest program possible to help you. Given a string of text and a page size, generate and output each page of the text. ## Examples For example, with a page width of 14, height 7, and some text, here is your book: ``` 14, 7, "Fruits make an extremely good snack due to their utterly scrumptious sweetness. They are also very healthy for you." +------------+ | Fruits | | make an | | extremely | | good snack | | due to | +------------+ +------------+ | their | | utterly | | scrumptio- | | -us | | sweetness. | +------------+ +------------+ | They are | | also very | | healthy | | for you. | | | +------------+ ``` Here's the basic page setup: ``` |---i.e.14---| +------------+ - | Xxxxxxxxxx | | | Xxxxxxxxxx | i. | Xxxxxxxxxx | e. | Xxxxxxxxxx | 7 | Xxxxxxxxxx | | +------------+ - ``` ## A few things 1. There is a one-space margin between the page edges and the text. 2. The width and height include the box edges, if that wasn't clear. 3. Wraparound only occurs if a word can't fit on a single line. 4. The program needs to be able to output as many pages as needed, and only that many. 5. Your program has to support any page size, not just 14 by 7. 6. This is code golf, so the smallest solution in bytes (any language) wins. 7. Don't ruin the fun. Standard loopholes are obviously not allowed. ## Oh, and, by the way: ``` +------------+ | May the | | best book | | publisher | | win. Good | | Luck! | +------------+ +------------+ | Best | | program | | so far: | | Charcoal | | | +------------+ ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~306~~ ~~304~~ ~~283~~ 279 bytes ``` def f(w,h,s): b=[];w-=4;h-=2;H='+-'+'-'*w+'-+';x=l='';s=s.split() while s: W=s.pop(0) if W[w:]:W,s=W[:w-1]+'-',['-'+W[w-1:]]+s if len(l+W)<=w-(l>x):l+=' '*(l>x)+W else:b+=[l];l=W b+=[l]+[x]*h while any(b):print'\n'.join([H]+['| %-*s |'%(w,b.pop(0))for _ in' '*h]+[H,x,x]) ``` [Try it online!](https://tio.run/##NU/LbtswEDxbX7EJEJA0JaNOAwSgyhwD99CeAuigCIVkr0I2NCmQVCUB@XeXMpLLYB@zM7PDEpWz95fLCXvo6ZSrPDCRQSfrppwK@VCqQt6XB0l4QTgpyHZKyEk5SyMJKYMMuzAYHSnLYFLaIASRbao0HtxAv7Fso3uo6kk0osqDrGoxFftmVcrrBDytir1oGh6uTIOWGl6xH3IqqHmamTBcEiDba8OrbIMmoOi4rE1TGlmlqNea13OzVV8ZWrvQjonBaxvJqyW7v05bWh8SjXzAXbEN8EHu0rvdZ0zWOw9/QNvVSyXaIZ/zuWGXnu4fcnjM4fbZjzoGOLfvqz7gHD2e0Szw5twJgm2P73AaEaKDqFB7GGNEn/bh6MfzELUbA4QJMVoMYQcvChdofRIzwcE/9AsobE1UC6xhFjfublnW0@T9Pdm/KI8IP8N6B7/aN32E3@O5Q3@TWJf/ "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~105~~ 83 bytes ``` NθNηM⁺η²↑F⪪S «W›Lι⁻θ⁴«⊞υ⁺…ι⁻θ⁵-≔⁺-✂ι⁻θ⁵Lι¹ι»⊞υι»Fυ«¿‹Lι±ⅈ «M⁻⁻⁴ⅈθ¹¿¬﹪ⅉ⊕η«↙↙Bθη↘→»»ι ``` [Try it online!](https://tio.run/##bVHBSgMxED13v2LwlIVVUCqCnhRRCm0pVkGP6@50E0yTNpm0XaTfvk6yqLV4SGAmb96891LJ0lW21F03MqtA07B8RyfW@U12WEuuJ3aDYqaDF7KAi7yA65cVtxfWgZivtCKRJubklGkEv5/ASZ7DZzbYSqURxKPDkphsjKYhKRRDJsow37qAYd5DB7PgpQgFpEUTq2uhDmCXeeQ9Zd4bxt56rxrTa@JmAXOtKjwaKOBg3zkfFWf32c@mWO97GyFpUAtgjd4fCp1iw9rFq8ij0BlbJBH9ZQPUHpPylE@/uL@HBUR8Aeu0OSqO1FNLbKwO2oq3GNPIVA6XaAhrzvk7h57u@t5uzRgXlKb/7d3ZXTQqjxFPqpF/xn4b@95/MpHcd935MLvKHlxQ5GFZfiCUBnBHUZhuobG2Bm/K6gPqgEAWSKJyEIj/k9995cJyRcoGD36LSIbjO4NniS2Ujsm0t7BB14LEUpNsIcbd2nDWnW70Fw "Charcoal – Try It Online") Link is to verbose version of code ~~the deverbosifier can't handle the `ⅈ` and `ⅉ` nilary operators~~. If leading blank lines were acceptable, I could get it down to 76 bytes: ``` ≔⁻N⁴θMθ→NηF⪪S «W›Lιθ«⊞υ⁺…ι⊖θ-≔⁺-✂ι⊖θLι¹ι»⊞υι»Fυ«¿‹⁺ⅈLιθ «F¬﹪ⅉ⊕η«⸿↙↙B⁺θ⁴η»⸿»ι ``` Explanation: ``` NθNη ``` Input the width into `q` and the height into `h`. ``` M⁺η²↑ ``` Move to a position that will trigger the first box to be drawn, but without generating a top margin. ``` F⪪S « ``` Loop over all the words in the input string. ``` W›Lι⁻θ⁴« ``` Repeat while a word is too wide to fit into a box. ``` ⊞υ⁺…ι⁻θ⁵- ``` Push as much of the word that will fit plus a trailing hyphen. ``` ≔⁺-✂ι⁻θ⁵Lι¹ι» ``` Prefix a hyphen to the rest of the word. ``` ⊞υι» ``` Push the rest of the word. ``` Fυ« ``` Loop over all the hyphenated words. ``` ¿‹Lι±ⅈ ``` Check whether the word fits on the current line. ``` « ``` If so then print a space. ``` M⁻⁻⁴ⅈθ¹ ``` Otherwise move to the start of the next line. ``` ¿¬﹪ⅉ⊕η ``` Check whether we need a new box. ``` «↙↙Bθη↘→»» ``` If so then draw the box. ``` ι ``` Finally, print the word. [Answer] # [Perl 5](https://www.perl.org/), ~~203~~ 182 + 1 (`-a`) = 183 bytes ``` $t=($\=-3+shift@F)-2;$h=shift@F}{say$_='+'.'-'x$\.'-+';map{$_="";{$_.=shift@F;s/.{$t}\K..+/-/&&unshift@F,-$&;$_.=$";y///c+length$F[0]<$\&&redo}printf"| %-$\s| ",$_}3..$h;say;@F&&redo ``` [Try it online!](https://tio.run/##NY/BTsMwEETvfMUqMgkotdNSKg4mUk@5IG7cCKqsdltHTezIXkOtNr9OCKKcRrvzdjTbo2tX48iovGN1yZe5182e1tU9f5BMl9dpOHsV2abM8kxkPDuxepI8k53qz9M6SeQk4p@WvhBnRkP9IkRe8CJNg7laM85S@YuyRMaiKLZ5i@ZAmlXv849nVqepw50detcY2icXuOWs9pebZMY2w1IIpuVURK6rP24cF4/wBJULDXno1BFBGcATOeywjXCwdgfeqO0RdgGBLJDGxkEgmt6O4LcudD01NnjwX4hk0HsBbxojKDeFtd7CJ7oIGlVLOsLeOog2iG/7e2b8yF9XYr6Yj1z9AA "Perl 5 – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 92 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` Aē:b⁾\&?Q¶oQ}cI@*¼|a31žO■ .⁾:0EHC┌*¼+Q,θK;{⁴D@Κ+lc<‽Xd■Flc<‽ø;c⁾{Kh+;}D┌+■d┌Κ}}}■beb⁾%-⁾{ø■} ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=QSV1MDExMyUzQWIldTIwN0UlNUMlMjYlM0ZRJUI2b1ElN0RjSUAqJUJDJTdDYTMxJXUwMTdFTyV1MjVBMCUwQS4ldTIwN0UlM0EwRUhDJXUyNTBDKiVCQytRJTJDJXUwM0I4SyUzQiU3QiV1MjA3NERAJXUwMzlBK2xjJTNDJXUyMDNEWGQldTI1QTBGbGMlM0MldTIwM0QlRjglM0JjJXUyMDdFJTdCS2grJTNCJTdERCV1MjUwQysldTI1QTBkJXUyNTBDJXUwMzlBJTdEJTdEJTdEJXUyNUEwYmViJXUyMDdFJTI1LSV1MjA3RSU3QiVGOCV1MjVBMCU3RA__,inputs=MTQlMEFGcnVpdHMlMjBtYWtlJTIwYW4lMjBleHRyZW1lbHklMjBnb29kJTIwc25hY2slMjBkdWUlMjB0byUyMHRoZWlyJTIwdXR0ZXJseSUyMHNjcnVtcHRpb3VzJTIwc3dlZXRuZXNzLiUyMFRoZXklMjBhcmUlMjBhbHNvJTIwdmVyeSUyMGhlYWx0aHklMjBmb3IlMjB5b3UuJTBBNw__,v=0.12) [Answer] # JavaScript (ES8), 242 bytes *Thanks to @Tvde1 for reporting a bug* ``` (s,w,h)=>s.split` `.map(g=s=>l=(l+s)[W=w-5]?s[l&&A(l),l='',w-4]?g('-'+s.slice(W),A(s.slice(0,W)+'-')):s:l?l+' '+s:s,n=o=l='',h-=2,b=`+${'-'.repeat(w-2)}+ `,A=s=>o+=(!n|n++%h?'':b+` `+b)+`| ${s.padEnd(w-3)}| `)&&(g=s=>A(s)&&n%h?g(''):b+o+b)(l) ``` [Try it online!](https://tio.run/##NZDRasIwFIbvfYozcTYhadmcY1CI4sX2BAMvhtBoj7YzTUpOalfUZ3fZxu7O4fzfz8f51CdNO1@3IbWuxNte3RjJXlZcLSij1tShgCJrdMsOitTCKGYE8Y@16tPnzZI@zHS6YoZLo5JE9ul8szywJE1EhE29Q7bmcsX@lwe55iJeOc8pN0sjEojJnKRVTv02VKmaya0qxOQcc5nHFnVgfTrjVzEq5OrHwQnF7uzFCnFfLZMk34piVIgtF8UFJmfKWl2@2jJCT/x6GRV8Ov1zjx5xthGKigmPnItUlL/tnCVnMDPuwPZs/Oa7OhA0@oigLeBX8NigGeDgXAlk9e4IZYcQHIQKaw9dCOjjPX6ya9pQu46AesRgkSiD9woH0D6WGXJwQj9AhdqEaoC98zC4LhtLeJxLeOH89g0 "JavaScript (Node.js) – Try It Online") ### Commented ``` (s, w, h) => // given s = string, w = width, h = height s.split` ` // get all words by splitting the string on spaces .map(g = s => // for each word s: l = (l + s)[W = w - 5] ? // if the word is too long for the current line: s[ l && A(l), // append the line (if not empty) l = '', // clear the line w - 4 ] ? // if the word itself doesn't fit: g( // do a recursive call with: '-' + s.slice(W), // a hyphen + the next part A(s.slice(0, W) + '-') // and append the current part + a hyphen ) // end of recursive call : // else: s // initialize a new line with this word : // else: l ? // if the current line is not empty: l + ' ' + s // append a space + the word : // else: s, // initialize a new line with this word n = o = l = '', // n = line counter, o = output, l = line h -= 2, // adjust h b = `+${'-'.repeat(w - 2)}+\n`, // b = border + linefeed A = s => // A = function that updates the output o: o += ( // append to o: !n | n++ % h ? // if we haven't reached an end of page: '' // an empty string : // else: b + `\n` + b // bottom border + linefeed + top border ) + // followed by `| ${s.padEnd(w - 3)}|\n` // left border + padded text + right border ) && // end of map() (g = s => // g = recursive function taking s: A(s) && // append s n % h ? // if we haven't reached an end of page: g('') // go on with an empty line : // else: b + o + b // return top border + output + bottom border )(l) // initial call to g() with the last pending line ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 93 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 1,⁴Ṭị⁾+-W,` ṣ⁶µḊṖs⁴_6¤j⁾--;@Ḣ;Ṫḟ0s⁴_©4¤µ€ẎŒṖK€€µL€>®ẸµÐḟṪ;€⁶x®¤ḣ€®s⁵_2¤Zz⁶x®¤j@€€⁾| ,U¤j@€¢ẎY ``` A full program taking three arguments (`text`, `width`, `height`) which prints the pages. **[Try it online!](https://tio.run/##y0rNyan8/99Q51Hjloc71zzc3f2ocZ@2brhOAtfDnYsfNW47tPXhjq6HO6cVAxXEmx1akgWU19W1dni4Y5H1w52rHu6YbwCWOrTS5NCSQ1sfNa15uKvv6CSgDm8gG4gObfUBknaH1j3ctePQ1sMTgDqA@qxBko3bKg6tO7Tk4Y7FIHXrgOZsjTc6tCSqCiaT5QAxA2hnjYJOKFTg0CKgFZH///9XCskoSk1V8CxWCMlIVfBNTM9MVvArzU1KLVJU@m/@3wQA "Jelly – Try It Online")** N.B. Too inefficient to run the example from the OP within the 60 second limit. ([97 bytes](https://tio.run/##y0rNyan8/99Q51Hjloc71zzc3f2ocZ@2brhOAtfDnYsfNW47tPXhjq6HO6cVAxXEmx1akgWU19W1dni4Y5H1w52rHu6YbwCWOrTS5NCSQ1sfNa15uKvv6CSgDm8gG4gObfUBknaH1j3ctePQ1sMTgDqA@qxBko3bKg6tO7Tk4Y7FIHXrgOZsjTc6tCSqCiaT5QAxA2hnjYJOKFTg0KJIIAlyyKFth7b9//8/JKMoNVXBs1ghJCNVwTcxPTNZwa80Nym1SPG/@X8TAA "Jelly – Try It Online") if the blank line between pages is actually a requirement) ### How? ``` 1,⁴Ṭị⁾+-W,` - Link 1, make header & footer: no arguments ⁴ - program's 2nd argument, width 1 - literal one , - pair = [1,width] Ṭ - untruth = [1,0,0,...,0,0,1] (a 1 at index 1 and index width; 0 elsewhere) ⁾+- - literal list of characters = "+-" ị - index into (1-based & modular) = "+--...--+" W - wrap = ["+---...--+'] ` - use as both arguments of the dyad: , - pair = [["+---...--+'],["+---...--+']] ṣ⁶µḊṖs⁴_6¤j⁾--;@Ḣ;Ṫḟ0s⁴_©4¤µ€ẎŒṖK€€µL€>®ẸµÐḟṪ;€⁶x®¤ḣ€®s⁵_2¤Zz⁶x®¤j@€€⁾| ,U¤j@€¢ẎY - Main link. This is long so splitting it up into parts like so: ṣ⁶µ "A" µ€ "B" µ "C" µÐḟ "D" ṣ⁶ - split 1st argument (text) at spaces µ "A" µ€ - for €ach resulting word do "A" (get hyphenated parts) "B" - do "B" (all ways to partition those joining with spaces) µÐḟ - filter discard if: µ "C" - do "C" (any parts are too long) "D" - do "D" (format the resulting list into the page-format) "A" = ḊṖs⁴_6¤j⁾--;@Ḣ;Ṫḟ0s⁴_©4¤ - Hyphenate: list, word e.g. "Something" Ḋ - dequeue "omething" Ṗ - pop "omethin" ¤ - nilad followed by link(s) as a nilad ⁴ - program's 2nd argument e.g. 9 (width) 6 - literal six 6 _ - subtract 3 s - split into chunks ["ome","thi","n"] ⁾-- - literal list of characters "--" j - join "ome--thi--n" Ḣ - head (word) "S" ;@ - concatenate (sw@p arguments) "Some--thi--n" Ṫ - tail (word) "g" ; - concatenate "Some--thi--ng" ḟ0 - filter out zeros (tail yields 0 for words of length 1) ¤ - nilad followed by link(s) as a nilad: ⁴ - program's 2nd argument 9 4 - literal four 4 _ - subtract 5 © - copy to register & yield 5 s - split into chunks ["Some-","-thi-","-ng"] "B" = ẎŒṖK€€ - Line arrangements: list of lists of hyphen-parts / single words Ẏ - flatten by one (make a list of words and hyphen-parts - e.g. [["Not"],["hyph-","-ena-","-ted"]] -> ["Not","hyph-","-ena-","-ted"] ŒṖ - partition e.g. [1,2,3]->[[[1],[2],[3]],[[1],[2,3]],[[1,2],[3]],[[1,2,3]]] K€€ - join with spaces for €ach for €ach e.g. ["one","two"]->"one two" "C" = L€>®Ẹ - Any part too long?: one of the list of lines from "B" L€ - length of €ach ® - recall from the register (width minus 4) > - greater than (vectorises) - 1 if so 0 if not Ẹ - any truthy? (1 if any too long) "D" = Ṫ;€⁶x®¤ḣ€®s⁵_2¤Zz⁶x®¤j@€€⁾| ,U¤j@€¢ẎY - Format as pages: list of valid arrangements Ṫ - tail (last valid partition is greediest) ¤ - nilad followed by links as a nilad: ⁶ - literal space character ® - recall from register (width minus 4) x - repeat elements ;€ - concatenate to €ach ® - recall from register (width minus 4) ḣ€ - head €ach to index ¤ - nilad followed by links as a nilad: ⁵ - program's 3rd argument, height 2 - literal two _ - subtract Z - transpose ¤ - nilad followed by link(s) as a nilad: ⁶ - literal space character ® - recall from register (width minus 4) x - repeat elements z - transpose with filler (repeated spaces) ¤ - nilad followed by link(s) as a nilad: ⁾|<space> - literal list of characters = "| " U - upend = " |" , - pair = ["| "," |"] j@€€ - join for €ach for €ach (sw@p arguments) ¢ - call last link (1) as a nilad j@€ - join for €ach (sw@p arguments) Ẏ - flatten by one Y - join with line feeds - implicit print ``` [Answer] # PHP, 299 bytes ``` for($a=explode(" ",$argv[3]);$y|$e=strlen($d=$a[+$i++]);$x||print"|",$x|$e<$w?$e<$w-$x?$x+=$e+print" $d":$i-=!$x=!$y+=print str_pad("",$w-$x)." | ":$y+=print" ".substr($d,0,$w-2)."- | ".!$a[--$i]="-".substr($d,$w-2),$y>$argv[2]-2&&$y=!print"$t ")$y||$y=print$t=str_pad("+",2+$w=$argv[1]-3,"-")."+ "; ``` Run with `php -nr '<code>' <width> <height> '<text>'` or or [try it online](http://sandbox.onlinephpfunctions.com/code/0ad8bd1baeea07f4799904a590177032a05cc293). ]
[Question] [ [Inspiration.](https://chat.stackexchange.com/transcript/message/39052298#39052298) [Inverse.](https://codegolf.stackexchange.com/questions/84162/convert-an-expression-to-panfix-notation) Evaluate a given omnifix expression. Omnifix is like normal mathematics' infix notation, but with additional copies of each symbol surrounding the arguments. The outer symbols take the place of parentheses, and there is therefore no need for additional parentheses. You must support addition, subtraction, multiplication, division, and positive real numbers (negative ones can be written `-0-n-`) within a reasonable range for your language. Plus and minus must be `+` and `-`, but you may use `*` or `×` for times and `/` or `÷` for divide. Other reasonable symbols will be allowed upon request. Brownie points for explanation and additional features (like additional operations, negative numbers, strings, etc.) Even if your answer does not have these features, feel free to show how it could. Please provide a link to test your solution if at all possible. ### Examples For clarity, the explanations below use high minus (`¯`) to indicate negative numbers. You may return negative numbers using any reasonable format. `-5-2-` → `3` `+2+×3×2×+` → `8` (`+2+×3×2×+` → `+2+6+` → `8`) `-14--3-1--` → `12` (`-4--3-1--` → `-14-2-` → `12`) `+2.1+×3.5×2.2×+` → `9.8` (`+2.1+×3.5×2.2×+` → `+2.1+7.7+` → `9.8`) `×3×÷-0-6-÷2÷×` → `-9` (`×3×÷-0-6-÷2÷×` → `×3×÷¯6÷2÷×` → `×3ׯ3×` → `¯9`) `÷4÷-3-÷1÷2÷-÷` → `1.6` (`÷4÷-3-÷1÷2÷-÷` → `÷4÷-3-0.5-÷` → `÷4÷2.5÷` → `1.6`) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 198 197 188 bytes ``` float O(string s){try{return float.Parse(s);}catch{var f=s[0];int i=s.IndexOf(f,1);float a=O(s.Substring(1,i-1)),b=O(s.Substring(i+1,s.Length-i-2));return f<43?a*b:f<44?a+b:f<46?a-b:a/b;}} ``` [Try it online!](https://tio.run/##lU87b8IwEN75FRZTnORsHAIDKWLoVIkKJIYOqMMlOMESOJJtUFGU356a0IfKVG6wPt35exUWitrIjvgpDmgtWZu6MngcXDdN/17HOnSq6MpDjY6sAuuM0hWxtHHm0hjpTkaT/sjWaKwMLM3aAl2xb85oSDm329F7prQjam7Zi97Jj1UZlLGg2U0S516UbU75TTkQsQJBaZzf7VUkYsuWUlduDwoSSrNv96d0vMAwn3mQLjDqwXSBkM@Q51nbdoO7NuRcqx15RaW/@mzfCZrK0p9/v/2vs7lYJ4/suda2Pkj2ZpSTS6VlsAqGMIEEhj7NvxlREoXjMAmjh1ggUoAxCHjUjAlvxyZhwh619Ck5jGAKPOHhQ0yecp@VC08E/ofZ9qjtPgE "C# (.NET Core) – Try It Online") Uses `*` and `/`. A recursive function. It first tries to parse the input string as a `float`. If it fails, it calls itself recursively passing as arguments the first and second operands and then performs the selected operation on the results. * 1 byte saved thanks to Mr. Xcoder! * 9 bytes saved thanks to TheLethalCoder! [Answer] # Python 3, ~~159~~ ~~158~~ ~~152~~ ~~144~~ ~~136~~ ~~135~~ 132 bytes ``` def t(i,a=1): while'-'<l[i]!='/':i+=1;a=0 if a:l[i]='(';i=t(t(i+1));l[i-1]=')' return-~i *l,=input() t(0) print(eval(''.join(l))) ``` [Try it online!](https://tio.run/##HY67UsMwEEXr7FcIN3plLctOKGxUZUJLQ8ek0ARlIsZjexQZkoZfN2vKe869szs98nUcmuXgiqJYPsOFZRG33lnZAvu5xj5w5C/9Rzw9OW54G7WznXcVsHhhvl2F44J30WVBS22l7AiiJSw5sBTynAb8jaD6rYvDNGchIYtKwpTikEX49r3gvPwa4yB6KeVCj0BOjxY2//fZe5oDhU24h7M4SAj3c5gyO769HlMaE6nJ324L7rFG0LVWjaqVBrQ7xAYtrrC0hMu9qstVUcNghc9oaqPA7Az1jKWA5g8 "Python 3 – Try It Online") Doesn't allow negative numbers (though `-0-5-` works of course) and requires python operators. [Answer] # [Retina](https://github.com/m-ender/retina), ~~290~~ ~~287~~ 286 bytes ``` \d+ ¦$&$* ¯¦ ¯ {`\+([¯¦]1*)\+([¯¦]1*)\+ -$1-¯$2- -(¯|¦)(1*)-([¯¦]+1*\2)- -¯$3-¯$1$2- (×|÷)¯(1*\1)([¯¦]1*\1) $1¦$2¯$3 צ×[¯¦]1*×|¯¯¦? ¦ ¯¦|¦¯ ¯ +`-((¯|¦)1*)(1*)-\2\3- $1 -([¯¦]1*)-[¯¦](1*)- $1$2 צ1(1*)×([¯¦]1*)× +צ$1×$2×+$2+ }`÷¦(?=1*÷(¯|¦)(1+)÷)(\2)*1*÷\1\2÷ $1$#3$* ((¯)|¦)(1*) $2$.3 ``` [Try it online!](https://tio.run/##VVA7TgUxEOvnGkRPyUaDmATo0DsIQVokKGgoEB2Pc@QGabdMnznYPs/yPkJaRU7stT3z9f798fm6ruUt0mhu5yYay2g46Gcu0T/b7UWm8B8TO@GxuMTEfiyH0YIHwSdNlKmkAA6SbIeY0ms9aA9jgbRIuPgBkxOkJ5OT1tG0nkn8AwS8p63WaAhDO3xxZn8KR/aWX1LJDDPia1v@QxtP1mRLELtrvcq0UjTCiVaXtEaXIv3O2kfz@ycU6ZdBY8AYHhNO9lykJO3mfJOxPqsUzgshl9xtXld@YCwgJiRkreZOLPfMmYWZtkftfMePrB1mWo8 "Retina – Try It Online") Note: Only capable of integer arithmetic, so some of the test cases have been removed. Accepts and returns negative numbers using the `¯` prefix. Edit: Saved ~~3~~ 4 bytes thanks to @Cowsquack. Explanation: ``` \d+ ¦$&$* ``` I needed some way of handling zero, so I use `¦` as a positive number prefix. The numbers are then converted to unary. ``` ¯¦ ¯ ``` But negative numbers only need a `¯` prefix. ``` {`\+([¯¦]1*)\+([¯¦]1*)\+ -$1-¯$2- ``` Quoting `+`s gets ugly, so I turn additions into subtractions. ``` -(¯|¦)(1*)-([¯¦]+1*\2)- -¯$3-¯$1$2- ``` If the absolute value of the LHS of a subtraction is less than the RHS, switch them around and negate both sides. ``` (×|÷)¯(1*\1)([¯¦]1*\1) $1¦$2¯$3 ``` Also if the LHS of a multiplication or division is negative, negate both sides. ``` צ×[¯¦]1*×|¯¯¦? ¦ ``` Also if the LHS of a multiplication is zero, then the result is zero. Also, two minuses make a plus. ``` ¯¦|¦¯ ¯ ``` But a minus and a plus (or vice versa) make a minus. ``` +`-((¯|¦)1*)(1*)-\2\3- $1 ``` Subtract two numbers of the same sign. Do this repeatedly until there are no such subtractions left. ``` -([¯¦]1*)-[¯¦](1*)- $1$2 ``` If there's still a subtraction, the signs must be different, so add the numbers together. (But only do this once, since this may reveal a subtraction of two numbers of the same sign again.) ``` צ1(1*)×([¯¦]1*)× +צ$1×$2×+$2+ ``` Perform multiplication by repeated addition. ``` }`÷¦(?=1*÷(¯|¦)(1+)÷)(\2)*1*÷\1\2÷ $1$#3$* ``` Perform integer division. One of the above steps will have simplified the expression, so loop back until there are no operations left. ``` ((¯)|¦)(1*) $2$.3 ``` Convert back to decimal. [Answer] # [PHP](https://php.net/), ~~116~~ ~~114~~ 109 bytes *-5 thanks to Martin Ender* ``` for($s=$argv[$o=1];$o!=$s;)$s=preg_replace('#([*+/-])(([\d.]+|(?R))\1(?3))\1#','($2)',$o=$s);eval("echo$s;"); ``` Uses `*` for multiplication and `/` for division. Negative numbers happen to work despite me making no specific attempts for that to be the case. [Try it online!](https://tio.run/##FYxBCsMgEADf0mTBXU1bYo5W/EOvRoqkNjkEFIWc@ndjLjMwh0lbqi@TGn8xIxQNPq@HhahHpyDeNBRFLacc1k8OafdLQNaj5eJ5d4Ro5@/DiT@aN9E8opku9WxgCJLY0EZQSIXD79iFZYvt15GqtQop@MQlFyc "PHP – Try It Online") ### Ungolfed and Explained ``` for($s=$argv[$o=1]; # Initialize with $s = input and $o = 1; $o!=$s;) # While $o != $s # Set $o to $s and set $s to be $s after this regex replacement: $s=preg_replace('#([*+/-])(([\d.]+|(?R))\1(?3))\1#','($2)',$o=$s); # i.e., continue to do this replacement until the result is the same on two consecutive # steps (no replacement was made) # Once $o == $s (i.e. no more replacement can be made), eval the result and print eval("echo$s;"); ``` I'll also explain the regex because it's a bit magical: ``` ([*+/-])(([\d.]+|(?R))\1(?3))\1 ``` ``` ([*+/-]) ``` First, we want to match any of the four operators: `*+/-` ``` ([\d.]+|(?R)) ``` Then, we need to match either a number `[\d.]+` or another valid omnifix expression `(?R)`. ``` \1 ``` Then, we match the same operator that was at the beginning. ``` (?3) ``` Then we do the same thing we did in group 3: match a number or an omnifix expression. ``` \1 ``` Finally, match the initial operator again. Whatever matches this is replaced with `($2)`. This takes the part inside the surrounding operators and puts it inside brackets, so it looks like normal infix notation. [Answer] # [QuadR](https://github.com/abrudz/QuadRS), ~~33~~ ~~32~~ 27 bytes -1 thanks to [Cows Quack](https://codegolf.stackexchange.com/users/41805/cows-quack). -5 thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer). ``` ((.)[\d¯\.]+){2}\2 ⍎¯1↓1↓⍵M ``` with the argument/flag `≡` [Try it online!](https://tio.run/##KyxNTCn6/19DQ08zOibl0PoYvVhtzWqj2hgjrke9fYfWGz5qmwzCj3q3@v7/r2uqa6TLpW2kfXi68eHpRoena3PpGpro6hrrGuqCxPUMQTJ6pkA5PbAsWN3h7boGuma6h7cbHd5@eDrX4e0mQBFjIN8QLARk/H/UuRAA "APL (Dyalog Unicode) – Try It Online") This is equivalent to the 40-byte Dyalog APL solution: ``` '((.)[\d¯\.]+){2}\2'⎕R{⍕⍎1↓¯1↓⍵.Match}⍣≡ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wR1DQ09zeiYlEPrY/RitTWrjWpjjNQf9U0Nqn7UO/VRb5/ho7bJh9aDyEe9W/V8E0uSM2of9S5@1LkQqF9BXddU10hXnQvI0jbSPjzd@PB0o8PTtcECuoYmurrGuoa6MHk9Q5AKPVOgGj24KrCew9t1DXTNdA9vNzq8/fB0iPh2E6CoMVDMECwMZKgDAA "QuadR – Try It Online") ### Explanation (parenthesised text refers to Dyalog APL instead of QuadR)  `(`…`){2}\2` the following pattern twice, and the whole match twice too:   `(.)` any character (`⎕R` is **R**eplaced with:) (`{`…`}` the result of the following anonymous function applied to the namespace ⍵:)  `⍵M` (`⍵.Match`) the text of the **M**atch  `¯1↓` drop the last character (the symbol `+` `-` `×` or `÷`)  `1↓` drop the first character (symbol)  `⍎` execute as APL code  (`⍕` stringify) `≡` (`⍣≡`) repeat the replacement until no more changes happen [Answer] # [Haskell](https://www.haskell.org/), 132 chars (134 bytes, because `×` and `÷` take two bytes in UTF-8) ``` f y|(n@(_:_),r)<-span(`elem`['.'..'9'])y=(read n,r) f(c:d)|(l,_:s)<-f d,(m,_:r)<-f s=(o[c]l m,r) o"+"=(+) o"-"=(-) o"×"=(*) o"÷"=(/) ``` [Try it online!](https://tio.run/##bY9BboNADEX3OYU1GzwdPC2QVCoqUS/QVZcEJSgMSlQgCOgiUtY9QDcchQPMTXoRalg1Srx6tt@35EPafpqiGMcczhes3nAbbqXbyFdq67TCnSlMuYsd7WjtvDiJPEfYmDSDip1Fjvswkxcs3G3YciSHzMWSm2Zu2ghP8T4poJzkk1AiQjUBMdAEtmd6mGlgepRjmR4riKBM63fAjQFaQ/3VfXQNoFFKbLrf7x8QEtY8b45VB5iDkXIB/yoGQSvySVxNXRDKV7YPbO/bXt0syVsSBeTRvZz2pqRecVbfTc937UBP9Ex28O3Ar904w5KNgPferDBcO8n4Bw "Haskell – Try It Online") `f` parses as much of the input as it can and yields the result as well as the remaining string (which is empty in the test cases). If that's not rule-conformant, strip the unparseable remainder string with # [Haskell](https://www.haskell.org/), 139 chars ``` ... g=fst.f ``` [Answer] # Perl, ~~64~~ 53 bytes Include `+1` for `-p` ``` perl -pe 's%([*-/])(([\d.]+|(?0))\1(?3))\1%($2)%&&redo;$_=eval' <<< "/4/-3-/1/2/-/" ``` Accidentally also implements `,` (throws away the first argument) and sometimes `.` (append the arguments together). `.` doesn't work very reliable though since it interferes with decimal point both at the parsing level and at the evaluation level [Answer] # Java 8, ~~205~~ 200 bytes ``` float O(String s){try{return new Float(s);}catch(Exception e){int f=s.charAt(0),i=s.indexOf(f,1);float a=O(s.substring(1,i)),b=O(s.substring(i+1,s.length()-1));return f<43?a*b:f<44?a+b:f<46?a-b:a/b;}} ``` Port of [*@Charlie*'s C# answer](https://codegolf.stackexchange.com/a/136056/52210). -5 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##hY@xboMwEIb3PsUpkw2cHQjJEBpFHdqtYshYdTDEJE6JQdikiRDPTp2UqUPZzr5P/3/fSVwEVrXUp/3XkJfCGHgXSndPAMYKq3IYirISFlKys43SBzC0s82ta6RtGw1afsPbHSCGJn0ubH4kr9dc1lZVGiTtlLZQbAzLj6J5sWROA@VeSu/lNS1IEYQ0@S0Qm5QYZtrMPHpIGChKg@zPr/LDwLBS6oM9Eoohpcl4SfEcL7bCy9ZuiLfCfwyrrcBsLXiW9P0AULdZ6ZRGs0ul9nB2tqPaxycIejcH2N2MlWdWtZbVbmVLTVIywyVGOHOV/zB@5HsLL/L8CQ7DGHGBIU4HstBFsqUXselY181xjivkEfcmWB5zdwEPHYp8ZPunfvgB) ]
[Question] [ In this question each answer will get a "toolbox" that can be used to construct a program/function. The toolbox will consist of two things: * a list of programming languages * a list of valid characters You must write a valid program/function in one of the languages provided using only the characters in the toolbox. Your program/function should output the number of answers already present on this question. Once you have written and posted an answer the language and characters you have used will be removed from the toolbox and 1 new language and 8 new characters will be randomly added to be used as the toolbox for the next answer. ## Rules * Each answer will: + Output the number of valid answers coming before it + Contain a subset of the characters provided in the toolbox for that answer. (repeats are allowed) + Be in one of the languages from the provided toolbox * The next toolbox will determined by [this](https://tio.run/##dVbpbts4EP4dP4VhYFEbKIPIbdJksfskTdFSJCXSpkguD9vqy2dnhpSd7vFjNB@POTkcKsxZe7d/s9yNaf3n@uvm4ZH3ndp83OwT7y2CTycegX0BenmBD2dB8chyVLjKRS7c2hmhlCEgH72jsR29fXoeCRpBu23QRRwRBcvkzK0ffxkwYXlKRrRJNzpEUcy@EHDeSlpMSU29nRlP70ej@GXR8TThuPQqjsaRB2eyfvHw7XnSyFCmV3yqzFWWnTkSUunML4SG4kZ1Q@zlGQeWxCMXeq7RXPG@Doxjg@XHZdB7bxc81GQQhmQNhA13TLQ09aWHUxgL@iYwOW4kVAMVLFfOozSOo1qhwDKGIDTorBx8taYKasilrxu1kpJOVmiDxyaMc3zyjjVrB0qIsCbRqvWHEjF64YcBkiKiCZmGTpoGTupC4IzfEBYvI5@rS3FOuRpPTPiqLTGwiachSm9IHGtHItXjofOWSpiJRCXEMpFBqbIvGIAErZQtZdWkXCaEuVQTB/0tAjXhGulQERPJbkGozPF7Mrg6QE171Duo6LiTniDW32Ci6qHaCZJzyFjSaplLhiJtCAtg8IJsDp70@JhV45qNxNowwrGPDdBUiUaRG9cUQdkJk8nCaOeg/RWAD6gKvMUpmodyusY3RrgTxM2kiHt/wjyPCX3UPB1rCJrPSzJ1LzTKanVZbrRBclnFGtIBiZUelw6cDB34iTMflDvI4z@GL21cnWI97xVccC/Vr/PLjKpNhXhL9sHTTLGGL/wRwJEdveMEPBo9WkWVf/TZVkDSlvdzBO8JG1Ju7QlrHK6qEdWs9XZBBVXiMtRd7y3d/IlH49slnHjWRqSKLLGTioZyN/ELlCsC47Bu2V4uA1vBcVEDU/jNwwHr3JUJetW5LnmeDOr3/UGJbE6K3VoAVBWp8iKDWQQa9QQeoci1ytRCYWTYiMUfqMUggNp/bPwJuaZliL9dk0DNIKDu4M8qLsV9GyxXN0Rli6zIY@9OZyyQUGKghyOUpDHLYT7SEBtTIhD5ZCRL0IKmukKHEugx6q5of0MszGG@Dj8BwosBffaoMgG6uBEv68Ted9aoohqpK0XMSbHU8RBTxUR1oTXa6iVNeR@I1R4QITZ6hCpg6FSsJR9LQuMJLgMnjuFA51Y/34@gIJS7TYzFUHKSkvSFeiqJijGp5DE9SfNw60x0r0UFdM6JDizpDBuqDmOrHLycWhGa@oGYZZOt7SI5SBGtOX@eqMEkP1H201/WUE@iiy94Tguu6jOPkfzLsX45tvc0T7gPtnliFzz6LCx96b5lNQXLM3mUNfwtcEmoqMoydlQ4h7kVHva9a9gQ3ThS98uxTOE2X2K25FeB15uKvDgJtexJe3GWTz2dY3ERLLZ/mBNSPaaTSfDDwkiaOZWX3noyOWGYZ22irRx8D5z@W84mEfPw8te@dE6Y4rmg5z8h3m9vZgpwVGvopdqafrUKPmUj4acKEvbduFDydrfC29v7C8wuM/gk1xnIQ9626R3IRzfCbNN3P8nHbVUJayvwzqq1VW7bNO7Wf6y//L66c@qMMyC42azu6jbn83qZ9/EKjVs3YZC7Q3P3JUg4sW3bsYPpmz76R/wKDuYt7YV3QZpRgc@7j93T7rfFmbTbfVvdNc33PED3lzeNK3jh1t/RdsT/ku3zrjqNafiX09u2sGtu0yYQXXIG951y0MaYg27//B/RkJIaTTMkdPz/UEAJ7DbD1SY6c7OLBhp8F1@1AccGapfEttGPzeb@4I3bJnz@5dXf3Y@3N7D1@enz6uu31YfXy8MDUAe0B/oE9BnoEegJ6AvQ82t@dcB7IPEa4auAhtdLB5IdSHYg2YFkB5IdSHYg2YFk9wz0AsSBQLoTQBII5LuB3FRC@4cPfwM) python program. To generate the next toolbox put in the remaining languages and characters along with the *post id* of the last answer. * The language list here is all the languages available on try it online at the time of this post. The characters have char codes 0-127. * You may write either a full program or a function as your answer. Since REPLs are different languages they will not be allowed. (use the TIO version of every language) * If a language uses a special encoding the characters should be interpreted as *bytes* (decoded from ASCII and padded with a zero). * The starting toolbox will be randomized from this questions post id ([128464](https://tio.run/##dVbpbts4EP4dP4VhYFEbKIPIbdJksfskTdFSJCXSpkguD9vqy2dnhpSd7vFjNB@POTkcKsxZe7d/s9yNaf3n@uvm4ZH3ndp83OwT7y2CTycegX0BenmBD2dB8chyVLjKRS7c2hmhlCEgH72jsR29fXoeCRpBu23QRRwRBcvkzK0ffxkwYXlKRrRJNzpEUcy@EHDeSlpMSU29nRlP70ej@GXR8TThuPQqjsaRB2eyfvHw7XnSyFCmV3yqzFWWnTkSUunML4SG4kZ1Q@zlGQeWxCMXeq7RXPG@Doxjg@XHZdB7bxc81GQQhmQNhA13TLQ09aWHUxgL@iYwOW4kVAMVLFfOozSOo1qhwDKGIDTorBx8taYKasilrxu1kpJOVmiDxyaMc3zyjjVrB0qIsCbRqvWHEjF64YcBkiKiCZmGTpoGTupC4IzfEBYvI5@rS3FOuRpPTPiqLTGwiachSm9IHGtHItXjofOWSpiJRCXEMpFBqbIvGIAErZQtZdWkXCaEuVQTB/0tAjXhGulQERPJbkGozPF7Mrg6QE171Duo6LiTniDW32Ci6qHaCZJzyFjSaplLhiJtCAtg8IJsDp70@JhV45qNxNowwrGPDdBUiUaRG9cUQdkJk8nCaOeg/RWAD6gKvMUpmodyusY3RrgTxM2kiHt/wjyPCX3UPB1rCJrPSzJ1LzTKanVZbrRBclnFGtIBiZUelw6cDB34iTMflDvI4z@GL21cnWI97xVccC/Vr/PLjKpNhXhL9sHTTLGGL/wRwJEdveMEPBo9WkWVf/TZVkDSlvdzBO8JG1Ju7QlrHK6qEdWs9XZBBVXiMtRd7y3d/IlH49slnHjWRqSKLLGTioZyN/ELlCsC47Bu2V4uA1vBcVEDU/jNwwHr3JUJetW5LnmeDOr3/UGJbE6K3VoAVBWp8iKDWQQa9QQeoci1ytRCYWTYiMUfqMUggNp/bPwJuaZliL9dk0DNIKDu4M8qLsV9GyxXN0Rli6zIY@9OZyyQUGKghyOUpDHLYT7SEBtTIhD5ZCRL0IKmukKHEugx6q5of0MszGG@Dj8BwosBffaoMgG6uBEv68Ted9aoohqpK0XMSbHU8RBTxUR1oTXa6iVNeR@I1R4QITZ6hCpg6FSsJR9LQuMJLgMnjuFA51Y/34@gIJS7TYzFUHKSkvSFeiqJijGp5DE9SfNw60x0r0UFdM6JDizpDBuqDmOrHLycWhGa@oGYZZOt7SI5SBGtOX@eqMEkP1H201/WUE@iiy94Tguu6jOPkfzLsX45tvc0T7gPtnliFzz6LCx96b5lNQXLM3mUNfwtcEmoqMoydlQ4h7kVHva9a9gQ3ThS98uxTOE2X2K25FeB15uKvDgJtexJe3GWTz2dY3ERLLZ/mBNSPaaTSfDDwkiaOZWX3noyOWGYZ22irRx8D5z@W84mEfPw8te@dE6Y4rmg5z8h3m9vZgpwVGvopdqafrUKPmUj4acKEvbduFDydrfC29v7C8wuM/gk1xnIQ9626R3IRzfCbNN3P8nHbVUJayvwzqq1VW7bNO7Wf6y//L66c@qMMyC42azu6jbn83qZ9/EKjVs3YZC7Q3P3JUg4sW3bsYPpmz76R/wKDuYt7YV3QZpRgc@7j93T7rfFmbTbfVvdNc33PED3lzeNK3jh1t/RdsT/ku3zrjqNafiX09u2sGtu0yYQXXIG951y0MaYg27//B/RkJIaTTMkdPz/UEAJ7DbD1SY6c7OLBhp8F1@1AccGapfEttGPzeb@4I3bJnz@5dXf3Y@3N7D1@enz6uu31YfXy8MDUAe0B/oE9BnoEegJ6AvQ82t@dcB7IPEa4auAhtdLB5IdSHYg2YFkB5IdSHYg2YFk9wz0AsSBQLoTQBII5LuB3FRC@4cPfwM)), there will be 7 languages to start and I will add the characters `echoprint0` and ascii 0-31 for free to get people started. * You may not answer twice in a row ## Scoring Each time a person answers they will get a number of points for their answer. The goal is to get as many points as possible. For an answer in language X you will get as many turns as language X has gone unused in the toolbox. For example the first person to answer will get 1 point because the language was just added to the toolbox. There will not necessarily be an end and I will not be accepting any answers. ## Sporting This is a competition, but I encourage you to put fun above winning while still staying competitive (if I could make the winning criteria "fun had" I would). Some things that are not fun: * Intentionally using characters you don't need to stunt future answers. * Attempting to game the post id system to make future tool boxes harder to use. * Attempting to game the post id system to make future tool boxes easier to use. I can't prevent any one from doing these things, but I will be downvoting any answers I suspect are doing this. On a more positive note, here are some things that are good sporting and encouraged: * Coordinating with other users in chat. * Saving characters for harder or more restrictive languages > > This is a second iteration of a challenge found [here](https://codegolf.stackexchange.com/questions/126063/macgyvers-toolbox). It improves a number of problems with the first one. [Here](https://codegolf.meta.stackexchange.com/questions/12950/second-iteration-of-a-challenge) is a meta discussing these questions. > > > [Answer] # This is impossible Going through all of the languages in the langbox: 1. The tcl programming language consists of words separated by spaces. The space character is not in the toolbox, so no valid programs can be written. 2. Str programs by default transform input. In order for them to do anything when given no input, the `;` character is required, which is not in the toolbox. 3. The only means for a program in scheme-chez to do anything is by calling a function using parentheses. All scheme-chez programs therefore need the `(` character, which is not in the toolbox 4. Brain-Flak programs need balanced brackets. The only bracket character in the toolbox is `)`, so no programs containing balanced brackets are possible. 5. Similar to scheme, maxima programs require parentheses to do anything. 6. Java programs require the `{` or `->` character sequences to declare a function (and all full programs need at least one function), none of which are in the toolbox. 7. Condit programs require the word `when`, which contains the "e" character, which is not in the toolbox. [Proofs of impossibility are allowed as answers](https://codegolf.meta.stackexchange.com/questions/16172) [Answer] # 2. [Oasis](https://github.com/Adriandmen/Oasis) ``` n! ``` [Try it online!](https://tio.run/##y08sziz@/z9P8f9/AA "Oasis – Try It Online") [Next toolbox](https://tio.run/##dVZLkxsnED5bv0K1VamVqsyWZ@19pZJjTrmmkkq8js0AMyAxQHhImhzy1zfdDSOt8zgw/TXQT5pmwpy1d7cvlrsxrb9ff7x6d8f7Tl29vbpNvLcI3h94BPIA4@kJPpwFxSPLUeEqF7lwa2eEUoaAdPSOeDt6e/84EjSCdtugi9gjCpbJmVs/fsUwYXlKRrRJNzpEUcy@EHDeSlpMSU29nRlPr7lRfLXoeJqQL72Ko3HkwZGsnzx8e540EpTpFZ8qcZVkZ/aEVDryE6GhuFFdEHt6RMaSeORCzzWaM76tjHFssHy/ML33dsFDTQZhSNZA2HDHREtTX3o4hbGgbwKT40ZCNVDBcqU8SuM4qhUKLGMIQoPOSsFXa6qghlz6ulErKelkhTZ4bMI4xyfvWLO2o4QIaxKtWr8rEaMXfhggKSKakIl10jRwUCcCR/yGsHgZ@VxdinPK1XhiwldtiYFNPA1RekPiWDsSRz0eOm@phJlIVEIsExmUKvuCAUjQStlSVk3KZUKYSzVx0N8iUBOukQ4VMZHsEoTKHL8Hg6sD1LRHvYOKjjvpCWL9DSaqHqqdIDmHhCWtlrlkKNKGsAAGL8jm4EmPj1k1qtlIpLERjn1sgKZKNIrcOKcIyk6YTBZGOwftzwB8QFXgLU7RPJTTOb4xwp0gaiZF1PsD5nlM6KPmaV9D0Hxekql7oVFWq9Nyow0Ol1WsIe1wsNLj0o6ToR0/cOaDcju5/wf71PjqFOt5r@CCe6m@nl9mVG0qRFuyd55mijV8oXcA9mzvHSfg0ejeKqr8vc@2ApK2vJ8jeE/YkHJrD1jjcFWNqGattwsqqBKXoe56b@nmTzwa3y7hxLM2IlVkiRxUNJS7iZ@gXBEYh3XLbuXC2Ar2ixqYwm8edljnrkzQq451yfNkUL/vd0pkc1Ds0gKgqkiVFxnMItCoJ/AIRa5VphYKnGEjFn@gFoMAav@u0XukmpYh/nZNAjWDgLqDP6q4FPeFWa5uiMoWWZHH3p2OWCChxEAPRyhJY5bDvCcWG1MiEPlkJEvQgqa6QocS6DHqzuj2gliYw3xm3wPCiwF9dq8yAbq4ES/rxF531qiiGqkrRcxJsdTxEFPFRHWiNdrqJU15H4jUHhAhNnqEKmDoVKwlH0tC4wkuAyeK4UDnVn@@5qAglLtMjMVQcpKS9IV6KomKMankMT1J83DpTHSvRQV0zokOLOkMG6oOY6scvJxaEZr6gYhlk63tIjlIEa05f5yowSQ/UfbTH9ZQT6KLL3hOC67qM4@R/Muxfjm29zRPuA@2eSInPPosLH3pvmU1BcszeZQ1/C1wSaioSjJ2VDiHuRUe9r1z2BDdOFL3y7FM4TJfYrbkV4HXm4q8OAm17El7cZZPPZ1jcREstn@YA456TAeT4IeFkTRzKi@99WBywjCP2kRbKfgeOP23HE0i4uHlr33pmDDFc0HP/4R4P72YKcBRraGXamv61Sr4lI2EnypI2GfjQsmb7Qpvb@9PMLvM4JNcZyAPedOmtyAf3QizTd/NJO82VSWsrcA7q9ZWuU3TuF1/t374dvXGqSPOgODV1epN3eZ8Xi/zPp6hcesmDHJv0NxNCRJObNN2bGH6oo/@ET@Cg3lDe@FdkGZU4PP2bXe//WZxJm23n1ZvmuYbHqD7y4vGFbxw689oO@J/yeZxW53GNPzL6U1b2Da3aROILjmD@045aDzmoLt9/I9oSEmNphkSOv5/KKAEdpvhbBOdudhFAw2@iq/agGMDtUtiG/fl6upm543bJHz@5dnf7ZeXF7D14eFu9fEaLs/12/U1XDAil26C7OU3Ern6vCB6/cBef1pdP5/evYPRwbiF8R7GBxh3MO5hPMB4fHbw7WGI5whfBWN4PnUg14FcB3IdyHUg14FcB3IdyHWPMJ5gcBgg3QkYEgbId8P25uGHH3/6@Zdff/sdTi/EfPzr@m8) [Answer] # 1. [Bash](https://www.gnu.org/software/bash/), outputs 0 ``` echo 0 ``` [Try it online!](https://tio.run/##S0oszvj/PzU5I5/T4P9/AA "Bash – Try It Online") The code contains a literal tab. [Next toolbox](https://tio.run/##dVZLcyMnED5bv0LlqpSlqsXl8a5fqeQX5J5D1ptdBpgBiQHCQ9LkkL/udDeM5M3jwPTXQD9pmglz1t7dv1nuxrT@ef35@u6B9526/nB9n3hvEXw88AjkCcbLC3w4C4pHlqPCVS5y4dbOCKUMAenoHfF29PbxeSRoBO22QRexRxQskzO3fvyOYcLylIxok250iKKYfSHgvJW0mJKaejsznt5zo/hu0fE0IV96FUfjyIMjWT95@PY8aSQo0ys@VeIqyc7sCal05CdCQ3GjuiD28oyMJfHIhZ5rNGd8Xxnj2GD5fmF67@2Ch5oMwpCsgbDhjomWpr70cApjQd8EJseNhGqgguVKeZTGcVQrFFjGEIQGnZWCr9ZUQQ259HWjVlLSyQpt8NiEcY5P3rFmbUcJEdYkWrV@VyJGL/wwQFJENCET66Rp4KBOBI74DWHxMvK5uhTnlKvxxISv2hIDm3gaovSGxLF2JI56PHTeUgkzkaiEWCYyKFX2BQOQoJWypayalMuEMJdq4qC/RaAmXCMdKmIi2SUIlTl@DwZXB6hpj3oHFR130hPE@htMVD1UO0FyDglLWi1zyVCkDWEBDF6QzcGTHh@zalSzkUhjIxz72ABNlWgUuXFOEZSdMJksjHYO2p8B@ICqwFuconkop3N8Y4Q7QdRMiqj3B8zzmNBHzdO@hqD5vCRT90KjrFan5UYbHC6rWEPa4WClx6UdJ0M7fuDMB@V2cv8P9qXx1SnW817BBfdSfT@/zKjaVIi2ZO88zRRr@EIfAOzZ3jtOwKPRvVVU@XufbQUkbXk/R/CesCHl1h6wxuGqGlHNWm8XVFAlLkPd9d7SzZ94NL5dwolnbUSqyBI5qGgodxM/QbkiMA7rlt3LhbEV7Bc1MIXfPOywzl2ZoFcd65LnyaB@3@@UyOag2KUFQFWRKi8ymEWgUU/gEYpcq0wtFDjDRiz@QC0GAdT@Q6OPSDUtQ/ztmgRqBgF1B39UcSnuC7Nc3RCVLbIij707HbFAQomBHo5QksYsh3lPLDamRCDyyUiWoAVNdYUOJdBj1J3R/QWxMIf5zH4EhBcD@uxeZQJ0cSNe1om976xRRTVSV4qYk2Kp4yGmionqRGu01Uua8j4QqT0gQmz0CFXA0KlYSz6WhMYTXAZOFMOBzq3@fM9BQSh3mRiLoeQkJekL9VQSFWNSyWN6kubh0pnoXosK6JwTHVjSGTZUHcZWOXg5tSI09QMRyyZb20VykCJac/44UYNJfqLspz@soZ5EF1/wnBZc1WceI/mXY/1ybO9pnnAfbPNETnj0WVj60n3LagqWZ/Ioa/hb4JJQUZVk7KhwDnMrPOx757AhunGk7pdjmcJlvsRsya8CrzcVeXESatmT9uIsn3o6x@IiWGz/MAcc9ZgOJsEPCyNp5lReeuvB5IRhHrWJtlLwPXD6bzmaRMTDy1/70jFhiueCnv8J8X55M1OAo1pDL9XW9KtV8CkbCT9VkLCvxoWSN9sV3t7en2B2mcEnuc5AHvKmTW9BProRZpu@20k@bKpKWFuBd1atrXKbpnG7/mn99OPqyqkjzoDg9fXqqm5zPq@XeR/P0Lh1Ewa5KzR3W4KEE9u0HVuYvuijf8TP4GDe0F54F6QZFfi8/dA9bn9YnEnb7ZfVVdN8ywN0f3nRuIIXbv0VbUf8L9k8b6vTmIZ/Ob1pC9vmNm0C0SVncN8pB43HHHT3z/8RDSmp0TRDQsf/DwWUwG4znG2iMxe7aKDBd/FVG3BsoHZJbOO@XV/f7rxxm4TPvzz7u/329ga2Pj3drT7fwOW5@bC@gQuGhHo/8Ze2guzlfxK5@s7cfFndvJ7u7mB0MO5hfITxCcYDjEcYTzCeXx18exjiNcJXwRheTx3IdSDXgVwHch3IdSDXgVwHct0zjBcYHAZIdwKGhAHy3bD95dfffjfWhZiPf938DQ) ]
[Question] [ Are there any functional programming languages designed for code golfing? I know that golfscript and CJam fulfill the same category for stack based, but I couldn't find a functional code golfing language. [Answer] # [Husk](https://github.com/barbuz/Husk) Husk is a pure functional golfing language created by me and [Leo](https://codegolf.stackexchange.com/users/62393/leo) and inspired by Haskell. It combines a rigid type system, type inference and extensive overloading. Functions are first class values and can be manipulated as easily as other data. Development of Husk is ongoing and many features are still missing, but you can try it out at [TIO](https://tio.run/#husk). We also have a [SE chatroom](https://chat.stackexchange.com/rooms/53097/husk) for the language. [Answer] ## [cQuents](https://esolangs.org/wiki/cQuents) cQuents is an inpure functional golfing language. It incorporates a lot of functional programming concepts, notably lazy evaluation and infinite lists, since it's specifically designed to do well in [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") related challenges. [Answer] # Pyth Pyth is a functional language that transpiles to python ]
[Question] [ A binary convolution is described by a number `M`, and is applied to a number `N`. For each bit in the binary representation of `M`, if the bit is set (`1`), the corresponding bit in the output is given by XORing the two bits adjacent to the corresponding bit in `N` (wrapping around when necessary). If the bit is not set (`0`), then the corresponding bit in the output is given by the corresponding bit in `N`. A worked example (with 8-bit values): 1. Let `N = 150`, `M = 59`. Their binary respresentations are (respectively) `10010110` and `00111011`. 2. Based on `M`'s binary representation, bits 0, 1, 3, 4, and 5 are convolved. 1. The result for bit 0 is given by XORing bits 1 and 7 (since we wrap around), yielding `1`. 2. The result for bit 1 is given by XORing bits 0 and 2, yielding `0`. 3. The result for bit 2 is given by the original bit 2, yielding `1`. 4. The result for bit 3 is given by XORing bits 2 and 4, yielding `0`. 5. The result for bit 4 is given by XORing bits 3 and 5, yielding `0`. 6. The result for bit 5 is given by XORing bits 4 and 6, yielding `1`. 7. The results for bits 6 and 7 are given by the original bits 6 and 7, yielding `0` and `1`. 3. The output is thus `10100110` (`166`). ## The Challenge Given `N` and `M`, output the result of performing the binary convolution described by `M` upon `N`. Input and output may be in any convenient, consistent, and unambiguous format. `N` and `M` will always be in the (inclusive) range `[0, 255]` (8-bit unsigned integers), and their binary representations should be padded to 8 bits for performing the binary convolution. ## Test Cases ``` 150 59 -> 166 242 209 -> 178 1 17 -> 0 189 139 -> 181 215 104 -> 215 79 214 -> 25 190 207 -> 50 61 139 -> 180 140 110 -> 206 252 115 -> 143 83 76 -> 31 244 25 -> 245 24 124 -> 60 180 41 -> 181 105 239 -> 102 215 125 -> 198 49 183 -> 178 183 158 -> 181 158 55 -> 186 215 117 -> 198 255 12 -> 243 ``` [Answer] ## Python 2, 35 bytes ``` lambda m,n:n^m&(n^n*257/2^n*2^n>>7) ``` [Answer] ## JavaScript (ES6), 31 bytes ``` (n,m)=>n^m&(n^(n*=257)>>1^n>>7) ``` [Answer] # J, 34 bytes ``` 2#.[:({"_1],._1&|.~:1&|.)/(8#2)#:] ``` Straight-forward approach that applies the process defined in the challenge. Takes input as an array `[n, m]`. Forms seven smileys, `[:`, `:(`, `:1`, `(8`, `8#`, `#:`, and `:]`. ## Usage ``` f =: 2#.[:({"_1],._1&|.~:1&|.)/(8#2)#:] f 150 59 171 f 59 150 166 f 209 242 178 f 17 1 0 f 139 189 181 ``` [Answer] # x64 machine code, 17 bytes ``` 88CD88C8D0C9D0C530E930C120D130C8C3 ``` Disassembled: ``` 0: 88 cd mov ch,cl 2: 88 c8 mov al,cl 4: d0 c9 ror cl,1 6: d0 c5 rol ch,1 8: 30 e9 xor cl,ch a: 30 c1 xor cl,al c: 20 d1 and cl,dl e: 30 c8 xor al,cl 10: c3 ret ``` Suitable for the Win64 calling convention (arguments in rcx, rdx). [Answer] # Haskell, 66 bytes ``` import Data.Bits n%m=n.&.(255-m)+(rotate n 1`xor`rotate n(-1)).&.m ``` Works as intended when called with `Word8` data. Replace `(255-m)` with `complement m` (+5 bytes) to make the function work with any unsigned integral datatype. ]
[Question] [ ***[Read this yng Nghymraeg](https://notehub.org/lbb69)*** ## Challenge Given a word in Welsh, output all of the possible mutated forms of the word. ## Mutations A mutation is a change of the first letter of a word when following certain words or in certain grammatical contexts. In Welsh, the following are considered "consonants": ``` b c ch d dd f ff g ng h l ll m n p ph r rh s t th ``` Note that multiple character consonants such as ch, ng and rh are counted as *one letter* in Welsh, and therefore one consonant. The other letters in the Welsh alphabet are vowels, listed below: ``` a e i o u w y ``` See below, all of the mutations with the original letter on the left and the resulting mutated letters on the right: ``` Original | Mutations ---------+--------------- p | b mh ph t | d nh th c | g ngh ch b | f m d | dd n g | [no letter] ng m | f ll | l rh | r ``` Here, `[no letter]` means that the g is removed from the start of the word. Note that there are some consonants which do not mutate: ``` ch dd f ff j l n ng ph r s th ``` Vowels may also be found at the start of words but do not mutate: ``` a e i o u w y ``` ## Examples **Input:** `dydd` **Output:** ``` dydd ddydd nydd ``` --- **Input:** `pobl` **Output:** ``` pobl bobl mhobl phobl ``` --- **Input:** `gwernymynydd` **Output:** ``` gwernymynydd wernymynydd ngwernymynydd ``` --- **Input:** `ffrindiau` **Output:** ``` ffrindiau ``` --- **Input:** `enw` **Output:** ``` enw ``` --- **Input:** `theatr` **Output:** ``` theatr ``` --- *On the request of ArtOfCode ;)* **Input:** `llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch` **Output:** ``` llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch lanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch ``` ## Rules The input will only ever be one word. There will always be more letters after the leading consonant in your input. ## Winning The shortest code in bytes wins. [Answer] # JavaScript (ES6), 180 bytes ``` x=>x.replace(/^([cpt](?!h)|d(?!d)|[bgm]|ll|rh)(.+)/,(_,y,z)=>({p:"b mh ph",t:"d nh th",c:"g ngh ch",b:"f m",d:"dd n",g:" ng",m:"f"}[y]||y[0]).split` `.map(b=>a.push(b+z)),a=[x])&&a ``` Outputs as an array of strings. This is my first try, so it's almost certainly not optimal. ### Try it out ``` f=x=>x.replace(/^([cpt](?!h)|d(?!d)|[bgm]|ll|rh)(.+)/,(_,y,z)=>({p:"b mh ph",t:"d nh th",c:"g ngh ch",b:"f m",d:"dd n",g:" ng",m:"f"}[y]||y[0]).split` `.map(b=>a.push(b+z)),a=[x])&&a ``` ``` <input id=A value="pobl"><button onclick="B.innerHTML=f(A.value).join('<br>')">Run</button><br> <pre id=B> ``` [Answer] ## C#, 356 ~~338~~ ~~360~~ bytes I know that C# is a poor choice for code golf, but it's worth the shot: Third attempt, all cases now pass, including th- ph- etc. This adjustment cost roughly 18 bytes. Thanks pinkfloydx33 for the tips saving 24 bytes! ``` namespace System{using Linq;using S=String;class P{static void Main(S[]a){Action<S>w=Console.WriteLine;w(a[0]);foreach(S r in"th-dd-ch-ph-p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-')){var b=r.Split('.');if(a[0].StartsWith(b[0])){foreach(S f in b.Skip(1))w(Text.RegularExpressions.Regex.Replace(a[0],$"^{b[0]}",f));break;}}}}} ``` ## Output ``` $> ./p gwernymynydd gwernymynydd wernymynydd ngwernymynydd ``` ## Formatted Version ``` namespace System { using Linq; using S = String; class P { static void Main(S[] a) { Action<S> w = Console.WriteLine; w(a[0]); foreach (S r in "th-dd-ch-ph-p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r" .Split('-')) { var b = r.Split('.'); if (a[0].StartsWith(b[0])) { foreach (S f in b.Skip(1)) w(Text.RegularExpressions.Regex.Replace(a[0], $"^{b[0]}", f)); break; } } } } } ``` [Answer] ## Python 3, ~~196,189~~ 185 bytes Original attempt ``` w=input();print(w);[w.startswith(a)and[print(w.replace(a,i,1))for i in r]+exit()for(a,*r)in(j.split(',')for j in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())] ``` Vaultah noted that `not w.find(a)` would be a replacement for `w.startswith(a)` that would save 2 characters. But instead of `not x and y` we can use `x or y` which saves some characters more: ``` w=input();print(w);[w.find(a)or[print(w.replace(a,i,1))for i in r]+exit()for(a,*r)in(j.split(',')for j in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())] ``` Yet further savings by replacing `w.replace(a,i,1)` with `i+w[len(a):]`: ``` w=input();print(w);[w.find(a)or[print(i+w[len(a):])for i in r]+exit()for(a,*r)in(j.split(',')for j in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())] ``` Then I noticed that there was a bug, `rh` was listed twice; once in my short-circuit list that would take care of those double-letter consonants. Unfortunately `dd` was missing from there, so no savings, and we have ``` w=input();print(w);[w.find(a)or[print(i+w[len(a):])for i in r]+exit()for(a,*r)in(j.split(',')for j in'th ph dd p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())] ``` Given any of the sample inputs, it gives the desired output; given ``` gorsaf ``` it outputs ``` gorsaf orsaf ngorsaf ``` and given input ``` theatr ``` it prints ``` theatr ``` [Answer] ## PowerShell v3+, ~~254~~ 231 bytes ``` param($a)$a;$z=-join$a[1..$a.length] if(($x=@{112='b mh ph';116='d nh th';99='g ngh ch';98='f m';100='dd n';109='f'})[+$a[0]]-and$a-notmatch'^[cpt]h|^dd'){-split$x[+$a[0]]|%{"$_$z"}} ($z,"ng$z")*($a[0]-eq103) $z*($a-match'^ll|^rh') ``` working to golf further... ### Examples (Output is space-separated because that's the default Output Field Separator for stringified arrays. I don't know if the words I used for testing are actual words, but they fit the exceptions.) ``` PS C:\Tools\Scripts\golfing> 'dydd','pobl','gwernymynydd','ffrindiau','enw','rhee','llewyn','chern','ddydd','phobl'|%{"$_ --> "+(.\golff-yr-cod.ps1 $_)} dydd --> dydd ddydd nydd pobl --> pobl bobl mhobl phobl gwernymynydd --> gwernymynydd wernymynydd ngwernymynydd ffrindiau --> ffrindiau enw --> enw rhee --> rhee hee llewyn --> llewyn lewyn chern --> chern ddydd --> ddydd phobl --> phobl ``` [Answer] ## C#, 349 bytes Based on @grizzly's [submission](https://codegolf.stackexchange.com/a/92843/41565), but corrected to work with the consonants that don't get transformed (ph/ch/th/dd) that it wasn't working with, plus trimmed some excess out. Hope that's alright? I had it down to 290 until I realized that I was missing the th/ch/ph/dd cases :-(. Adding in the Regex call killed it ``` namespace System{class P{static void Main(string[]a){var x=a[0];if(!Text.RegularExpressions.Regex.IsMatch(x,"^[pct]h|^dd"))foreach(var r in"p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-')){var b=r.Split('.');if(a[0].StartsWith(b[0]))for(int i=1;i<b.Length;)x+='\n'+b[i++]+a[0].Substring(b[0].Length);}Console.Write(x);}}} ``` Interesting note, never knew that you could omit the space between `var r in"string"` Formatted: ``` namespace System { class P { static void Main(string[] a) { var x = a[0]; if (!Text.RegularExpressions.Regex.IsMatch(x, "^[pct]h|^dd")) foreach (var r in"p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-')) { var b = r.Split('.'); if (a[0].StartsWith(b[0])) for (int i = 1; i < b.Length;) x += '\n' + b[i++] + a[0].Substring(b[0].Length); } Console.Write(x); } } } ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 162 bytes ``` {/^(.|<[cprt]>h|dd|ff|ng|ll)(.*)/;(%('p',<b mh ph>,'t',<d nh th>,'c',<g ngh ch>,'b',<f m>,'d',<dd n>,'g',«'' ng»,'m',<f>,'ll',<l>,'rh',<r>){$0}//~$0).map(*~$1)} ``` [Try it online!](https://tio.run/##FYxBrsIgFEXHdhUvhi9gmlYnTlq7EaOmLQImgARrDCl1Q38Jf@bG@l9n57x78vwtmMNsI2wkHOexvLAi1afeh@Hc6CREkjI5lYzhrNjysmI/jHqa1x1YDV43OR3QBDgNw2I9mgKnNPSLdqgSLJJYMuwQFc2/v5Ri9f3LqV0SvBqDYBCCRggNH8luKssP2fHCtp5tP2TPp7nK5CNALSI@84/OgJTh7sS9fYF634KLNjrcGhiz1bONsCZXGCUjVz6tq2ya/wE "Perl 6 – Try It Online") ]
[Question] [ ## Explanation [Befunge](https://esolangs.org/wiki/Befunge) is a two-dimensional program that uses [stacks](https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29). That means, to do 5 + 6, you write `56+`, meaning: ``` 56+ 5 push 5 into stack 6 push 6 into stack + pop the first two items in the stack and add them up, and push the result into stack (to those of you who do not know stacks, "push" just means add and "pop" just means take off) ``` However, as the intelligent of you have observed, we cannot push the number `56` directly into the stack. To do so, we must write `78*` instead, which multiplies `7` and `8` and pushes the product into the stack. ## Details Input can be taken in any format, meaning it can be STDIN or not, at the programmer's discretion. The input will be a positive integer (no bonus for including `0` or negative integers). The output will be a string consisting of only these characters: `0123456789+-*/` (I would **not** use `%` modulo.) The goal is to find the **shortest** string that can represent the input, using the format described above. For example, if the input is `123`, then the output would be `67*99*+`. The output should be evaluated from left to right. If there are more than one acceptable outputs (e.g. `99*67*+` is also acceptable), any one can be printed (no bonus for printing all of them). ## Further Explanation If you still do not understand how `67*99*+` evaluates to `123`, here is a detailed explanation. ``` stack |operation|explanation 67*99*+ [6] 6 push 6 to stack [6,7] 7 push 7 to stack [42] * pop two from stack and multiply, then put result to stack [42,9] 9 push 9 to stack [42,9,9] 9 push 9 to stack [42,81] * pop two from stack and multiply, then put result to stack [123] + pop two from stack and add, then put result to stack ``` ## TL;DR The program needs to find the **shortest** string that can represent the input (number), using the format specified above. ## Notes This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code in bytes wins. ## Disambiguation The `-` can either be `x-y` or `y-x`, at the programmer's discretion. However, the choice must be consistent within the solution. Likewise for the `/`. ## Sample program # Lua, 1862 bytes ([try it online](http://www.lua.org/cgi-bin/demo)) Since I am the author, I will not golf it at all. Explanation: ``` This uses the depth-first search method. ``` More about depth-first search: [here](https://en.wikipedia.org/wiki/Depth-first_search). The program: ``` local input = (...) or 81 local function div(a,b) if b == 0 then return "error" end local result = a/b if result > 0 then return math.floor(result) else return math.ceil(result) end end local function eval(expr) local stack = {} for i=1,#expr do local c = expr:sub(i,i) if c:match('[0-9]') then table.insert(stack, tonumber(c)) else local a = table.remove(stack) local b = table.remove(stack) if a and b then if c == '+' then table.insert(stack, a+b) elseif c == '-' then table.insert(stack, b-a) elseif c == '*' then table.insert(stack, a*b) elseif c == '/' then local test = div(b,a) if test == "error" then return -1 else table.insert(stack, a+b) end end else return -1 end end end return table.remove(stack) or -1 end local samples, temp = {""}, {} while true do temp = {} for i=1,#samples do local s = samples[i] table.insert(temp, s..'0') table.insert(temp, s..'1') table.insert(temp, s..'2') table.insert(temp, s..'3') table.insert(temp, s..'4') table.insert(temp, s..'5') table.insert(temp, s..'6') table.insert(temp, s..'7') table.insert(temp, s..'8') table.insert(temp, s..'9') table.insert(temp, s..'+') table.insert(temp, s..'-') table.insert(temp, s..'*') table.insert(temp, s..'/') end for i=1,#temp do if input == eval(temp[i]) then print(temp[i]) return end end samples = temp end ``` # Bonus **A cake for you if you use [Befunge](https://esolangs.org/wiki/Befunge) (or any variant of it) to write the code.** [Answer] # Python 2, 278 bytes My best solution, which everytime gives shortest answer. (but very slow) ``` def e(c): s=[];x,y=s.append,s.pop while c: d,c=c[0],c[1:] if"/"<d<":":x(d) else:a,b=y(),y();x(str(eval(b+d+a))) return int(y()) def g(v): s="0123456789+-*";t=list(s) while 1: for x in t: try: if e(x)==v:return x except:0 t=[x+y for x in t for y in s] ``` # Python 2, 437 bytes This solution is longer, but very fast (not brute force). And I'm quite sure, that it always return shortest possible result. ``` r=range;l=len;a=input() def f(n): if n<=9:return str(n) for d in r(9,1,-1): if n%d==0:return f(n/d)+"%d*"%d h=sum(map(int,list(str(n))))%9 return f(n-h)+"%d+"%h m={x:f(x) for x in r(a*9)} for b in m: if a-b in m and l(m[b])+l(m[a-b])+1<l(m[a]):m[a]=m[a-b]+m[b]+"+" if a+b in m and l(m[b])+l(m[a+b])+1<l(m[a]):m[a]=m[a+b]+m[b]+"-" if b!=0 and a%b==0 and a/b in m and l(m[b])+l(m[a/b])+1<l(m[a]):m[a]=m[a/b]+m[b]+"*" print m[a] ``` [Answer] # Perl, ~~134~~ ~~133~~ ~~132~~ 128 bytes Includes +5 for `-Xlp` (2 extra because the code contains `'`) Run with the target number on STDIN: ``` perl -Xlp befour.pl <<< 123 ``` `befour.pl`: ``` @1{1..9}=1..9;$.+=2,map{for$a(%1){"+-*/"=~s%.%"\$1{\$-=$a$&$_/'$1{$a}$1{$_}$&'=~/^.{$.}\$/}||=\$&"%eegr}}%1until$\=$1{$_}}{ ``` It has no artificial limits and is conceptually somewhat efficient but has terrible run times nevertheless even though I sacrificed a few bytes to speed it up. Generating a length 11 solution (e.g. target number 6551) takes about 5 hours on my system. Sacrificing 7 more bytes makes the speed somewhat more bearable. ``` @1{1..9}=1..9;$.+=2,map{for$a(@a){"+-*/"=~s%.%"\$1{\$-=$a$&$_/'$1{$a}$1{$_}$&'=~/^.{$.}\$/}||=\$&"%eegr}}@a=keys%1until$\=$1{$_}}{ ``` 17 minutes for a length 11 solution, about 5 hours for a length 13 solution. The first number that needs length 15 is 16622 which takes about 2 days. The first number that needs length 17 is 73319. Notice that it assumes that division returns an integer by truncating towards 0 (per the befunge 93 specification) [Answer] # C, ~~550~~ 545 bytes ``` #define L strlen #define y strcpy #define t strcat char c[9999][99];i=1,k=3;main(j){for(;i<10;i++)*c[i]=i+'0';for(;k--;){ for(i=1;i<9999;i++)for(j=1;j<=i;j++)*c[i]&&*c[j]&&(i+j>9998||*c[i+j]&& L(c[i+j])<L(c[i])+L(c[j])+2||t(t(y(c[i+j],c[i]),c[j]),"+"), i*j>9998||*c[i*j]&&L(c[i*j])<L(c[i])+L(c[j])+2||t(t(y(c[i*j],c[i]),c[j]),"*")); for(i=9999;--i;)for(j=i;--j;)*c[i]&&*c[j]&&(*c[i/j]&& L(c[i/j])<L(c[i])+L(c[j])+2||t(t(y(c[i/j],c[i]),c[j]),"/"), *c[i-j]&&L(c[i-j])<L(c[i])+L(c[j])+2||t(t(y(c[i-j],c[i]),c[j]),"-"));} scanf("%d",&i);printf("%s",c[i]);} ``` ~~550~~ 545 bytes after deleting the unnecessary newlines (all but the three newlines after the preprocessing directives). @Kenny Lau - It can receive as input an integer between 1 and 9998, but I think that the range of input for which an optimal solution is computed is smaller than 9998. On the other hand, both ranges can be extended, if the memory allows it. The program cannot push onto the stack any number higher than 9998. (9998 can be modified.) I ran the program in a different version, iterating over the outer loop (the one with k) for as long as there is improvement for any number between 1 and 9998 (as in Dijkstra's algorithm). After three iterations there is no improvement. So to save bytes, I hardcoded k=3. To extend the range, two things are necessary - modifying the constants 9999 and 9998, running it with a variable number of iterations over the outter loop for as long as there is improvement, to see how long it takes until no improvement takes place, then modify the constant k=3 to that value. [Answer] # Python 2, 284 bytes Disclaimer: Takes freaking *forever* for some values ... but *should* be guaranteed to always return the shortest string, and has no artificially imposed range limit ... even works on negative values. :) ``` def f(v): i,z=0,'+-*/' while 1: s=('%x'%i).translate(__import__('string').maketrans('abcd',z),'ef');t=s;q=[];a,p=q.append,q.pop;i+=1 try: while t: o,t=t[0],t[1:] if o in z:n,m=p(),p();a(eval(`m`+o+`n`)) else:a(int(o)) if p()==v and not q:return s except:pass ``` Algorithm: * Start with `i = 0` * Take the string representing the hex value of `i`, and replace `abcd` with `+-*/` respectively, and remove any `ef` * Attempt to process string as [postfix notation (RPN)](https://en.wikipedia.org/wiki/Reverse_Polish_notation) * If successful, and result matches input value, return the string used. * Otherwise, increment `i` and try again. [Answer] ## Python 2, 182 bytes ``` n=input() L=[[[],""]] while 1: s,c=L.pop(0);L+=[[s+[i],c+`i`]for i in range(10)]+(s[1:]and[[s[:-2]+[eval(`s[-2]`+o+`s[-1]`)],c+o]for o in"/+-*"[s[-1]==0:]]) if[n]==s[-1:]:print c;E ``` So obscenely slow, I've left it running for an hour on input `221` and it *still* hasn't terminated. A great deal of the slowness is because I'm using a list as a queue for a breadth-first search, and `.pop(0)` is `O(n)` for lists. `L` is just a queue containing `(stack, code to reach stack)` pairs. At each step, digits are always added, and operators are performed if the stack has at least two elements. Division is only performed if the last element is not 0, although I have a strong suspicion that division is never necessary (although I have no way of proving it, but I have checked this is the case up to 500). The program terminates via a `NameError` after printing the result (eventually). [Answer] # CJam, 79 ``` ri:M;A,:s:L;{L2m*{s,Y=},{~:A+AS*~!"/+-*">\f{\+}~}%Y2+:Y;_L@+:L;{S*~M=},:R!}gR0= ``` [Try it online](http://cjam.aditsu.net/#code=ri%3AM%3BA%2C%3As%3AL%3B%7BL2m*%7Bs%2CY%3D%7D%2C%7B%7E%3AA%2BAS*%7E!%22%2F%2B-*%22%3E%5Cf%7B%5C%2B%7D%7E%7D%25Y2%2B%3AY%3B_L%40%2B%3AL%3B%7BS*%7EM%3D%7D%2C%3AR!%7DgR0%3D&input=120) This is horribly inefficient, but given enough memory and time, it eventually works. 123 runs out of memory with 16GB, but 120 and 125 are ok. [Answer] # Pyth - 35 bytes Brute force. A weird thing is that the new implicit input actually *hurts* my score because it seems to be working for `.v` pyth\_eval also. ``` .V1IKfqQ.x.v+jd_T\;N^s+"+-*/"UTbhKB ``` [Try it online here](http://pyth.herokuapp.com/?code=.V1IKfqQ.x.v%2Bjd_T%5C%3BN%5Es%2B%22%2B-%2a%2F%22UTbhKB&input=56&debug=0). [Answer] # Python 3, 183 bytes ``` e,n=enumerate,input() v=list('0123456789')+[' '*n]*n*2 for i,s in e(v): for j,t in e(v): for o,k in zip('+*-',(i+j,i*j,i-j)): if 9<k<2*n:v[k]=min(v[k],s+t+o,key=len) print(v[n]) ``` Speed isn't totally unreasonable (123, 221, 1237, 6551 finish on the order of seconds or minutes). Changing the `if` statement to `if j<=i and <k<2*n` speeds it up more, at the cost of 9 more bytes. I left out division (`/`), because I can't see how it would be needed. ]
[Question] [ ## Introduction Some ASCII characters are just so expensive these days... To save money you've decided to write a program that encodes expensive characters using inexpensive ones. However, character prices change frequently and you don't want to modify your program every time you need to encode or decode a different character! You'll need a more dynamic solution. ## Challenge Your task is to write two programs: an ***encoder*** and a ***decoder***. The ***encoder*** should accept a list of five inexpensive characters, and a single expensive character. It should output a single string made up of the inexpensive characters, that encodes the expensive character. *This string* ***may not be longer than 4 characters****, to remain inexpensive. However, it does not have to use all of the inexpensive characters in the encoding and encodings may be of different lengths.* The ***decoder*** should accept the string outputted by the encoder, and output the expensive character. *The decoder shall accept no input other than the encoded string. It must work, unmodified, from the encoder's output for any (valid) combination of inputs. In other words, your decoder program* ***doesn't know which characters are expensive or inexpensive.*** ## Scoring Shortest combined code wins! ## Notes * All characters will be either uppercase letters `[A-Z]`, lowercase letters `[a-z]`, or numbers `[0-9]`. * The list of inexpensive characters won't contain duplicates. No character will be both inexpensive and expensive. * The encoder and decoder don't have to be written in the same language, but they can be. You may write a program or a function. * Input and output may be in any reasonable format for your language. * The two programs may not share any variables or data. ## Summary * Input of some inexpensive characters and an expensive character is given to encoder. * Encoder outputs a string of inexpensive characters, encoding the expensive character. * Decoder is given the encoder's output, and outputs the expensive character. ## Examples *Input:*     `a, b, c, d, e`     `f` *Encoder Possibilities:*     `a`     `eeee`     `caec` *Decoder:*     `f` *Input:*     `a, b, c, d, e`     `h` *Encoder Possibilities:*     `bc`     `cea`     `eeaa` *Decoder:*     `h` *Input:*     `q, P, G, 7, C`     `f` *Encoder Possibilities:*     `777`     `P7`     `PPCG` *Decoder:*     `f` [Answer] # CJam, ~~55~~ ~~50~~ ~~48~~ 47 bytes ### Encoder, ~~24~~ ~~22~~ 21 bytes ``` l$:L4m*{$L|L=},rc'0-= ``` [Try it online.](http://cjam.aditsu.net/#code=l%24%3AL4m*%7B%24L%7CL%3D%7D%2Crc'0-%3D&input=abcde%0AW) ### Decoder, ~~31~~ ~~28~~ ~~27~~ 26 bytes ``` 4_m*{$4,|4,=},l_$_|f#a#'0+ ``` [Try it online.](http://cjam.aditsu.net/#code=4_m*%7B%244%2C%7C4%2C%3D%7D%2Cl_%24_%7Cf%23a%23'0%2B&input=bbac) [Answer] # Pyth, 46 bytes ## Encoder, 22 bytes ``` @smfql{Td^<Szd4S4-Cw48 ``` ## Decoder, 24 bytes ``` C+48xsmfql{Td^<sS{zd4S4z ``` [Answer] ## gawk, 163 + 165 = 328 Tested with gawk 4.1.1, but should work in older gawk versions as well. Needs to be slightly modified (lengthened) to work with mawk. **encoder** (163): ``` {for(gsub(", ",_);sprintf("%c",++r)!=$NF;asort(a))split($1,a,_);r-=r>64?53:46;for(k=4^5;r-=_~i;j=_)for(i=++k;gsub(++j,_,i);)split(k,b,_);for(j in b)printf a[b[j]]} ``` **decoder** (165): ``` {split($1,a,_);for(i in a)d[a[i]]=a[i];asort(d);for(k=4^5;c!~$1;x+=_~i){i=++k;for(c=j=_;gsub(++j,_,i);split(k,b,_));for(g in b)c=c d[b[g]]}printf"%c",x+(x>10?54:47)} ``` Well, it works, but I'm aware that this might not be the best approach for this. I have no idea what the fifth inexpensive letter is for, because I use only four. These are for single use only. If you want to enter a second code you have to restart them. The spaces after the commas are required in the input to encode. ## What I thought about My first question was "What could a decoder get from these 4 characters?" (I'll call them a, b, c and d), and my initial idea was to get 6 bits of Information from following relations: ``` a>b a>c a>d b>c b>d c>d ``` Wow, 6 bit, that's perfect! I thought it was genius, but testing showed this would not work. There are only 24 possible combinations. Damn. The next step was trying to count, based on what I already knew. So the first letter appearing in the string would become 0, then the second letter introduced in the string would become 1 and so on. But it wouldn't bring me all the way to the 62 combinations needed. ``` 0000 0001 0010 0011 0012 0100 0101 0102 0110 0111 0112 0120 0121 0122 0123 ``` But I like the idea anyhow. Well, then it struck me, that I could combine these two, because the characters in the input already have relations, and I wouldn't have to wait until they were introduced to give them a value. ## How it works *Note: This is no longer exactly how the golfed versions work, but the principle stayed the same.* For the decoder: An array is constructed, whose index contains all the four digit numbers whose largest digit isn't greater than the number of distinct digits in that number. There are 75 different four digit numbers meeting that condition. I brute force them, because so far I couldn't figure out a way to construct them, and I'm not sure this would be shorter to do in awk anyway. While I find these I assign them the expensive characters in asciibetical order. Then I replace every character from the input string with a digit. The smallest (for instance is 'B' smaller than 'a') becomes 1, the second smallest becomes 2, and so on up to 4. Of course it depends on how many different characters are in the input, what the highest digit in the resulting string will be. Then I simply print the array element, which has that string as an index. The encoder works accordingly. ## How to use Either copy the code directly in an awk bash line command or make two files "encode.awk" and "decode.awk" and paste the code accordingly. Or even better use the following code, which exits automatically after en/decoding, or can be used multiple times by removing the exit command at the end. *encode.awk* ``` { if(!x) # only do first time for(i=1e3;i++<5e3;delete a) { for(m=j=0;p=substr(i,++j,1);p>m?m=p:0)++a[p]; length(a)>=m&&i!~0?c[(x>9?55:48)+x++]=i:_ } r=u=_; # clear reused variables for(gsub(",",FS);sprintf("%c",++r)!=$NF;); # more flexible concerning --NF; # spaces in input split($0,b); asort(b); split(c[r],a,_); for(j in a)u=u b[a[j]]; # prettier printing than golfed version print u exit # <=== remove to encode input file } ``` *decode.awk* ``` { if(!x) # only do first time for(i=1e3;i++<5e3;delete a) { for(m=j=0;p=substr(i,++j,1);p>m?m=p:_)++a[p]; length(a)>=m&&i!~0?c[i]=sprintf("%c",(x>9?55:48)+x++):_ } delete t; delete d; o=_; # clear reused variables split($1,a,_); for(i in a)t[a[i]]=1; for(i in t)d[++y]=i; asort(d); for(i in a)for(j in d)if(d[j]~a[i])o=o j; print c[o] exit # <=== remove to encode input file } ``` Here is a usage example: ``` me@home:~/$ awk -f encode.awk w, 0, R, 1, d X 10R1 me@home:~/$ awk -f decode.awk 10R1 X ``` Remember that the space after each comma is required, if you use the golfed versions. If you want, you can use this short and dirty script to generate some sample data ``` BEGIN{ for(srand();i++<1000;) { erg=""; for(j=0;j++<5;) { while(erg~(a[j]=substr(c="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",rand()*62+1,1))); erg=erg a[j] } print a[1]", "a[2]", "a[3]", "a[4]", "a[5](rand()>.5?" ":rand()>.5?" ":" ")substr(c,rand()*62+1,1) } } ``` and do something funny like ``` me@home:~/$ awk -f gen.awk|awk -f encode.awk|awk -f decode.awk|sort -u|wc -l 62 ``` I've seen this more as a programming puzzle. I think it's a little sad, that almost everything on here is golfed, because you can learn a lot more from well documented, readable code, but that's just my opinion. And I golfed it like requested ;) ]
[Question] [ Another [XKCD](https://codegolf.stackexchange.com/search?q=XKCD+is%3Aquestion) inspired competition. This one is based on [Keyboard Mash](http://xkcd.com/1530/). Given a input string, identify the anomalous characters, assuming that the majority have been typed on a single row of the [standard US QWERTY keyboard](http://en.wikipedia.org/wiki/File:Qwerty.svg). Input strings can contain shifted key strokes, but they will not contain carriage returns (Enter), CTRL/ALT affected characters, spaces, tabs and backspaces (because that would be silly). The number pad will not be considered as part of the keyboard for this challenge. The challenge is to output the characters that aren't on the same keyboard row as the majority of individual characters in the single string. The output should contain each anomalous character only once and no other characters. In the case of a equal count of anomalous characters across two or more rows, the tie break is determined in this order: * Shortest unique list * Top most row **Input** A string through either STDIN, ARGV or a function parameter **Output** A string to STDOUT or a function return. It should have each anomalous character only once, but does not need to be ordered. **Examples** > > **Input:** FJAFJKLDSKF7KFDJ > **Output:** 7 > > > > **Input:** ASDF11111 > **Output:** ASDF > > > > **Input:** lkjrhsDdftkjhrksRjd > **Output:** rtR > > > > **Input:** }\*3%&2098@$2k234#@$M > **Output:** } > > > > Topmost row list returned > **Input:** ASD!@#Vcx > **Output:** !@# > > > > Shortest unique list returned > **Input:** ASdf1233qwER > **Output:** 123 > > > > Topmost shortest list returned > **Input:** 12334QWTTSDFDSXVVBBX > **Output:** QWT > > > This is code golf, so shortest entry wins. [Answer] # CJam, ~~111~~ ~~89~~ ~~88~~ ~~86~~ ~~84~~ 83 bytes ``` la9*~"{}qwertyuiop ;':asdfghjkl ,./<>?zxcvbnm"{_32^}%_'ÿ,^a\S%+{[f&s\e|__|]:,}$0=& ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=la9*~%22%7B%7Dqwertyuiop%20%3B'%3A%02asdfghjkl%20%2C.%2F%3C%3E%3Fzxcvbnm%22%7B_32%5E%7D%25_'%7F%2C%5Ea%5CS%25%2B%7B%5Bf%26s%5Ce%7C__%7C%5D%3A%2C%7D%240%3D%26&input=12334QWTTSDFDSXVVBBX). ### How it works ``` la9*~ e# Push the input 9 times on the stack. "{}qwertyuiop ;':<STX>asdfghjkl ,./<>?zxcvbnm" {_32^}% e# XOR a copy of each character with 32. _'<DEL>,^ e# Push a string of all ASCII characters that are missing. a\ e# Wrap it in an array. S%+ e# Split the string at spaces and concatenate with the array. { e# Sort the chunks according to the following: [ e# f&s e# Push the string of characters from the input that are in this chunk. \e| e# If the result is empty, replace it with the input. __| e# Push a copy with duplicates removed. ] e# Collect both strings in an array. :, e# Replace each string with its length. }$ e# 0= e# Retrieve the minimum. & e# Intersect it with the input. ``` [Answer] # CJam, ~~90 88 86 84~~ 83 bytes This is just a straight forward implementation. ``` " qwertyuiop[] asdfghjkl;': zxcvbnm<>?,./"_32f^.\_'¦,^\+S%qf{_@--}{},{__&]:,}$0=_& ``` [Try it online here](http://cjam.aditsu.net/#code=%22%20qwertyuiop%5B%5D%20asdfghjkl%3B%27%3A%02%20zxcvbnm%3C%3E%3F%2C.%2F%22_32f%5E.%5C_%27%C2%A6%2C%5E%5C%2BS%25qf%7B_%40--%7D%7B%7D%2C%7B__%26%5D%3A%2C%7D%240%3D_%26&input=12334QWTTSDFDSXVVBBX) . [Pastebin](http://pastebin.com/6nZw6B8H) ]
[Question] [ # Introduction Suppose that you are handed a random permutation of `n` objects. The permutation is sealed in a box, so you have no idea which of the `n!` possible ones it is. If you managed to apply the permutation to `n` distinct objects, you could immediately deduce its identity. However, you are only allowed to apply the permutation to length-`n` binary vectors, which means you'll have to apply it several times in order to recognize it. Clearly, applying it to the `n` vectors with only one `1` does the job, but if you're clever, you can do it with `log(n)` applications. The code for that method will be longer, though... This is an experimental challenge where your score is a combination of code length and *query complexity*, meaning the number of calls to an auxiliary procedure. The spec is a little long, so bear with me. # The Task Your task is to write a **named function (or closest equivalent)** `f` that takes as inputs a positive integer `n`, and a permutation `p` of the first `n` integers, using either 0-based or 1-based indexing. Its output is the permutation `p`. However, **you are not allowed to access the permutation `p` directly**. The only thing you can do with it is to apply it to any vector of `n` bits. For this purpose, you shall use an auxiliary function `P` that takes in a permutation `p` and a vector of bits `v`, and returns the permuted vector whose `p[i]`th coordinate contains the bit `v[i]`. For example: ``` P([1,2,3,4,0], [1,1,0,0,0]) == [0,1,1,0,0] ``` You can replace "bits" with any two distinct values, such as `3` and `-4`, or `'a'` and `'b'`, and they need not be fixed, so you can call `P` with both `[-4,3,3,-4]` and `[2,2,2,1]` in the same call to `f`. The definition of `P` is not counted toward your score. # Scoring The *query complexity* of your solution on a given input is the number of calls it makes to the auxiliary function `P`. To make this measure unambiguous, your solution must be deterministic. You can use pseudo-randomly generated numbers, but then you must also fix an initial seed for the generator. In [this repository](https://github.com/iatorm/permutations/tree/master) you'll find a file called `permutations.txt` that contains 505 permutations, 5 of each length between 50 and 150 inclusive, using 0-based indexing (increment each number in the 1-based case). Each permutation is on its own line, and its numbers are separated by spaces. Your score is **byte count of `f` + average query complexity on these inputs**. Lowest score wins. # Extra Rules Code with explanations is preferred, and standard loopholes are disallowed. In particular, individual bits are indistinguishable (so you can't give a vector of `Integer` objects to `P` and compare their identities), and the function `P` always returns a new vector instead of re-arranging its input. You can freely change the names of `f` and `P`, and the order in which they take their arguments. If you are the first person to answer in your programming language, you are strongly encouraged to include a test harness, including an implementation of the function `P` that also counts the number of times it was called. As an example, here's the harness for Python 3. ``` def f(n,p): pass # Your submission goes here num_calls = 0 def P(permutation, bit_vector): global num_calls num_calls += 1 permuted_vector = [0]*len(bit_vector) for i in range(len(bit_vector)): permuted_vector[permutation[i]] = bit_vector[i] return permuted_vector num_lines = 0 file_stream = open("permutations.txt") for line in file_stream: num_lines += 1 perm = [int(n) for n in line.split()] guess = f(len(perm), perm) if guess != perm: print("Wrong output\n %s\n given for input\n %s"%(str(guess), str(perm))) break else: print("Done. Average query complexity: %g"%(num_calls/num_lines,)) file_stream.close() ``` In some languages, it is impossible to write such a harness. Most notably, Haskell does not allow the pure function `P` to record the number of times it is called. For this reason, you are allowed to re-implement your solution in such a way that it also calculates its query complexity, and use that in the harness. [Answer] ## J, ~~44.0693~~ 22.0693 = ~~37~~ 15 + 7.06931 If we can't call `P` on `i. n`, we can at least call `P` on each bit of `i. n` separately. The number of invocations of `P` is `>. 2 ^. n` (⌈log2 *n*⌉). I believe this is optimal. ``` f=:P&.|:&.#:@i. ``` Here is an implementation of the function `P` which uses the permutation vector `p` and saves the number of invocations into `Pinv`. ``` P =: 3 : 0"1 Pinv =: Pinv + 1 assert 3 > # ~. y NB. make sure y is binary p { y ) ``` Here is a testing harness that receives a permutation and returns the number of invocations of `p`: ``` harness =: 3 : 0 Pinv =: 0 p =: y assert y = f # y NB. make sure f computed the right permutation Pinv ) ``` And here is how you can use it on the file `permutations.txt`: ``` NB. average P invocation count (+/ % #) harness@".;._2 fread 'permutations.txt' ``` ## Explanation The short explanation is already provided above, but here is a more detailed one. First, `f` with spaces inserted and as an explicit function: ``` f =: P&.|:&.#:@i. f =: 3 : 'P&.|:&.#: i. y' ``` Read: > > Let *f* be P under transposition under base-2 representation of the first *y* integers. > > > where *y* is the formal parameter to *f.* in J, the parameters to a (function) are called *x* and *y* if the verb is dyadic (has two parameters) and *y* if it is monadic (has one parameter). Instead of invoking `P` on `i. n` (i.e. `0 1 2 ... (n - 1)`), we invoke `P` on each bit position of the numbers in `i. n`. Since all permutations permute in the same way, we can reassemble the permutated bits into numbers to get a permutation vector: * `i. y` – integers from `0` to `y - 1`. * `#: y` – `y` represented in base 2. This is extended to vectors of numbers in the natural way. For instance, `#: i. 16` yields: ``` 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1 ``` * `#. y` – `y` interpreted as a base 2 number. Notably, this is the inverse to `#:`; `y ~: #. #:` always holds. * `|: y` – `y` transposed. * `u&.v y` – `u` under `v`, that is `vinv u v y` where `vinv` is the inverse to `v`. Notice that `|:` is its own inverse. * `P y` – the function `P` applied to each vector in `y` by definition. [Answer] # Pyth 32 + 7.06931 = 37.06931 I found the following algorithm completely independent. But it's more or less the same thing as FUZxxl very short J solution (as far as I understand it). First the definition of the function `P`, which permutes an bit-array according to an unknown permutation. ``` D%GHJHVJ XJ@HN@GN)RJ ``` And then the code, that determines the permutation. ``` Mmxmi_mbk2Cm%dHCm+_jk2*sltG]0GdG ``` This defines a function `g`, that takes two arguments. You can call it by `g5[4 2 1 3 0`. Here's an [online demonstration](https://pyth.herokuapp.com/?code=D%25GHJHVJ+XJ%40HN%40GN)RJMmxmi_mbk2Cm%25dHCm%2B_jk2*sltG%5D0GdGg50%5B26+7+39+17+48+43+24+36+23+47+35+40+14+30+18+49+28+44+29+25+34+4+21+41+11+19+6+9+38+3+45+46+13+15+12+22+27+8+33+20+16+42+0+1+10+37+2+31+5+32&debug=0). Never used so many (5) nested maps. Btw I haven't actually made a test harness. Neither does the function `P` count how many times I call it. I have spend way to much time already figuring out the algorithm. But if you read my explanation, it's quite obvious that it uses `int(log2(n-1)) + 1` calls (`= ceil(log2(n))`). And `sum(int(log2(n-1)) + 1 for n in range(50, 151)) / 101.0 = 7.069306930693069`. ## Explanation: I actually had quite a hard time finding this algorithm. It was not clear to me at all, how to achieve `log(n)`. So I started doing some experiments with small `n`. First note: A bit-array gathers the same information as the complement bit-array. Therefore all bit-arrays in my solution have at most `n/2` active bit. **n = 3:** Since we can only use bit-array with 1 active bit, the optimal solution depends of two calls. E.g. `P([1, 0, 0])` and `P([0, 1, 0])`. The results tell us the first and second number of the permutation, indirectly we get the third one. **n = 4:** Here it get's a little bit interesting. We now can use two kinds of bit-array. Those with 1 active bit and those with 2 active bits. If we use a bit-array with one active bit, we only gather information about one number of the permutation, and fall back to `n = 3`, resulting in `1 + 2 = 3` calls of `P`. The interesting part is that we can do the same thing with only 2 calls, if we use bit-arrays with 2 active bits. E.g. `P([1, 1, 0, 0])` and `P([1, 0, 1, 0])`. Let's say we get the outputs `[1, 0, 0, 1]` and `[0, 0, 1, 1]`. We see, that the bit number 4 is active in both output arrays. The only bit that was active in both input arrays was bit number 1, so clearly the permutation starts with `4`. Now it's easy to see, that bit 2 was moved to bit 1 (first output), and bit 3 was moved to bit 3 (second output). Therefore the permutation must be `[4, 1, 3, 2]`. **n = 7:** Now something bigger. I'll show the calls of `P` immediately. They are the once, that I came up with after a little thinking and experimenting. (Notice these are not the ones, that I use in my code.) ``` P([1, 1, 1, 0, 0, 0, 0]) P([1, 0, 0, 1, 1, 0, 0]) P([0, 0, 1, 1, 0, 1, 0]) ``` If in the first two output arrays (and not in the third) the bit 2 is active, we know that the permutation moves bit 1 to bit 2, since bit one is the only bit that is active in the first two input arrays. The important thing is, that (interpreting the inputs as matrix) each of the columns are unique. This remembered me on [Hamming codes](http://en.wikipedia.org/wiki/Hamming(7,4)#Goal), where the same thing is accomplished. They simply take the numbers 1 to 7, and use their bit-representation as columns. I'll use the numbers 0 to 6. Now the nice part, we can interpret the outputs (again the columns) as numbers again. These tell us the result of the permutation applied to `[0, 1, 2, 3, 4, 5, 6]`. ``` 0 1 2 3 4 5 6 1 3 6 4 5 0 2 P([0, 1, 0, 1, 0, 1, 0]) = [1, 1, 0, 0, 1, 0, 0] P([0, 0, 1, 1, 0, 0, 1]) = [0, 1, 1, 0, 0, 0, 1] P([0, 0, 0, 0, 1, 1, 1]) = [0, 0, 1, 1, 1, 0, 0] ``` So we only have to trace back the numbers. Bit 0 ended up in bit 5, bit 1 ended up in bit 0, bit 2 ended up in bit 6, ... So the permutation was `[5, 0, 6, 1, 3, 4, 2]`. ``` Mmxmi_mbk2Cm%dHCm+_jk2*sltG]0GdG M define a function g(G, H), that will return the result of the following computation: G is n, and H is the permutation. m G map each k in [0, 1, ..., Q-1] to: _ their inverse jk2 binary representation (list of 1s and 0s) + extended with *sltG]0 int(log2(Q - 1)) zeros C transpose matrix # rows that are longer # than others are shortened m%dH map each row (former column) d of the matrix to the function P (here %) C transpose back m map each row k to: i 2 the decimal number of the _mbk inverse list(k) # C returns tuple :-( Let's call the result X. m G map each d in [0, 1, ..., Q - 1] to: x X d the index of d in X ``` And the code for the permutation function: ``` D%GHJHVJ XJ@HN@GN)RJ D%GH def %(G, H): # the function is called % JH J = copy(H) VJ ) for N in [0, 1, ..., len(J) - 1]: XJ@HN@GN J[H[N]] = G[N] RJ return J ``` [Answer] # Mathematica, 63 + 100 = 163 I'm using one-based permutations, since that's how indexing works in Mathematica. First, the test harness. This is the query function `p` (user-defined names shouldn't be upper-case in Mathematica): ``` p[perm_, vec_] := ( i += 1; vec[[Ordering@perm]] ); ``` And input preparation along with the test loop: ``` permutations = ToExpression@StringSplit@# + 1 & /@ StringSplit[Import[ "https://raw.githubusercontent.com/iatorm/permutations/master/permutations.txt" ], "\n"]; total = 0; ( i = 0; result = f@#; If[# != result, Print["Wrong result for ", #, ". Returned ," result ", instead."] ]; total += i; ) & /@ permutations; N[total/Length@permutations] ``` And finally, my actual submission which uses the naive algorithm for now: ``` f=(v=0q;v[[#]]=1;Position[q~p~v,1][[1,1]])&/@Range@Length[q=#]& ``` Or with indentation: ``` f = ( v = 0 q; v[[#]] = 1; Position[q~p~v, 1][[1, 1]] ) & /@ Range@Length[q = #] & ``` ]
[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 9 years ago. [Improve this question](/posts/2985/edit) Goal: Create and save file in Vim containing at least 25 ASCII characters. The *exact keystrokes* used during the creation and saving of this file must also produce identical contents in Windows Notepad (without having to save in Notepad). Rules: * For the purposes of this challenge, Vim begins open in command mode. * The mouse is **not** allowed. * `Shift` ***is*** allowed. `Ctrl`, `alt`, or any other modifier keys are ***not*** allowed. * Your solution must work with the **default** "terminal" (non-GUI) Vim shipped with either Ubuntu 11.04 or OS X 10.6.7 (one of the two). Assume this Vim's `.vimrc` contains only `set nocompatible` (with no line break after it), which is itself located at `~/.vimrc`. Pretend your operating system was *just* installed before opening Vim. * You must not open any *pre-existing* files except for your `.vimrc`. Any files you create while solving this puzzle may be saved and re-opened as many times as necessary. * Vim cannot be closed! *Disclosure, and a possible reason to close:* I do not have a solution. [Answer] The edited sequence (the first version was mangled). `2` `A` `2` `A` `Esc` `2` `A` `2` `A` `Esc` `2` `A` `2` `A` `Esc` `2` `A` `2` `A` `Esc` `2` `A` `2` `A` `Esc` `2` `A` `2` `A` `Esc` `2` `A` `2` `A` `Esc` `2` `A` `2` `A` `Esc` `A` `:` `w` `q` `Enter` `Esc` `Backspace` `Backspace` `Backspace` `Backspace` `Backspace` `:` `w` `q` `Enter` Should do the trick, if I'm counting my keystrokes correctly. No wait, is the escape key allowed? [Answer] `I` `Backspace` `H` `E` `L` `L``O` `,` `Space` `W` `O` `R` `L``D` `Esc` `Shift`+`;` `W` `Enter` `I` `Backspace` `Backspace` `Backspace` `Backspace`. Produces "hello, world" in both. [Answer] 34 keystrokes. Produces twenty-two A's followed by :x and a new line. `i` `Backspace` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `a` `:` `x` `Enter` `Esc` `Backspace` `Backspace` `Backspace` `:` `x` `Enter` ]
[Question] [ In prefix notation, the operator comes before the arguments, so you can kind of imagine that the operator calls `next()` which is recursively called. In infix notation, the operator goes between the arguments, so you can imagine it simply as a parse tree. In postfix notation, the operator comes after the arguments, so you can just imagine it as stack-based. In anyfix notation, the operator can go anywhere\*. If an operator shows up and there aren't enough arguments, then the operator waits until there are enough arguments. For this challenge, you are to implement a very basic anyfix evaluator. (Note that anyfix is a recreational language that I abandoned that you can play around with [here](https://tio.run/#anyfix) or check out [here](https://github.com/alexander-liao/anyfix)) You will need to support the following commands: ### (Arity 1) * duplicate * negative ### (Arity 2) * addition * multiplication * equality: returns `0` or `1`. You may choose to use any five non-whitespace symbols for these commands. For demonstrational purposes, I will use `"` as duplicate, `×` as multiplication, and `+` as addition. For literals, you only need to support non-negative integers, but your interpreter must be able to contain all integers (within your language's (reasonable) integer range). Let's take a look at an example: `10+5`. The storage should behave as a stack, not a queue. So first, the stack starts at `[]`, and the queued operator list starts at `[]`. Then, the literal `10` is evaluated which makes the stack `[10]`. Next, the operator `+` is evaluated, which requires two arguments. However, there is only one argument on the stack, so the queued operator list becomes `['+']`. Then, the literal `5` is evaluated which makes the stack `[10, 5]`. At this point, the operator `'+'` can be evaluated so it is, making the stack `[15]` and the queue `[]`. The final result should be `[15]` for `+ 10 5`, `10 + 5`, and `10 5 +`. Let's take a look at a harder example: `10+"`. The stack and queue start as `[]` and `[]`. `10` is evaluated first which makes the stack `[10]`. Next, `+` is evaluated, which doesn't change the stack (because there are not enough arguments) and makes the queue `['+']`. Then, `"` is evaluated. This can run immediately so it is, making the stack `[10, 10]`. `+` can now be evaluated so the stack becomes `[20]` and the queue `[]`. The final result is `[20]`. What about order of operations? Let's take a look at `×+"10 10`. The stack and queue start both as `[]`: * `×`: The stack is unchanged and the queue becomes `['×']`. * `+`: The stack is unchanged and the queue becomes `['×', '+']`. * `"`: The stack is unchanged and the queue becomes `['×', '+', '"']`. * `10`: The stack becomes `[10]`. Even though `×` should be the first operator to be evaluated since it appears first, `"` can run immediately and none of the operators before it can, so it is evaluated. The stack becomes `[10, 10]` and the queue `['×', '+']`. `×` can now be evaluated, which makes the stack `[100]` and the queue `['+']`. * `10`: The stack becomes `[100, 10]`, which allows `+` to be evaluated. The stack becomes `[110]` and the queue `[]`. The final result is `[110]`. The commands used in these demonstrations are consistent with that of the anyfix language; however, the last example will not work due to a bug in my interpreter. (Disclaimer: Your submissions will not be used in the anyfix interpreter) # Challenge Select a set of 5 non-whitespace non-digit characters and create an anyfix interpreter according to the specifications above. Your program can either output the singular array or the value contained by it; it is guaranteed that the stack of values will only contain a single value at the end of execution and that the queue of operators will be empty at the end of execution. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. # Test Cases For these test cases, duplicate is `"`, negative is `-`, addition is `+`, multiplication is `×`, and equality is `=`. ``` Input -> Output 1+2×3 -> 9 1"+"+ -> 4 2"××" -> 16 3"×+" -> 18 3"+×" -> 36 123"= -> 1 ("= always gives 1) 1+2=3 -> 1 1"=2+ -> 3 1-2-+ -> -3 -1-2+ -> 3 (hehe, the `-1` becomes `+1` at the `-` rather than making the `2` a `-1`) +×"10 10 -> 200 (after the 10 is duplicated (duplication is delayed), 10 + 10 is performed and then 20 * 10, giving 200) ``` # Rules * Standard Loopholes Apply * You may take the anyfix official interpreter and golf it if you would like. Expect to lose horribly. Input will be given as a string and output as an array, a single integer, out the string representation of either. You may assume that the input will only contain spaces, digits, and the 5 characters you choose. \* not actually [Answer] # JavaScript (ES6), ~~204~~ ~~203~~ 200 bytes Returns an integer. ``` e=>e.replace(/\d+|\S/g,v=>{for((1/v?s:v>','?u:b)[U='unshift'](v);!!u[0]/s[0]?s[U](u.pop()>'c'?s[0]:-S()):!!b[0]/s[1]?s[U](+eval(S(o=b.pop())+(o<'$'?'==':o)+S())):0;);},s=[],u=[],b=[],S=_=>s.shift())|s ``` Characters used: * `+`: addition * `*`: multiplication * `#`: equality * `d`: duplicate * `-`: negative ### Test cases ``` let f = e=>e.replace(/\d+|\S/g,v=>{for((1/v?s:v>','?u:b)[U='unshift'](v);!!u[0]/s[0]?s[U](u.pop()>'c'?s[0]:-S()):!!b[0]/s[1]?s[U](+eval(S(o=b.pop())+(o<'$'?'==':o)+S())):0;);},s=[],u=[],b=[],S=_=>s.shift())|s ;[ '10+5', '10+d', '*+d10 10', '1+2*3', '1d+d+', '2d**d', '3d*+d', '3d+*d', '123d#', '1+2#3', '1d#2+', '1-2-+', '-1-2+' ] .forEach(e => console.log(e, '-->', f(e))) ``` ### Formatted and commented ``` e => e.replace( // given an expression e, for each value v matching /\d+|\S/g, v => { // a group of digits or any other non-whitespace char. for( // this loop processes as many operators as possible ( // insert v at the beginning of the relevant stack: 1 / v ? s : v > ',' ? u : b // either value, unary operator or binary operator )[U = 'unshift'](v); // (s[], u[] or b[] respectively) !!u[0] / s[0] ? // if there's at least 1 value and 1 unary operator: s[U]( // unshift into s[]: u.pop() > 'c' ? // for the duplicate operator: s[0] // a copy of the last value : // else, for the negative operator: -S() // the opposite of the last value ) : // end of unshift() !!b[0] / s[1] ? // if there's at least 2 values and 1 binary operator: s[U]( // unshift into s[]: +eval( // the result of the following expression: S(o = b.pop()) + // the last value, followed by the (o < '$' ? '==' : o) + // binary operator o with '#' replaced by '==' S() // followed by the penultimate value ) // end of eval() ) : 0; // end of unshift() ); // end of for() }, // end of replace() callback s = [], // initialize the value stack s[] u = [], // initialize the unary operator stack u[] b = [], // initialize the binary operator stack b[] S = _ => s.shift() // S = helper function to shift from s[] ) | s // return the final result ``` [Answer] # JavaScript (ES6), ~~162~~ ~~152~~ ~~143~~ 150 bytes ``` (s,N=s.replace(/(-?\d+)-|-(-)/g,'- $1 ').match(/(- ?)*?\d+|R/g))=>+eval(`R=${N[0]>'9'?N[1]:N[0]},${s.match(/[+*=]/g).map((o,i)=>'R=R'+o+'='+N[i+1])}`) ``` **Slightly ungolfed:** ``` (s, N=s.replace(/(-?\d+)-|-(-)/g,'- $1 '). //change postfix negatives to prefix, //and change "--" to "- - " match(/(- ?)*?\d+|R/g) //grab numbers and duplicates )=>+eval(`R=${N[0] > '9' ? N[1] : N[0]}, //handle a delayed duplicate ${s.match(/[+*=]/g). //grab the operators map((o,i)=>'R=R'+o+'='+N[i+1]) //create a comma-separated list of assignments } `) ``` **Explanation** I'm using `*` for multiplication and `R` for duplicate. The other operators are the same as in the question. `N` becomes the array of the numbers (including the duplicates). The `replace` handles the case where the negative sign comes *after* the number. For example, it will change `1-` to `- 1` and `-1-` to `- -1` . Within the `eval`, `s.match` creates the array of binary operators. Note that this will always have one fewer elements than `N`. The result of the function is the `eval` of the mapping of the numbers and operators. Here is what is `eval`ed for each of the test cases: ``` 0+2*3 R=0,R=R+=2,R=R*=3 = 6 1+2*3 R=1,R=R+=2,R=R*=3 = 9 1R+R+ R=1,R=R+=R,R=R+=R = 4 2R**R R=2,R=R*=R,R=R*=R = 16 3R*+R R=3,R=R*=R,R=R+=R = 18 3R+*R R=3,R=R+=R,R=R*=R = 36 123R= R=123,R=R==R = 1 1+2=3 R=1,R=R+=2,R=R==3 = 1 1R=2+ R=1,R=R==R,R=R+=2 = 3 1-2-+ R=- 1,R=R+=- 2 = -3 -1-2+ R=1,R=R+=2 = 3 *+R10 10 R=10,R=R*=10,R=R+=10 = 110 +*R10 10 R=10,R=R+=10,R=R*=10 = 200 -1+--2 R=-1,R=R+=- -2 = 1 -1+-2 R=-1,R=R+=-2 = -3 ``` The comma operator in a JavaScript expression returns the result of its last expression, so the `map` automatically returns a usable expression. The `+` sign is needed before the `eval` to change `true` to `1` and `false` to `0`. Using `R` as both the variable *and* the duplicate operator greatly simplifies the `map`'s sub-expressions. **Test cases:** ``` let f= (s,N=s.replace(/(-?\d+)-|-(-)/g,'- $1 ').match(/(- ?)*?\d+|R/g))=>+eval(`R=${N[0]>'9'?N[1]:N[0]},${s.match(/[+*=]/g).map((o,i)=>'R=R'+o+'='+N[i+1])}`) console.log(f('1+2*3')) // 9 console.log(f('1R+R+')) // 4 console.log(f('2R**R')) // 16 console.log(f('3R*+R')) // 18 console.log(f('3R+*R')) // 36 console.log(f('123R=')) // 1 console.log(f('1+2=3')) // 1 console.log(f('1R=2+')) // 3 console.log(f('1-2-+')) // -3 console.log(f('-1-2+')) // 3 console.log(f('*+R10 10')) //110 console.log(f('+*R10 10')) //200 console.log(f('-1+--2')); // 1 console.log(f('-1+-2')); // -3 ``` [Answer] # JavaScript, ~~321~~ 311 bytes ``` _="f=a=>(a.replace(/\\d+|./g,mq!~(b='+*=\"- '.indexOf(a))|b>2j3j4j5&&o+aw1/y?(y*=-1wcz:1/y?oywcz:hz,rql.map(z=>m(lki,1)[0],i)),hq1/s[1]?sk0,2,+eval(`y${a=='='?a+a:a}s[1]`)):cz,cqlki,0,a),s=[],l=[],e='splice'),s)z(a,i)ys[0]w)^r``:q=z=>os.unshift(k[e](j?b-";for(i of"jkoqwyz")with(_.split(i))_=join(pop());eval(_) ``` [Try it online!](https://tio.run/##RVHbjtowFHz3V1Cr2tjYceJQKpWV4RP6AYQSE5zFwcRJnG4uZfvrNEZV@3I056KZ0ZlSvkuXt7ruwsqe1eNxFLAQUmyRZK2qjcwVitL0TO4seqO35tNvdBIBWYoUhouA6eqshu8FkhjfT9ukXJVfyvXLiyWy59G4Q@NShLzPp43v7OjRZaJtY9hN1mgS2xsyV0053scHqjGml4ZHbs8PO3eNaUKJepcGZePnX1KIQAQ7SeRGfviLDONNPtG88QQxlZg6sT9Q44sSgauNzlUwT/GE5Mw9ulmjxz/aLNs0Ypa2jv2s3EUXHbru1QGVu1MIXwvbIr2wBSyvtunHCeJedxd0ZJ6wQ7PHoyitrlBta4Tx69PgET9yWzlrFDP2DWWAk2RYAQ4JJCCBwwDBCg7EVzJjHpM1mFseL3gMvopvIFyLcA34IoGEgOyvVpS2aXVP23taRZgV2nSqRXM0Ej@/59H/jIY5nmAZ4H@7ZyjMW83SKsOPPw) The five characters are the same as in the question, except `*` is for multiplication. The script is compressed using [RegPack](https://siorki.github.io/regPack.html). The original script is stored in the variable `_` after evaluation. [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 697 bytes ``` 00 C0 A2 00 86 29 86 26 86 27 86 28 86 4B 86 4C 86 CC 20 E4 FF F0 FB C9 0D F0 10 C9 20 30 F3 A6 27 9D B7 C2 20 D2 FF E6 27 D0 E7 C6 CC A9 20 20 1C EA A9 0D 20 D2 FF 20 95 C0 20 09 C1 20 95 C0 A6 26 E4 27 F0 4E BD B7 C2 E6 26 C9 20 F0 E8 C9 2D D0 09 A6 4C A9 01 9D B7 C3 D0 32 C9 22 D0 09 A6 4C A9 02 9D B7 C3 D0 25 C9 2B D0 09 A6 4C A9 81 9D B7 C3 D0 18 C9 2A D0 09 A6 4C A9 82 9D B7 C3 D0 0B C9 3D D0 0D A6 4C A9 83 9D B7 C3 E6 28 E6 4C D0 A3 4C 8A C2 A6 29 F0 6F A4 28 F0 6B CA F0 4B C6 28 A6 4B E6 4B BD B7 C3 F0 F5 30 14 AA CA D0 0B 20 7B C2 20 E1 C1 20 4D C2 D0 D9 20 5C C2 D0 D4 29 0F AA CA D0 0B 20 6D C2 20 08 C2 20 4D C2 D0 C3 CA D0 0B 20 6D C2 20 16 C2 20 4D C2 D0 B5 20 6D C2 20 F4 C1 20 4D C2 D0 AA A4 4B B9 B7 C3 F0 02 10 AC C8 C4 4C F0 0F B9 B7 C3 F0 F6 30 F4 AA A9 00 99 B7 C3 F0 A6 60 A0 00 A6 26 E4 27 F0 15 BD B7 C2 C9 30 30 0E C9 3A 10 0A E6 26 99 37 C4 C8 C0 05 D0 E5 C0 00 F0 08 A9 00 99 37 C4 20 39 C2 60 A2 FF E8 BD 37 C4 D0 FA A0 06 88 CA 30 0A BD 37 C4 29 0F 99 37 C4 10 F2 A9 00 99 37 C4 88 10 F8 A9 00 8D 3D C4 8D 3E C4 A2 10 A0 7B 18 B9 BD C3 90 02 09 10 4A 99 BD C3 C8 10 F2 6E 3E C4 6E 3D C4 CA D0 01 60 A0 04 B9 38 C4 C9 08 30 05 E9 03 99 38 C4 88 10 F1 30 D2 A2 06 A9 00 9D 36 C4 CA D0 FA A2 10 A0 04 B9 38 C4 C9 05 30 05 69 02 99 38 C4 88 10 F1 A0 04 0E 3D C4 2E 3E C4 B9 38 C4 2A C9 10 29 0F 99 38 C4 88 10 F2 CA D0 D6 C0 05 F0 06 C8 B9 37 C4 F0 F6 09 30 9D 37 C4 E8 C8 C0 06 F0 05 B9 37 C4 90 F0 A9 00 9D 37 C4 60 A9 FF 45 FC 85 9F A9 FF 45 FB 85 9E E6 9E D0 02 E6 9F 60 A2 00 86 9F A5 FB C5 FD D0 07 A5 FC C5 FE D0 01 E8 86 9E 60 A5 FB 18 65 FD 85 9E A5 FC 65 FE 85 9F 60 A9 00 85 9E 85 9F A2 10 46 FC 66 FB 90 0D A5 FD 18 65 9E 85 9E A5 FE 65 9F 85 9F 06 FD 26 FE CA 10 E6 60 20 33 C1 A6 29 AD 3D C4 9D 3F C4 AD 3E C4 9D 3F C5 E6 29 60 A6 29 A5 9E 9D 3F C4 A5 9F 9D 3F C5 E6 29 60 A6 29 BD 3E C4 9D 3F C4 BD 3E C5 9D 3F C5 E6 29 60 C6 29 A6 29 BD 3F C4 85 FD BD 3F C5 85 FE C6 29 A6 29 BD 3F C4 85 FB BD 3F C5 85 FC 60 A6 29 BD 3E C5 10 13 20 7B C2 20 E1 C1 20 4D C2 A9 2D 20 D2 FF A6 29 BD 3E C5 8D 3E C4 BD 3E C4 8D 3D C4 20 8B C1 A9 37 A0 C4 4C 1E AB ``` **[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"anyfix.prg":"data:;base64,AMCiAIYphiaGJ4YohkuGTIbMIOT/8PvJDfAQySAw86YnnbfCINL/5ifQ58bMqSAgHOqpDSDS/yCVwCAJwSCVwKYm5CfwTr23wuYmySDw6Mkt0AmmTKkBnbfD0DLJItAJpkypAp23w9AlySvQCaZMqYGdt8PQGMkq0AmmTKmCnbfD0AvJPdANpkypg523w+Yo5kzQo0yKwqYp8G+kKPBryvBLxiimS+ZLvbfD8PUwFKrK0Asge8Ig4cEgTcLQ2SBcwtDUKQ+qytALIG3CIAjCIE3C0MPK0AsgbcIgFsIgTcLQtSBtwiD0wSBNwtCqpEu5t8PwAhCsyMRM8A+5t8Pw9jD0qqkAmbfD8KZgoACmJuQn8BW9t8LJMDAOyToQCuYmmTfEyMAF0OXAAPAIqQCZN8QgOcJgov/ovTfE0PqgBojKMAq9N8QpD5k3xBDyqQCZN8SIEPipAI09xI0+xKIQoHsYub3DkAIJEEqZvcPIEPJuPsRuPcTK0AFgoAS5OMTJCDAF6QOZOMSIEPEw0qIGqQCdNsTK0PqiEKAEuTjEyQUwBWkCmTjEiBDxoAQOPcQuPsS5OMQqyRApD5k4xIgQ8srQ1sAF8AbIuTfE8PYJMJ03xOjIwAbwBbk3xJDwqQCdN8Rgqf9F/IWfqf9F+4We5p7QAuafYKIAhp+l+8X90Ael/MX+0AHohp5gpfsYZf2FnqX8Zf6Fn2CpAIWehZ+iEEb8ZvuQDaX9GGWehZ6l/mWfhZ8G/Sb+yhDmYCAzwaYprT3EnT/ErT7EnT/F5ilgpimlnp0/xKWfnT/F5ilgpim9PsSdP8S9PsWdP8XmKWDGKaYpvT/Ehf29P8WF/sYppim9P8SF+70/xYX8YKYpvT7FEBMge8Ig4cEgTcKpLSDS/6YpvT7FjT7EvT7EjT3EIIvBqTegxEweqw=="%7D,"vice":%7B"-autostart":"anyfix.prg"%7D%7D)** **Usage** `sys49152`, then enter the anyfix expression and press return. * close to no error checking, so expect funny outputs on invalid expressions. * the symbol for multiplication is `*`, all others as suggested. * maximum input length is 256 characters, there can be no more than 127 operators queued. * The input routine **doesn't** handle control characters, so don't mistype ;) * integers are 16bit signed, overflow will silently wrap around. * byte count is a bit large because this CPU doesn't even know multiplication and the C64 OS / ROM doesn't give you **any** integer arithmetics or conversions to/from decimal strings. Here's the [readable ca65-style assembler source code](https://github.com/Zirias/c64anyfix/tree/a071e10c977321b5bd5a8771536836a0c90d90ee). [Answer] # [Haskell](https://www.haskell.org/), 251 bytes ``` (#([],[])) (x:r)#(o,n)|x>'9'=r#h(o++[x],n)|[(a,t)]<-lex$x:r=t#h(o,read a:n) _#(o,n:_)=n h=e.e e(o:s,n:m:r)|o>'N'=e(s,g[o]n m:r) e(o:s,n:r)|o=='D'=e(s,n:n:r)|o=='N'=e(s,-n:r) e(o:s,n)|(p,m)<-e(s,n)=(o:p,m) e t=t g"a"=(+) g"m"=(*) g"q"=(((0^).abs).).(-) ``` [Try it online!](https://tio.run/##TU5JbsMgFN1zCkQqGYqxClRRY4WsvK0v4LoRTZ1BNXhcWGp6jhwo96oLdhR19cb/4Ki7r6Isx716G/ECZ3mY5YQAPMQtWeAqtOQ8bIJVoNrFEVeUZkPuvQzrsCf5mpXF8OC6qvdx2Bb6E@rYErCdjuMtURYcVREVoMBV3DnLuOVztQnSQBW4Cw9ZlVvozXvD50oFyVyw8d25nTD7r03OuA4NWbOpS5RzvQYF7FUPDkgjhSlxxDjy6EnjCMZP7yTSHx2JSIQZGY0@Waig0fUrxHV7sj2M4J7ADHEtjEQh4olOtEORGJM4lInRM@pJcyGTxqMWzdxvhO/zVKQeU0c8uisJ@RPKwTcDnIrrRUK2gSvAEUXU02cg0PVyvSAv@BJIp@gsXpygt0QugXsTqSnwS0reKFJiGpKAM8EmyiRgTtxsv@c/MfVXgP2Mv7t9qQ/dyHZ1/Qc "Haskell – Try It Online") Uses the following characters: `a` for addition, `m` for multiplication, `q` for equality, `D` for duplicate and `N` for negation. (I wanted to use `e` for equality, but ran into the problem that `lex` parses `2e3` as a number.) Example usage: `(#([],[])) "2a3 4m"` yields `20`. [Answer] # VB.NET (.NET 4.5) ~~615~~ 576 bytes *-39 bytes thanks to Felix Palmen by changing `\r\n` to `\n`* Requires `Imports System.Collections.Generic` (included in byte count) ``` Dim s=New Stack(Of Long),q=New List(Of String),i=Nothing,t=0,c=0 Function A(n) For Each c In n If Long.TryParse(c,t)Then i=i &"0"+t Else If c<>" "Then q.Add(c) If i<>A Then s.Push(i) i=A End If If i=A Then E Next If i<>A Then s.Push(i) E A=s End Function Sub E() c=s.Count If c=0Then Exit Sub For Each op In q If op="-"Or op="d"Or c>1Then Select Case op Case"*" s.Push(s.Pop*s.Pop) Case"+" s.Push(s.Pop+s.Pop) Case"=" s.Push(-(s.Pop=s.Pop)) Case"-" s.Push(-s.Pop) Case"d" s.Push(s.Peek) End Select q.Remove(op) E Exit Sub End If Next End Sub ``` The entry point is Function `A`, which takes a string as input and returns a `Stack(Of Long)`. Symbols: * Addition - `+` * Multiplication - `*` * Equality - `=` * Negation - `-` * Duplication - `d` Overview: Function `A` takes the input and tokenizes it. It uses a `Long?` to do a running total for multi-digit integers, which `Nothing` signifying we are not currently reading an integer. Subroutine `E` takes the stack of integers and queue of operators, and evaluates the anyfix notation. It calls itself recursively until there are no actions left. I declare global params all at once to save bytes on both declaration and parameter passing. The return value from `A` is set by assigning a value to the matching variable `A`. VB `True` is equivalent to `-1`, so that operation has to negate the result to get the correct value. [Try it online!](https://tio.run/##hZRNj5swEIbv/hUjDi2EgIBUVSutV4q2bBVpv9Ss1GscPFmsBZxgs9v8@tQ2bEIPFTmEYd5nXnsmjt@2USFbPK3qvWy1gvVRaazjG1lVWGghGxX/xAZbUZB7ybsK4T49/RA1KPqA77DWrHj1H3dwJ5uXYH5wyTuhtM2tdStsVtAHqUsTzjVN5gVNyG3XOHNY@k1AbmULOStKKGDVQENWvV383B6fWKvQL@Y6eC6xIYIK@OQlXqhJXim0ZHF17YFnVTjES879IrBpcXW9BJdV8VOnSl8EpnpJ8obDaucIOgA5ecA/@n9FOVlS5co@Nk3W3RZyPyAFVWZQXeNqTVu92x@hwRCXruTetnWwkNxTL/IeWxdwGxTXqetsjXbecMMUGpHYpzfzyLAP85D7mfsOei38VwvHGj1rUa/SXh3k6CKPq/jYEfE1cE33@yKH@BfW8g19i@fk3OQwTjdAh3fbkx3PPRMNITB8bswxkhXGv1uh8U406C99Lw2z2cIL7A6AwvdgguYhD8/0lwk647MZP9Pp1wl8wWfhCP82iYcj98WUe5otOL24B/AZfE6BVe/sqOBFvKEy2clh0cXIY2pYNLsMazFFR1l0oaMpPDL82Ny2U2KJc9AlwiZKN7DFQtamq01oXpgehA20zESteWUN1OzV3Ai9lBnKVU4sbcaeJpAm59WzJHHrs512vmhEEAp4t69EwTRyM@ohtteNlbBiR@TB3KLhwO@x3cm2Njgzh1jb/3GWwMyoc/sD2Y3apQj5OOR90N@Ip78) ]
[Question] [ ASCII boxes look like this: ``` ++ +---+ +------+ +---+ +---+ ++ | | | | | | | | | | | | | | | | +-+ | | | | | | | | +-+ | | | | | | +---+ +---+ | | | | +--+ | | | | ++ | | | | | | || | | +------+ | | || +--+ | | || +---+ || || +-----+ || +------------+ | | ++ | | | | | | | | +------------+ +-----+ ``` Here are some examples of the same ASCII boxes, imploded: ``` ++ +- -+ +- -+ +- -+ +- -+ ++ | - | | - - | | - | | - | | | | -- | | | | | +-+ | | | | " | - | +-+ | - | || | | +- -+ +- -+ | | | | +--+ | -- | | | ++ | | | - - | " || | | +- -+ | | || +--+ | - | | | +- -+ | | -- || - - +- -+ || +- - - -+ | - - | ++ | -- -- | | = | | -- -- | | - - | +- - - -+ +- -+ - - -- ``` [Here](https://github.com/allenkev/annieflow/blob/master/testcases) is a link to all of these test case boxes in an easier-to-copy format. The order is all inputs followed by all outputs in the same order. Your goal is to take an ASCII box as input, and return the imploded box. The rules of implosion are: 1. "+" never changes; neither do "-" or "|" directly adjacent to "+" 2. Starting from the corners, the "-" and "|" move inward by one space more than the same character closer to the corner did. If a "-" and "|" would ever move to the same spot, neither moves. 3. If a "-" and "-" move to the same spot, put a "=" in that spot. If a "|" and "|" move to the same spot, put a " in that spot. These count as two of their respective characters in the same spot moving in opposite directions. 4. Two "-" or two "|" can move past each other, as seen in the bottom left example. 5. If the box is skinny enough, it will start expanding outwards in the same way, always moving away from the side it started out part of. 6. The result should be symmetric across the center line in both the x and y directions (ignoring newlines); this includes spaces, so the result may need to be padded with spaces to satisfy that. **Rule Details:** 1. This is code-golf, so shortest program in bytes wins. 2. Standard loopholes apply. 3. You can assume each line ends in a newline character. 4. The only characters in the input string will be "+", "-", "|", " ", and "\n" (newline), and your output string should follow the same rules, with the addition of "=" and " as possible characters. 5. You may optionally have a single trailing newline at the end of the last line. 6. The smallest ASCII box you need to handle is the top-left example. Every ASCII box will have exactly 4 "+"s, exactly at its corners. 7. You will need to handle boxes of size `m x n` for any integers `m,n` such that `2<=m,n<256` (largest possible string size of `255*(255+1)`) 8. You can assume you will always get a single valid ASCII box as input. [Answer] # [Python 2](https://docs.python.org/2/), ~~591~~ ~~555~~ ~~545~~ ~~527~~ ~~525~~ ~~496~~ ~~436~~ ~~351~~ ~~334~~ ~~333~~ 303 bytes ``` s=input() w=len(s[0]) h=len(s) V=max(0,w/2-h) H=max(0,h/2-w) p=[[' ']*w]*V q=[' ']*H s=[q+k+q for k in p+s+p] d,c=' -=',' |"' exec"c,d,V,H,w,h=d,c,H,V,h,w;s=map(list,zip(*s))[::-1]\nfor j in range(h-4):q=s[V+j+2];q[H]=c[q[H]==c[2]];r=H+min(j+1,h-4-j);q[r]=c[1+(q[r]>' ')]\n"*4 for x in s:print''.join(x) ``` [Try it online!](https://tio.run/##fY/BboMwEETv/gorF3uxoQnKicg98wVcHB8o0GACxmAqaJV/pyapGvXSveyMPPO0tp9T3Zt41cZ@TFjgNu/eyjzBXW5pq93Ee1sZSqL7ezTpnnAyEojGKi8pRM62eqLkbAjA6sQ9RQHNovUtJ/cKUP3QgDLR5Qvd8/klDmtA6Y@tvZ0BWSElwUQFswoyNIiHSZETcmBXNuD3fsRXrA22zDGrUMkLQXAo/EH4tiOoWqpiV/CSZzzlM6@FD3iV8ZrPJyd@P/SlLQ0cgEyS8KDOZuM2G3fMzaWidXiEZBBOZqxhsToNMlWikPfld6zUaRQp67ShDTtwHw8b8KlxSx0Y3dSrvx08ehcc0YZfNrxL7KjNREjU9L68wLqy8DkM3fBzbv@6P71v "Python 2 – Try It Online") **EDIT**: My old method first imploded the top and bottom, and then the left and right. Instead, we can implode the top, rotate 90 degrees, and do that 4 times. Also, I was using the user-friendly code, this one requires input be in the form `[['+', '-', '-', '-', '-', '-', '+'], ['|', ' ', ' ', ' ', ' ', ' ', '|'], ['|', ' ', ' ', ' ', ' ', ' ', '|'], ['|', ' ', ' ', ' ', ' ', ' ', '|'], ['+', '-', '-', '-', '-', '-', '+']]` which is ugly but shorter for the program :P (Thanks to Phoenix for catching that) Credits to Leaky Nun for the header code in the TIO link used for converting human-readable input into computer-readable input. -85 bytes thanks to Leaky Nun! -17 bytes by switching from top-implosion to left-implosion which allows the entire row to be stored into a variable and modified. Thanks to Leaky Nun for the suggestion! -1 byte by switching things around to remove a space. -30 bytes thanks to Leaky Nun! [Answer] # [C (clang)](http://clang.llvm.org/), 693 bytes New lines added for readability. The first two are required but the rest are not. ``` #define P B[i][l] #define m malloc(8) I(B,h,V,S,J,Z,i,j,l,n,H,W,c,C,a,z,_,L,G,u,N,M)char**B,**Z;char*L,*G,*u;{ V=strlen(B[0]); S=J=0; Z=m; for(i=0,j=h-1;i<h/2+h%2;i++,j--){ for(l=0,n=V-1;l<V/2+V%2;l++,n--){ if(P!=43&&((B[i][l-1]!=43&&i<1)||(B[i-1][l]!=43&&l<1))){ H=P==45; W=P=='|'; P=B[j][l]=B[i][n]=B[j][n]=32; if(H){ c=(N=i+l-1)==(M=j-l+1)?61:45; if(M<0)L=m,sprintf(L,"%*s",V,""),L[l]=L[n]=c,Z[J]=L,J++; else B[N][l]=B[N][n]=B[M][l]=B[M][n]=c; } if(W){ c=(N=l+i-1)==(M=n-i+1)?34:'|'; if(M<0)G=m,sprintf(G,"|%*s%s%*s|",i-n-2,"",B[i],i-n-2,""),B[i]=B[j]=G,S++; else B[i][N]=B[j][N]=B[i][M]=B[j][M]=c; } } } } for(a=-J+1;a<=h+J;u=a<1?Z[-a]:a<=h?B[a-1]:Z[a-h-1],C=S+1-strlen(u)/2,printf("%*s%s\n",C>0?C:0,"",u),a++); } ``` Thanks for the great challenge! It was quite tricky but I still had a lot of fun. This takes the input as command-line arguments and outputs to STDOUT a multi-line string of the imploded box. As always, golfing tips are very much appreciated. [Try it online!](https://tio.run/##nVLfb9owEH73X5GlahvH55XQbppwXCR4gCKCkJCoRBZNmQmNkTETlD606Z@9Z3YOYar2OEeK7z59vvvuh@LK5PbpeKGtModl4cX756Xefi7vyUdop@3Tv9jS6J@IHS@WxUrbwpt6vVRnqcnIGdl4m9yYrQq@UfIQ9KCEOcxgBAvQsAYDFobwCAr6kMMr/IAxDOAAE0ioKvNdGPYgDBeitscQDiA8iDcylyjHFDbopa2MCjKTI9kSZCE3gqy2u0DLFqxlySOh4/KmzcrLttCMwZpz@lYzDDKsnCPDxHNkzJFhkGFrhl4F00/y7vbqKghOBfEoOwE6jmhVORQhLPSEGkQpPhzKqZR3XwR5dMZ1dS3IVPbStWPKOpLNTj7et23hMg3xnZLBRGqGaaiUQSLX3LCIdr9GHRcMSUncomO5gf0vHMPzKhiDfxnufWym71MYu/BjF1PBIh2hDSPGBCnMvsCJTJr0kyZ90vhJ7StB3l2Kx7MOw/RZh@Xa6bi969S1NEIGH4QMwK9QyeUef5UPmlveRk3giv3r0dqtC5cDmH2Qhh2ZNB2ZNB1KGj9ppJ0@N7Rc8hGLRB7Lko3EQeZx1F2kPM86Dur20hxn0lnghaPPoC9nLOLNphzoTRsazX4t@Lv1oX/f6vY7LSf4QCFnDJfp/Ygk3FptA2fkuycFp11E84V6b8Rz4IurorYU5856CBwKDnBRyPHIeH3YsfLqU/2ncY7z2265ylVZ/AE "C (clang) – Try It Online") ]
[Question] [ Your task is make program that do following: 1. You should take number. (Positive, negative, fraction is possible input) 2. If it is negative, you reverse the quine. and negate that number (Become positive) 3. Then you repeat <integer part of the input number> times and print first <floor(fraction part of the input number\*length)> from your source program. If it is integer, then the fraction part is zero. -10% bonus if your program isn't palindrome. ## Example If your program is "ABCDEFG", then 1. ``` 5 ABCDEFGABCDEFGABCDEFGABCDEFGABCDEFG ``` Explanation > > ABCDEFG five times > > > 2. ``` -2 GFEDCBAGFEDCBA ``` Explanation > > GFEDCBA (reversed ABCDEFG) 2 times > > > 3. ``` 7.5 ABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABC ``` Explanation > > ABCDEFG 7 times followed by ABC (first 3(floor(0.5\*7)=floor(3.5)=3) letter on ABCDEFG) > > > 4. ``` -0.3 GF ``` Explanation > > GFEDCBA (reversed ABCDEFG) 0 times followed by GF (first 2(floor(0.3\*7)=floor(2.1)=2) letter on GFEDCBA(reversed ABCDEFG)) > > > 5. ``` 0 <empty> ``` Explanation: > > <empty> here means that your program doesn't output. It is ABCDEFG zero times that is defined as empty string. > > > [Answer] ## CJam, ~~28~~ 26 bytes \* 0.9 = 23.4 Thanks to Sp3000 for saving 2 bytes. ``` {`"_~"+rd_z26*,\g1|@%f=}_~ ``` [Test it here.](http://cjam.aditsu.net/#code=%7B%60%22_~%22%2Brd_z26*%2C%5Cg1%7C%40%25f%3D%7D_~&input=-7.5) ### Explanation ``` {`"_~"+ e# Generalised quine framework. Leaves the source code on the stack. rd e# Read input and parse as double. _z e# Copy and get absolute value. 26* e# Multiply by 26, the length of the quine to get length N of the output. , e# Get a range [0 1 ... floor(N-1)]. \g e# Swap with other copy and computer signum to determine direction of string. 1| e# This might be zero though, so take bitwise OR with 1 to avoid an error. @% e# Pull up source string. Reverse it if the signum was -1 (no-op otherwise). f= e# The range we pushed earlier corresponds to the (cyclic) indices of the source e# which make up the desired result, so we map each index to the corresponding e# character to get the final result. }_~ ``` [Answer] # Vitsy, 34 \* 0.9 = 30.6 Bytes Thanks to @Sp3000 for pointing out a flaw in my code! Woo. My Physics teacher reminded me I had power functions to help me with this. Go figure. ``` 'r(;Vd3*V2^12/^DvV/1+(rvl1-*\[DO{] ' Start recording as a string - this grabs everything and pushes it to the stack as a string. r Reverse the stack order. (; If the top item is zero, exit the program. V Grab the input as a final global variable. d3* Push the character ' to the stack. V2^12/^ Get the absolute value of the input value. Dv Duplicate and save in a temp variable. V Push the global variable to the stack. / Divide the top two items - this gets -1 or 1 depending on the polarity of the input. 1+( If it's -1, do the next instruction. Otherwise, don't. r Reverse the stack v Push the temporary variable to the stack. l1-* Multiply by the length of the stack minus 1. \[ ] Repeat everything in brackets top item of the stack times. DO{ Duplicate an item, pop it off the stack and output it, then move one item over in the stack. ``` [Answer] # Perl, 104 bytes - 10% = 93.6 ``` perl -i-0.3 -e '$_=q{$_="\$_=q{$_};eval";$_=reverse if$^I<0;$n=abs$^I;print+($_ x$n).substr$_,0,y///c*($n-int$n)};eval' ``` 102 bytes + 2 bytes for `-i` - 10% for not being a palindrome. Input is passed as the argument to `-i` (e.g. `-0.3` above). ## How it works This solution is based on the following quine: ``` $_=q{print"\$_=q{$_};eval"};eval ``` This works as follows. First, set `$_` to the string: ``` print"\$_=q{$_};eval" ``` Next, call `eval`, which works on `$_` by default. This calls `print` with one argument, a string literal: ``` "\$_=q{$_};eval" ``` Since this string is double-quoted, variables are interpolated. After interpolating `$_`, the value of the string is: ``` \$_=q{print"\$_=q{$_};eval"};eval ``` When printed, this outputs: ``` $_=q{print"\$_=q{$_};eval"};eval ``` which is the source code of the program itself. The nice thing about this quine is that you can embed arbitrary code inside the string to be `eval`'d. --- Here's a breakdown of the full solution: ``` perl -i-0.3 -e' $_=q{ # string to be eval'd $_="\$_=q{$_};eval"; # append beginning and end of quine so the # entire thing can be reversed if necessary $_=reverse if $^I<0; # reverse if input < 0 $n=abs $^I; # set $n to absolute value of input print # print +($_ x $n) # $_ repeated $n times . # concatenated with substr $_, # substring of $_ 0, # starting at the beginning y///c # having length x, where x is length of $_ * # multiplied by ($n-int$n) # fractional part of $n }; eval # eval $_ ' ``` [Answer] # Mathematica, 139 - 10% = 125.1 bytes ``` StringJoin[Table[s = If[#1 > 0, #1 & , StringReverse][ToString[#0, InputForm]], {Abs[Floor[#1]]}], StringTake[s, Floor[Mod[#1, 1]*139]]] & ``` Note the trailing space. The whitespace, standard notation, etc. are the result of the `ToString[#0, InputForm]`. [Answer] ## Haskell, 158 \* 0.9 = 142.2 bytes ``` c i|i<0=reverse|1<2=id;f i=putStr$take(floor$abs i*158)$cycle$c i$s++show s;s="c i|i<0=reverse|1<2=id;f i=putStr$take(floor$abs i*158)$cycle$c i$s++show s;s=" ``` A quine function. ``` *Main> f (-0.3) "=s;s wohs++s$i c$elcyc$)851*i sba$roolf(ekat$r *Main> f 1.1 c i|i<0=reverse|1<2=id;f i=putStr$take(floor$abs i*158)$cycle$c i$s++show s;s="c i|i<0=reverse|1<2=id;f i=putStr$take(floor$abs i*158)$cycle$c i$s++show s;s="c i|i<0=reverse *Main> f 0 <-- empty ``` [Answer] # Python 2, 193 bytes - 10% = 173.7 ``` x=input();y=int(x);_='x=input();y=int(x);_=%r;_=(_%%_)[::y/abs(y)];x,y=abs(x),abs(y);_=_*y+_[:int(y*(x-y)*193)];print _';_=(_%_)[::y/abs(y)];x,y=abs(x),abs(y);_=_*y+_[:int(y*(x-y)*193)];print _ ``` Errors out on `0`, but, ignoring STDERR, you still get empty output. ]
[Question] [ You need to build a pyramid from cubes. Cubes can be viewed from 2 angles: ``` _____ _____ /\ \ / /\ / \____\ /____/ \ \ / / \ \ / \/____/ \____\/ ``` This is an example for 2-size cubes from the 2 possible angles. The height of the cubes is `$size` slashes (or back-slashes), and the width of the cube is `2 * $size` underscores. The top level width should contain an extra underscore character. Input will be provided as a string containing a number (size of cubes), slash or backslash (to indicate direction/angle), and another number (height of the pyramid). Examples: Input: ``` 1/1 ``` Output: ``` ___ /\__\ \/__/ ``` Input: ``` 1\1 ``` Output: ``` ___ /__/\ \__\/ ``` Input: ``` 2/1 ``` Output: ``` _____ /\ \ / \____\ \ / / \/____/ ``` Input: ``` 1/2 ``` Output: ``` ___ ___/\__\ /\__\/__/ \/__/\__\ \/__/ ``` Input: ``` 2\2 ``` Output: ``` _____ / /\ /____/ \_____ \ \ / /\ \____\/____/ \ / /\ \ / /____/ \____\/ \ \ / \____\/ ``` Input: ``` 1/3 ``` Output: ``` ___ ___/\__\ ___/\__\/__/ /\__\/__/\__\ \/__/\__\/__/ \/__/\__\ \/__/ ``` * Trailing/leading whitespaces are OK. * Standard loopholes are disallowed. * You can assume input will always be valid. * You may assume the input won't cause too big output, i.e: no line wrapping when the output is printed to the terminal. * Size of cube & height of pyramid is positive (i.e. ≥ 1) * This is code-golf, so shortest code in bytes wins. # Current Winner is: **Glen O** with 270 bytes in julia challenge stays open. if you beat the current best, I'll update the accepted answer. [Answer] # Perl, 343 bytes ``` $_=<>;$_=~/(\d+)(\S)(\d+)/;$v=$2eq'/';$w=$1*3+1;for$y(0..$1*2*$3){$k=$w*$3+$1-1;for$z(0..$k){$x=$v?$k-$z:$z;$q=($y+$1-1)/$1|0;$r=$x/$w|0;$d=$q+$r&1;$f=($y-1)%$1;$f=$1-$f-1if$d;$g=($x-$f)%$w;$u=$r;$q=2*$3-$q+1,$u++if$q>$3;print(($q>=$r&&$q&&$g==0)||($q>$r&&$g==$w-$1)?$d^$v?'/':'\\':$q>=$u&&$y%$1==0&&$g>0&&$g<($w-$1+($q==$r))?"_":$")}print$/} ``` Multiline with comments: ``` $_=<>;$_=~/(\d+)(\S)(\d+)/;$v=$2eq'/'; # read input $w=$1*3+1; # compute width of each cube in chars for$y(0..$1*2*$3){$k=$w*$3+$1-1;for$z(0..$k){ # iterate over rows, columns $x=$v?$k-$z:$z; # flip x co-ordinate based on 2nd param $q=($y+$1-1)/$1|0;$r=$x/$w|0; # parallelogram row and column index $d=$q+$r&1; # flag parallelogram as left or right leaning $f=($y-1)%$1;$f=$1-$f-1if$d; # compute a zig-zag offset $g=($x-$f)%$w; # compute column position, offset by zig-zag $u=$r;$q=2*$3-$q+1,$u++if$q>$3; # vertical threshold for printing chars print(($q>=$r&&$q&&$g==0)||($q>$r&&$g==$w-$1)?$d^$v?'/':'\\': # output slash $q>=$u&&$y%$1==0&&$g>0&&$g<($w-$1+($q==$r))?"_":$") # underscore or space }print$/} # print out newline at end of row ``` Example output: ``` 2/3 _____ /\ \ _____/ \____\ /\ \ / / _____/ \____\/____/ /\ \ / /\ \ / \____\/____/ \____\ \ / /\ \ / / \/____/ \____\/____/ \ / /\ \ \/____/ \____\ \ / / \/____/ ``` I also tried implementing it as a C function using the same algorithm, hoping to save bytes from the luxury of single-character variable names, but it ended up 15 bytes larger, at 358 bytes (needs to be compiled with `-std=c89` under gcc to leave off the `void` in the function header): ``` j(char*s){int c,p,v,x,y,k,z,u,g,w,r,d,q,f;char e;sscanf(s,"%d%c%d",&c,&e,&p);v=e=='/';w=c*3+1;for(y=0;y<=c*2*p;y++){k=w*p+c-1;for(z=0;z<=k;z++){x=v?k-z:z;q=(y+c-1)/c;r=x/w;d=q+r&1;f=(y+c-1)%c;if(d)f=c-f-1;g=(x-f)%w;u=r;if(q>p){q=2*p-q+1;u++;}printf("%c",(q>=r&&q&&g==0)||(q>r&&g==w-c)?d^v?'/':'\\':q>=u&&y%c==0&&g>0&&g<(w-c+(q==r))?'_':' ');}printf("\n");}} ``` [Answer] # Julia - ~~503~~ ~~455~~ ~~369~~ ~~346~~ ~~313~~ 270 bytes ``` f=A->(t=47∉A;h='/'+45t;(m,n)=int(split(A,h));W=2m*n+1;X=(l=3m+1)n+m+1;s=fill(' ',X,W);s[end,:]=10;for i=1:n,j=i:n,M=1:m s[M+i*l+[[L=[J=(2j-i)m,J,J-m]+M W-L]X.-[l,m,0] [0 m].+[1,m,m].+[J,J+m,J-m]X-l]]=[1,1,1]*[h 139-h 95 s[i*l,i*m-m+1]=95]end;print((t?s:flipud(s))...)) ``` Ungolfed: ``` function f(A) t=47∉A # Determine if '/' is in A ('/' = char(47)) h='/'+45t # Set h to the appropriate slash ('\\' = char(92), 92=47+45) (m,n)=int(split(A,h)) # Get the two integers from A W=2m*n+1 # Get number of rows of output (vertical height of pyramid) X=(l=3m+1)n+m+1 # Get columns of output + 1 (for newlines) s=fill(' ',X,W) # Create 'canvas' of size X x W s[end,:]=10 # Put newlines at end of each output row for i=1:n, j=i:n, M=1:m # This is where the fun happens. # K and L represent the shifting points for '/' and '\\' in the # horizontal and vertical directions. # They are used to make the code neater (and shorter). K=M+i*l-[l,m,0] L=[J,J,J-m]+M # The next two assign the slashes to appropriate places s[K+L*X]=h s[K+(W-L)X]=139-h # This one puts the first 2m underscores in each of the underscore sets s[M+i*l-l+[0 m].+[1,m,m].+[J,J+m,J-m]X]=95 # This places the final underscores on the top edges (repeatedly) s[i*l,i*m-m+1]=95 end # The above produces the array orientation for backslash, but uses # the "wrong" slashes along the diagonals if there's a forward slash. # This line flips the matrix in that case, before printing it. print((t?s:flipud(s))...)) end ``` Usage: ``` f("3/2") ``` or ``` f("2\\3") ``` [Answer] # Ruby, 332 The only golfing done so far is elimination of comments and indents. I will golf later. ``` gets.match(/\D/) d=$&<=>"@" n=$`.to_i m=2*n p=$'.to_i a=(0..h=4*n*p).map{' '*h*2} (p*p).times{|j| x=h-j/p*(3*n+1)*d y=h/2+(j/p-j%p*2)*n if j%p<=j/p (-n).upto(n){|i| a[y+i][i>0?x+m+1-i :x-m-i]=?/ a[y+i][i>0?x-m-1+i :x+m+i]='\\' a[y+n][x+i]=a[y-n][x+i]=a[y][x-d*(n+i-1)]=?_ a[y+i+(i>>9&1)][x+d*i.abs]='\_/'[(0<=>i*d)+1] } end } puts a ``` I set up an array of spaces and poke the individual characters into it. There is quite a lot of overdrawing both of one cube on top of another (work from bottom to top) and within the cube itself, to avoid extra code. I make the pyramid by drawing a rhombus (similar to <https://codegolf.stackexchange.com/a/54297/15599>) and surpressing the top half. The hard part was drawing the scalable cube. I started off with a perimeter hexagon with 2n+1 `_`characters on the horizontal sides. I also had had 2n+1 `/` and `\` ,so I had one too many, but by plotting the `_` last I overwrite them. The internal lines are the only ones that are changed depending on the direction the cube is facing. I plot all the `/` and `\` with a single assignment. `abs` helps reverse the direction, and `i>>9&1` adds an extra 1 to the negative values of i, which lowers the top part down. for `i`=0 one of the required `_` is overplotted, so the selector string `'\_/'` contains all three symbols, selected according to the sign of `i`. The whitespace around the output is ample but not excessive: 4\*p\*n high and 8\*p\*n wide (the latter is to enable the apex cube to always be in the centre of the output.) I understand "trailing / leading whitespaces" to include whole lines, but can revise if necessary. **Ungolfed code** ``` gets.match(/\D/) #find the symbol that is not a digit. it can be extracted from $& d=$&<=>"@" #direction, -1 or 1 depends if ascii code for symbol is before or after "@" n=$`.to_i #side length extracted from match variable $` m=2*n p=$'.to_i #pyramid height extracted from match variable $' a=(0..h=4*n*p).map{' '*h*2} #setup an array of h strings of h*2 spaces (p*p).times{|j| #iterate p**2 times x=h-j/p*(3*n+1)*d #calculate x and y coordinates for each cube, in a rhombus y=h/2+(j/p-j%p*2)*n #x extends outwards (and downwards) from the centre, y extends upwards if j%p<=j/p #only print the bottom half of the rhombus, where cube y <= cube x (-n).upto(n){|i| #loop 2n+1 times, centred on the centre of the cube a[y+i][i>0?x+m+1-i :x-m-i]=?/ #put the / on the perimeter of the hexagon into the array a[y+i][i>0?x-m-1+i :x+m+i]='\\' #and the \ also. a[y+n][x+i]=a[y-n][x+i]=a[y][x-d*(n+i-1)]=?_ #plot all three lines of _ overwriting the / and \ on the top line a[y+i+(i>>9&1)][x+d*i.abs]='\_/'[(0<=>i*d)+1]#plot the internal / and \ overwriting unwanted _ } end } puts a ``` ]
[Question] [ You don't want to pay money for the expensive architectural program, so you decide to roll your own. You decide to use ASCII to design your buildings. Your program will take in a single string formatted in a specific way, and the program will output the building. ## Input Input consists of a single line of characters. It can be assumed to only contain the letters `a-j`, the numbers `1-9`, and the symbols `-` and `+`. ## Output Description For each letter `a-j`, the program will output a vertical line as follows. We will call this a column. ``` . .. ... **** ***** ****** ------- -------- +++++++++ ++++++++++ abcdefghij ``` For instance, the input `abcdefgfedefghgfedc` would output: ``` . * *** *** ***** ***** ******* --------------- ----------------- ++++++++++++++++++ +++++++++++++++++++ ``` A letter may be prefixed with a positive integer `n`, which will add `n` whitespace characters below the column. We will call this an offset. For instance, using `S` to notate a whitespace, the input `3b2b3b` would output: ``` + + +++ S+S SSS SSS ``` A letter may also be prefixed with a *negative* integer `-m`, which will *remove* the bottom `m` *non-whitespace* characters of the column (not replace them with whitespace, remove them entirely). We will call this a slice. For instance, the input `-1j-2j-3j-4j-5j-6j-7j-8j` would output: ``` . .. ... *... **... ***... -***... --***... +--***.. ``` An offset and a slice can be applied to the same line, but the offset must go first. In other words, the letter may be prefixed with `n-m`, where `n` is the size of the offset, and `m` is the size of the slice. For instance, using `S` to notate a whitespace, the input '2-4j' would output: ``` . . . * * * S S ``` Lastly, the `+` operator used between two columns indicates that they should be stacked on top of each other in the same column instead of in seperate columns. For instance, the input `2-4ja' outputs: ``` . . . * * * S S+ ``` Whereas the input `2-4j+a` outputs: ``` + . . . * * * S S ``` Here is a sample input: ``` abiehef+ehfhabc ``` And the resultant output: ``` * - . - . . +. . * * +* * * * **** ******** -------- -------- - +++++++++ ++ +++++++++++++ ``` Looks like an old destroyed castle tower of some sort. Here is another sample input: ``` 6b5b+a6b1-2d+3-4f1-2d+-2c+2-4f+1-2d+-2c2-2d+1-4g+1-2c+b+-2c+-4e2-7j+-4g+d+-2c+-4f2-7j+-5h+b+-2c+a+-3f2-7j+-7i+-4e+b+b+a+-4f2-7i+a+-7h+-4f+b+b+a+-4f2-7j+-7h+-4f+a+-7h+a+-7i+-4f2-7j+-7i+-6h+a+-7i+b+-4e3-7i+a+-7h+-4e+a+-7h+b+1-7h3-7j+1-4f+-7h+b+-4f+a3-7j+2-4f+a+-4f+b3-2d+-2d+3-4g+b3-2d+-2d+-2c ``` And the resultant output: ``` ****** +++ ******+.*++ ---++.+ *** -+-+++..++** -+--+++.+++* --++++.+..* +++++.+** +++****.****** - +++*****.**.. -- + ***....+..-- ...+.....-- --.........-- ---...... -- ``` (It was supposed to be Mario but didn't turn out very good...) If the specification still isn't clear, I have a [non-golfed implementation](http://pastebin.com/N9jdF6Z5) written in Python 2.7. You can run it and experiment to get a feel for how the specification works. You may also choose to laugh at my programming skills. This is code-golf, so shortest entry wins. Ask questions in comments if unclear. [Answer] ## Ruby, ~~223~~ 214 bytes ``` g=$*[0].split(/(?<=[a-j])(?!\+)/).map{|r|r.scan(/(\d*)(-\d+)?([a-j])/).map{|a,b,c|' '*a.to_i+'++--***...'[-b.to_i..c.ord-97]}*''} puts g.map{|s|s.ljust(g.map(&:size).max).chars.reverse}.transpose.map(&:join).join$/ ``` That was fun. :) Although it should be quite obvious, I discovered a new way to do these challenges where strings have be constructed from columns: just do them in rows, and transpose the array of characters before joining everything. ``` g=$*[0].split(/(?<=[a-j])(?!\+)/) # Split into columns. .map{|r| # For each column r.scan(/(\d*)(-\d+)?([a-j])/) # Split into components. .map{|a,b,c| # For each component ' '*a.to_i+ # Prepend spaces if any. '++--***...'[-b.to_i..c.ord-97] # Select the appropriate slice of the tower. }*'' # Join all components together. } puts g.map{|s| # For each column s.ljust(g.map(&:size).max) # Pad with spaces on the right such that. # all columns are the same height. .chars.reverse # Turn into character array and reverse. } .transpose # Mirror in the main diagonal. .map(&:join) # Join lines. .join$/ # Join columns. ``` [Answer] # Cobra - 473 I don't think Cobra's ever going to win one of these :/ ``` use System.Text.RegularExpressions class P def main r=Regex.matches(Console.readLine,r'(?<=^|[a-j])(([^a-j]*[a-j])+?)(?=[^+]|$)') z,l=0String[](r.count) for m in r.count,for n in'[r[m]]'.split('+'),l[m]+=' '.repeat(int.parse('0[Regex.match(n,r'(?<!-)\d+')]'))+'++--***...'[int.parse('0[Regex.match(n,r'(?<=-)\d+')]'):' abcdefghij'.indexOf(n[-1:])] for y in l,if y.length>z,z=y.length for x in-z+1:1 for y in l,Console.write(if(-x<y.length,y[-x],' ')) print ``` All nice and commented: EDIT: Just realized this looks suspiciously similar to the Ruby solution. Great minds think alike? ``` use System.Text.RegularExpressions class P def main r=Regex.matches(Console.readLine,r'(?<=^|[a-j])(([^a-j]*[a-j])+?)(?=[^+]|$)') # Split into columns z,l=0,String[](r.count) # Assign the column-array for m in r.count # Loop through columns for n in'[r[m]]'.split('+') # Loop through individual letter instructions # - within columns l[m]+= # Add characters to the last column ' '.repeat(int.parse('0[Regex.match(n,r'(?<!-)\d+')]'))+ # Any spaces, plus '++--***...'[:' abcdefghij'.indexOf(n[-1:])] # The default column string [int.parse('0[Regex.match(n,r'(?<=-)\d+')]'):] # Sliced to the right length for y in l,if y.length>z,z=y.length # Determine the maximum length of any column for x in-z+1:1 for y in l # Loop through columns so that they rotate to the left Console.write(if(-x<y.length,y[-x],' ')) # Write the character in the current position print # Insert newlines ``` [Answer] # Lua - 451 ``` a=arg[1]j='++--***...'I=io.write M=string.match U=string.sub T=table.insert n=''y=0 t={}m=0 for i in a:gmatch('[%-%d]*[a-j]%+?')do b=M(i,'-(%d)')b=b or 0 s=M(U(i,1,1),'%d')s=s or 0 n=n..(' '):rep(s)..U(U(j,1,M(U(i,-2),'[a-j]'):byte()-96),1+b,-1)if U(i,-1,-1)~="+"then T(t,n)m=m<#n and #n or m n=""y=y+1 end end T(t,n)n=''for k,v in pairs(t)do n=#v<m and n..v..(' '):rep(m-#v)or n..v end for i=m,1,-1 do for k=0,m*y-1,m do I(U(n,i+k,i+k))end I'\n'end ``` Nothing special. It was fun to rename a butt-load of functions for once though. I'll edit the ungolfed code in later. [Try it out here.](http://ideone.com/8o6ETx) Sample Output: ![SampleOutput](https://i.stack.imgur.com/zxzYA.jpg) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~214~~ ~~212~~ ~~209~~ ~~206~~ 200 bytes *-3 bytes thanks @Veskah* ``` switch -r($args-split'(-?.)'){\+{$c=1}\d{sv('ps'[0-gt$_])$_}[a-j]{if(!$c){$t+=,''}$t[-1]+=' '*$p+-join'++--***...'[-$s..($_[0]-97)];$c=$p=$s=0}}($t|% Le*|sort)[-1]..1|%{-join($t|% *ht $_|% ch*($_-1))} ``` [Try it online!](https://tio.run/##fZVtk5owEMff@ylSmyuSdTMHeNpOx2k/QN/3hec4gEFgPLXC9dpBPrvNA2hErjujZP@/ZPO0LIf9mzgWqdhuzzQhc1Kdi7esjFOCxxENj5sCi8M2K50RfuOu41bPUNF47tXP66r4PXIOhbN4xE1JV0uXrupFiPmyypLRBxq7FS1hPnacmpYL9JYwd4jD6AEw32c7BwCRMcY5dxZIC85HdLV4XOKXmbv8Kqeghzkt5o91PaLl6YH8EOxU7I@lq0Jx7p0eKh3HUJaWhK5kI06ZjIOe69bnejD4PhoQaWPzcMIoXotkkwj1n2Z5lqp27IwNJrfGm2c/lgv/D@a85beYmX9jd9hojF25jY3GmMUtjPdmYeyzC4ZeazG8gzV1BzcnHER@FESXkcQOcp3OXrfd7IuIXo5@jkGOkxyfcpzmOMvxc96O695S91q698Aa4eI3wtU3Qus3SXr126xtN9YIvYsPo0ykIgGRJqlMvr5c6CQIdkXeL3ICnPAbUeYGAUbYnXiXS70JdsmafrEnW8g7OdJ7FNPoKYJwGnnoryHASaIb6MfgSwdaz1dPDycbpcQQ6R44Eb68dVDyulESozylTZ8QMGi0WaZGSD1Squ6ZqdYsVd6Nnl9Uw8NmtBVp2qqRihrYsUTTiuRiZ2mghngqltF0VC36zQRq8sBsVJ/BxnLlHjrpYa5InXO3SEgDzrpAXhMAB11FbIAgdeAc4B5oIn8doGSpc866@QmG2MVHDVevQJtT2AGKqDfKLjhmH6pIykks0BZP0AX0FiDy1m4AtqD7OiHaJfmdKm@VHZecyAOptEt/7o/rMaHiz0HEpfww0pXRj6J43Srhk/xe6l5aHzZgiOLXsBk11ORjO0S1yesu3r@8iF1JyjQryDbbCVLuyTqTn9nwLzFdi0F9/gc "PowerShell – Try It Online") Less golfed version: ``` # make table with lines instead columns switch -r($args-split'(-?.)'){ \+ {$c=1} \d {set-variable ('ps'[0-gt$_]) $_} [a-j] { if(!$c){$t+=,''} $t[-1]+=' '*$p+-join'++--***...'[-$s..($_[0]-97)] $c=$p=$s=0 } } # transpose ($t|% Length|sort)[-1]..1|%{ -join($t|% padRight $_|% chars($_-1)) } ``` [Answer] # Python 3, 268 bytes ``` import re q,t=[(p,' '*int(o or 0)+'++--***...'[-int(s or 0):ord(l)-96])for p,o,s,l in re.findall('(\+?)(\d?)(-\d)?(.)',input())],[] while q:p,s=q.pop(0);t+=[t.pop()+s if p else s] t=[*zip(*[[*c.ljust(max(map(len,t)))]for c in t])][::-1] for l in t:print(*l,sep='') ``` Mostly ungolfed: ``` # import the regex module import re # array to store initial input q = [] # array to store translated output t = [] # split string from stdin into column groups, like: ('plus or blank', 'offset or blank', 'slice or blank', 'letter') # ex: 6b1-2d+a would become: # [('','6','','b'), ('', '1', '-2', 'd'), ('+', '', '', 'a')] i = re.findall('(\+?)(\d?)(-\d)?(.)',input()) # iterate through the groups returned by the regex for p,o,s,l in i: # create offset string # int() cannot parse '', but empty strings are falsey, # so (o or 0) is equivalent to 'parse the string as an int, or return 0 if it is empty' offset = ' ' * int(o or 0) # get the starting point of the slice # since the regex returns the minus, it must be negated after converting the string to an int # as before, (s or 0) ensures that the slice is converted to an int properly start = -int(s or 0) # since 'a' is ordinal 97, this ensures that the end position will be 1-9 end = ord(l) - 96 # slice the largest possible column string with the calculated start and end positions a = '++--***...'[start:end] # add the space offset a = offset + a # add the plus sting and the column string to the array q.append( (p, a) ) # while q is not empty while q: # remove the first item from the list and separate it into a plus variable and a column string p, s = q.pop(0) # if p is not blank, it is a '+' # if p is truthy, remove the last item added and add s to it # otherwise just return s # append the resulting item to the ongoing list t += [t.pop()+s if p else s] temp = [] for c in t: # call len() on all items in t, then return the maximum length m = max(map(len, t)) # left justify c by adding spaces to the right, up to m total characters c = c.ljust(m) # unpack c into a list # this is equivalent to list(c), but shorter c = [*c] # add the list of characters to the array temp.append(c) t = temp # t is currently a list of rows, and needs to be rotated so that it displays correctly # input: 'abcdefghij' # before: # # + # ++ # ++- # ++-- # ++--* # ++--** # ++--*** # ++--***. # ++--***.. # ++--***... # # after: # # ++++++++++ # +++++++++ # -------- # ------- # ****** # ***** # **** # ... # .. # . # t = [*zip(*t)] # t is currently upside down, reverse the list t = t[::-1] # for each line (currently a list of characters) for l in t: # unpack the list into print as arguments, do not add a space between arguments print(*l,sep='') ``` ]
[Question] [ Your goal is to write a program that creates a random 10x10 map using `0`, `1`, and `2`, and finds the shortest path from top-left to bottom-right, assuming that: **0** represents a grass field: anyone can walk on it; **1** represents a wall: you cannot cross it; **2** represents a portal: when entering a portal, you can move to any other portal in the map. **Specs:** * The top-left element and the bottom-right one must be **0**; * When creating the random map, every field should have 60% chance of being a **0**, 30% of being a **1** and 10% of being a **2**; * You can move in any adjacent field (even diagonal ones); * Your program should output the map and the number of steps of the shortest path; * If there isn't a valid path that leads to the bottom-right field, your program should output the map only; * You can use any resource you'd like to; * Shortest code wins. **Calculating steps:** A step is an actual movement; every time you change field, you increment the counter. **Output:** ``` 0000100200 0100100010 1000000111 0002001000 1111100020 0001111111 0001001000 0020001111 1100110000 0000020100 9 ``` [Answer] # Mathematica (344) Bonus: highlighting of the path ``` n = 10; m = RandomChoice[{6, 3, 1} -> {0, 1, 2}, {n, n}]; m[[1, 1]] = m[[n, n]] = 0; p = FindShortestPath[Graph@DeleteDuplicates@Join[Cases[#, Rule[{ij__}, {k_, l_}] /; 0 < k <= n && 0 < l <= n && m[[ij]] != 1 && m[[k, l]] != 1] &@ Flatten@Table[{i, j} -> {i, j} + d, {i, n}, {j, n}, {d, Tuples[{-1, 0, 1}, 2]}], Rule @@@ Tuples[Position[m, 2], 2]], {1, 1}, {n, n}]; Grid@MapAt[Style[#, Red] &, m, p] If[# > 0, #-1] &@Length[p] ``` ![enter image description here](https://i.stack.imgur.com/h9hX2.png) I create the graph of all possible movies to neighbor vertices and add all possible "teleports". [Answer] # Mathematica, ~~208~~ 202 chars Base on David Carraher and ybeltukov's solutions. And thanks to ybeltukov's suggestion. ``` m=RandomChoice[{6,3,1}->{0,1,2},n={10,10}];m〚1,1〛=m〚10,10〛=0;Grid@m {s,u}=m~Position~#&/@{0,2};If[#<∞,#]&@GraphDistance[Graph[{n/n,n},#<->#2&@@@Select[Subsets[s⋃u,{2}],Norm[#-#2]&@@#<2||#⋃u==u&]],n/n,n] ``` [Answer] ### GolfScript, 182 characters ``` ;0`{41 3 10rand?/3%`}98*0`]10/n*n+.[12n*.]*.0{[`/(,\+{,)1$+}*;]}:K~\2K:P+${[.12=(]}%.,,{.{\1==}+2$\,{~;.P?0<!P*3,{10+}%1+{2$1$-\3$+}%+~}%`{2$~0<@@?-1>&2$[~;@)](\@if}++%}/-1=1=.0<{;}* ``` Examples: ``` 0000001002 1010000001 0011010000 2001020000 0100100011 0110100000 0100000100 0010002010 0100110000 0012000210 6 0000100000 0100000001 1100000000 1011010000 0010001100 0101010200 0000200012 1100100110 0000011001 2201010000 11 0012010000 1000100122 0000001000 0111010100 0010012001 1020100110 1010101000 0102011111 0100100010 2102100110 ``` [Answer] ## Python 3, 279 Some Dijkstra variant. Ugly, but golfed as much as I could... ``` from random import* R=range(10) A={(i,j):choice([0,0,1]*3+[2])for i in R for j in R} A[0,0]=A[9,9]=0 for y in R:print(*(A[x,y]for x in R)) S=[(0,0,0,0)] for x,y,a,c in S:A[x,y]=1;x*y-81or print(c)+exit();S+=[(X,Y,b,c+1)for(X,Y),b in A.items()if a+b>3or~-b and-2<X-x<2and-2<Y-y<2] ``` **Sample Run** ``` 0 1 1 1 0 0 1 0 1 0 0 0 0 1 0 1 0 1 0 0 0 1 2 1 2 1 0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 1 0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 1 0 0 1 0 0 1 1 1 0 0 0 0 0 1 0 0 0 0 1 0 1 2 1 0 1 1 0 0 0 10 ``` [Answer] # Python 3 (695) ``` import random as r if __name__=='__main__': x=144 g,t=[1]*x,[] p=lambda i:12<i<131 and 0<i%12<11 for i in range(x): if p(i): v=r.random() g[i]=int((v<=0.6 or i in (13,130)) and .1 or v<=0.9 and 1 or 2) if g[i]>1:t+=[i] print(g[i],end='\n' if i%12==10 else '') d=[99]*x d[13]=0 n = list(range(x)) m = lambda i:[i-1,i+1,i-12,i+12,i-13,i+11,i+11,i+13] while n: v = min(n,key=lambda x:d[x]) n.remove(v) for s in m(v)+(t if g[v]==2 else []): if p(s) and g[s]!=1 and d[v]+(g[s]+g[v]<4)<d[s]: d[s]=d[v]+(g[s]+g[v]<3) if d[130]<99:print('\n'+str(d[130])) ``` Dijkstra ! ## Example output: ``` 0000202000 2011000111 0000002000 0101001000 0000100110 1110100101 0020101000 0011200000 1010101010 0000001000 6 ``` [Answer] # Mathematica ~~316 279~~ 275 The basic object is a 10x10 array with approximately 60 0's, 30 1's and 10 2's. The array is used to modify a 10x10 `GridGraph`, with all edges connected. Those nodes which correspond to cells holding 1 in the array are removed from the graph. Those nodes "holding 2's" are all connected to each other. Then the Shortest Path is sought between vertex 1 and vertex 100. If such a path does not exist, the map is returned; if such a path does exist, the map and the shortest path length are shown. ``` m = Join[{0}, RandomChoice[{6, 3, 1} -> {0, 1, 2}, 98], {0}]; {s,t,u}=(Flatten@Position[m,#]&/@{0,1,2}); g=Graph@Union[EdgeList[VertexDelete[GridGraph@{10,10},t]],Subsets[u,{2}] /.{a_,b_}:>a \[UndirectedEdge] b]; If[IntegerQ@GraphDistance[g,1,100],{w=Grid@Partition[m,10], Length@FindShortestPath[g,1,100]-1},w] ``` **Sample Run**: ![graph](https://i.stack.imgur.com/72saq.png) [Answer] # Python (1923) Backtracking Search Admittedly not the shortest or the most efficient, although there is some memoization present. ``` import random l = 10 map = [ [(lambda i: 0 if i < 7 else 1 if i < 10 else 2)(random.randint(1, 10)) for i in range(0, l)] for i in range(0, l) ] map[0][0] = map[l-1][l-1] = 0 print "\n".join([" ".join([str(i) for i in x]) for x in map]) paths = {} def step(past_path, x, y): shortest = float("inf") shortest_path = [] current_path = past_path + [(x, y)] pos = map[x][y] if (x, y) != (0, 0): past_pos = map[past_path[-1][0]][past_path[-1][1]] if (((x, y) in paths or str(current_path) in paths) and (pos != 2 or past_pos == 2)): return paths[(x, y)] elif x == l-1 and y == l-1: return ([(x, y)], 1) if pos == 1: return (shortest_path, shortest) if pos == 2 and past_pos != 2: for i2 in range(0, l): for j2 in range(0, l): pos2 = map[i2][j2] if pos2 == 2 and (i2, j2) not in current_path: path, dist = step(current_path, i2, j2) if dist < shortest and (x, y) not in path: shortest = dist shortest_path = path else: for i in range(x - 1, x + 2): for j in range(y - 1, y + 2): if i in range(0, l) and j in range(0, l): pos = map[i][j] if pos in [0, 2] and (i, j) not in current_path: path, dist = step(current_path, i, j) if dist < shortest and (x, y) not in path: shortest = dist shortest_path = path dist = 1 + shortest path = [(x, y)] + shortest_path if dist != float("inf"): paths[(x, y)] = (path, dist) else: paths[str(current_path)] = (path, dist) return (path, dist) p, d = step([], 0, 0) if d != float("inf"): print p, d ``` [Answer] # JavaScript (541) ``` z=10 l=[[0]] p=[] f=[[0]] P=[] for(i=0;++i<z;)l[i]=[],f[i]=[] for(i=0;++i<99;)P[i]=0,l[i/z|0][i%z]=99,f[i/z|0][i%z]=(m=Math.random(),m<=.6?0:m<=.9?1:(p.push(i),2)) f[9][9]=0 l[9][9]=99 Q=[0] for(o=Math.min;Q.length;){if(!P[s=Q.splice(0,1)[0]]){P[s]=1 for(i=-2;++i<2;)for(j=-2;++j<2;){a=i+s/z|0,b=j+s%z if(!(a<0||a>9||b<0||b>9)){q=l[a][b]=o(l[s/z|0][s%z]+1,l[a][b]) if(f[a][b]>1){Q=Q.concat(p) for(m=0;t=p[m];m++)l[t/z|0][t%z]=o(l[t/z|0][t%z],q+1)}!f[a][b]?Q.push(a*z+b):''}}}}for(i=0;i<z;)console.log(f[i++]) console.log((k=l[9][9])>98?"":k) ``` Graph generation happens in the first five lines. `f` contains the fields, `p` holds the portals. The actual search is implemented via BFS. ## Example output: ``` > node maze.js [ 0, 0, 0, 0, 1, 0, 0, 0, 2, 0 ] [ 0, 1, 1, 0, 0, 1, 0, 0, 0, 2 ] [ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ] [ 1, 1, 1, 0, 2, 2, 0, 1, 0, 1 ] [ 1, 1, 0, 0, 0, 0, 1, 0, 0, 0 ] [ 1, 1, 0, 0, 1, 0, 0, 0, 1, 1 ] [ 0, 0, 1, 1, 0, 1, 0, 0, 2, 0 ] [ 0, 0, 1, 0, 1, 2, 0, 1, 0, 1 ] [ 1, 0, 0, 0, 1, 1, 1, 0, 1, 1 ] [ 0, 1, 0, 0, 0, 0, 0, 0, 1, 0 ] ``` ``` >node maze.js [ 0, 0, 0, 0, 1, 0, 1, 0, 0, 1 ] [ 0, 2, 0, 1, 1, 2, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ] [ 0, 0, 0, 1, 2, 1, 1, 0, 1, 0 ] [ 2, 0, 1, 0, 2, 2, 2, 0, 1, 0 ] [ 1, 0, 0, 0, 1, 0, 0, 0, 1, 0 ] [ 0, 0, 1, 0, 0, 1, 0, 1, 0, 0 ] [ 0, 1, 2, 0, 0, 0, 0, 0, 0, 1 ] [ 1, 0, 2, 1, 0, 1, 2, 0, 0, 1 ] [ 0, 1, 2, 0, 0, 0, 0, 0, 0, 0 ] 5 ``` [Answer] ## Python, 314 ``` import random,itertools as t r=range(10) a,d=[[random.choice([0]*6+[1]*3+[2])for i in r]for j in r],eval(`[[99]*10]*10`) a[0][0]=a[9][9]=d[0][0]=0 for q,i,j,m,n in t.product(r*10,r,r,r,r): if a[m][n]!=1and abs(m-i)<2and abs(n-j)<2or a[i][j]==a[m][n]==2:d[m][n]=min(d[i][j]+1,d[m][n]) w=d[9][9] print a,`w`*(w!=99) ``` It's a disgusting implementation of Bellman-Ford. This algorithm is O(n^6)! (Which is okay for n=10) ]
[Question] [ Consider a zero-sum game with 2 contestants. Each round, each contestant chooses, independently of each other, one of \$n \ge 2\$ different choices. Depending on the two chosen choices, one player is awarded an amount from the other player's pot. For example, the following table shows the gains (positive integers) and losses (negative integers) for Player 1 for each of \$9\$ possible choices: $$\begin{array}{c|c|c|c} & \text{Player 1 chooses A} & \text{Player 1 chooses B} & \text{Player 1 chooses C} \\ \hline \text{Player 2 chooses A} & 1 & 2 & 2 \\ \hline \text{Player 2 chooses B} & -2 & 1 & 2 \\ \hline \text{Player 2 chooses C} & 3 & -1 & 0 \\ \end{array}$$ For example, if Player 1 chooses \$A\$ and Player 2 chooses \$C\$, Player 1 gains \$3\$ and Player 2 loses \$3\$. However, this table is needlessly complex. We can see that, assuming both players are playing to win, some choices are always suboptimal. For example, Player 1 would never choose \$B\$. No matter what Player 2 chooses, Player 1 choosing \$C\$ will produce a result that is either better or equal to \$B\$, as each element in \$C\$ is greater than or equal to its corresponding element in \$B\$. Therefore, we can say that \$C\$ **dominates** \$B\$, and we can remove \$\text{Player 1 chooses B}\$ from our matrix: $$\begin{array}{c|c|c} & \text{Player 1 chooses A} & \text{Player 1 chooses C} \\ \hline \text{Player 2 chooses A} & 1 & 2 \\ \hline \text{Player 2 chooses B} & -2 & 2 \\ \hline \text{Player 2 chooses C} & 3 & 0 \\ \end{array}$$ Additionally, we can see that Player 2 would never choose \$A\$ over \$B\$, as their payoff is always higher or equal from \$B\$ than it is from \$A\$, as each value in \$B\$ is *less than or equal to* it's corresponding element in \$A\$. So if Player 1 chooses \$A\$, then Player 2 either loses \$1\$ (\$A\$), gains \$2\$ (\$B\$) or loses \$3\$ (\$C\$). If Player 1 instead chooses \$C\$, then Player 2 either loses \$2\$ (\$A\$), loses \$2\$ (\$B\$) or gains \$0\$ (\$C\$). In either case, Player 2 would choose \$B\$ over \$A\$, as their result would never be worse when choosing \$B\$. Therefore, we can say that \$B\$ **dominates** \$A\$, and we can remove \$\text{Player 2 chooses A}\$ from the matrix: $$\begin{array}{c|c|c} & \text{Player 1 chooses A} & \text{Player 1 chooses C} \\ \hline \hline \text{Player 2 chooses B} & -2 & 2 \\ \hline \text{Player 2 chooses C} & 3 & 0 \\ \end{array}$$ Here however, no more choices dominate. This is our final matrix, and would be the output for this input. --- You are to take a rectangular matrix \$n\times m\$, where \$n, m \ge 2\$, and output the same matrix with all dominated options removed. You may also take the matrix transposed and/or with reversed signs from the examples provided in the question. The matrices will only contain integers between \$-9\$ and \$9\$ (inclusive). You may also take \$n\$ and/or \$m\$ as input if you wish. The matrix is not guaranteed to contain any dominated options. The matrix may be reduced to a \$1\times1\$ matrix, at which point there are no more dominated options. You may input and output in any [convenient format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). If there is more than one valid output, you may output any valid one. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. ## Test cases Done by hand, don't hesitate to point out mistakes or suggest more ``` Input Output Explanation [[ 1 2 2] [-2 1 2] [ 3 -1 0]] [[-2 2] [ 3 0]] Column C dominates Column B, Row B dominates Row A [[ 2 1 3 3] [ 0 0 -1 0] [ 1 1 0 0]] [[0]] Column A dominates B, Column D dominates C, Row B dominates Rows A+C, Column B dominates Column D (or vice versa) [[ 2 0 4 1 2] [-1 6 0 -3 3] [ 0 -2 1 -1 1] [ 4 -2 1 2 3]] [[1]] Column E dominates Column D, Row C dominates Row D, Column E dominates Column A, Row C dominates Row A, Column E dominates Column E, Row C dominates Row B, Column E dominates Column B [[ 7 -3 -5 -9 -8 -2] [ 6 7 6 -1 2 0] [-5 -8 3 -1 -8 -8] [-8 8 1 0 9 -2] [-3 0 -1 -4 8 1] [-2 2 -4 3 -7 -2] [ 4 8 1 8 -9 -9] [-1 -6 -4 1 9 5]] [[ 7 -3 -5 -9 -8 -2] [-5 -8 3 -1 -8 -8] [-8 8 1 0 9 -2] [-3 0 -1 -4 8 1] [-2 2 -4 3 -7 -2] [ 4 8 1 8 -9 -9] [-1 -6 -4 1 9 5]] Row C dominates Row B [[ 4 -6 2 ] [ -2 -5 -9 ] [ 6 -2 -2 ] [ 8 0 7 ] [ -9 4 2 ]] [[ 4 -6 2] [-2 -5 -9] [-9 4 2]] Row C dominates Row D, Row B dominates Row C [[ 9 -7] [ 2 4]] [[ 9 -7] [ 2 4]] No rows or columns dominate [[ 2 2 2] [ 2 3 2] [ 2 2 2]] [[2]] Column B dominates Columns A+C, Row A dominates Rows B+C [[ 1 4] [ 2 0] [ 1 4]] [[ 2 0] or [[ 1 4] [ 1 4]] [ 2 0]] Rows A and C are equal so we remove one of them. Either output is OK, but removing both rows isn't. ``` Note that for the 7th test case, there are many different ways to get to the final version [Answer] # [J](http://jsoftware.com/), 43 41 40 39 bytes ``` f=.(#~1=1#.]*/ .>:|:)@~. f&.:-&.|:@f^:_ ``` [Try it online!](https://tio.run/##xVJLbsIwEN3nFCOBEEHgehyHOJZScRE6i6oBsekFEFdP5@OQdtE1@djO@4xn4rlN0zi47eqBA67cefcG7j3fc316uOoyuHHj8mHj7vk0fmSavj6v37ANEGANJBM04Gs4ZLjwqmEUQWEm0WhC8JX59m7RRtYyjyKRhy8vD8tloYwtFzcWd4TW3MxGlQVxiPWoMeaQXvJgniyYqA3Q1KoSuGPXGjqxUQvUAyWV6VcqNQiWBOMhzan1RdeUzCnOpBJBAbZ3pnuySXfpLWc6qgwlHLQ1SI1cZPovKy6xk5GsDP@iROe/14trnzlGLMfzC3keXfjTJMGahN@mzHwXLfLual56JWhfRRV6bY04/QA "J – Try It Online") ## tldr how Create a function `f` to filter out dominated rows. Apply plain `f`, followed by `f` "under" a negative transpose, until we reach a fixed point. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Qµ>Ạ€TLʋ€’ỊTịNZ Ç⁺$ƬṪ ``` **[Try it online!](https://tio.run/##y0rNyan8/z/w0Fa7h7sWPGpaE@JzqhtIPWqY@XB3V8jD3d1@UVyH2x817lI5tubhzlX///@PjlYw1FFQMALhWC6daF0QyxDGUzDWUdAF8QxiYwE "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##XVK9TsMwEN7zFB4YbalO3MZZeIIKCakTkUeWqi/ARrsg0Y2JbswoK5XaSgxBMPAWzosYn@/i2Awn@@6@77sfe32/2Tw4d9t/XNvz27DrVsvfvT@Gx4O9PK/sZX9zV3w9Ddvz1U9nT@/O33fd94s9vfpzPWw/@2N/dK5tWyY5YyWYKRhvBVxldFnFmQB35l1TcI8fARUYgmYASIAcVSWG/3EhorIigbcgjVx2bCdAJIbVFA6CVZSvkS/m3hpvGpBIAvkay4iRiK0GtMaBIBVYGlMQ1skkTRQMfdLMQo2waYUlhUG0ntpQiaCmLpu4BLEglsRabB5HU5hNXgmnjNOFEFXR1G6N4IY2XkY1KIvJsAiVPdD0GXC9uVtmQpLYlEweXxlTmD8 "Jelly – Try It Online"). ### How? ``` Ç⁺$ƬṪ - Link: matrix Ƭ - collect up inputs to this until no change: $ - last two links as a monad: Ç - call Link 1 (see below) ⁺ - repeat that Ṫ - tail Qµ>Ạ€TLʋ€’ỊTịNZ - Link 1: matrix Q - de-duplicate (since one of any repeats wants keeping) µ - start a new monadic chain, call that X ’ - with a decremented version of X, say Z, on the right: ʋ€ - for each row in X: > - (row) greater than (Z) (vectorises) Ạ€ - for each comparison: all truthy? T - truthy indices (i.e. indices in X which dominate row, including the index of row itself) L - length Ị - insignificant? (vectorises) (i.e. 1 if no other row dominates, else 0) T - truthy indices ị - index into: N - negated (X) Z - transpose ``` --- As a single Link (21): `Qµ>Ạ€TLʋ€’ỊTịNZµ$⁺$ƬṪ` ...or: `Qµ>Ạ€TLʋ€’ỊTịNZµ$Ƭm2Ṫ` [Answer] # [Haskell](https://www.haskell.org/), ~~106~~ ~~101~~ 100 bytes * -5 bytes thanks to [kops](https://codegolf.stackexchange.com/users/101474/kops). ``` until=<<((==)<*>)$g.g g m=transpose.map(map(0-))$nub m\\(m>>=tail.mapM(\i->[i..9])) import Data.List ``` [Try it online!](https://tio.run/##XVFNb4MwDL3nV1hVD8lEELTdukqE047baUeCqgxRFg1oRMLfH6vDR8sOluL3np8d@1vZn7KuB92Ya@fgTTkVvmvryEXIoW@drkWSUCoES55Stq3CilTQCNep1pqrLcNGGYoRcca2bf8FjZS0SVPhlK6R/aBS8zTTYXjKGSOcrxsNrrSuULa0IpMkyyAOAHYYeUAg4/iMlxT2AXBMozwPvHzm9xijJkJ@0XkonlTR/1IEDqsWvuxlsli7zsN4STzChzvsDfezu2fQZwcwSlHHn29xmhHs49FFA6/TUMel6jSNiJrJ@wbx40hjz8Pjj@67G@dZpyM7yWNfu3APu7o5SpKTRulW4A3PlKap6d2n6zay3TB/2DOYTrcuvLDlhsNvcalVZQdeGPMH "Haskell – Try It Online") The relevant function is `until=<<((==)<*>)$g.g`, which takes as input a matrix in the format described in the statement (not transposed and without flipped signs). Very slow, but hey, we are codegolfing! See below for a (much) more efficient version. ## How? Most of the work is done by `g`. This function takes a matrix `m` as input and returns the matrix obtained after "half an operation". To be more specific, `g` takes `m`, removes dominated rows, then transposes `m` and flips all the signs. These last two operations are basically equivalent to swapping the roles of Player 1 and Player 2. It's not hard to see that applying `g` twice performs a full iteration: dominated rows and columns are removed, the two transpositions cancel out, and so do the two sign flipping. Let's now look at the code. ``` g m= -- the function g takes a matrix m and returns transpose. -- the transpose of map(map(0-))$ -- the matrix obtained by flipping the signs of nub m -- m with duplicate rows removed \\( -- to which we also remove m>>= -- any row obtained by taking a row of m (say r) tail. -- and taking any but the first mapM( -- list whose j-th entry \i->[i..9])) -- lies between i and 9 (where i is the j-th entry of r) ``` `nub m` yields `m` with duplicate rows deleted; this is necessary since otherwise duplicate rows could potentially stick around forever. `m>>=tail.mapM(\i->[i..9])` basically generates a list of all the possible rows (strictly) dominated by some row of `m` (this is obviously the slow part, since there can be up to \$\approx m\cdot19^n\$ such rows). --- The anonymous function `until=<<((==)<*>)$g.g` (courtesy of [kops](https://codegolf.stackexchange.com/users/101474/kops)) iterates `g.g` until the resulting matrix stops changing. # [Haskell](https://www.haskell.org/), ~~107~~ ~~102~~ 101 bytes, much faster * -5 bytes thanks to [kops](https://codegolf.stackexchange.com/users/101474/kops). ``` until=<<((==)<*>)$g.g g m=transpose[(0-)<$>r|r<-nub m,all(or.zipWith(<)r)$m\\(r<$m)] import Data.List ``` [Try it online!](https://tio.run/##XVKxboMwFNz5CitiMBVGkJAAEjB1bKcOHQBVbkQIKhBkO0vVby/Ns42BDpbwvbt79x6@Uv5Vd93U9uONCfRMBfVeWi6sS1ZO90G0XZamGGeZkz7ljt14jdWgPhOMDny88brAPnFSO2c/LCXD/RP1Lu06fGPedzu@t@KKU4c5dl@WmKV271QWIdtOk6i5OFNe86woraJAgYvQHk7lWqgg8BmYKzq4iMDVrypX0uf6AY7i@FA3PAkFmuX/lwIQblpI2UlbbF3nMJISKDhcYGl4mN0jJSfHx0keJwai0oB7pLqQWaeCSnasxoGSVMWqBHC8miMxhjKmnpiEM23Z317DYBotMcKVYaxTJmYH5KRVgeqFjvNkcmaYYY@QcoIuatAZkbMBajiyFeSOjCrRyweO9oYMkSpD8nD9r5ZXoTa9vaqqpgdSa2qrV/BwLK3K6mk7ZD0dXz8wzvPxLt4E25XDzvEkiEbWDsK7OOZ1Tr/nS0cbPpHzOP4B "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes ``` F⊗L⁺θ§θ⁰≔E§θ⁰±EΦθ⬤θ⎇⁼μνπ⊙μ‹ρ§ξς§μλθIθ ``` [Try it online!](https://tio.run/##VY5PC8IwDMXvfoocU6gw9ehp@A9BZQdvY4eqcQ5i59puzE9f2yKIgUfC772EXB/KXFvF3t9bA7hu@wvTDQ@ka/fAgnuLnYTc7fWNxjhmIhbk1ja1xqN64Z8p4US1cpScbcOOTDrAHNuZjFbmjZuuV2zxKWGMG63DnSEVs1rCSwSW63e0D2Qtmt8Do4QhPSB@LMQ4gU4sJ4VptMOVsg47IZbel2UJcwkwC1pEVXICUEIW5qBp5NmXzb655FVV5acDfwA "Charcoal – Try It Online") Link is to verbose version of code. Outputs using Charcoal's default format (each cell on its own line with rows double-spaced from each other). Explanation: ``` F⊗L⁺θ§θ⁰ ``` Loop a large enough number of times (twice the number of rows and columns; probably overkill, so 4 bytes could be saved if this is the case). ``` Φθ⬤θ⎇⁼μνπ⊙μ‹ρ§ξς ``` Keep rows which, for each row, have at least one cell less than the corresponding cell from the other row, unless the two rows are equal, in which case keep the first of the duplicates. ``` ≔E§θ⁰±E...§μλθ ``` Transpose and negate the filtered matrix. (Actually to save bytes the matrix is filtered for each column of the transpose. Fortunately this doesn't result in enough nesting to trouble the buggy deverbosifier on the version of Charcoal currently on TIO.) ``` Iθ ``` Output the remaining matrix. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~112 ...~~ 102 bytes ``` ->m{1until m==[:min,:max].map{|x|m=m.transpose|[];m-=m.combination(2).map{|a,b|a.zip(b).map &x}}[1];m} ``` [Try it online!](https://tio.run/##bY7LCoMwEEX3fsWsioVEjEoXLemPhCxiqRDoRPEBtuq3pyY@itDFwMzh3Jmpu/xtC27pHQfWmVa/ADkXV9SGXFH1MkJVDWM/IseorZVpqrJ5jkLekM7kUWKujWp1acLkvLiK5KOKProKc0/g1E@TYHNishUUQghgBCBxJUkAgrqW7SOkBKgbYyllEKyRzUldLV7snN31iK1W/CfuWHa45JOXdctx8faTV9iCsx/276TzAfsF "Ruby – Try It Online") ]
[Question] [ It's a well-known fact that [Fermat's Last Theorem](https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem) is true. More specifically, that for any integer \$n \gt 2\$, there are no three integers \$a, b, c\$ such that $$a^n + b^n = c^n$$ However, there are a number of near misses. For example, $$6^3 + 8^3 = 9^3 - 1$$ We'll call a triple of integers \$(a, b, c)\$ a "Fermat near-miss" if they satisfy $$a^n + b^n = c^n \pm 1$$ for some integer \$n > 2\$. Note that this includes negative values for \$a, b, c\$, so \$(-1, 0, 0)\$ is an example of such a triple for any \$n\$. --- Your task is to take an integer \$n > 2\$ as input, in [any convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). You may then choose which of the following to do: * Take a positive integer \$m\$ and output the \$m\$-th Fermat near-miss for that specific \$n\$ * Take a positive integer \$m\$ and output the first \$m\$ Fermat near-misses for that specific \$n\$ + For either of these two, you may choose any ordering to define the "\$m\$th" or "first \$m\$" terms, so long as the ordering eventually includes all possible triples. For example, the test case generator program below orders them lexographically. * Output all Fermat near-misses for that specific \$n\$ + The output may be in any order, so long as it can be shown that all such triples will eventually be included. The output does not have to be unique, so repeated triples are allowed. + You may output in any format that allows for infinite output, such as an infinite list or just infinite output. You may choose the delimiters both in each triple and between each triple, so long as they are distinct and non-digital. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins --- [This program](https://tio.run/##yygtzv7/P03j0PJHnR0a5xY/aptopPmobVJu3KPGDZrnG4yBAoYGBkc2RP3//98YAA) was [helpfully provided](https://chat.stackexchange.com/transcript/message/56123330#56123330) by [Razetime](https://codegolf.stackexchange.com/users/80214/razetime) which outputs all solutions with \$|a|, |b|, |c| \le 50\$ for a given input \$n\$\*. [This](https://mathoverflow.net/q/377513/168573) is a question asked over on MathOverflow about the existence of non-trivial solutions to $$a^n + b^n = c^n \pm 1$$ Unfortunately, it appears (although is not proven, so you may not rely on this fact) that no non-trivial solutions exist for \$n \ge 4\$, so for most \$n\$, your output should be the same. \*Currently, this also returns exact matches, which your program shouldn’t do. [Answer] # [R](https://www.r-project.org/), ~~119~~ ~~110~~ ~~108~~ ~~105~~ 100 bytes *Edit: -2 bytes thanks to Giuseppe* ``` n=scan();repeat for(b in -(F=-F+!(F>0)):F)for(i in (d=-(c=F^n+b^n):c)[abs(d^n-c)==1])cat(F,b,i,'\n') ``` [Try it online!](https://tio.run/##FclBCoMwEAXQq8SV8zEBS3eWcTmXaA0ko0I2U4neP@Lbvtqa8anJCJ@6HVu63P6vlF0xF0g4yNCRzCMwCZ4pz9DKgZQl2pCjYVJ8Uz5pjRYUzK8Fmi4Sn33x/c96tHe7AQ "R – Try It Online") Prints the infinite list of near-misses, without duplicates (this includes duplicates by re-ordering `a` and `b`, so the triples `(a,b,c)` and `(b,a,c)` are considered duplicates: add an extra `,b,F,i,'\n'` (11 bytes) to print the list *with* duplicates). Wastes a few bytes avoiding taking nth-roots, to prevent floating-point errors. **How?** ``` function(n){ # note: F (false), which represents variable a, is initialized to zero; repeat{ # repeat for ever: for(b in -F:F){ # try all possible values of b from -a to a, c=F^n+b^n # calculate c as a^n+b^n, c=(-c:c) # now find value in the range -c to c [(-c:c)^n%in%(c+c(1,-1))] # that gives either c+1 or c-1 when raised to the n-th power # replace c with this value (if there is one), for(i in c) # now, if there were any: print(c(F,b,i))} # print out the a,b,c combination F=-F+!(F>0)}} # update F to the next value of variable a, in the sequence: # 0, 1, -1, 2, -2, 3, -3 ... and so on ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÜTCÑ ¢@∙╡·Gò╝╠Δh÷╠╧m ``` [Run and debug it](https://staxlang.xyz/#p=9a5443a5209b40f9b5fa4795bcccff68f6cccf6d&i=3) This uses the fact that results need not be unique. As with most of caird's challenges, you get brownie points for finding/outgolfing my 16 byte Husk solution :P ## Explanation ``` Wi:r3:${{x#mNs|+:-2<f|uP W iterate forever i push current iteration index :r symmetric range (-n..n) 3:$ cartesian power of 3 { f filter each triple by the following: {x#m map each number to the power of input Ns push the last element separately |+ sum the first two :- absolute difference 1= equals 1? |u stringify the result P print with newline ``` [Answer] # JavaScript (ES7), 124 bytes Expects `(n)(m)` and returns the \$m\$-th solution (1-indexed). ``` n=>(a=b=c=1,g=m=>(t=[A,B,C]=[a=a<c+2?a+1:b<c+2?++b/b:b=++c/c,b,c].map(v=>(v>>1)*(v&1||-1)),A**n+B**n-C**n)**2-1||--m?g(m):t) ``` [Try it online!](https://tio.run/##HYtBDoIwFET3nKIr09/fCsUd@DHKMQiLtgLRWEqQsFHPjtXNm5lM3t2s5unm27SoMVy7radtpIobsuRIy4F8XAs1Z3mRdUuNIXN0mJ8M6sL@G6JNbWEJ0aVOWunavTcTX6O3VpUGwdedfr@VBpBnIUa8RKg6AoTI1e9S/jRwD8UCWx9m7hkxXTLPjjGzLDZEYK@EMRfGZ3h0@0cYeM8PECUok8/2BQ "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞εD(Ÿ3ãʒIm`+α ``` Looks for \$\left\vert a^n+b^n−c^n\right\vert = 1\$ (near-misses). Inspired by [*@Razetime*'s Stax answer](https://codegolf.stackexchange.com/a/216546/52210). The program outputs an infinite list of lists of triplets in the order \$[c,b,a]\$ (including duplicated triplets) with only \$n\$ as input. [Try it online.](https://tio.run/##AR8A4P9vc2FiaWX//@KIns61RCjFuDPDo8qSSW1gK86x//8z) **Explanation:** ``` ∞ # Push an infinite list of positive integers: [1,2,3,...] ε # Map each integer y to: D( # Duplicate it, and negate the copy: -y Ÿ # Pop both, and push a list in that range: [y,...,-y] 3ã # Create triplets of this list with the cartesian power ʒ # Filter this list of [c,b,a]-triplets by: Im # Take each value to the power of the input n: [c^n,b^n,a^n] ` # Pop the list, and push the three values separated to the stack + # Add the top two together: b^n+a^n α # Take the absolute difference: |c^n-a^n+b^n| # (NOTE: only 1 is truthy in 05AB1E) # (after which the infinite list of lists of triplets is output implicitly) ``` ]
[Question] [ You are to write a program that, when given an integer between 1 and 5 (or 0 and 4 if you wish to use 0-indexing), outputs one of `Code`, `Golf`, `and`, `Coding` or `Challenges`. Each input can map to any of the five outputs. However, the mapping must be one to one (each input goes to a different output) and consistent when running the program multiple times. For example, `1 -> Coding`, `2 -> Golf`, `3 -> and`, `4 -> Code` and `5 -> Challenges` is a perfectly acceptable mapping. The capitalisation and spelling of the outputs must match, but leading and trailing whitespace is perfectly acceptable. Rather than [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), we will use a different scoring system (lets use `abcdef` as an example program): * If your program works **whenever any single (\$1\$) character is removed**, your score is \$1\$. + So `bcdef`, `acdef`, `abdef`, `abcef`, `abcdf` and `abcde` should **all** work as program on their own + By "work", I mean that the program still fulfils the first two paragraphs of this challenge spec. The 5 possible inputs may be different to the unaltered program, and to each of the other altered programs, so long as they meet the rules above. * If your program **still works whenever any pair (\$2\$) of consecutive characters are removed**, your score is \$2\$ + So, to qualify for a score of \$2\$, `abcd`, `abcf`, `abef`, `adef` and `cdef` must all work according to the challenge spec * And so on. If your program still works whenever any subset of length \$n\$ of consecutive characters is removed from it, your score is \$n\$. The program with the largest \$n\$ wins. In order to compete, all programs must have a score of at least \$1\$. Your program must work for *all* \$i \le n\$ in order to qualify for a score of \$n\$. So in order to score \$5\$, your program must also score \$1, 2, 3\$ and \$4\$. [This](https://tio.run/##XZCxbsMwDERn@yu4SWrtoEa3oukndOloeDCSc6LApgRFAZKvd0XZadqOvOM9Huhv8ej4dZ59cIfQT7QlpdQ7OCLQXTsi4CPJZTm4QOcIT5Yp9HyAbioawXpdNeatLHywHLX62rkA2qoqJ0xZSNg@kr9jVC/YZ2qEUOycv6Uq7UtHT3/4ybO8x1VM26VJoKcHNFPqlbKsbnrvwXudh7ZuunxljaIijJgEAL5MCH3Ez7GFMRDEzvGs5HYtutTh0zFEwnjGf0@4SVq/oTYnZ1kPdkyf1ZKrSHaNMfePmXn@Bg) is a Python program which will output all the possible alterations to your original program, along with the score they're worth. [Answer] # 8086 machine code (MS-DOS .COM), score 26 402 The file is 52 947 bytes long. The length was a product of what produced benign instruction sleds, and the maximum file size for .COM files (65 280 bytes -- 65 264 in case an interrupt happens before you can stop it). Here in binary form, with repeating lines snipped out for obvious reasons: ``` 00000000 : E9 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 : .ggggggggggggggg 00000010 : 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 : gggggggggggggggg <...> 00006720 : 67 67 67 67 67 90 D1 EE AD 93 AC E8 00 00 5A 2C : ggggg.........Z, 00006730 : 30 01 C2 3C 04 75 03 83 C2 02 D1 E0 D1 E0 01 C2 : 0..<.u.......... 00006740 : 83 C2 1B B4 09 CD 21 CD 20 43 6F 64 65 24 47 6F : ......!. Code$Go 00006750 : 6C 66 24 61 6E 64 24 24 43 6F 64 69 6E 67 24 43 : lf$and$$Coding$C 00006760 : 68 61 6C 6C 65 6E 67 65 73 24 EB 9F 9F 9F 9F 9F : hallenges$...... 00006770 : 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F : ................ <...> 0000CE80 : 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F D1 : ................ 0000CE90 : EE AD 93 AC E8 00 00 5A 2C 30 01 C2 3C 04 75 03 : .......Z,0..<.u. 0000CEA0 : 83 C2 02 D1 E0 D1 E0 01 C2 83 C2 1B B4 09 CD 21 : ...............! 0000CEB0 : CD 20 43 6F 64 65 24 47 6F 6C 66 24 61 6E 64 24 : . Code$Golf$and$ 0000CEC0 : 24 43 6F 64 69 6E 67 24 43 68 61 6C 6C 65 6E 67 : $Coding$Challeng 0000CED0 : 65 73 24 : es$ ``` In readable form: ``` org 0x100 cpu 8086 SLED_LEN equ (0x6767 - (part1_end - part1) + 2) db 0xe9 times SLED_LEN db 0x67 part1: nop shr si, 1 ; SI = 0x80 lodsw ; SI = 0x82 xchg bx, ax ; AX = 0 lodsb ; AL = first character of command line argument ; Load DX with IP, since we only know our strings' relative position call near .nextline .nextline: pop dx sub al, '0' add dx, ax cmp al, 4 jne .skip add dx, 2 .skip: shl ax, 1 shl ax, 1 add dx, ax add dx, 0x1b mov ah, 0x09 int 0x21 int 0x20 p1_msg0 db "Code$" p1_msg1 db "Golf$" p1_msg2 db "and$$" p1_msg3 db "Coding$" p1_msg4 db "Challenges$" part1_end: part2: db 0xeb times SLED_LEN db 0x9f shr si, 1 ; SI = 0x80 lodsw ; SI = 0x82 xchg bx, ax ; AX = 0 lodsb ; AL = first character of command line argument ; Load DX with IP, since we only know our strings' relative position call near .nextline .nextline: pop dx sub al, '0' add dx, ax cmp al, 4 jne .skip add dx, 2 .skip: shl ax, 1 shl ax, 1 add dx, ax add dx, 0x1b mov ah, 0x09 int 0x21 int 0x20 p2_msg0 db "Code$" p2_msg1 db "Golf$" p2_msg2 db "and$$" p2_msg3 db "Coding$" p2_msg4 db "Challenges$" ``` # Rundown This is a slightly adapted variation on a [previous answer](https://codegolf.stackexchange.com/a/191375/75886) of mine. The active part is duplicated so that there is always one untouched by radiation. We select the healthy version by way of jumps. Each jump is a near jump, and so is only three bytes long, where two last bytes are the displacement (i.e. distance to jump, with sign determining direction). This displacement is replicated over and over, forming a long NOP sled of sorts. We can divide the code into four parts which could be irradiated: jump 1, code 1, jump 2, and code 2. The idea is to make sure a clean code part is always used. If one of the code parts is irradiated, the other must be chosen, but if one of the jumps is irradiated, both code parts will be clean, so it will not matter which one is chosen. The reason for having two jump parts is to detect irradiation in the first part by jumping over it. If the first code part is irradiated, it means we will arrive off mark, somewhere in the second NOP sled. If we make sure that such a botched landing selects code 2, and a proper landing selects code 1, we're golden. For both jumps, we duplicate the displacement word, making each jump part one opcode followed by a massive repetition of the displacement. This ensures that irradiation somewhere in the sled will still make the jump valid, as long as at least two bytes of the sled remains. Irradiation in the first byte will stop the jump from happening at all, since the following sled will form a completely different instruction. Take the first jump: ``` E9 67 67 67 67 ... jmp +0x6767 / dw 0x6767 ... ``` If either of the `0x67` bytes are removed, it will still jump to the same place, as long as at least one word remains. If the `0xE9` byte is removed, we will instead end up with ``` 67 67 67 67... ``` each of which is a address-size override prefix. The CPU will gladly chomp them all down, and then we fall through to code 1, which must be clean, since the damage was in jump 1. If the jump is taken, we land at the second jump: ``` EB 9F 9F 9F 9F ... jmp -0x61 / db 0x9f ``` If this byte sequence is intact, and we land right on the mark, that means that code 1 was clean, and this instruction jumps back to that part. The replicated displacement byte guarantees this, even if it is one of these displacement bytes that were damaged. The astute reader will notice that this instruction jumps too far back, but that's alright, since if we hit the jump, then part1's NOP sled must be wholly intact, making a slightly longer jump backwards okay. If we either land off the mark (because of a damaged code 1 or jump 1) or the `0xEB` byte is the damaged one, the remaining bytes will also here be benign: ``` 9F 9F 9F 9F ... lahf / lahf ``` Whichever the case, if we end up executing that sled of instructions, we know that either jump 1, code 1, or jump 2 were irradiated, which makes a fall-through to code 2 safe. ## Testing Testing proved problematic. I've done some tests on certain corner-cases and a few random ones, but I have to find a better way for exhaustive testing. It should not be a problem up to the above-mentioned score. The following program was used to automatically create all versions of the .COM file for a certain gap size. It also creates a BAT file that can be run in the target environment, which runs each irradiated binary, and pipes their outputs to separate text files. Comparing the output files to validate is easy enough, but DOSBox does not have `fc`, so it was not added to the BAT file. ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *fin, *fout, *fbat; int fsize; char *data; int gapsize = 1; if (!(fin = fopen(argv[1], "rb"))) { fprintf(stderr, "Could not open input file \"%s\".\n", argv[1]); exit(1); } if (!(fbat = fopen("tester.bat", "w"))) { fprintf(stderr, "Could not create BAT test file.\n"); exit(2); } if (argc > 2) { gapsize = atoi(argv[2]); } fseek(fin, 0L, SEEK_END); fsize = ftell(fin); fseek(fin, 0L, SEEK_SET); if (!(data = malloc(fsize))) { fprintf(stderr, "Could not allocate memory.\n"); exit(3); } fread(data, 1, fsize, fin); fprintf(fbat, "@echo off\n"); for (int i = 0; i <= fsize - gapsize; i++) { char fname[512]; sprintf(fname, "%06d.com", i); for (int j = 0; j < 5; j++) fprintf(fbat, "%s %d >> %06d.txt\n", fname, j, i); fout = fopen(fname, "wb"); fwrite(data, 1, i, fout); fwrite(data + i + gapsize, 1, fsize - i - gapsize, fout); fclose(fout); } free(data); fclose(fin); fclose(fbat); } ``` ]
[Question] [ **Challenge** The challenge is simple: Taking no inputs and output the following message: ``` _ __ __ | | | | | |_ |__| | | ``` A number of times equal to the number of hours before or after midnight UTC on 31st Dec 2016. **Examples** For example if it is 19:01 UTC dec 31st you should output: ``` _ __ __ | | | | | |_ |__| | | _ __ __ | | | | | |_ |__| | | _ __ __ | | | | | |_ |__| | | _ __ __ | | | | | |_ |__| | | _ __ __ | | | | | |_ |__| | | ``` if it is 23:24 UTC dec 31st you should output: ``` _ __ __ | | | | | |_ |__| | | ``` and if it is 1:42 UTC jan 1st you should output: ``` _ __ __ | | | | | |_ |__| | | _ __ __ | | | | | |_ |__| | | ``` Clarification: if it is 10-11pm dec 31st you should output two, 11-12pm dec 31st output one, 00-01am jan 1st output one, 01-02am jan 1st output two etc... **Rules** * No Inputs * Trailing lines or spaces are ok. * Your program should work any time or day I run it (albeit with a large output). For example on jan 2nd at 00:15am your code should output 25 times. (This is my first Code Golf question so if I have left any thing important out please let me know.) **This is Code Golf so Shortest bits win** [Answer] # JavaScript (ES6), 107 As an anonymous method with no parameters Note `1483228800000` is `Date.UTC(2017,0)` ``` _=>` _ __ __ | | | | | |_ |__| | | `.repeat((Math.abs(new Date-14832288e5)+36e5-1)/36e5) ``` **Test** This keeps updating every 1 minute, but you'll need a lot of patience to see the output change. ``` F=_=>`_ __ __ | | | | | |_ |__| | | `.repeat((Math.abs(new Date-14832288e5)+36e5-1)/36e5) update=_=>O.textContent=F() setInterval(update,60000) update() ``` ``` <pre id=O></pre> ``` [Answer] # Python 2 - 97 + 17 = 114 bytes ``` import time print'_ __ __\n | | | | |\n |_ |__| | |\n'*int((abs(time.time()-1483228800)+3599)/3600) ``` Borrowed logic for ceiling from [edc65's answer](https://codegolf.stackexchange.com/a/105189/47650). **Python 3.5 - 116 bytes** ``` import time,math print('_ __ __\n | | | | |\n |_ |__| | |\n'*math.ceil(abs(time.time()/3600-412008))) ``` `math.ceil` returns an integer in `3.x` whereas in `2.x` it returns a float. Thanks [elpedro](https://codegolf.stackexchange.com/a/105189/47650) for saving 3 bytes. [Answer] # [Pyth](https://github.com/isaacg1/pyth) - ~~71~~ 68 bytes ``` *"_ __ __ | | | | | |_ |__| | | ".Ea412008c.d0 3600 ``` Uses the same logic used in my python 3.5 answer. [Try it here!](http://pyth.herokuapp.com/?code=%2A%22_%20%20%20%20%20__%20%20%20%20__%0A%20%7C%20%20%20%7C%20%20%7C%20%7C%20%20%20%7C%0A%20%7C_%20%20%7C__%7C%20%7C%20%20%20%7C%0A%22.Ea412008c.d0%203600&debug=0) [Answer] # C compiled with Clang 3.8.1 ~~327~~ ~~317~~ 145 Bytes *172 bytes saved thanks to @edc65* ``` #include <time.h> t;main(){time(&t);t=abs(difftime(t,1483228800)/3600);while(t--)puts(" _ __ __\n | | | | |\n |_ |__| | |\n");} ``` # Ungolfed ``` #include <time.h> t; main() { time(&t); t=difftime(t, 1483228800)/3600; while(t--) puts(" _ __ __\n | | | | |\n |_ |__| | |\n"); } ``` **317 bytes** *10 bytes saved thanks to @LegionMammal978* ``` #include <time.h> t,y,w;main() {struct tm n;time(&t);n=*localtime(&t);n.tm_hour=n.tm_min=n.tm_sec=n.tm_mon=0;n.tm_mday=1;w=n.tm_year;if((w&3)==0&&((w % 25)!=0||(w & 15)==0))w=8784;else w=8760;t=(int)difftime(t, mktime(&n))/3600;t=t<w/2?t:w-t;for(;y++<t;)puts(" _ __ __\n | | | | |\n |_ |__| | |\n"); ``` # Ungolfed ``` #include <time.h> t,y,w; main() { struct tm n; time(&t); n=*localtime(&t); n.tm_hour=n.tm_min=n.tm_sec=n.tm_mon=0; n.tm_mday=1; w=n.tm_year; if((w&3)==0&&((w % 25)!=0||(w & 15)==0))w=8784;else w=8760; t=(int)difftime(t, mktime(&n))/3600; t=t<w/2?t:w-t; for(;y++<t;) puts(" _ __ __\n | | | | |\n |_ |__| | |\n"); } ``` I will add some explanations when I'll be able to. ]
[Question] [ Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation. For example, if the input grid of text is ``` abcd 1234 WXYZ ``` then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output: ``` ab 123c WXYZ4d ``` Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level. # Details * The input grid of text will be at minimum 1×1 in size and all lines will be the same length. * You may take the input grid as a multiline string or as a list of single line strings. * The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space). * The output may optionally have one trailing newline but there should be no other empty lines. * The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces. # Other Examples Empty lines separate examples. Each input is directly followed by its output. ``` 123 456 789 1 452 78963 123.?! 456??! 789!!! 123. 456??? 789!!!!! **@ @ ** @ @ /\/\ \/ / / /\ \/\/ / \/\ / / / \/\/\/\ 12 34 56 78 90 7531 908642 Code Code G O L F FLOG ~ ~ ``` # Scoring The shortest code in bytes wins. [Answer] ## [J](http://jsoftware.com/), 12 bytes ``` |./.&.|:&.|. ``` Defines an anonymous verb. [Try it online!](https://tio.run/nexus/j#@5@mYGulUKOnr6emV2MFxHr/S0AixgomCioK6olJySmGRsYm4RGRUepcqckZ@QrqnnkFpSVQTglUzL@0BCGYplDyHwA "J – TIO Nexus") ## Explanation ``` |./.&.|:&.|. |. Reversed /. anti-diagonals &. under |: transpose &. under |. reversal ``` In J, `u &. v` (read: `u` under `v`) means "v, then u, then inverse of v". Reversal and transpose are self-inverses, so the program really means "reverse, transpose, extract reversed anti-diagonals, transpose, reverse". With example input: ``` abcd 1234 WXYZ ``` Reverse: ``` WXYZ 1234 abcd ``` Transpose: ``` W1a X2b Y3c Z4d ``` Extract reversed anti-diagonals (and pad with spaces): ``` W X1 Y2a Z3b 4c d ``` Transpose: ``` WXYZ4d 123c ab ``` Reverse: ``` ab 123c WXYZ4d ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 or 10 bytes ``` ZŒDṙLUz⁶ṚUY ``` [Try it online!](https://tio.run/nexus/jelly#@x91dJLLw50zfUKrHjVue7hzVmjk////lRKTklNSlXSU0tIzMrOAdHZObl6@EgA "Jelly – TIO Nexus") A fairly different algorithm from my other solution; this one uses a builtin to get at the diagonals, rather than doing things manually. Explanation: ``` ZŒDṙLUz⁶ṚUY Z transpose ŒD diagonals, main diagonal first L number of lines in the original array ṙ rotate list (i.e. placing the short diagonal first) U reverse inside lines z⁶ transpose, padding with spaces ṚU rotate matrix 180 degrees Y (possibly unnecessary) join on newlines ``` The diagonals come out in possibly the worst possible orientation (requiring repeated transpositions, reversals, and rotations), and in the wrong order (Jelly outputs the main diagonal first, so we have to move some diagonals from the end to the start to get them in order). However, this still comes out shorter than my other Jelly solution. [Answer] ## [CJam](https://sourceforge.net/p/cjam), 29 bytes ``` qN/{)\z}h]2/{~W%+}%eeSf.*W%N* ``` [Try it online!](https://tio.run/nexus/cjam#@1/op1@tGVNVmxFrpF9dF66qXauamhqcpqcVruqn9f@/oZGxnr0il4mpmT2QMrewVFRUBAA "CJam – TIO Nexus") ### Explanation Instead of extracting the diagonals, we peel off layers from the end, alternating left and right. Consider the following input: ``` GFDB EEDB CCCB AAAA ``` If we write out the diagonals as required by the challenge, we get: ``` G EEF CCCDD AAAABBB ``` Note that this is simply (from bottom to top), the bottom-most row, concatenated with the right-most column. This definition also works if the input is rectangular. ``` { e# Run this loop while there are still lines left in the input. ) e# Pull off the bottom-most row. \ e# Swap with the remaining rows. z e# Transpose the grid so that the next iteration pulls off the last e# column instead. However, it should be noted that transposing e# effectively reverses the column, so the second half of each output e# line will be the wrong way around. We'll fix that later. }h e# When the loop is done, we'll have all the individual layers on the e# stack from bottom to top, alternating between horizontal and vertical e# layers. There will be an empty string on top. ] e# Wrap all those strings in a list. 2/ e# Split into pairs. There may or may not be a trailing single-element e# list with the empty string. { e# Map this block over each pair... ~ e# Dump the pair on the stack. W% e# Reverse the second element. + e# Append to first element. e# If there was a trailing single-element list, this will simply e# add the empty string to the previous pair, which just removes e# the empty string. }% ee e# Enumerate the list, which pairs each string (now containing both halves) e# of an output line from bottom to top) with its index. Sf.* e# Turn those indices X into strings of X spaces, to get the correct e# indentation. W% e# Reverse the list of strings so the longest line ends up on the bottom. ``` [Answer] # JavaScript, ~~116~~ 101 bytes ``` f=(s,r='$&',l='',z=s.replace(/.$|\n?(?!.*\n)..+/gm,x=>(l=x+l,'')))=>l?f(z,r+' ')+l.replace(/\n?/,r):l G.onclick=()=>O.textContent=f(I.value); ``` ``` <textarea id=I style=height:100px>/\/\ \/ / / /\ \/\/</textarea><button id=G>Go</button><pre id=O></pre> ``` I just wanted to use this regex pattern `/.$|\n?(?!.*\n)..+/gm` idea. (<https://regex101.com/r/mjMz9i/2>) JavaScript regex flavour is disappointing, I had to use `(?!.*\n)` because it doesn't have `\Z` implemented, and somehow I didn't get to use `\0`. * 15 bytes off thanks @Neil. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 or 14 bytes ``` L’⁶x;\Ṛ;"µZUZṚY ``` [Try it online!](https://tio.run/nexus/jelly#@@/zqGHmo8ZtFdYxD3fOslY6tDUqNArIivz//7@SoZGxnr2iko6SiamZPZhhbmGpqKioBAA "Jelly – TIO Nexus") This is an algorithm that doesn't use Jelly's built-in for diagonals. Doing that might make it shorter; I might well try that next. Here's how the algorithm works. Let's start with this input: ``` ["abc", "def", "ghi"] ``` We start off with `L’⁶x;\`. `L’` gives us the length of the input minus 1 (in this case, 2). Then `⁶x` gives us a string of spaces of that length (`" "` in this case); and `;\` gives us the cumulative results when concatenating it (a triangle of spaces). We then reverse the triangle and concatenate it to the left side of the original (`;"` concatenates corresponding elements of lists, `µ` forcibly causes a break in the parsing and thus uses the original input as the second list by default), giving us this: ``` [" abc", " def", "ghi"] ``` This is almost the solution we want, but we need to move the elements downwards to be flush with the last string. That's a matter of transposing (`Z`), reversing inside each line (`U`), transposing again (`Z`), and reversing the lines (`Ṛ`): ``` [" abc", " def", "ghi"] ``` transpose ``` [" g", " dh", "aei", "bf", "c"] ``` reverse within rows ``` ["g ", "hd ", "iea", "fb", "c"] ``` transpose ``` ["ghifc", " deb", " a"] ``` reverse the rows ``` [" a", " deb", "ghifc"] ``` Finally, `Y` joins on newlines. It's unclear to me whether or not this is required to comply with the specification (which allows input as a list of strings, but doesn't say the same about output), so the exact byte count depends on whether it's included or omitted. [Answer] # Pyth, 16 bytes ``` j_.t_M.Tm+*;l=tQ ``` ### [Big Pyth](https://github.com/isaacg1/pyth/blob/master/big-pyth.py): ``` join-on-newline reverse transpose-and-fill-with-spaces reverse func-map transpose-justified map plus times innermost-var length assign tail input implicit-innermost-var implicit-input ``` Since people say golfing languages are hard to read, I've designed Big Pyth, which is both easily readable and easily translatable to Pyth. The linked file translates an input stream of Big Pyth to Pyth. Each whitespace-separated Big Pyth token corresponds to a Pyth token, either a character or a `.` followed by a character. The exceptions are the `implicit` tokens, which are implicit in the Pyth code. I want to see how good an explanatory format Big Pyth is, so I'm not going to give any other explanation. Ask me if you want something explained, however. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 5 bytes ``` Þ√Ṙṅ§ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJhIiwidmYiLCLDnuKImuG5mOG5hcKnIiwiIiwiL1xcL1xcXG5cXC8gL1xuLyAvXFxcblxcL1xcLyJd) Header converts it into a single character matrix which is a valid input form. [Answer] ## JavaScript (ES6), 140 bytes ``` a=>[...Array(m=(h=a.length)<(w=a[0].length)?h:w)].map((_,i)=>[...Array(h+w-1)].map((_,j)=>(a[x=i+h-m-(++j>w&&j-w)]||``)[x+j-h]||` `).join``) ``` Takes input and output as arrays of strings. Also accepts a two-dimensional character array input, and save 7 bytes if a two-dimensional character array output is acceptable. Explanation: The height of the result `m` is the minimum of the height `h` and width `w` of the original array, while the width is simply one less than the sum of the height and width of the original array. The source row for the characters on the main portion of the result come directly from the appropriate row of the original array, counting up from the bottom, while on the extra portion of the result the source row moves up one row for each additional column. The source column for both halves of the result turns out to be equal to the destination column moved one column left for each source row above the bottom. [Answer] # Octave, 57 bytes ``` @(A){B=spdiags(A),C=B>0,D=' '(C+1),D(sort(C))=B(C),D}{5} ``` [Answer] # Python 3, 247 bytes ``` def a(s): s=s.split('\n') for i,l in enumerate(s):r=len(s)-i-1;s[i]=' '*r+l+' '*(len(s)-r-1) print(*[''.join(i) for i in list(zip(*[''.join(a).rstrip([::-1].ljust(min(len(s),len(s[0])))for a in zip(*[list(i)for i in s])]))[::-1]],sep='\n')` ``` [Answer] # Python 2, 150 bytes ``` def f(l):w=len(l[0]);h=len(l);J=''.join;R=range;print'\n'.join(map(J,zip(*['%%-%ds'%h%J(l[h+~i][j-i]for i in R(h)if-w<i-j<1)for j in R(h-~w)]))[::-1]) ``` Takes input as list of strings. [Answer] ## Clojure, 194 bytes Implemented the hard way by grouping characters to `G` and then generating lines. ``` #(let[n(count %)m(count(% 0))G(group-by first(for[i(range n)j(range m)][(min(- n i)(- m j))((% i)j)]))](apply str(flatten(for[k(reverse(sort(keys G)))][(repeat(dec k)" ")(map last(G k))"\n"])))) ``` Takes input as a `vec` of `vec`s like `[[\a \b \c \d] [\1 \2 \3 \4] [\W \X \Y \Z]]`. Example: ``` (def f #( ... )) (print (str "\n" (f (mapv vec(re-seq #".+" "abcd\n1234\nWXYZ"))))) ab c123 d4WXYZ ``` ]
[Question] [ *Inspired by [this](https://i.stack.imgur.com/womc0.png). No avocados were harmed in the making of this challenge.* Hello I have challenge I need help juic an avocado so I need program to tell me how long to juic avocad for Observe this ASCII art avocado: ``` ###### # # # #### # # # p# # ## #### # # # ###### ``` This avocado consists of an exterior of `#`s (specifically the first and last sequences of `#`s on each line) and a pit (a shape of `#`s in the avocado that does not touch the avocado exterior). Through rigorous experiments on these ASCII art avocados I have discovered the following: ``` avocado juice in fluid ounces = number of spaces inside avocado but outside pit (the pit is marked with a p in the example) + 2 * number of spaces inside pit time to juice avocado in minutes = 13 * number of spaces inside pit ``` For example, this avocado will take 26 (2 spaces inside pit \* 13) minutes to juice and will give 23 (19 spaces inside avocado but outside pit + 2 \* 2 spaces inside pit) fl oz of juice. ## Challenge Given an input of **exactly one** ASCII art avocado such as the one above that consists of only `#` and whitespace, output the amount of time in minutes it will take to juice it and the amount of juice it will produce in any order. You may assume that the input avocado will always have exactly one pit and both the avocado and the pit will always be closed. The pit and avocado will always be connected, and any subset of the pit will be connected as well. The avocado and the pit will always be convex. Note that the avocado exterior may be arbitrarily thick. ## Sample Inputs and Outputs ``` ###### # # # #### # # # # # -> 26 23 ## #### # # # ###### ####### # # # ### ## # # # # -> 26 35 # ## # # # ########## ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Answer] # Pyth, ~~59~~ 51 bytes ``` *Ksm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z13+-/s.sR\ .zdK*2K ``` [Try it here!](http://pyth.herokuapp.com/?code=*Ksm%2F.s.s.sd%5C+%5C%23%5C+%5C+fq4l%3AT%22%23%2B%224.z13%2B-%2Fs.sR%5C+.zdK*2K&input=+++%23%23%23%23%23%23%23%0A++%23+++++++%23%0A++%23++%23%23%23+++%23%23%0A++%23++%23++%23+++%23%0A++%23+++%23%23+++%23%0A++%23++++++++%23%0A++%23%23%23%23%23%23%23%23%23%23&debug=0) Outputs the time to juic the advacado (totally correct english) first and on the next line the amount of juic. ## Explanation ### Code - Overview ``` *Ksm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z13+-/s.sR\ .zdK*2K # .z=list of all input lines fq4l:T"#+"4.z # Get the pit-lines m/.s.s.sd\ \#\ \ # Map the pit-lines to the whitespace amount Ks # Sum the amount of pit-spaces and assign to K * 13 # Print the juic time /s.sR\ .zd # Count all whitespaces in the advacado - K # Subtract the pit size from it + *2K # Do the Rest of the amount calcluation and print it ``` *Detailed explanations of the size calculation parts see below.* ### Getting the advacado size Let's look at this one: ``` ###### # # # #### # # # # # ## #### # # # ###### ``` First the leading and trailing whitespaces get removed. After that we wrap everything in one line, which results in this string: ``` ####### ## #### ## # # ### #### ## ####### ``` This contains all whitespaces in the advacado, so we just have to count them (the advacado will always be convex, so this works for all valid inputs). This number still contains the spaces in the pit, but for the juic amount calculation we only need the spaces in the fruit without the pit-spaces. So we need to calculate them too. **The code for that explained in detail:** ``` /s.sR\ .zd # .z=list of all input lines .sR\ .z # strip spaces from every input line s # Concatenate all lines / d # Count all spaces ``` ### Getting the pit size This is a bit trickier. First we remove the lines which don't contribute to the pit size. This is done by filtering out all lines that have less than 4 groups of hashes (using the regex `#+` and counting its matches). In the example above only one line will survive this process: ``` # #--# # ``` The spaces I marked with a `-` here are the ones we need to count. So we just strip spaces, then hashes and then spaces again which leaves us with this: ``` # # ``` There we just have to count the spaces. We do all that for every line which survived the filtering process, sum everything and we are done. The rest is trivial math. **The code for that explained in detail:** ``` sm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z # .z=list of all input lines f .z # filter the input l:T"#+"4 # length of the matches for the regex `#+` q4 # if there are 4 groups of hashes its a pit line m # map the pit lines to... / \ # The occurences of spaces in.. .s.s.sd\ \#\ # ...the stripped pit line (see explanation above) s # Sum all amounts of spaces in the pits ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 70 * 25 bytes saved thanks to @FryAmTheEggman and @randomra ``` T` `i`(?<=# +#+) *(?=#+ +#) T` `f`# +# i 13$*iff ((i)|(f)|\W)+ $#2 $#3 ``` [Try it online.](http://retina.tryitonline.net/#code=VGAgYGlgKD88PSMgKyMrKSAqKD89IysgKyMpClRgIGBmYCMgKyMKaQoxMyQqaWZmCigoaSl8KGYpfFxXKSsKJCMyICQjMw&input=ICAgICMjIyMjIyAKICAgIyAgICAgICMKICAgIyAjIyMjICMKICAjICAjICAjICMKICAjIyAjIyMjICMKICAgIyAgICAgICMKICAgICMjIyMjIw) [Answer] ## Python, ~~141~~ 119 bytes ``` import sys s=str.strip;l=len;o=i=0 for x in sys.stdin:x=s(s(x),'#');y=s(x);o+=l(x)-l(y);i+=l(s(y,'#')) print o+2*i,13*i ``` ]
[Question] [ You have `n` coins which each weigh either -1 or 1. Each is labelled from `0` to `n-1` so you can tell the coins apart. You have one (magic) weighing device as well. At the first turn you can put as many coins as you like on the weighing device which is able to measure both negative and positive weights and it will tell you exactly how much they weigh. However, there is something really strange about the weighing device. If you put coins `x_1, x_2, ..., x_j` on the device the first time, then the next time you have to put coins `(x_1+1), (x_2+1) , ..., (x_j+1)` on the scale with the exception that you of course can't put on a coin numbered higher than `n-1`. Not only that, for every new weighing you get to choose if you also want to put coin `0` on the scale. > > Under this rule, what is the smallest number of weighings that will always tell you > exactly which coins weigh 1 and which weigh -1? > > > Clearly you could just put coin `0` on the device in the first turn and then it would take exactly `n` weighings to solve the problem. **Languages and libraries** You can use any language or library you like (that wasn't designed for this challenge). However, I would like to be able to test your code if possible so if you can provide clear instructions for how to run it in Ubuntu that would be very much appreciated. **Score** For a given `n` your score is `n` divided by the number of weighings you need in the worst case. Higher scores are therefore better. There is no input to this puzzle but your goal is to find an `n` for which you can get the highest score. If there is a tie, the first answer wins. In the extremely unlikely situation where someone finds a way to get an infinite score, that person wins immediately. **Task** Your task is simply to write code that gets the highest score. Your code will have to both choose an n cleverly and then also optimize the number of weighings for that `n`. **Leading entries** * 4/3 7/5 in **Python** by Sarge Borsch * 26/14 in **Java** by Peter Taylor [Answer] ## Score = 26/14 ~= 1.857 ``` import java.util.*; public class LembikWeighingOptimisation { public static void main(String[] args) { float best = 0; int opt = 1; for (int n = 6; n < 32; n+=2) { long start = System.nanoTime(); System.out.format("%d\t", n); opt = optimise(n, n / 2 + 1); float score = n / (float)opt; System.out.format("%d\t%f", opt, score); if (score > best) { best = score; System.out.print('*'); } System.out.format(" in %d seconds", (System.nanoTime() - start) / 1000000000); System.out.println(); } } private static int optimise(int numCoins, int minN) { MaskRange.N = numCoins; Set<MaskRange> coinSets = new HashSet<MaskRange>(); coinSets.add(new MaskRange(0, 0)); int allCoins = (1 << numCoins) - 1; for (int n = minN; n < numCoins; n++) { for (int startCoins = 1; startCoins * 2 <= numCoins; startCoins++) { for (int mask = (1 << startCoins) - 1; mask < (1 << numCoins); ) { // Quick-reject: in n turns, do we cover the entire set? int qr = (1 << (n-1)) - 1; for (int j = 0; j < n; j++) qr |= mask << j; if ((qr & allCoins) == allCoins && canDistinguishInNTurns(mask, coinSets, n)) { System.out.print("[" + Integer.toBinaryString(mask) + "] "); return n; } // Gosper's hack to update int c = mask & -mask; int r = mask + c; mask = (((r^mask) >>> 2) / c) | r; } } } return numCoins; } private static boolean canDistinguishInNTurns(int mask, Set<MaskRange> coinsets, int n) { if (n < 0) throw new IllegalArgumentException("n"); int count = 0; for (MaskRange mr : coinsets) count += mr.size(); if (count <= 1) return true; if (n == 0) return false; // Partition. Set<MaskRange>[] p = new Set[Integer.bitCount(mask) + 1]; for (int i = 0; i < p.length; i++) p[i] = new HashSet<MaskRange>(); for (MaskRange range : coinsets) range.partition(mask, p); for (int d = 0; d < 2; d++) { boolean ok = true; for (Set<MaskRange> s : p) { if (!canDistinguishInNTurns((mask << 1) + d, s, n - 1)) { ok = false; break; } } if (ok) return true; } return false; } static class MaskRange { public static int N; public final int mask, value; public MaskRange(int mask, int value) { this.mask = mask; this.value = value & mask; if (this.value != value) throw new IllegalArgumentException(); } public int size() { return 1 << (N - Integer.bitCount(mask)); } public void partition(int otherMask, Set<MaskRange>[] p) { otherMask &= (1 << N) - 1; int baseline = Integer.bitCount(value & otherMask); int variables = otherMask & ~mask; int union = mask | otherMask; partitionInner(value, union, variables, baseline, p); } private static void partitionInner(int v, int m, int var, int baseline, Set<MaskRange>[] p) { if (var == 0) { p[baseline].add(new MaskRange(m, v)); } else { int lowest = var & (1 + ~var); partitionInner(v, m, var & ~lowest, baseline, p); partitionInner(v | lowest, m, var & ~lowest, baseline + 1, p); } } @Override public String toString() { return String.format("(x & %x = %x)", mask, value); } } } ``` Save as `LembikWeighingOptimisation.java`, compile as `javac LembikWeighingOptimisation.java`, run as `java LembikWeighingOptimisation`. Many thanks to [Mitch Schwartz](https://codegolf.stackexchange.com/users/2537/mitch-schwartz) for pointing out a bug in the first version of the quick-reject. This uses some fairly basic techniques which I can't rigorously justify. It brute-forces, but only for starting weighing operations which use at most half of the coins: sequences which use more than half of the coins aren't directly transferable to the complementary weighings (because we don't know the total weight), but on a hand-wavy level there should be about the same amount of information. It also iterates through starting weighings in order of the number of coins involved, on the basis that that way it covers dispersed weighings (which hopefully give information about the top end relatively early) without first crawling through a bunch which start with a dense subset at the bottom end. The `MaskRange` class is a massive improvement on the earlier version in terms of memory usage, and removes GC from being a bottleneck. ``` 20 [11101001010] 11 1.818182* in 5364 seconds 22 [110110101000] 12 1.833333* in 33116 seconds 24 [1000011001001] 13 1.846154* in 12181 seconds 26 [100101001100000] 14 1.857143* in 73890 seconds ``` [Answer] # Python 2, score = 1.0 This is the easy score, in case nobody finds a better score (doubtful). `n` weighings for each `n`. ``` import antigravity import random def weigh(coins, indices): return sum(coins[i] for i in indices) def main(n): coins = [random.choice([-1,1]) for i in range(n)] for i in range(len(coins)): print weigh(coins, [i]), main(4) ``` I imported [`antigravity`](https://xkcd.com/353/) so the program can work with negative weights. [Answer] # C++, Score ~~23/12~~ ~~25/13~~ ~~27/14~~ ~~28/14 = 2~~ 31/15 The solutions of [Matrix property X revisited (or the Joy of X)](https://codegolf.stackexchange.com/questions/49218/matrix-property-x-revisited-or-the-joy-of-x) are directly usable as solutions to this problem. E.g. the solution of 31 rows 15 columns: ``` 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 0 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 ``` row N represent which coins you put on the scale for measurement N. Whatever the results of the weighting you get, there is obviously some set of coin values that gives that weight. If there is another combination too (the solution is not unique) consider how they differ. You must replace a set of coins weighting `1` by coins weighting `-1`. This gives a set of columns that correspond to that flip. There is also set of coins weighting `-1` that you replace by `1`. That is another set of columns. Because the measurements do not change between the two solutions that means the column sums of the two sets must be the same. But the solutions to [Matrix property X revisited (or the Joy of X)](https://codegolf.stackexchange.com/questions/49218/matrix-property-x-revisited-or-the-joy-of-x) are exactly these matrices where such column sets do not exist, so there are no duplicates and each solution is unique. Each actual set of measurements can be described by some `0/1` matrix. But even if some column sets sum to the same vectors it could be that signs of the candidate solution coin values do not exactly correspond to such a set. So I don't know if matrices such as the one above are optimal. But at least they provide a lower bound. So the possibility that 31 coins can be done in less that 15 measurements is still open. Notice that this is only true for a non fixed strategy where your decision to put coin `0` on the scales depends on the result of the previous weightings. Otherwise you ***will*** have solutions where the signs of the coins correspond with the sets that have the same column sum. [Answer] ## Python 3, ~~score = 4/3 = 1.33… (N = 4)~~ score = 1.4 (N = 7) ### Update: implemented brute-force search in "static" solvers set, and got a new result I think it can be further improved by searching for dynamic solvers, which can use weighting results for further decisions. Here is a Python code that searches through all static solvers for *small* `n` values (these solvers always weigh the same coin sets, hence "static" name) and determines their worst case number of steps by simply checking that their measurement results allow only one matching coin set in all cases. Also, it keeps track of best score found so far and early prunes solvers which had shown that they are definitely worse than those which were found before. This was an important optimization, otherwise I could not wait for this result with `n` = 7. (But it's clearly still not very well optimized) Feel free to ask questions if it's not clear how it works… ``` #!/usr/bin/env python3 import itertools from functools import partial def get_all_possible_coinsets(n): return tuple(itertools.product(*itertools.repeat((-1, 1), n))) def weigh(coinset, indexes_to_weigh): return sum(coinset[x] for x in indexes_to_weigh) # made_measurements: [(indexes, weight)] def filter_by_measurements(coinsets, made_measurements): return filter(lambda cs: all(w == weigh(cs, indexes) for indexes, w in made_measurements), coinsets) class Position(object): def __init__(self, all_coinsets, coinset, made_measurements=()): self.all_coinsets = all_coinsets self.made_measurements = made_measurements self.coins = coinset def possible_coinsets(self): return tuple(filter_by_measurements(self.all_coinsets, self.made_measurements)) def is_final(self): possible_coinsets = self.possible_coinsets() return (len(possible_coinsets) == 1) and possible_coinsets[0] == self.coins def move(self, measurement_indexes): measure_result = (measurement_indexes, weigh(self.coins, measurement_indexes)) return Position(self.all_coinsets, self.coins, self.made_measurements + (measure_result,)) def get_all_start_positions(coinsets): for cs in coinsets: yield Position(coinsets, cs) def average(xs): return sum(xs) / len(xs) class StaticSolver(object): def __init__(self, measurements): self.measurements = measurements def choose_move(self, position: Position): index = len(position.made_measurements) return self.measurements[index] def __str__(self, *args, **kwargs): return 'StaticSolver({})'.format(', '.join(map(lambda x: '{' + ','.join(map(str, x)) + '}', self.measurements))) def __repr__(self): return str(self) class FailedSolver(Exception): pass def test_solvers(solvers, start_positions, max_steps): for solver in solvers: try: test_results = tuple(map(partial(test_solver, solver=solver, max_steps=max_steps), start_positions)) yield (solver, max(test_results)) except FailedSolver: continue def all_measurement_starts(n): for i in range(1, n + 1): yield from itertools.combinations(range(n), i) def next_measurement(n, measurement, include_zero): shifted = filter(lambda x: x < n, map(lambda x: x + 1, measurement)) if include_zero: return tuple(itertools.chain((0,), shifted)) else: return tuple(shifted) def make_measurement_sequence(n, start, zero_decisions): yield start m = start for zero_decision in zero_decisions: m = next_measurement(n, m, zero_decision) yield m def measurement_sequences_from_start(n, start, max_steps): continuations = itertools.product(*itertools.repeat((True, False), max_steps - 1)) for c in continuations: yield tuple(make_measurement_sequence(n, start, c)) def all_measurement_sequences(n, max_steps): starts = all_measurement_starts(n) for start in starts: yield from measurement_sequences_from_start(n, start, max_steps) def all_static_solvers(n, max_steps): return map(StaticSolver, all_measurement_sequences(n, max_steps)) def main(): best_score = 1.0 for n in range(1, 11): print('Searching with N = {}:'.format(n)) coinsets = get_all_possible_coinsets(n) start_positions = tuple(get_all_start_positions(coinsets)) # we are not interested in solvers with worst case number of steps bigger than this max_steps = int(n / best_score) solvers = all_static_solvers(n, max_steps) succeeded_solvers = test_solvers(solvers, start_positions, max_steps) try: best = min(succeeded_solvers, key=lambda x: x[1]) except ValueError: # no successful solvers continue score = n / best[1] best_score = max(score, best_score) print('{}, score = {}/{} = {}'.format(best, n, best[1], score)) print('That\'s all!') def test_solver(start_position: Position, solver, max_steps): p = start_position steps = 0 try: while not p.is_final(): steps += 1 if steps > max_steps: raise FailedSolver p = p.move(solver.choose_move(p)) return steps except IndexError: # solution was not found after given steps — this solver failed to beat score 1 raise FailedSolver if __name__ == '__main__': main() ``` ## The output: ``` Searching with N = 1: (StaticSolver({0}), 1), score = 1/1 = 1.0 Searching with N = 2: (StaticSolver({0}, {0,1}), 2), score = 2/2 = 1.0 Searching with N = 3: (StaticSolver({0}, {0,1}, {0,1,2}), 3), score = 3/3 = 1.0 Searching with N = 4: (StaticSolver({0,1}, {1,2}, {0,2,3}, {0,1,3}), 3), score = 4/3 = 1.3333333333333333 Searching with N = 5: Searching with N = 6: Searching with N = 7: (StaticSolver({0,2}, {0,1,3}, {0,1,2,4}, {1,2,3,5}, {0,2,3,4,6}), 5), score = 7/5 = 1.4 Searching with N = 8: Searching with N = 9: (I gave up waiting at this moment) ``` This line `(StaticSolver({0,2}, {0,1,3}, {0,1,2,4}, {1,2,3,5}, {0,2,3,4,6}), 5), score = 7/5 = 1.4` uncovers the best solver found. The numbers in `{}` braces are the indices of coins to put on weighting device at each step. ]
[Question] [ [This tweet](https://twitter.com/seanposting/status/1054136447362629637) lists the possible orders for Wings of a Chinese restaurant1: [![Wings menu](https://i.stack.imgur.com/gkvx6.jpg)](https://i.stack.imgur.com/gkvx6.jpg) When ordering Pizza I usually calculate what size gives me the best Pizza-price ratio which is a simple calculation. However minimizing the price of an order at this restaurant isn't such a simple task, so I'd like to be prepared for my next order there. # Challenge Given an integer greater or equal to \$4\$, your task is to return one possible order which minimizes the price (overall cheapest) and the number of deals. # Example If I were to order \$100\$ Wings, it turns out the best bargain will cost \$$111.20\$. However there are multiple orders which will cost that amount, namely: ``` [50,50],[25,25,50],[25,25,25,25] ``` Since the first order will use the least amount of deals (\$2\$) the result will be `[50,50]`. # Rules * Input will be some integer \$n \geq 4\$ * Output will be a list/array/... of order sizes that sum up to \$n\$ and minimize the order's price + you may choose to return all possible orders # Testcases ``` 4 -> [4] (4.55) 23 -> [23] (26.10) 24 -> [6,18],[9,15],[12,12] (27.20) 31 -> [6,25] (34.60) 32 -> [4,28],[6,26],[7,25] (35.75) 33 -> [4,29],[5,28],[6,27],[7,26],[8,25] (36.90) 34 -> [6,28],[9,25] (38.00) 35 -> [35] (39.15) 125 -> [125] (139.00) 200 -> [25,50,125] (222.40) 201 -> [26,50,125] (223.55) 250 -> [125,125] (278.00) 251 -> [26,50,50,125] (279.15) 418 -> [15,28,125,125,125],[18,25,125,125,125] (465.20) 1001 -> [26,50,50,125,125,125,125,125,125,125] (1113.15) 12345 -> [15,80,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125],[25,70,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125],[45,50,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125] (13728.10) ``` **Note:** These testcases list *all* possible outputs including the price, you're only required to output *one* and you're **not** required to output the price! --- 1: You can find the data as a CSV [here](https://pastebin.com/2P3ZECcA). [Answer] # JavaScript (ES6), 123 bytes Returns the order as a space-separated string. ``` f=n=>n?(x=n>128|n==125?125:n>50?n<54?25:n-70?302256705>>n-80&n>79&n<109?80:50:n:n-24&&n-49?n<31|n%5<1?n:25:9)+' '+f(n-x):'' ``` [Try it online!](https://tio.run/##dZLLbsIwEEX3/YpsmodIjGfs8SMiyYcgFqiFqhVyqlJVLPj31CaFEJlGGlmJzr2TueOP7c/2@PL1/vlduf51Nwz7xjWt6/JT41pAc3ZNA0idr9q1xDu3ItmFl0rzTnBEUppT27rK8NS12qZuBdx2htfEa@c5lGnqKmm9VMDZPdMKOld7C1sssiRb7HNXnYo6y4aX3h37w44d@rd8n8uiSMKzXCZruUmSXDKi4mkOoRipAKEIFCoGPMLkhKkSzKZc2xLIH4Al4EWnGUY6Afc6pAAKyVQM4gTKEkMDzyt/6KuMmI5@X4iZzHqebmo9qoOJuZooZuPes@FwHO6PN4zHPE28GDHLII7WK4trtFQS90FdaERkMo6Yw4SrGS4eLE6CueEQZg74tcJewsizb@EGKHqwJOBj66nz2Py/Ck4AIB7MDChkSOeyD7r3YYzdtEKjCZds@AU "JavaScript (Node.js) – Try It Online") ## How? Given a number \$n\$ of wings, we recursively apply the following strategy. ### High values: \$n>128\$ or \$n=125\$ For high values, our best option is to buy \$125\$ wings. So that's what we're doing as long as \$n\$ is greater than or equal to \$129\$ or when \$n\$ is exactly equal to \$125\$. We can't do that for \$125 < n < 129\$ because we'd be left with less than \$4\$ wings to buy, which is not possible. ### Low values: \$n<31\$ For \$n<31\$, the best deal is to buy all remaining wings at once, except for \$n=24\$ which must be purchased as either \$2\times 12\$, \$18+6\$ or \$15+9\$. We arbitrarily buy \$9\$ wings in that case. ### Range \$31 \le n \le 50\$ In this range, buying \$25\$ wings usually leads to an optimal order. But the following exceptions apply: * If \$n\$ is a multiple of \$5\$, we must buy all remaining wings at once. * If \$n=49\$, the best deals are \$40+9\$ and \$28+21\$. We arbitrarily buy \$9\$ wings in that case. ### Range \$51 \le n \le 53\$ We can't buy \$50\$ wings in that range or we'll be left with less than \$4\$ wings. Our best option is to buy \$25\$ of them instead. (We *could* buy \$2\times26\$ wings for \$n=52\$, but buying \$25+27\$ is just as good.) ### Range \$54 \le n \le 128\$ with \$n \neq 125\$ In this range, buying \$50\$ wings usually leads to an optimal order. But the following exceptions apply: * If \$n=70\$, we must buy all of them at once. * If \$n\$ is in \$\{80,86,89,92,98,105,108\}\$, we must buy \$80\$ wings. These values are encoded with the following bitmask, where the least significant bit is mapped to \$80\$ and the most significant one to \$108\$: $$10010000001000001001001000001\_{(2)} = 302256705\_{(10)}$$ [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~112~~ ~~108~~ ~~106~~ 105 bytes ``` f=n=>n?(x=n>128|n==125?125:n>53&n!=70?1629>>n/3+6&n<99==n%3/2?80:50:~n%25?n>30&&n%5?25:n:9)+' '+f(n-x):'' ``` [Try it online!](https://tio.run/##dZLbboMwDIbv@xTZRQsRNMTOgcMaeJCtF1VXpk1VmNqq6sW0V@8SGKWIDskyRN//G9v53Jw3x@3h4@u0tM3b7nqtjTWlrcKLsSVg9m2NAVSVi8KWSizsk0l5BRrzsrSJiPTCrvLcGDsXCVYZLxQvfuzcSWwp@GJh56ry2iKnUUCCqA7t8kKLILhuG3ts9ju2b97DOpSUEv8kCXmRa0JCyZSiszGEoqM8hMJTqBnwCSYHTMeQreOXPAblEmAM2OpShhOdgHsdKg8KyfQUxAGUMfoCjtcupb1MsXTy@0KMZLnj1U2ddmpvkvUmmuXT2qPmsGvuj88Yn/Jq4EWH5Qymo3VK2o9WxYq7QbU0IjI5HTGHAdcjXDxYnITshoPv2eN9@L34lkdn/gZo9WBJwLvSQ@Wu@H/hnQBAPOgZUEg/nXYf6t6HMXbTihSz9pLN6uYQnnd7I5@JSytQ0L5EESX3xu6IRCR4PQUu1f6T0usv "JavaScript (Node.js) – Try It Online") Optimized from Arnauld's answer # Differences * 51≤n≤53 is merged into 31≤n≤50 (8 bytes save) * Rewrite the bitmap (3 bytes save) * Rearrange some logic (~~4~~ ~~6~~ 7 bytes saved) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~160~~ 155 bytes ``` .+ $* {`\b(1{80}(?=((111){2,6}|1{25}|1{28})?$)|1{70}$|1{9}(?=.{15}$|.{40}$)|(1{5}){6,9}$|1{26,29}$|1{4,23}$|1{125}|1{50}|1{25})+$ $1,$& (1+),\1(1*)$ $.1,$2 ``` [Try it online!](https://tio.run/##LYwxDoMwDEX33KKSi2wSRbFLKAwVJ@gNGGilDl06oG4mZ6cu4OH7@fvrz6/v@/NYo3dQu/upmtjGuzNOphCr46PT@ETWLhUcboiWIZXQloVV8qZdoQHI6JoK2Or/yaic7YramEmLNeRC2oZ@i0gbZKcmyGUD3ttyOprJgwMOUDlkT2Fk5JrMiubJukpOPw "Retina 0.8.2 – Try It Online") Link includes header that tests all values from \$ n \$ down to 1, remove it if you only want to test \$ n \$ itself. Uses @Arnauld's algorithm. Edit: Saved 5 bytes by purchasing 95 wings as 80 + 15 instead of 50 + 45. Explanation: ``` .+ $* ``` Convert to unary. ``` {` ``` Repeat until no more deals can be purchased. ``` {`\b(1{80}(?=((111){2,6}|1{25}|1{28})?$)|1{70}$|1{9}(?=.{15}$|.{40}$)|(1{5}){6,9}$|1{26,29}$|1{4,23}$|1{125}|1{50}|1{25})+$ $1,$& ``` Find a way of purchasing deals and capture and duplicate one of the deals. ``` (1+),\1(1*)$ $.1,$2 ``` Convert the captured deal to decimal and subtract it from \$ n \$. Deals are purchased under the following conditions: ``` 1{80}(?=((111){2,6}|1{25}|1{28})?$) ``` Purchase 80 wings if that leaves 0, 6, 9, 12, 15, 18, 25 or 28 wings. ``` 1{70}$ ``` Purchase 70 wings if that's all we need. ``` 1{9}(?=.{15}$|.{40}$) ``` Purchase 9 wings if that leaves 15 or 40 wings. ``` (1{5}){6,9}$ ``` Purchase 30, 35, 40 or 45 wings if that's all we need. ``` 1{26,29}$ ``` Purchase 26, 27, 28 or 29 wings if that's all we need. ``` 1{4,23}$ ``` Purchase 4 to 23 wings if that's all we need. ``` 1{125}|1{50}|1{25} ``` Purchase 125, 50 or 25 wings if we can and if we can still purchase more wings exactly. Note that we have these options at the end of the alternation so that the exact purchases are tested first. ]
[Question] [ Given a String and an Array as input, your task is to output the text the input String will print when typed on a typical Mobile Keypad. In a Mobile Keypad, a letter is typed by pressing a button n times, where n is the position of where the letter is at on the button's label. So, `22` should output `b`. [![Keypad](https://i.stack.imgur.com/BoopQ.png)](https://i.stack.imgur.com/BoopQ.png) --- # Rules * The Helper Array will contain the Character Map (`[" ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]`). This will be given to save you some bytes. * The `#` symbol will toggle case. Initial Case will be lower. So `2#3` should output `aD`. * The `0` will add a space. So, `202` should output `a a`. * There will be a space () in the input String to start a new letter that is on the same numeric button. For Example to type `aa`, the input String will be `2 2`. * It is guranteed that the input String will always be a valid KeyPad Code. --- # Input You can take input in whatever way your language supports. --- # Output You can output the result in any way you want. Function `return` is also allowed. --- # Test Cases ``` #4440555#666888330#999#66688111 -> "I Love You!" #6#33777 7779990#222#4477744477778627777111 -> "Merry Christmas!" #44#27 79990#66#3390#999#332777111 -> "Happy New Year!" ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # Pyth - 31 bytes The new key thing cost me too much. ``` ss.emr!FZk@@QsedthdfndeTrb8cz\# ``` [Test Suite](http://pyth.herokuapp.com/?code=ss.emr%21FZk%40%40QsedthdfndeTrb8cz%5C%23&test_suite=1&test_suite_input=%5B%22+%22%2C%22.%2C%21%22%2C%22abc%22%2C%22def%22%2C%22ghi%22%2C%22jkl%22%2C%22mno%22%2C%22pqrs%22%2C%22tuv%22%2C%22wxyz%22%5D%0A%234440555%23666888330%23999%2366688111%0A%5B%22+%22%2C%22.%2C%21%22%2C%22abc%22%2C%22def%22%2C%22ghi%22%2C%22jkl%22%2C%22mno%22%2C%22pqrs%22%2C%22tuv%22%2C%22wxyz%22%5D%0A%236%2333777+7779990%23222%234477744477778627777111%0A%5B%22+%22%2C%22.%2C%21%22%2C%22abc%22%2C%22def%22%2C%22ghi%22%2C%22jkl%22%2C%22mno%22%2C%22pqrs%22%2C%22tuv%22%2C%22wxyz%22%5D%0A%2344%2327+79990%2366%233390999332777111&debug=0&input_size=2). [Answer] # JavaScript, ~~105~~ 99 bytes ``` f= (s,a)=>s.replace(/#| ?((.)\2*)/g,(m,n,d)=>d?(l=a[d][n.length-1],x?l:l.toUpperCase()):(x=!x,''),x=1) a=[' ','.,!','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz'] F=s=>console.log( f(s,a) ) F('#4440555#666888330#999#66688111') F('#6#33777 7779990#222#4477744477778627777111'); F('#44#27 79990#66#3390#999#332777111'); ``` * 6 bytes off thanks @Neil. [Answer] # [Perl 6](https://perl6.org), ~~119~~ 97 bytes map based solution 119 bytes ``` ->$_,\a{my$u=0;[~] map {/'#'/??{$u+^=1;|()}()!!(&lc,&uc)[$u](a[.substr(0,1)].substr(.chars-1,1))},.comb(/(\d)$0*|'#'/)} ``` [Try it](https://tio.run/nexus/perl6#XZHLbtpAFIb3forji2CG@m5jsAwkUjetlHTVTQQ0MvYE3OJLPTaJS@Bh2ufIM@UR6LEpadXF/HMu8/1HM1NzBjtPjwKhxugz41UgCGkD13GyTiquVbkWbotNCFOQACRV0lURNVxFqDF7QF1vEtSv37aoaZajFt9LjltV71Afn5ofUtB69qI8ZjA9aTPlXl2E@7RR6qkZzI9LSMMC9kZf7htXV3ulfvdlagXPhB4IFUXS20Zqr47oXKmXJJzrvF7xqiSmatHlJdGjTVhyzcIaPah6lKcrYpBFTBVz8Nz60sPpIS9hm2SMEwp7ASA1UACUSZIVdTXDK5LJXDZ13V/AcjagXXfBB9DXZv026AqvLz@l15dfcHyLlAl7KlhUsbj1AKJ3qIEPiTMaUDp77Bwvk4I/jQt27r2ZdGDCoX0ucqbV//@Dqn9xDO8D4SDEeca0Cr8wydbBSXZd1xwOh7LneePx2HFM2ff9c2ZZFmgzkD7CTb5jcJfXoiTInuw4o9EIcOFJU7ZtG00wczsdjT273S7wLSvLBt5vyoRXachbB9eVbeQ72mvt/PNQx7H/AT@ERdHAJ/YIdywsRek3 "Perl 6 – TIO Nexus") substitution based solution 97 bytes ``` ->$_,\a{my$u=0;S:g/(\d)$0*|./{$0??(&lc,&uc)[$u](a[$0].substr($/.chars-1,1))!!($u+^=$/eq'#')x 0}/} ``` [Try it](https://tio.run/nexus/perl6#jZJLcptAEIb3nKKBKQkU3iAkgl5V2SRVTjbJxiUprjGMJRLxMMPIIrJ8mOQcPpOPoAzIclIpL7KYf3povr@7p4ZRAlvfiEKB8egLoVUoyPoEXWkzDPu0RmxshZ/frkxlEavI6t135a65R9Z0qnQ2kdZhkTpHbKnM8BxZS4Oya1qVCjKNaI1LqtuaraqiqCD25uvYVndgHcyDIKQ1zOJklVRUr3Idb4o1hjFIAJImGZrIFV9HXGNyw3W1Trh@@77hmmY51@K2pHyr2Jbr3a7@IYWNZyfKYwLjY9v/Ar/WvvFa8//ROzLJLR/9eYLjTV7CJskIVVTYCwCpyQUAjZKsYNWED6OM5rJlGMEClpPeVG3TC9qDrj7pNkH74enxp/T0@AseXiI0IruCRBWJGxNQjF6DmqHQFKkBtf4883AuFT4nztgp92LSggmF5maUE639e/Wq9gfn4VUoHIQ4z4he8eeQZKvwKHueZ/X7fdn3/eFw6LqWHATB6WTbNugTkD7ARb4lcJkzURJkX3bdwWAAfPE/LdlxHG7CT16rg6HvNNsZ/kjKsoZ36zKhVYpp4@B5ssP5lvYbu@BU1HWdv8D3uChq@ETu4JLgUpR@Aw "Perl 6 – TIO Nexus") ## Expanded: ``` -> # pointy block lambda $_, # input string \a # helper array { my $u = 0; S # substitute (implicit against 「$_」) :global / | (\d) $0* # digit followed by same digit | . # everything else /{ $0 # is 「$0」 set (digit) ?? # if so then (&lc,&uc)[$u]( # call either 「lc」 or 「uc」 a[$0] # get the value from the input array .substr( # select the correct character $/.chars - 1, 1 ) ) !! ( $u +^= $/ eq '#' # numeric xor $u if 「#」 was matched ) x 0 # string repeated zero times (empty string) }/ } ``` [Answer] # JavaScript ES6 - 124 bytes Golfed: ``` f=h=>a=>(o=c="")+a.match(/#|(.)\1*/g).forEach(e=>e==" "?0:e=="#"?c=!c:(n=h[e[0]][e.length-1])*(o+=c?n.toUpperCase():n))?o:0; ``` ``` f=h=>a=>(o=c="")+a.match(/#|(.)\1*/g).forEach(e=>e==" "?0:e=="#"?c=!c:(n=h[e[0]][e.length-1])*(o+=c?n.toUpperCase():n))?o:0; console.log(f([" ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"])("#4440555#666888330#999#66688111")); console.log(f([" ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"])("#6#33777 7779990#222#4477744477778627777111")); console.log(f([" ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"])("#44#27 79990#66#3390999332777111")); ``` Ungolfed: ``` f=(a,h)=>{ //out string o=""; //uppercase or lowercase (initialized as "" and then inverted in golfed version) c=0; //split it into array of instructions, which are sets of repeated characters, or # solely alone a.match(/#|(.)\1*/g).forEach((e)=>{ e==" "?0: e=="#" ? (c=!c) : ( ()=>{ //lambda added because two statements ungolfed, multiplied in the golfed version n=h[e[0]][e.length-1]; o+=c?n.toUpperCase():n; })() }) return o; } ``` [Answer] # JavaScript, 301 bytes ``` (a,b)=>{u="l";p=[];r="";a.split``.map((c,i)=>p.push(c!=a[i-1]?" "+c:c));p.join``.trim().replace(' ', ' ').split` `.map(l=>{if(l=="#"){u=(u=="l"?b.forEach((y,j)=>b[j]=y.toUpperCase())||"u":b.forEach((y,j)=>b[j]=y.toLowerCase())||"l")}else{if(l!=" "){r+=b[+l[0]][l.length-1]}else{r+=" "}}});return r} ``` ``` f=(a,b)=>{u="l";p=[];r="";a.split``.map((c,i)=>p.push(c!=a[i-1]?" "+c:c));p.join``.trim().replace(' ', ' ').split` `.map(l=>{if(l=="#"){u=(u=="l"?b.forEach((y,j)=>b[j]=y.toUpperCase())||"u":b.forEach((y,j)=>b[j]=y.toLowerCase())||"l")}else{if(l!=" "){r+=b[+l[0]][l.length-1]}else{r+=" "}}});return r} console.log(f("#4440555#666888330#999#66688111 ",[" ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"])); console.log(f("#6#33777 7779990#222#4477744477778627777111",[" ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"])); console.log(f("#44#27 79990#66#3390#999#332777111",[" ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"])); ``` I know this is very long, but this is the best I can. [Answer] # [V](https://github.com/DJMcMayhem/V), 60 bytes ``` Í /| ͨ䩨±*©/½a[submatch(1)][len(submatch(2))] Í| ò/# g~$x ``` (There's an unprintable `½<Ctrl+r>a`) [Try it online!](https://tio.run/nexus/v#PYw7EoJAEERzQk@AjAFYlsDussBZKAJEBH/4AfyV5Q24hYGEmpssB8MBqgzmdfVM9zR1Ket3qS7Fq36KSrzEeywqXXwHgZcVs22Qh4lqar63iVL1vyCa5mMHex8dpPgxujQNMMYMy7KAc@44DqUGuK7bO9M0JeBAqW3bMg4eDCCEYAcd62g7nLTSZRkDgskux9ui23@jlECfaTxFVibKdDJEBrMQOY8WyDhZIlfrDXKb7pD7wzFDyYsT8ny53hT/Bw "V – TIO Nexus") ### Explain ``` Í /| #Replace all " " with "|" ͨ䩨±*© #Replace all (\d)(\1*) /½ #With = ^Ra #(Inserts the passed array) [submatch(1)][len(submatch(2))] #Index into the array Í| #Replace all "|" with "" (second ò implied) ò ò #Recursively (until breaking) /# #Go to the next # g~$ #Toggle case until the of the line x #Delete current char (#) ``` ]
[Question] [ # Challenge description Let's call a two-dimentional, rectangular array (meaning its every subarray has the same length), a **grid**. Every unit of a grid is either an **empty space** or a **border**. In a grid of characters, empty space is represented by a single whitespace; any other character is treated as a border. Sample grids (`+`'s, `|`'s and `-`'s added for readability - *they are not part of the grid*): ``` +----+ | | | | | | | | | | +----+ an empty 4x5 grid +------+ | | | # | | # | +------+ a 6x3 grid with 2 borders +----------+ | | | | | ##### | | # # | | ## # <------ enclosed area | # # | | ###### | | | +----------+ a 10x8 grid with an enclosed area ``` Given a 2D grid and a pair of coordinates, fill the enclosed area surrounding the point represented by the coordinates. # Sample inputs / outputs **1)** ``` 0 0 +----------+ +----------+ | | |XXXXXXXXXX| | | -> |XXXXXXXXXX| | | |XXXXXXXXXX| +----------+ +----------+ ``` **2)** ``` 6 5 +-----------------+ +-----------------+ | | | | | | | | | ######## | | ######## | | # # | | #XXXXXXX# | | # #### | | #XXXX#### | | # # | | #XXXX# | | # # | -> | #XXXX# | | # # | | #XXXX# | | #### | | #### | | | | | | | | | +-----------------+ +-----------------+ ``` **3)** ``` 4 6 +-----------------+ +-----------------+ | | |XXXXXXXXXXXXXXXXX| | #### | |XXXX####XXXXXXXXX| | # # | -> |XXX# #XXXXXXXX| | #### | |XXXX####XXXXXXXXX| | | |XXXXXXXXXXXXXXXXX| +-----------------+ +-----------------+ ``` **4)** ``` 4 5 +-----------------+ +-----------------+ +-----------------+ | | | | | | | | | | | | | #### | | #### | | XXXX | | #### | -> | #### | or | XXXX | | #### | | #### | | XXXX | | | | | | | +-----------------+ +-----------------+ +-----------------+ ``` **5)** ``` 2 6 +----------------+ +----------------+ | | |XXXXXXXXXXXXXXXX| | | |XXXXXXXXXXXXXXXX| | | |XXXXXXXXXXXXXXXX| | | -> |XXXXXXXXXXXXXXXX| | | |XXXXXXXXXXXXXXXX| |BBBBBBBBBBBBBBBB| |BBBBBBBBBBBBBBBB| | | | | | | | | +----------------+ +----------------+ ``` # Notes * An empty grid is considered enclosed, i.e. borders are implicitly situated along the edges of the grid as well (see examples 1. and 5.), * A corner of an enclosed area doesn't need to be L-shaped. The following two areas are therefore equivalent: ``` #### ## # # # # # # == # # # # # # #### ## ``` * If a unit under the coordinates happens to be a border you can either leave the grid unchanged (as in example 4.) or treat it as an empty space, * You can choose any character for filler / empty space as long as you include this information in the submission, * If using a type other than `char` suits your purposes better, you can use `ints` (`0` for empty space, `1` for border) or `booleans` (`true` and `false` respectively) or any other type - just make sure to include this information in your submission, * Coordinates used in the examples above are 0-indexed `(row, column)` coordinates, as it's more convenient for two-dimensional array. If you want to use `(column, row)` (cartesian) system and/or non-0-indexed coordinates, specify it in your submission. * If you don't know where to start, check out [Wikipedia article on flood fill](https://en.wikipedia.org/wiki/Flood_fill) * Remember that this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so make your code as short as possible! [Answer] # MATLAB, ~~30~~ 7 bytes As we can use logical inputs instead of strings, we can use the bare function, as it is: ``` @imfill ``` This is an anonymous function. For the usage, we have to assume a name, e.g. `f=@`[`imfill`](http://ch.mathworks.com/help/images/ref/imfill.html). Then we can just evaluate it as `f(input,point)`, where `input` is a logical matrix, e.g. `[0,0;0,1]`, and `point` is a 2d-vector with 1-based coordinates, e.g. `[1,2]`. Old version working on strings: ``` @(a,p)[imfill(a>32,p)*3+32,''] ``` This anonymous function accepts the input as well as a vector with the coordinates (1-based index). The function `imfill` does exactly what we need, but operates only on binary images. That is why we convert the input matrix to a logical array (where `#` are the boundaries, and (spaces) are the void), performs the filling and is then converted back. (again `#` is filled, space is not filled). Thanks @LuisMendo for -~~1~~ byte. [Answer] # C, 162 bytes ``` w,l;char*d;f(z){z<0||z>l||d[z]^32||++d[z]&&f(z+1)+f(z-1)+f(z+w)+f(z-w);}main(c,v)char**v;{l=strlen(d=v[3]),w=strchr(d,10)-d+1,f(atoi(v[2])*w+atoi(v[1]));puts(d);} ``` Takes input from arguments (`./floodfill X Y grid`). Grid must contain `\n` or `\r\n` between each line, final newline is optional. Simplest way I've found to invoke from shell: ``` ./floodfill 1 0 "$(printf " \n###\n \n")" # or ./floodfill 1 0 "$(cat gridfile)" ``` Outputs to stdout, using `!` for the fill character. If the start position coincides with a `#`, makes no change. ### Breakdown: ``` // GCC is happy enough without any imports w,l; // Globals (line width, total length) char*d; // Global grid pointer f(z){ // "Fill" function - z=current cell z<0||z>l|| // Check if out-of-bounds... d[z]^32|| // ...or not empty ++d[z]&& // Fill cell... f(z+1)+f(z-1)+f(z+w)+f(z-w);// ...and continue in "+" pattern } main(c,v)char**v;{ // K&R style function to save 2 bytes l=strlen(d=v[3]), // Store grid & length w=strchr(d,10)-d+1, // Store width of grid (including newlines) f(atoi(v[2])*w+atoi(v[1])); // Parse X & Y arguments and invoke fill puts(d);} // Print the result ``` Note that this relies on modifying the input argument string, which is forbidden, so this may not work on all platforms (implicit declarations also make this non-standard). [Answer] # C - ~~263~~ ~~247~~ ~~240~~ 238 bytes *This is ~~first~~ ~~second~~ third version, I believe code can be shrinked too.* ``` m[99][99],x,y,a,b,c,n;f(v,w){if(m[v][w]==32){m[v][w]=88;f(v,w+1);f(v+1,w);f(v,w-1);f(v-1,w);}}main(){scanf("%d %d\n",&a,&b);for(;~(c=getchar());m[x++][y]=c,n=x>n?x:n)c==10&&++y&&(x=0);f(b+2,a+1);for(a=-1;++a<y*n+n;)putchar(m[a%n][a/n]);} ``` And readable version: ``` m[99][99], x, y, a, b, c, n; /* a, b - flood fill start coordinates v, w - recursive function start coordinates x, y - iterators c - character read m - map n - maximum map width found */ //Recursive flood function f( v, w ) { if ( m[v][w] == 32 ) //If field is empty (is ' '?) { m[v][w] = 88; //Put 'X' there f(v,w+1);f(v+1,w); //Call itself on neighbour fields f(v,w-1);f(v-1,w); } } main( ) { //Read coordinates scanf( "%d %d\n", &a, &b ); //Read map (put character in map, track maximum width) for ( ; ~( c = getchar( ) ); m[x++][y] = c, n = x > n ? x : n ) c == 10 && ++y && ( x = 0 ); //Flood map f( b + 2, a + 1 ); //Draw for ( a = -1; ++a < y * n + n; ) putchar( m[a % n][a / n] ); } ``` Compile and run: `gcc -o flood floodgolf.c && cat 1.txt | ./flood` Resources: * [Input format](http://paste.ubuntu.com/17907754/) * [Results](http://paste.ubuntu.com/17905672/) *Note: I'm working on `int` values. Every (32) is treated as empty space. Any other value is treated as border. Coordinates are in format `(row, column)`* [Answer] ## Python 2, 158 bytes [Try it online](https://tio.run/nexus/python2#rY4xD4IwEIX3/opu9MJh2hXhJ8DApKkdmgBJjZYGMaGLf72WiJMdzRvuy8u9exc0nvBcG@ueCwPS1LfBMg2k/YDkCkg/jLRjK3ooCTXji1dr1VBt@0i@ajeiWq5KelXus@bHmChEzGyQfwF9IXbIBZCOxXIgbjZ2yS42O1wnY9ldO/ZYZtQAIUgpMCGF0ee7fv2N/@Gn76f@UUjj6hs). Simple recursive solution ``` a,X,Y=input() M=len(a) N=len(a[0]) def R(x,y): if~0<x<M and~0<y<N and a[x][y]:a[x][y]=0;R(x-1,y);R(x+1,y);R(x,y-1);R(x,y+1) R(X,Y) print'\n'.join(map(str,a)) ``` 0-indexed in row-column order 1 - empty space, 0 - filled space Takes input as array of arrays of 1 and 0, and two numbers [Answer] # [Perl 5](https://www.perl.org/), 129 + 1 (-a) = 130 bytes ``` sub f{my($r,$c)=@_;$a[$r][$c]eq$"&&($a[$r][$c]=X)&&map{f($r+$_,$c);f($r,$c+$_)}-1,1}@a=map[/./g],<>;f$F[0]+1,$F[1]+1;say@$_ for@a ``` [Try it online!](https://tio.run/##hY3BC4IwGMXv/RWSH0OZUwfZZRk7desejCFLXASZpnUQ9V9vrTwEEvQuj/fjve@ri@aSGNM@jo7uy86DJoDcT3nGQAlopIBcFjdYIuR9QXrwESpV3Wvbx5C9J0xPWxv9kdCAjlyltiOiMDrJYLNlGnYilpgG1ql11qqOQ@boquHKmJWzXmAyF14MzlzDxFyrGftk939vfu/H32dV38/VtTVkn4QxjQ1RLw "Perl 5 – Try It Online") **How?** ``` sub f{ # recursive subroutine my($r,$c)=@_; # taking row and column as inputs $a[$r][$c]eq$"&& # using Boolean short circuit as an 'if' statement to # check if the current position in the global array is blank ($a[$r][$c]=X)&& # then setting it to 'X' map{f($r+$_,$c);f($r,$c+$_)}-1,1 # and checking the four surrounding spaces } # -a command line option implicitly splits the first line into the @F array @a=map[/./g],<>; # put the input in a 2-D array f$F[0]+1,$F[1]+1; # start the fill at the given position, correcting for # Perl's 0 based arrays say@$_ for@a # output the resulting pattern ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 53 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [©g_#®ć©d®IgIнg‚‹«PisD®нèD®θèi2®θǝ®нǝs1Ý‚D(«ε®+}ìë\s ``` Input-coordinate as a wrapped pair of integers \$[[x,y]]\$, and input-grid as a matrix of 1s and 0s for empty spaces and borders respectively. Flood-fills with 2s. [Try it online](https://tio.run/##yy9OTMpM/f8/@tDK9HjlQ@uOtB9amXJonWe654W96Y8aZj1q2HlodUBmscuhdRf2Hl4BpM7tOLwi0whEH58LEjw@t9jw8NzDTUDFLhqHVp/bemiddu3hNYdXxxT/j/U6tPt/dLSZjmlsLFd0tKEOARirQ5IaAzSIXQ2qfgO8atBMwqEGt3uoo8YQ00dkhQ9uNbH/dXXz8nVzEqsqAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@ZoOMS6nVot05lgtL/6EMr0@OVD6070n5oZcqhdRHpERf2pj9qmPWoYeeh1QGZxS6H1l3Ye3gFkDq34/CKTCMQfXwuSPD43GLDw3MPNwEVu2gcWn1u66F12rWH1xxeHVP8X0kvTMm/tARoI9BCHZBdh7bZ/48GAkMdLDBWh0RxoES0gY5BLJChgMtQYgzCocYADWJXg6rfAK8aNJNwqMHtHuqoMcT0EVnhg1sNKGLMdEzJiRgcTkNSg9OLJJpDyAMmOmaxYAbNEhY91BDyoymtcg891BjoEIDUswsUWkbgFBH7X1c3L183J7GqEgA). (The `]J»` in the footer of the single TIO is used to pretty-print the output-matrix. Feel free to remove it to see the actual output.) **Explanation:** Despite being a codegolf language, 05AB1E's matrix builtins aren't too useful here. And 05AB1E's modular indexing is only a disadvantage for a challenge like this, where you want to stay within the dimension of the grid. ``` [ # Start an infinite loop: © # Store the list of coordinates in variable `®` (without # popping) # (which is the first implicit input in the first iteration) g_ # If it's empty: # # Stop the infinite loop ©ć # Extract head of `®`; pop and remainder-list and first # coordinate separated to the stack © # Store this coordinate as new variable `®` (without popping) d # Check [x>=0,y>=0] Ig # Push the amount of rows of the input-matrix Iнg # Push the amount of columns of the input-matrix ‚ # Pair them together ® ‹ # Check [x<rowCount,y<columnCount] « # Merge the two lists together Pi # Pop, and if all were truthy (so [x,y] is within bounds): s # Swap so the matrix is at the top D # Duplicate this matrix ®нè # Pop and get the x'th (of coordinate `®`) row of the matrix D # Duplicate this row ®θè # Pop and get the y'th (of coordinate `®`) cell of this row i # If this value is 1: 2®θǝ # Insert a 2 at this y'th cell of the row ®нǝ # Insert this modified x'th row into the matrix s # Swap so the list of coordinates is at the top again 1Ý # Push [0,1] ‚ # Bifurcate (Duplicate & Reverse copy) and pair: # [[0,1],[1,0]] D(« # Duplicate, negate, merge: [[0,1],[1,0],[0,-1],[-1,0]] ε®+} # Add coordinate `®` to each pair: # [[x,y+1],[x+1,y],[x,y-1],[x-1,y]] ì # Prepend-merge it at the front of the coordinates-list ë # Else: the value was 0 or 2 instead: \ # Discard the duplicated row s # And swap so the coordinates list is at the top again ] # Close the open if-statements and infinite loop \ # Discard the empty coordinates list # (after which the matrix is output implicitly as result) ``` [Answer] # Java, 112 bytes ``` int f(int[][]m,int x,int y){try{if(m[x][y]==0)f(m,x+f(m,x,y+f(m,x-f(m,x,y+--m[x][y]),y)),y);}finally{return 1;}} ``` Input as a matrix of 0s and 1s for empty spaces and borders respectively. Modifies the input-matrix directly, and flood-fills with -1s. Uses the same flood-fill recursive method I've used in [this answer](https://codegolf.stackexchange.com/a/188896/52210), [this answer](https://codegolf.stackexchange.com/a/154383/52210), and [this answer](https://codegolf.stackexchange.com/a/238484/52210) of mine. [Try it online.](https://tio.run/##zVZLb6wgGN33V3xhJRGNNm0X2klzl3fRR9KldUGnTstcByeIVmL87VMcmem8TG0zvRkJKHI4HA7ox5SW1Jm@/FuMU5rncEsZh/oMIJdUsvGCcQkTS5dRHMUz0larZalwLYWq2cSaRVUcqXg08rCukMpelkR1d2dVcxwDxEThNofNhHGapqoWiSwEBz9smgXAvHhO2dgIgDJjLzDTqqxHKRh/jWKguBUIIJNcWjx5ByOve2uu2iMHUkOOhPmENMQnPg5/qui7Iw/A@zvpa/w2rz8YvzPCAPww/b@L9/adOar//fjNXXNFLn911/TMsQff6@GR@Ie6ckGuTvJbOhX8UBcvT8rFU8H75Iv0X/8A52avN2freNuFu@WimQXTsU/HvWo78i5ZHlUuk5mbFdKd68goU26hv3xeyDyAaoTsykYElH5QZi/MdZyV6qHFWh2raTjEdF9ITRUAMpiJ6dLG8h/wHZ7oJsPqjNERHZ6ihaK1nky0XYCNvJBdd73cNOGv8i1kto2N0XsMU33ecQvJUvePEFTlrsy6g4WZQsRibFs7jI5/gwgKUPzEEd4QUFIBInsPtkR/aisD3YjXS76npbz2btAdCkpD2e9c612bm8UH) **Explanation:** ``` // Recursive method with integer matrix & x,y parameters and integer return-type int f(int[][]m,int x,int y){ try{if(m[x][y]==0) // If the current cell-value is 0: --m[x][y] // Decrement the current cell-value to -1 f(m,x,y+...)// Recursive call west f(m,x-...,y) // Recursive call north f(m,x,y+...) // Recursive call east f(m,x+...,y); // Recursive call south }finally{ // Catch and swallow any ArrayIndexOutOfBoundsExceptions // (shorter than manual if-checks) return 1;} // Always result in 1, so we use it to our advantage to // save bytes here by nesting, instead of having four // loose calls to each direction) ``` ]
[Question] [ Inspired by [this question](https://puzzling.stackexchange.com/questions/33263/correct-way-to-add-22-to-4-to-get-82) which was further inspired by [this one](https://puzzling.stackexchange.com/questions/33204/correct-way-to-add-22-to-4-to-get-given-value), write a program which takes two integers and adds them in a unique way, by performing an OR operation on the segments used to display them in a 7-segment display. For reference, the digits are represented in the following way: ``` _ _ _ _ _ _ _ _ | | | _| _| |_| |_ |_ | |_| |_| |_| | |_ _| | _| |_| | |_| _| ``` Note that the 1 uses the two segments on the right, not the left. There are two special characters that can be produced this way which are not numbers. See the addition table below: ``` | 0 1 2 3 4 5 6 7 8 9 --+-------------------- 0 | 0 0 8 8 8 8 8 0 8 8 1 | 0 1 a 3 4 9 8 7 8 9 2 | 8 a 2 a 8 8 8 a 8 8 3 | 8 3 a 3 9 9 8 3 8 9 4 | 8 4 8 9 4 9 8 Q 8 9 5 | 8 9 8 9 9 5 6 9 8 9 6 | 8 8 8 8 8 6 6 8 8 8 7 | 0 7 a 3 Q 9 8 7 8 9 8 | 8 8 8 8 8 8 8 8 8 8 9 | 8 9 8 9 9 9 8 9 8 9 ``` Useful observations: * Any digit plus itself equals itself * 8 plus any digit equals 8 * 2 plus 1, 3, or 7 equals the letter 'a' (must be lower-case) * 4 plus 7 equals either 'q' or 'Q', your choice * Numbers should be right-aligned, so the digits should be added from right to left. If one number has more digits than the other, the extra digits at the beginning should be unchanged. There are no leading 0's, unless the number is exactly 0. * All numbers will be 0 or greater. You don't need to handle a '-' sign. (Mainly because there's no good fit for the sum of a '-' and a '1' or '7'.) Your program should accept 2 integers in any format you choose, and output a string containing their "sum" when calculated in this manner. This is code-golf, so your program should be as small as possible. ## Examples: * Input: 12345, 123. Output: 12389 * Input: 88888, 42. Output: 88888 * Input: 0, 23. Output: 28 * Input: 120, 240. Output: a80 * Input: 270, 42. Output: 2Q8 (or 2q8) * Input: 1234567890, 1234567890. Output: 1234567890 [Answer] # Bash + Common Linux utilities, 80 ``` s=~0my3[_p^?{}s h()(tr 0-9 $s<<<$1|xxd -p) dc -e$[0x`h $1`|0x`h $2`]P|tr $s 0-9aQ ``` Note the `^?` in the source should be replaced with an ASCII 0x7f character. The string `s` is each 7 segment digit `0-9, a, Q` encoded with each segment corresponding to a bit of an ASCII char. The `h()` function transliterates the input number from decimal to the encoding specified by `s`, then outputs the result as a raw hex string. The two resulting raw hex strings are `OR`ed together using regular bash arithmetic, then output by `dc`'s `P` command as a bytestream. This bytestream is then transliterated back to decimal + a + Q and output. Note also that when using the `<<<` bash herestring construct in function `h()` a newline is implicitly appended to the redirected string. This doesn't matter - it is simply translated to `0x0a` at the end of each hex string; when the two hex numbers are `OR`ed together, the result is still `0x0a` in the last char which doesn't get transliterated and thus simply translates back to a newline which is output after the result. ### Test output: ``` $ for testcase in \ > "12345 123" \ > "88888 42" \ > "0 23" \ > "1234 56789" \ > "4 7"; do > ./7segadd.sh $testcase > done 12389 88888 28 58a89 Q $ ``` [Answer] # Python 2, 155 bytes ``` def f(a,b):exec"a=[ord('?(u|j^_,♥~'[int(c)])for c in a];a=max(len(b)-len(a),0)*[0]+a;a,b=b,a;"*2;print`['214567q3a980'[(c|d)%13]for c,d in zip(a,b)]`[2::5] ``` Replace the `♥` with a `DEL` character (0x7F). Calling `f("12345", "123")` prints `12389`. [Answer] ## JavaScript (ES6), ~~158~~ 144 bytes ``` f=(s,t)=>t[s.length]?f(t,s):s[t.length]?f(s,' '+t):s.replace(/./g,(c,i)=>"540q9361278a"[(a[c]|a[t[i]])%13],a=[119,20,47,31,92,91,123,22,127,95]) ``` Saved 14 bytes by shamelessly stealing @Lynn's `%13` trick. ``` f=(s,t)=>t[s.length]?f(t,s):s[t.length]?f(s,' '+t):s.replace(/./g,(c,i)=>"540q9361278a"[(a[c]|a[t[i]])%13],a=[119,20,47,31,92,91,123,22,127,95]) ;o.textContent=[...s="0123456789"].map(c=>f(c.repeat(10),s)).join` `; ``` ``` <pre id=o></pre> ``` [Answer] # Java, 170 bytes This is terribly long... but this is Java anyway. ``` String A(int a,int b){String c="|HgmY=?h}oy",r="";for(;a>0|b>0;a/=10,b/=10)r="0123456789aq".charAt(c.indexOf((a>0?c.charAt(a%10):0)|(b>0?c.charAt(b%10):0)))+r;return r;} ``` ## Full program, with ungolfed code ``` public class Q80716 { String A(int a,int b){String c="|HgmY=?h}oy",r="";for(;a>0|b>0;a/=10,b/=10)r="0123456789aq".charAt(c.indexOf((a>0?c.charAt(a%10):0)|(b>0?c.charAt(b%10):0)))+r;return r;} String Add(int a,int b){ String c = "|HgmY=?h}oy", d = "0123456789aq"; String r = ""; for(;a>0|b>0;a/=10,b/=10){ r = d.charAt(c.indexOf((a>0?c.charAt(a%10):0)|(b>0?c.charAt(b%10):0))) + r; } return r; } public static void main(String[]args){ int[][] testcases = new int[][]{ {12345,123}, {88888,42}, {0,23}, {120,240}, {270,42}, {1234567890,1234567890} }; for(int i=0;i<testcases.length;i++){ System.out.println(new Q80716().Add(testcases[i][0],testcases[i][1])); System.out.println(new Q80716().A(testcases[i][0],testcases[i][1])); } } } ``` ## All output (all duplicated once) ``` 12389 88888 23 a80 2q8 1234567890 ``` ]
[Question] [ Consider three number sequences, \$A\$, \$B\$ and \$C\$: * \$A\$: A sequence based on recurrence relations, \$f(n) = f(n-1)+f(n-2)\$, starting with \$f(1) = 3, f(2) = 4\$. So, the sequence begins like this: \$3, 4, 7, 11, 18, 29, 47, 76, ...\$ * \$B\$: The [composite numbers](https://oeis.org/A002808), that is all integers that aren't primes (or 1): \$4, 6, 8, 9, 10, 12, 14, 15, 16, ...\$ * \$C\$: The digits of \$\pi\$: \$3, 1, 4, 1, 5, 9, 2, 6, 5, ...\$ Given a positive integer \$N < 50\$, either as function argument or STDIN, return the decimal value of the fraction \$\frac{A(N)}{B(N)}\$ with \$C(N)\$ digits after the decimal point. Normal rules for rounding applies (round up if the \$N+1\$'th digit is 5 or higher). If the Nth digit of \$\pi\$ is zero, an integer should be printed. [scientific notation / Standard form](https://en.wikipedia.org/wiki/Scientific_notation) is accepted for numbers higher than 1000. This is code golf, so the shortest answer in bytes wins. Some examples: ``` N = 1: 0.750 N = 2: 0.7 N = 3: 0.8750 N = 4: 1.2 N = 6: 2.416666667 N = 10: 11.056 N = 20: 764.8750 ``` Of course, standard code golf rules applies. The function must terminate in less than two minutes on any modern laptop. [Answer] # Pyth, ~~60~~ ~~57~~ 58 bytes ``` .[K`.Rchu,eGsGQjT7e.ftPZQ)Je/u+/*GHhyHy^TQr^T3ZZT\0+xK\.hJ ``` [Test harness](https://pyth.herokuapp.com/?code=.%5BK%60.Rchu%2CeGsGQjT7e.ftPZQ%29Je%2Fu%2B%2F%2aGHhyHy%5ETQr%5ET3ZZT%5C0%2BxK%5C.hJ&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A6%0A10%0A20%0A33%0A49&debug=0) It's pretty straightforward - calculate pi, the fibonacci series and the composites, round to C(n) digits, pad to C(n) digits plus the location of the decimal point digits, done. A(n): `hu,eGsGQjT7` B(n): `e.ftPZQ)` C(n): `e/u+/*GHhyHy^TQr99ZZT` 60 -> 57: Cleaned up the n = 1 special case in the pi calculation. 57 -> 58: Wasn't using high enough precsion for pi for the entire input range - increased 99 iterations to 1000 iterations. **Note on rounding:** This uses Python's "nearest even" rounding system, rather than the OP specified "towards infinity" system. However, the difference only matters if the digits immediately following the rounding point are `5000...`, e.g. 1.25 rounded to 1 digit. I checked the input range, and this never happens, so the correct result is alway returned. [Answer] # PowerShell, 420 Bytes (ayyyyyyyy) 378 Bytes ``` param($n);[int[]]$p="03141592653589793238462643383279502884197169399375"-Split'';$a=@(0,3,4);for($i=3;$i-lt50;$i++){$a+=$a[$i-1]+$a[$i-2]};$c=[char[]]"00001010111010111010111011111010111110111010111011111011111010111110111";$b=@(0);for($i=4;$i-le70;$i++){if($c[$i]-eq'1'){$b+=$i}};[double]$r=$a[$n]/$b[$n];$q=$p[$n+1];$s="";(0..($q-1))|%{$s+="0"};([math]::Round($r,$q,[MidpointRounding]::AwayFromZero)).ToString("0.$s") ``` Thanks to [isaacg](https://codegolf.stackexchange.com/a/56013/42963) for saving 41 bytes, for calculating how the question does rounding. Means I didn't have to include the horrendous `[MidpointRounding]::AwayFromZero` and didn't need to explicitly cast as a `[double]`. This one was great fun! ### Expanded: ``` # Take input N param($n) # First digits of pi, stored as integer array [int[]]$p="03141592653589793238462643383279502884197169399375"-Split'' # Fibonacci sequence A(N) $a=@(0,3,4) for($i=3;$i-lt50;$i++){ $a+=$a[$i-1]+$a[$i-2] } # Zero-indexed bitmask for if the n-th integer is composite (1) or not (0) $c=[char[]]"00001010111010111010111011111010111110111010111011111011111010111110111" # Populate B(N) as an array using the $c mask $b=@(0) for($i=4;$i-le70;$i++){ if($c[$i]-eq'1'){ $b+=$i } } # Calculation Time! $r=(a($n))/$b[$n] # A small golf, as $p[$n+1] gets used a couple times $q=$p[$n+1] # Need to generate a string of zeroes for padding $s="" (0..($q-1))|%{$s+="0"} # Round the number, then send it to a string so we get the necessary number of zeroes ([math]::Round($r,$q)).ToString("0.$s") ``` Recursion in PowerShell is ... slow, shall we say, so we have to build `A(N)` the other direction and store it into an array, then index it. --- ### OLD Also, holy cow, did the output requirements kill this. PowerShell defaults to rounding-to-nearest a/k/a banker's rounding, which necessitates utilizing the extraordinarily verbose `[MidpointRounding]::AwayFromZero` to switch [rounding styles](https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx#Midpoint). On top of that, we then needing to pad trailing zeroes, if any. Those two requirements combined to turn the last couple of lines from **20 Bytes** `[math]::Round($r,$q)` to **102 Bytes** (from the `$s=""` to `+$s)`) ... wow. [Answer] # Javascript (ES6), 302 bytes One word: Unfinished. ``` x=>{a=[0,3,4],b=[0],c='03141592653589793238462643383279502884197169399375';for(i=1;i<x;a[i+2]=a[i]+a[++i]);for(i=1,p=[];++i<70;v=p.every(x=>i%x),(v?p:b).push(i));r=''+Math.round(a[x]/b[x]*(l=Math.pow(10,c[x])))/l;if(x==33)return r;r.indexOf`.`<0&&(r+='.');while(!r[r.indexOf`.`+ +c[x]])r+='0';return r} ``` The first 49 digits of pi are stored in a string, and the other two sequences are auto-generated. This has been golfed about halfway; I'm (almost) sure I could squeeze another 50 bytes out of it. Works for all the test cases, and should work for the rest. Crashes on anything more than 49 or less than 0 (it should never encounter these situations anyway). I especially like its result for 0: ``` NaN. ``` [Answer] # Octave, ~~276~~ 236 Bytes First of all I thought it would be cool to make use of some unlimited accuracy in these mathematical tools (and to refresh some knowledge about it) so I started writing some algorithms and then ended finally found out that the `pi` value is not so accurate that I will have to use the array again. So again, no great success: ``` function c(A)p="3141592653589793238462643383279502884197169399375";f=ones (1,50);f(1)=3;f(2)=4;for i=3:53f(i)=f(i-1)+f(i-2);end i=0;x=1;while i<A x++;for j=2:x/2 if mod(x,j)==0 i++;break;end end end printf(["%." p(A) "f\n"],f(A)/x);end ``` Still quite readable, isn't it? ## Usage copy-paste function into octave, call function `c` with argument of required value: ``` >>> c(1) 0.750 >>> c(49) 407880480.04348 ``` Optimizations: * Substitute `endif`, `endfor` and similar with `end` which works the same way * decreasing variable `i` by one save one byte * remove `num2str(str2num(p(A)))` nonsense :) ]
[Question] [ # Challenge Find the shortest regex that 1. validates, i.e. matches, every possible date in the [*Proleptic*](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar) Gregorian calendar (which also applies to all dates before its first adoption in 1582) and 2. does not match any invalid date. ## Output Output is therefore truthy or falsey. ## Input Input is in any of 3 expanded [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) date formats – no times. The first two are `±YYYY-MM-DD` (year, month, day) and `±YYYY-DDD` (year, day). Both need special-casing for the leap day. They are naively matched separately by these extended RXs: ``` (?<year>[+-]?\d{4,})-(?<month>\d\d)-(?<day>\d\d) (?<year>[+-]?\d{4,})-(?<doy>\d{3}) ``` The third input format is `±YYYY-wWW-D` (year, week, day). It is the complicated one because of the complex leap week pattern. ``` (?<year>-?\d{4,})-W(?<week>\d\d)-(?<dow>\d) ``` A basic, but insufficient validity check for all three combined would look something like this: ``` [+-]?\d{4,}-((0\d|1[0-2])-([0-2]\d|3[01]) ↩ |([0-2]\d\d|3[0-5]\d|36[0-6]) ↩ |(W([0-4]\d|5[0-3])-[1-7])) ``` # Conditions A **leap year** in the Proleptic Gregorian calendar contains the **leap day** `…-02-29` and thus it is 366 days long, hence `…-366` exists. This happens in any year whose ordinal number is divisible by 4, but not by 100 unless it’s also divisible by 400. **Year zero** exists in this calendar and it is a leap year. A **long year** in the ISO week calendar contains a 53rd week, which one could term a “**leap week**”. This happens in all years where 1 January is a Thursday and additionally in all leap years where it’s a Wednesday. It turns out to occur every 5 or 6 years usually, in a seemingly irregular pattern. A year has at least 4 digits. Years with more than 10 digits do not have to be supported, because that’s close enough to the age of the universe (ca. 14 billion years). The leading plus sign is optional, although the actual standard suggests it should be required for years with more than 4 digits. Partial or truncated dates, i.e. with less than day-precision, must not be accepted. The parts of the date notation, e.g. the month, do *not* have to be matched by a group that could be referenced. # Rules This is code-golf. The shortest regex without executed code wins. **Update:** You may use features like recursion and balanced groups, but will be fined by a factor of 10, which the character count then is multiplied with! This is now different from the rules in [Hard code golf: Regex for divisibility by 7](https://codegolf.stackexchange.com/questions/3503/hard-code-golf-regex-for-divisibility-by-7). Earlier answer wins a tie. # Test cases ## Valid tests ``` 2015-08-10 2015-10-08 12015-08-10 -2015-08-10 +2015-08-10 0015-08-10 1582-10-10 2015-02-28 2016-02-29 2000-02-29 0000-02-29 -2000-02-29 -2016-02-29 200000-02-29 2016-366 2000-366 0000-366 -2016-366 -2000-366 2015-081 2015-W33-1 2015-W53-7 2015-08-10 ``` The last one is optionally valid, i.e. leading and trailing spaces in input strings may be trimmed. ## Invalid formats ``` -0000-08-10 # that's an arbitrary decision 15-08-10 # year is at least 4 digits long 2015-8-10 # month (and day) is exactly two digits long, i.e. leading zero is required 015-08-10 # year is at least 4 digits long 20150810 # though a valid ISO format, we require separators; could also be interpreted as a 8-digit year 2015 08 10 # separator must be hyphen-minus 2015.08.10 # separator must be hyphen-minus 2015–08–10 # separator must be hyphen-minus 2015-0810 201508-10 # could be October in the year 201508 2015 - 08 - 10 # no internal spaces allowed 2015-w33-1 # letter ‘W’ must be uppercase 2015W33-1 # it would be unambiguous to omit the separator in front of a letter, but not in the standard 2015W331 # though a valid ISO format we require separators 2015-W331 2015-W33 # a valid ISO date, but we require day-precision 2015W33 ``` ## Invalid dates ``` 2015 # a valid ISO format, but we require day-precision 2015-08 # a valid ISO format, but we require day-precision 2015-00-10 # month range is 1–12 2015-13-10 # month range is 1–12 2015-08-00 # day range is 1–28 through 31 2015-08-32 # max. day range is 1–31 2015-04-31 # day range for April is 1–30 2015-02-30 # day range for February is 1–28 or 29 2015-02-29 # day range for common February is 1–28 2100-02-29 # most century years are non-leap -2100-02-29 # most century years are non-leap 2015-000 # day range is 1–365 or 366 2015-366 # day range is 1–365 in common years 2016-367 # day range is 1–366 in leap years 2100-366 # most century years are non-leap -2100-366 # most century years are non-leap 2015-W00-1 # week range is 1–52 or 53 2015-W54-1 # week range is 1–53 in long years 2016-W53-1 # week range is 1–52 in short years 2015-W33-0 # day range is 1–7 2015-W33-8 # day range is 1–7 ``` [Answer] # PCRE: ~~603~~ ~~940~~ ~~947~~ ~~949~~ 956 bytes ``` ^\s*[+-]?(\d{4,10}-((00[1-9]|0[1-9]\d|[12]\d\d|3[0-5]\d|36[0-5])|(0[1-9]|1[0-2])-(0[1-9]|1\d|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31|W(0[1-9]|[1-4]\d|5[0-2])-[1-7]))|((\d{2,8}([13579][26]|[2468][048]|0[48])|(\d{0,6}([13579][26]|[02468][048])00))-(366|02-29))|(\+?\d{0,6}(([02468][048]|[13579][26])([26]0|71|[38]2|[49]3|[05]4|15|[27]6|37|[48]8|[09]9)|([02468][159]|[13579][37])(50|[16]1|[27]2|33|[48]4|[09]5|[15]6|67|[27]8|[38]9)|([02468][26]|[13579][048])([48]0|[09]1|[15]2|63|[27]4|[38]5|[49]6|[05]7|[16]8|29)|([02468][37]|[13579][159])([27]0|[38]1|[49]2|[05]3|[16]4|25|[37]6|87|[049]8|[5]9))|-\d{0,6}(([02468][048]|[13579][26])(0[28]|1[39]|24|3[06]|4[17]|5[28]|6[49]|75|8[06]|9[27])|([02468][159]|[13579][37])(0[49]|15|2[06]|3[27]|4[38]|54|6[05]|7[16]|8[28]|9[39])|([02468][26]|[13579][048])(0[51]|16|2[28]|3[39]|44|5[06]|6[17]|7[28]|8[49]|95)|([02468][37]|[13579][159])(0[17]|1[28]|2[49]|35|4[06]|5[27]|6[38]|74|8[05]|9[16])))-W53-[1-7]\s*$ ``` **Note:** Some pairs of parentheses could possibly be dropped. * [Test valid dates and formats](https://regex101.com/r/eE4gA3/1) * [Test invalid dates](https://regex101.com/r/oD8uE9/1) * [Test invalid formats](https://regex101.com/r/eJ7xL8/1) ## Divisibility by 4 The multiples of 4 repeat in a simple pattern: * 00, 04, 08, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96, … This, or the inverse, could be matched by a likewise simple regular expression for all two-digit numbers with leading zero: ``` (?<divisible-by-four>[13579][26]|[02468][048]) (?<not-divisible-by-four>[13579][048]|[02468][26]|\d[13579]) ``` It could save some bytes if there were character classes for odd and even digits (like `\o` and `\e`), but there are not as far as I’m aware. ## Years That expression would suffice for the Julian calendar, but the Gregorian leap year detection needs to special-case trailing `00` with century divisibility by 4: ``` (?<leap-year>[+-]?(\d{2,8}([13579][26]|[2468][048]|0[48])|(\d{0,6}([13579][26]|[02468][048])00)) (?<year>[+-]?\d{4,10}) ``` This would need some changes to outlaw `-0000-…` (along with `-00000-…` etc.) or to enforce the plus sign for positive year numbers with more than 4 digits. The latter would be rather simple, but is not required: ``` (?<leap-year>([+-]?(\d\d([13579][26]|[2468][048]|0[48])|(([13579][26]|[02468][048])00)))|([+-](\d{3,8}([13579][26]|[2468][048]|0[48])|(\d{1,6}([13579][26]|[02468][048])00)))) (?<year>([+-]?\d{4})|([+-]\d{5,10})) ``` ## Day of year Three-digit ordinal dates are rather simple, we just have to restrict `-366` to leap years (and disallow `-000`). ``` (?<ordinal-day>-(00[1-9]|0[1-9]\d|[12]\d\d|3[0-5]\d|36[0-5])) (?<ordinal-leap-day>-366) ``` ## Day of month of year The seven months with 31 days are `01` January, `03` March, `05` May, `07` July, `08` August, `10` October and `12` December. Just four month have exactly 30 days, `04` April, `06` June, `09` September and `11` November. Finally, `02` February has 28 days in common years and 29 in leap years. We can first construct a regular expression for the always valid days `01` through `28` and then add special cases. ``` (?<month-day>-(0[1-9]|1[0-2])-(0[1-9]|1\d|2[0-8])) (?<short-month-day>-(0[13-9]|1[0-2])-(29|30)) (?<long-month-day>-(0[13578]|1[02])-31) (?<month-leap-day>-02-29) ``` Neither month nor day must be `00` which was not covered by an earlier version. ## Day of week of year All years include 52 weeks ``` (?<week-day>-W(0[1-9]|[1-4]\d|5[0-2])-[1-7]) ``` [Long years that include `-W53`](https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year) repeat in a 400-year cycle, e.g. add 2000 for the current cycle and find the current year in the third entry: * 004, 009, 015, 020, 026, 032, 037, 043, 048, 054, 060, 065, 071, 076, 082, 088, 093, 099, * 105, 111, 116, 122, 128, 133, 139, 144, 150, 156, 161, 167, 172, 178, 184, 189, 195, * 201, 207, 212, 218, 224, 229, 235, 240, 246, 252, 257, 263, 268, 274, 280, 285, 291, 296, * 303, 308, 314, 320, 325, 331, 336, 342, 348, 353, 359, 364, 370, 376, 381, 387, 392, 398. Each of the four centuries has a unique pattern. There is probably not much room for optimization. 1. `04|09|15|20|26|32|37|43|48|54|60|65|71|76|82|88|93|99` 2. `05|11|16|22|28|33|39|44|50|56|61|67|72|78|84|89|95` 3. `01|07|12|18|24|29|35|40|46|52|57|63|68|74|80|85|91|96` 4. `03|08|14|20|25|31|36|42|48|53|59|64|70|76|81|87|92|98` We can group by either digit to find out that we can save two bytes or so: * Grouped by 1st digit. 1. `0[49]|15|2[06]|3[27]|4[38]|54|6[05]|7[16]|8[28]|9[39]` 2. `05|1[16]|2[28]|3[39]|44|5[06]|6[17]|7[28]|8[49]|95` 3. `0[17]|1[28]|2[49]|35|4[06]|5[27]|6[38]|74|8[05]|9[16]` 4. `0[38]|14|2[05]|3[16]|4[28]|5[39]|64|7[06]|8[17]|9[28]` * Grouped by 2nd digit. 1. `[26]0|71|[38]2|[49]3|[05]4|15|[27]6|37|[48]8|[09]9` 2. `50|[16]1|[27]2|33|[48]4|[09]5|[15]6|67|[27]8|[38]9` 3. `[48]0|[09]1|[15]2|63|[27]4|[38]5|[49]6|[05]7|[16]8|29` 4. `[27]0|[38]1|[49]2|[05]3|[16]4|25|[37]6|87|[049]8|[5]9` The century number is easily matched again by a variation of the divisibility expression. * 1st century: `[02468][048]|[13579][26]` * 2nd century: `[02468][159]|[13579][37]` * 3rd century: `[02468][26]|[13579][048]` * 4th century: `[02468][37]|[13579][159]` So far, this does only work for positive years, including year zero. For negative years, we have to subtract the values from the list above from 400 and do the rest again, because the pattern is not symmetric. 1. `02|08|13|19|24|30|36|41|47|52|58|64|69|75|80|86|92|97` 2. `04|09|15|20|26|32|37|43|48|54|60|65|71|76|82|88|93|99` 3. `05|11|16|22|28|33|39|44|50|56|61|67|72|78|84|89|95` 4. `01|07|12|18|24|29|35|40|46|52|57|63|68|74|80|85|91|96` or 1. `0[28]|1[39]|24|3[06]|4[17]|5[28]|6[49]|75|8[06]|9[27]` 2. `0[49]|15|2[06]|3[27]|4[38]|54|6[05]|7[16]|8[28]|9[39]` 3. `0[51]|16|2[28]|3[39]|44|5[06]|6[17]|7[28]|8[49]|95` 4. `0[17]|1[28]|2[49]|35|4[06]|5[27]|6[38]|74|8[05]|9[16]` ## Putting it all together ### Any year ``` [+-]?\d{4,10}-((00[1-9]|0[1-9]\d|[12]\d\d|3[0-5]\d|36[0-5])|(0[1-9]|1[0-2])-(0[1-9]|1\d|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31|W(0[1-9]|[1-4]\d|5[0-2])-[1-7]) ``` ### Leap-day year additions ``` [+-]?(\d{2,8}([13579][26]|[2468][048]|0[48])|(\d{0,6}([13579][26]|[02468][048])00))-(366|02-29) ``` ### Leap-week year additions ``` +?\d{0,6}(([02468][048]|[13579][26])([26]0|71|[38]2|[49]3|[05]4|15|[27]6|37|[48]8|[09]9)|([02468][159]|[13579][37])(50|[16]1|[27]2|33|[48]4|[09]5|[15]6|67|[27]8|[38]9)|([02468][26]|[13579][048])([48]0|[09]1|[15]2|63|[27]4|[38]5|[49]6|[05]7|[16]8|29)|([02468][37]|[13579][159])([27]0|[38]1|[49]2|[05]3|[16]4|25|[37]6|87|[049]8|[5]9))-W53-[1-7] -\d{0,6}(([02468][048]|[13579][26])(0[28]|1[39]|24|3[06]|4[17]|5[28]|6[49]|75|8[06]|9[27])|([02468][159]|[13579][37])(0[49]|15|2[06]|3[27]|4[38]|54|6[05]|7[16]|8[28]|9[39])|([02468][26]|[13579][048])(0[51]|16|2[28]|3[39]|44|5[06]|6[17]|7[28]|8[49]|95)|([02468][37]|[13579][159])(0[17]|1[28]|2[49]|35|4[06]|5[27]|6[38]|74|8[05]|9[16]))-W53-[1-7] ``` [Answer] # PCRE (also Perl), 778 bytes ``` /^([+-]?\d*((([02468][048]|[13579][26]|\d\d(?!00))([02468][048]|[13579][26]))|\d{4}(?!-02-29|-366))-((?!02-3|(0[469]|11)-31|000)((0[1-9]|1[012])-(0[1-9]|[12]\d|30|31)|([012]\d\d|3([0-5]\d|6[0-6])))|(W(?!00)([0-4]\d|51|52)-[1-7]))|((\+?\d*([02468][048]|[13579][26])|-\d*([02468][159]|[13579][37]))(04|09|15|20|26|32|37|43|48|54|60|65|71|76|82|88|93|99)|(\+?\d*([02468][159]|[13579][37])|-\d*([02468][26]|[13579][048]))(05|11|16|22|28|33|39|44|50|56|61|67|72|78|84|89|95)|(\+?\d*([02468][26]|[13579][048])|-\d*([02468][37]|[13579][159]))(01|07|12|18|24|29|35|40|46|52|57|63|68|74|80|85|91|96)|\+?\d*(([02468][37]|[13579][159])(03|14|20|25|31|36|42|53|59|64|70|76|81|87|92|[049]8))|-\d*(([02468][048]|[13579][26])([059]2|08|13|19|24|30|36|41|47|58|64|69|75|80|86|97)))-W53-[1-7])$/ ``` I have included the delimiters in the byte count to show that it doesn't rely on any flags. It does **not** match valid dates within other strings, such as `1234-56-89 2016-02-29 9876-54-32`. The regex is shorter by not checking for a maximum of 10 digits for the year. Extended with comments: ``` /^ # Start of pattern (no leading space) ( # YEAR # Optional sign and digits if more than 4 in year [+-]?\d*( # Years 00??, 04??, 08?? ... 92??, 96?? OR dd not followed by 00 # followed by 00, 04, 08 ... 92, 96 OR (([02468][048]|[13579][26]|\d\d(?!00))([02468][048]|[13579][26])) | # any year not followed by 29 February or day 366 \d{4}(?!-02-29|-366) # dash ) - # MONTH AND DAY, or DAY OF YEAR, or WEEK OF YEAR AND DAY if less than 53 weeks ( # Not (30 or 31 February OR 31 April, June, September or December OR day 0) (?!02-3|(0[469]|11)-31|000) ( # Month dash day OR (0[1-9]|1[012]) - (0[1-9]|[12]\d|30|31) | # 001-299 OR 300-359 OR 360-366 ([012]\d\d | 3([0-5]\d | 6[0-6])) # OR ) | ( # W 01-52 dash 1-7 W(?!00)([0-4]\d|51|52)-[1-7] ) # OR ) | # WEEK OF YEAR AND DAY only if week is 53 ( # Optional plus and extra year digits \+?\d*( # Years +0303 - +9998 ([02468][37]|[13579][159])(03|14|20|25|31|36|42|53|59|64|70|76|81|87|92|[049]8) ) | # Minus and extra year digits -\d*( # Years -0002 - -9697 ([02468][048]|[13579][26])([059]2|08|13|19|24|30|36|41|47|58|64|69|75|80|86|97) ) | # Years +0004 - +9699, -0104 - -9799 (\+?\d*([02468][048]|[13579][26])|-\d*([02468][159]|[13579][37])) (04|09|15|20|26|32|37|43|48|54|60|65|71|76|82|88|93|99) | # Years +0105 - +9795, -0205 - -9895 (\+?\d*([02468][159]|[13579][37])|-\d*([02468][26]|[13579][048])) (05|11|16|22|28|33|39|44|50|56|61|67|72|78|84|89|95) | # Years +0201 - +9896, -0301 - -9996 (\+?\d*([02468][26]|[13579][048])|-\d*([02468][37]|[13579][159])) (01|07|12|18|24|29|35|40|46|52|57|63|68|74|80|85|91|96) # dash W 53 dash 1-7 )-W53-[1-7] # End of pattern (no trailing space) )$/x ``` ]
[Question] [ ## Background An [L-system](http://en.wikipedia.org/wiki/L-system) (or Lindenmayer system) is a parallel rewriting system that, among other things, can be easily used to model fractals. This question concerns **deterministic, context-free L-systems**. These consists of an alphabet of symbols, an initial axiom string and a set of rewrite rules mapping each alphabet symbol to a new string. The rules are applied to the axiom in parallel, generating a new string. This process is then repeated. For example, the system with the axiom "A" and the rules A=ABA;B=BBB generates the sequence of strings "ABA", "ABABBBABA", "ABABBBABABBBBBBBBBABABBBABA", etc. For conciseness, we don't explicitly mention the alphabet when defining the L-system. Furthermore, any symbol without an explicit rewrite rule is assumed to be unchanged (i.e. the default rule for a symbol A is A=A). L-systems can be visualised using a form of turtle graphics. By convention, the turtle starts facing to the right. A string is then drawn by iterating over its symbols: an F means "draw forward one unit", a G means "move forward one unit", a + means "turn left one angle unit" and a - means "turn right one angle unit". All other symbols in the string are ignored. For the purpose of this question, the angle units are assumed to always be 90°. ## Task Given a specification of any L-system and a number of iterations, your program should output an ASCII rendering of the resulting string (as described above) using box-drawing characters. * The parameters are passed in as a space-separated string comprising the axiom, rewrite rules (as a ;-separated list of equations) and number of rewrite iterations. For example, the input "F F=FGF;G=GGG 2" generates the string "FGFGGGFGF" and hence draws four lines with appropriate gaps. * The symbols used by the L-system can be any ASCII character apart from space and semicolon. There is at most one explicit rule specified per symbol (with the default rewrite rule being the identity mapping as described above). * You can assume that the output will always contain at least one F. * The output should use the following [UNICODE box-drawing characters](http://en.wikipedia.org/wiki/Box_Drawing) to represent the visualization: ─ (U+2500), │ (U+2502), ┌ (U+250C), ┐ (U+2510), └ (U+2514), ┘ (U+2518), ├ (U+251C), ┤ (U+2524), ┬ (U+252C), ┴ (U+2534), ┼ (U+253C), ╴ (U+2574), ╵ (U+2575), ╶ (U+2576) and ╷ (U+2577). See below for examples. * The output should not contain empty lines above the topmost box character or below the bottommost one. It should also not contain any spaces to the left of the leftmost box characer or to the right of the rightmost one. Lines with trailing spaces that don't extend beyond the rightmost box character are allowed. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument. Results should be printed to STDOUT (or closest alternative), saved to a file or returned as a string. ## Examples ``` # Cantor dust >> "F F=FGF;G=GGG 0" ╶╴ >> "F F=FGF;G=GGG 1" ╶╴╶╴ >> "F F=FGF;G=GGG 2" ╶╴╶╴ ╶╴╶╴ >> "F F=FGF;G=GGG 3" ╶╴╶╴ ╶╴╶╴ ╶╴╶╴ ╶╴╶╴ # Koch curve >> "F F=F+F−F−F+F 1" ┌┐ ╶┘└╴ >> "F F=F+F-F-F+F 2" ┌┐ ┌┘└┐ ┌┘ └┐ ┌┼┐ ┌┼┐ ╶┘└┘ └┘└╴ ``` Other examples to test your program with include: ``` # Dragon curve >> "FX X=X+YF+;Y=-FX-Y n" # Hilbert curve >> "A A=-BF+AFA+FB-;B=+AF-BFB-FA+ n" # Sierpinski carpet >> "F F=F+F-F-F-G+F+F+F-F;G=GGG n" ``` The first two of which look as follows (produced using @edc65's answer): ![enter image description here](https://i.stack.imgur.com/EZMdum.png) ![enter image description here](https://i.stack.imgur.com/BxzRbm.png) You can test out any of the systems at [this page](http://www.kevs3d.co.uk/dev/lsystems/). ## Scoring Shortest code (in bytes) wins. Standard rules apply. ## Miscellania This challenge was inspired by [Draw a Random Walk with Slashes](https://codegolf.stackexchange.com/questions/48297/draw-a-random-walk-with-slashes). In fact, it's possible to represent a random walk as an L-system if we extend the system to allow multiple rules per symbol, with the expansion chosen *non-determistically* during rewriting. One formulation is: ``` "F F=FF;F=F+F;F=F++F;F=F+++F" ``` Another common extension, often used when modeling plants, is to interpret the [ and ] characters as pushing and popping the current position and angle. Most plants use angles smaller than 90°, but here is one example that doesn't: ``` "FAX X=[-FAX][FAX][+FAX];A=AFB;B=A" ``` Neither of these examples need to be supported in this challenge. This challenge is also similar to ["Sorry, young man, but it's Turtles all the way down!"](https://codegolf.stackexchange.com/questions/9341/sorry-young-man-but-its-turtles-all-the-way-down). However, that challenge used line rendering rather than ASCII and allowed a more flexible syntax. [Answer] # JavaScript (ES6), 440 bytes (410 chars) ``` F=p=>([a,r,n]=p.split(' '),t=>{r.split(';').map(x=>r[x[0]]=x.slice(2),r={});for(;n--;)a=[...a].map(c=>r[c]||c).join('');u=x=y=0,g=[];for(c of a)c=='+'?[t,u]=[u,-t]:c=='-'?[u,t]=[t,-u]:c<'F'|c>'G'?0:((y+=u)<0?(g=[[],...g],++y):g[y]=g[y]||[],(x+=t)<0?(g=g.map(r=>[,...r]),++x):0,c>'F'?0:g[g[f=t?0.5:2,y][x]|=(3+t-u)*f,y-u][x-t]|=(3+u-t)*f)})(1)||g.map(r=>[for(c of r)' ╶╴─╵└┘┴╷┌┐┬│├┤┼'[~~c]].join('')).join('\n') ``` *Less golfed* ``` F=p=>{ [a,r,n]=p.split(' '), r.split(';').map(x=>r[x[0]]=x.slice(2),r={}); // set rules for(;n--;)a=[...a].map(c=>r[c]||c).join(''); // build string t=1,u=x=y=0, // start pos 0,0 start direction 1,0 g=[[]]; // rendering in bitmap g for(c of a) c=='+'?[t,u]=[u,-t] // left turn :c=='-'?[u,t]=[t,-u] // right turn :c=='F'|c=='G'?( // move or draw (y+=u)<0?(g=[[],...g],++y):g[y]=g[y]||[], // move vertical, enlarge grid if needed (x+=t)<0?(g=g.map(r=>[,...r]),++x):0, // move horizontal, enlarge grid if needed c=='F'&&( // draw: set bits f=t?0.5:2, g[y][x]|=(3+t-u)*f, g[y-u][x-t]|=(3+u-t)*f ) ):0; // render bits as box characters return g.map(r=>[' ╶╴─╵└┘┴╷┌┐┬│├┤┼'[~~c]for(c of r)].join('')).join('\n') } ``` **Test** Code snippet to test (in Firefox) ``` F=p=>([a,r,n]=p.split(' '),t=>{r.split(';').map(x=>r[x[0]]=x.slice(2),r={});for(;n--;)a=[...a].map(c=>r[c]||c).join('');u=x=y=0,g=[];for(c of a)c=='+'?[t,u]=[u,-t]:c=='-'?[u,t]=[t,-u]:c<'F'|c>'G'?0:((y+=u)<0?(g=[[],...g],++y):g[y]=g[y]||[],(x+=t)<0?(g=g.map(r=>[,...r]),++x):0,c>'F'?0:g[g[f=t?0.5:2,y][x]|=(3+t-u)*f,y-u][x-t]|=(3+u-t)*f)})(1)||g.map(r=>[for(c of r)' ╶╴─╵└┘┴╷┌┐┬│├┤┼'[~~c]].join('')).join('\n') fs=18;(Z=d=>(Result.style.fontSize=(fs+=d)+'px',Result.style.lineHeight=fs+'px'))(0) ``` ``` #Result { font-size: 10px } #Param { width: 400px } ``` ``` Param: <input type=text id=Param /> <button onclick="Result.innerHTML=F(Param.value)">Start</button><br> Output <button onclick="Z(-2)">Z-</button> <button onclick="Z(2)">Z+</button> <br> <pre id=Result></pre> ``` [Answer] # Haskell, 568 bytes ``` import Data.List.Split p=splitOn l=lookup m=maximum n=minimum o[h,x]=(h,x) Just x#_=x _#x=x g[s,r,i]=iterate((\c->lookup[c](map(o.p"=")(p";"r))#[c])=<<)s!!read i u v@(a,x,y,d,e)c|c=='+'=(a,x,y,-e,d)|c=='-'=(a,x,y,e,-d)|c=='G'=(a,x+d,y+e,d,e)|c=='F'=(s(x,y)(d%e)a:s(x+d,y+e)(d?e)a:a,x+d,y+e,d,e)|1<2=v s p n a=(p,n+(l p a)#0) 1%0=2;0%1=8;-1%0=1;0%(-1)=4 1?0=1;0?1=4;-1?0=2;0?(-1)=8 f z=unlines[[" ╴╶─╷┐┌┬╵┘└┴│┤├┼"!!(l(x,y)q#0)|x<-[n a..m a]]|y<-[m b,m b-1..n b]]where a=map(fst.fst)q;b=map(snd.fst)q;(q,_,_,_,_)=foldl u([],0,0,1,0)$g$p" "z ``` Test run: ``` *Main> putStr $ f "F F=F-F+F+F-F 3" ╶┐┌┐ ┌┐┌┐ ┌┐┌┐ ┌┐┌╴ └┼┘ └┼┼┘ └┼┼┘ └┼┘ └┐ ┌┼┼┐ ┌┼┼┐ ┌┘ └┐┌┼┘└┘ └┘└┼┐┌┘ └┼┘ └┼┘ └┐ ┌┘ └┐┌┐ ┌┐┌┘ └┼┘ └┼┘ └┐ ┌┘ └┐┌┐ ┌┐┌┘ └┼┘ └┼┘ └┐ ┌┘ └┐┌┘ └┘ ``` How it works: * rewriting (function `g`): I parse the rules into an association list (letter -> replacement string) and repeatedly map it over the axiom. * creating the path (function `u` for a single step): I do not store the path in a matrix but in another association list with (x,y) positions as the keys and bit patterns of the 4 basic blocks (`╴`,`╶`,`╷` and `╵`) as values. Along the way I keep track of the current position and direction. * drawing the path (function `f`): first I calculate the max/min dimensions from the path list and then I iterate over [max y -> min y] and [min x -> max x] and lookup the blocks to draw. [Answer] # ES7, 394 chars, 424 bytes ``` F=p=>([a,r,n]=p.split` `,t=>{r.split`;`.map(x=>r[x[0]]=x.slice(2),r={});for(;n--;)a=[...a].map(c=>r[c]||c).join``;u=x=y=0,g=[];for(c of a)c=='+'||c=='-'?[t,u]=[u,-t]:c<'F'|c>'G'?0:((y+=u)<0?(g=[[],...g],++y):g[y]=g[y]||[],(x+=t)<0?(g=g.map(r=>[,...r]),++x):0,c>'F'?0:g[g[f=t?0.5:2,y][x]|=(3+t-u)*f,y-u][x-t]|=(3+u-t)*f)})(1)||g.map(r=>[for(c of r)'╶╴─╵└┘┴╷┌┐┬│├┤┼'[~~c]].join``).join` ` ``` ]
[Question] [ Your goal is to output an ASCII art pie chart. This is code-golf, so the shortest program (counting the bytes of the source code, not the characters) wins. No external softwares or APIs are allowed. Only the native ones of each language. The starting angle and the direction (clockwise/anticlockwise) of the circle are not important. The output can look oval because the height of a character is always superior to its width. The "background" (characters at the left or the right of the pie) must be spaces. As input, you have three variables (please post the code for initializing it. The initialization of these variables is not counted in your score) : * `k` : Array of characters. Each character is the one which has to be used on the pie chart * `v` : Array of floats. It's the percentage of each character. The length of `v` is equal to the length of `k`. The sum of it's elements is always 1.0 * `r` : Integer > 1. It's the radius of the pie chart. Bonus : Subtract 20% of your score if your can output an incomplete pie (in case the \$(\sum\_{i=1}^{|v|} v\_i)<1\$). [Answer] ## JavaScript, 259 ``` d=r*2;M=Math;R=M.round;p=[];for(y=0;y<d;y++){p[y]=[];for(x=0;x<d;x++)p[y][x]=" "}t=0;i=-1;for(f=0;f<1;f+=1/(r*20)){if(f>t)t+=v[++i];a=M.PI*2*f;for(j=0;j<r;j++)p[R(M.sin(a)*j)+r][R(M.cos(a)*j)+r]=k[i]}s="";for(y=0;y<d;y++){for(x=0;x<d;x++)s+=p[y][x];s+="\n";}s ``` Works in Firefox scratchpad. ## First example Input : ``` var k = ["#", "+", "$", "X"]; var v = [0.2, 0.4, 0.15, 0.25]; var r = 10; ``` Output : ``` $$$XXXX $$$$$XXXXXX $$$$$$XXXXXXX $$$$$$$XXXXXXXX +$$$$$$$XXXXXXXXX ++$$$$$$XXXXXXXXX +++++$$$$XXXXXXXXXX ++++++$$$XXXXXXXXXX +++++++$$XXXXXXXXXX +++++++++XXXXXXXXXX ++++++++++######### +++++++++++######## +++++++++++######## ++++++++++####### +++++++++++###### ++++++++++##### +++++++++#### ++++++++### +++++++ ``` ## Second example : Input : ``` var k = ["A", "B", "C" ]; var v = [0.5, 0.25, 0.25]; var r = 5; ``` Output : ``` BBCCC BBBCCCC BBBBCCCCC BBBBCCCCC BBBBCCCCC AAAAAAAAA AAAAAAAAA AAAAAAA AAAAA ``` [Answer] # Python: 255 chars - 20% = 204 ``` from math import* def s(k,v,a): if not v:return ' ' if a<v[0]:return k[0] return s(k[1:],v[1:],a-v[0]) def p(k,v,r): d=range(-r,r) for y in d: t="" for x in d: if x*x+y*y<r*r: a=atan2(y,x)/pi/2+.5 t=t+s(k,v,a) else:t=t+" " print t ``` Examples: ``` >>> pie.p("ABCD", [0.25,0.125,0.125,0.125],8) AAABBBB AAAAABBBBBB AAAAAABBBBBCC AAAAAABBBBCCC AAAAAAABBBCCCCC AAAAAAABBCCCCCC AAAAAAABCCCCCCC DDDDDDDD DDDDDD DDDDD DDDD DD D >>> >>> pie.p(".$!@", [0.3,0.3,0.3,0.1],6) .....$$ ......$$$ ......$$$$$ ......$$$$$ ......$$$$$ @@@@@$$$$$$ @@@@!!!$$$$ @@@!!!!!$$$ @!!!!!!!!!$ !!!!!!!!! !!!!!!! >>> ``` ]