text
stringlengths
180
608k
[Question] [ (Note: this is an easier spin-off of my previous challenge [Find the Infinity Words!](https://codegolf.stackexchange.com/questions/96516/find-the-infinity-words), which is a spin-off of my other previous challenge [Find the Swirling Words!](https://codegolf.stackexchange.com/questions/95507/find-the-swirling-words) :) ) ### Definition of a *Wavy Word*: 1. If you connect with curves all the characters of a *Wavy Word* on the alphabet (A-Z) you obtain the path of a wave continuously going toward right or toward left and never changing direction, like in the diagrams below. 2. A *Wavy Word* can be: * *Raising* if each consecutive character is at the right (on the alphabet) of the previous one. * *Decreasing* if each consecutive character is at the left (on the alphabet) of the previous one. 3. All the even connection must be down, all the odd connections must be up. 4. You can ignore upper/lowercase or consider/convert all to upper case or all to lower case. 5. The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols. 6. If a word has double characters, like "SPOON", you must collapse the doubles to one character: "SPOON" > "SPON" (because if you go from O to O is zero distance). 7. The *Wavy Words* will contain at least 3 distinct characters (even after doubles collapsing). ### Here there are some examples: [![enter image description here](https://i.stack.imgur.com/bDWvz.png)](https://i.stack.imgur.com/bDWvz.png) ### Task: Write a full program or function that will take a word from standard input and will output if it is a *Wavy Word* or not, and in positive case, output if it is *raising* or *decreasing*. The output can be `True/False/Null`, `2/1/0`, `1/Null/0`, `-1/0/1`, `NO/WR/WD`, etc, you decide how to represent it. ### Test cases: ``` WAVY WORDS: ADEPT, BEGIN, BILL, BOSS, BOOST, CHIMP, KNOW, SPONGE, SPOON, TROLL, WOLF ADEPT > YES > RAISING BEGIN > YES > RAISING BILL > YES > RAISING BOSS > YES > RAISING BOOST > YES > RAISING CHIMP > YES > RAISING KNOW > YES > RAISING SPONGE > YES > DECREASING SPOON > YES > DECREASING TROLL > YES > DECREASING WOLF > YES > DECREASING NOT WAVY WORDS: WATCH, EARTH, NINON, FOO, BAR, WAVE, SELECTION, YES, NO, DEFINITION, WATER, WINE, CODE, AAAHHHH, I, MM, ABCA ``` ### Rules: * Shortest code wins. ### Optional Task: Find, as a list, as many *Wavy Words* as you can in an English dictionary, and the longest as well. You can take for example as reference the complete list of English words [here](https://github.com/dwyl/english-words). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~11~~ 9 bytes (Thanks to Adnan) ``` Dg2›iÇü‹Ù ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RGcy4oC6acOHw7zigLnDmQ&input=ZWJh) **Wavy Cases:** **0** - Decreasing Wavy **1** - Increasing Wavy **Not Wavy Cases:** **[0,1]** - Not wavy, initially decreasing, but then has an increase/equality that broke the pattern. **[1,0]** - Not wavy, initially increasing, but then has a decrease/equality that broke the pattern **Input String** - Not possible to be wavy in the first place due to length. **Explanation:** ``` Dg2›iÇü‹Ù # Full program D # Push 2 copies of input. g2›i # If length is greater than 2. Ç # Push ASCII values for all characters in the string. ü # Push pairwise array. ‹ # Vectorize 1 if negative difference, 0 if positive difference. Ù # Uniquify using right most unique values first. # Else just print the string back, letting them know it's not valid input. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OIṠḟ0µL’aQ ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=T0nhuaDhuJ8wwrVM4oCZYVE&input=&args=U09NRVRISU5H)** or [run all test cases](http://jelly.tryitonline.net/#code=T0nhuaDhuJ8wwrVM4oCZYVEKxbzDh-KCrA&input=&args=WyJBREVQVCIsIkJFR0lOIiwiQklMTCIsIkJPU1MiLCJCT09TVCIsIkNISU1QIiwiS05PVyIsIlNQT05HRSIsIlNQT09OIiwiVFJPTEwiLCJXT0xGIiwiV0FUQ0giLCJFQVJUSCIsIk5JTk9OIiwiRk9PIiwiQkFSIiwiV0FWRSIsIlNFTEVDVElPTiIsIllFUyIsIk5PIiwiREVGSU5JVElPTiIsIldBVEVSIiwiV0lORSIsIkNPREUiLCJBQUFISEhIIiwiSSIsIk1NIl0) Returns: `[1]` for wavy increasing `[-1]` for wavy decreasing something else otherwise (`[]`, `[0]`, `[-1,1]`, or `[1,-1]`) (Declared as unnecessary: For a single value for each `OIṠḟ0µL’aQS` (11 bytes) will return `1`, `-1`, and `0` respectively.) ### How? ``` OIṠḟ0µL’aQ - Main link: s O - cast to ordinals I - incremental differences Ṡ - sign (-1 for decreasing, 0 for no change, 1 for increasing) ḟ0 - filter out zeros µ - monadic chain separation L - length ’ - decremented a - and Q - unique items ``` [Answer] ## Python 2, 54 bytes ``` lambda s:[2<len(set(s))<s[::b]==sorted(s)for b in-1,1] ``` Takes input as a list of characters. Outputs: ``` [False, True] for ascending [True, False] for descending [False, False] for neither ``` Checks if the sorted input string equals its original or reverse. Does so by slicing with step sizes of 1 and -1. At the same time, we check whether the word has at least 2 distinct letters. If "exit with error" can be used an output for the neither case, we can go down to 51 bytes: ``` lambda s:[s,s[::-(len(set(s))>2)]].index(sorted(s)) ``` [Answer] # Python 3, ~~77~~ 75 bytes ``` lambda x:(len(set(x))>2)*(list(x)==sorted(x)or(list(x)==sorted(x)[::-1])*2) ``` Assumes all letters are of the same case. Returns: * `0` if not wavy * `1` if forwards wavy * `2` if backwards wavy Removed unnecessary spaces thanks @ETHproductions [Answer] # R, 96 95 bytes ``` function(x,d=diff(rle(utf8ToInt(x))$v))if(any(d>0)&any(d<0)|sum(1|d)<2)3 else`if`(all(d<1),2,1) ``` Returns: * `1` for wavy and raising * `2` for wavy and decreasing * `3` for non-wavy **Explained** * `d=diff(rle(utf8ToInt(x))$v)`: Generates a variable `d` by first converting the string into it's `ASCII` values using `utf8ToInt` which conveniently returns a vector. Subsequently perform run length encoding using `rle`. `rle(...)$v` returns the non-repeating values of the sequence (i.e. collapsing all runs). Finally take the difference. * `if(any(d>0)&any(d<0)|sum(1|d)<2)3`: If at least one of the differences are positive and at least one negative, or if the difference sequence has less than `2` elements (equivalent to the original word having less than 3 characters), the word is non-wavy and return `3` * `else``if``(all(d<1),2,1)`: Else if all differences are negative, return `2` for wavy and decreasing, else return `1` for wavy and raising. --- Try all the test cases at [R-fiddle](http://www.r-fiddle.org/#/fiddle?id=f2fccZ1G) (note that it's named such that it can be vectorized for the test cases). [Answer] ## JavaScript (ES6), ~~84~~ 81 bytes ``` s=>(new Set(t=[...s]).size>2)*(!t.some((c,i)=>c>s[i+1])-!t.some((c,i)=>c<s[i+1])) ``` Assumes the input is all in the same case. Returns `1` for raising wavy, `-1` for decreasing wavy, `0` or `-0` (both are falsy) for not wavy. Edit: Saved 3 bytes thanks to @RobertHickman. [Answer] ## Javascript (ES6), 84 80 78 bytes ``` i=>new Set(s=[...i]).size>2?[i,s.reverse().join``].indexOf(s.sort().join``):-1 ``` Where wavy increasing is 0, decreasing is 1, and -1 is not wavy. Thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil) for helping me save 2 bytes. [Answer] # Pyth, 12 bytes ``` x*<2lrQ8_BQS ``` [Try it online.](http://pyth.herokuapp.com/?code=x*%3C2lrQ8_BQS&input=%22BEGIN%22&test_suite_input=%22ADEPT%22%0A%22BEGIN%22%0A%22BILL%22%0A%22BOSS%22%0A%22BOOST%22%0A%22CHIMP%22%0A%22KNOW%22%0A%22SPONGE%22%0A%22SPOON%22%0A%22TROLL%22%0A%22WOLF%22%0A%22WATCH%22%0A%22EARTH%22%0A%22NINON%22%0A%22BAR%22%0A%22WAVE%22%0A%22SELECTION%22%0A%22YES%22%0A%22DEFINITION%22%0A%22WATER%22%0A%22WINE%22%0A%22CODE%22%0A%22NO%22%0A%22FOO%22&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=x*%3C2lrQ8_BQS&input=%22BEGIN%22&test_suite=1&test_suite_input=%22ADEPT%22%0A%22BEGIN%22%0A%22BILL%22%0A%22BOSS%22%0A%22BOOST%22%0A%22CHIMP%22%0A%22KNOW%22%0A%22SPONGE%22%0A%22SPOON%22%0A%22TROLL%22%0A%22WOLF%22%0A%22WATCH%22%0A%22EARTH%22%0A%22NINON%22%0A%22BAR%22%0A%22WAVE%22%0A%22SELECTION%22%0A%22YES%22%0A%22DEFINITION%22%0A%22WATER%22%0A%22WINE%22%0A%22CODE%22%0A%22NO%22%0A%22FOO%22&debug=0) [Answer] # Python 2, ~~53~~ ~~52~~ 50 bytes Expects input enclosed in quotes, e.g. `"watch"` As unnamed lambda: ``` lambda s:(sum(map(cmp,s[1:],s))+1)/min(len(s)-1,3) ``` Sums the sign of difference between each letters and integer-divides by `len-1`. If all were `1` (increasing) the sum is `len-1` it displays `1`, similar for decreasing `-1` and for mixed `1`,`-1` the sum is smaller than `len-1` so it displays `0`. -1 byte for changing `cmp,s[1:],s[:-1])` to `cmp,s[1:],s)+1` [Answer] # Ruby, 54 bytes ``` ->w{c=w.chars.uniq;c==(s=c.sort)?2:(c==s.reverse)?1:0} ``` Returns `0` if the word is not wavy, `1` if backwards wavy, and `2` if forwards wavy. [Answer] # Groovy - 56 bytes ``` {d=it[0];c=[0]*3;it.each{a->c[(a<=>d)]=1;d=a};c[1..-1]} ``` Outputs `[1,0]` for raising wavy, `[0,1]` for decreasing wavy, `[0,0]` for single character input or `[1,1]` for non-wavy. *NOTE:* Assumes input is either a String or a char[] and all letters are of the same case. [Answer] # PHP, 96 Bytes ``` for(;($t=$argv[1])[++$i];)$s+=$r[]=$t[$i-1]<=>$t[$i];echo(max($r)-min($r)<2)*(0<=>$s)*(1<$s*$s); ``` or 98 Bytes ``` $s=str_split($t=$argv[1]);sort($s);echo(-($t==strrev($j=join($s)))|$t==$j)*!!count_chars($t,3)[2]; ``` 0 not wavy 1 raising -1 decreasing [Answer] # PHP, 100 bytes ``` $n=$m=$l=str_split($argv[1]);sort($n);rsort($m);echo(($n==$l)-($m==$l))*(count(array_unique($l))>2); ``` Returns: * `-1` for wavy, decreasing. * `0` for not wavy. * `1` for wavy, raising. [Answer] # C, 164 bytes ``` main(){char s[99];scanf("%s",s);char *c=&s;int p=*c;while(*c^0){if(p>*c){if(c-&s[0]>1)return 0;while(*c^0){if(p<*c)return 0;p=*c;c++;}return 2;}p=*c;c++;}return 1;} ``` Returns 0 if not wawy, 1 if wawy and raising, 2 if decreasing. [Answer] ## Racket 321 bytes ``` (let*((ld(λ(sl)(for/list((i(sub1(length sl))))(-(list-ref sl(add1 i))(list-ref sl i)))))(l(ld(remove-duplicates(map (λ(x)(char->integer x))(string->list s)))))(am andmap)(N"Not WAVY")(d displayln))(cond[(<(length l)2)(d N)][(am(λ(x)(>= x 0))l) (d"YES; RAISING")][(am(λ(x)(<= x 0))l)(d"YES; DECREASING")][else(d N)]))) ``` Ungolfed: ``` (define (f s) (let* ((ld (lambda(sl) ; sub-fn to get differences in list elements (for/list ((i (sub1(length sl)))) (- (list-ref sl (add1 i)) (list-ref sl i) ) ))) (l (ld (remove-duplicates (map (lambda(x) (char->integer x)) (string->list s))))) (am andmap) (N "Not WAVY") (d displayln)) (cond [(< (length l) 2)(d N)] [(am (lambda(x) (>= x 0)) l) (d "YES; RAISING")] [(am (lambda(x) (<= x 0)) l) (d "YES; DECREASING")] [else (d N)] ))) ``` Testing: ``` (f "ADEPT"); > YES > RAISING (f "BEGIN"); > YES > RAISING (f "BILL"); > YES > RAISING (f "BOSS"); > YES > RAISING (f "BOOST"); > YES > RAISING (f "CHIMP"); > YES > RAISING (f "KNOW"); > YES > RAISING (f "SPONGE"); > YES > DECREASING (f "SPOON"); > YES > DECREASING (f "TROLL"); > YES > DECREASING (f "WOLF"); > YES > DECREASING (f "WATCH") (f "EARTH") (f "NINON") (f "FOO") (f "BAR") (f "WAVE") (f "SELECTION") ``` Output: ``` YES; RAISING YES; RAISING YES; RAISING YES; RAISING YES; RAISING YES; RAISING YES; RAISING YES; DECREASING YES; DECREASING YES; DECREASING YES; DECREASING Not WAVY Not WAVY Not WAVY Not WAVY Not WAVY Not WAVY Not WAVY ``` [Answer] # Java 7, ~~254~~ 240 bytes ``` import java.util.*;int c(String s){char[]a=s.toCharArray(),x=a.clone();Arrays.sort(x);return s.replaceAll("(.)\\1{1,}","$1").length()<3?0:Arrays.equals(a,x)|Arrays.equals(x,(new StringBuffer(s).reverse()+"").toCharArray())?a[0]>a[1]?1:2:0;} ``` Outputs `0` if the input string isn't wavy, `1` if it's a raising wave, and `2` if it's a decreasing wave. **Ungolfed & test code:** [Try it here.](https://ideone.com/AABR2A) ``` import java.util.*; class M{ static int c(String s){ char[] a = s.toCharArray(), x = a.clone(); Arrays.sort(x); return s.replaceAll("(.)\\1{1,}", "$1").length() < 3 ? 0 : Arrays.equals(a, x) | Arrays.equals(x, (new StringBuffer(s).reverse()+"").toCharArray()) ? a[0] > a[1] ? 1 : 2 : 0; } public static void main(String[] a){ System.out.print(c("ADEPT") + ", "); System.out.print(c("BEGIN") + ", "); System.out.print(c("BILL") + ", "); System.out.print(c("BOSS") + ", "); System.out.print(c("BOOST") + ", "); System.out.print(c("CHIMP") + ", "); System.out.println(c("KNOW")); System.out.print(c("SPONGE") + ", "); System.out.print(c("SPOON") + ", "); System.out.print(c("TROLL") + ", "); System.out.println(c("WOLF")); System.out.print(c("WATCH") + ", "); System.out.print(c("EARTH") + ", "); System.out.print(c("NINON") + ", "); System.out.print(c("FOO") + ", "); System.out.print(c("BAR") + ", "); System.out.print(c("WAVE") + ", "); System.out.print(c("SELECTION") + ", "); System.out.print(c("YES") + ", "); System.out.print(c("NO") + ", "); System.out.print(c("DEFINITION") + ", "); System.out.print(c("WATER") + ", "); System.out.print(c("WINE") + ", "); System.out.print(c("CODE") + ", "); System.out.print(c("AAAHHHH") + ", "); System.out.print(c("I") + ", "); System.out.print(c("MM") + ", "); System.out.println(c("ABCA")); } } ``` **Output:** ``` 2, 2, 2, 2, 2, 2, 2 1, 1, 1, 1 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ``` ]
[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/25014/edit). Closed 5 years ago. [Improve this question](/posts/25014/edit) **Scenario:** while programming you have a sudden nostalgic urge for the '80s and cheesy games. **Requirements:** Make a GUI program (text probably won't work) for Simon, the game. Input can be clicking, or pressing a key. You should divide the screen into 4 regions: yellow, blue, red, green. When the game starts, a random color lights up and you activate it. Then, two lights come on, one after the other, and you need to activate those in order, etc. The game ends when you press the wrong color. **Bonuses:** -100 if you include sound (a different note played when pressing each region and when the game shows you the colors) -25 if you include a score counter. [Answer] ## Scratch, 1604 – 125 = 1479 I'm here for the fun, not the golf. **Edit:** updated scoring method based on [community consensus](http://meta.codegolf.stackexchange.com/a/5013/12205). Main program: ![main](https://i.stack.imgur.com/WSu5g.png) Individual sprites: ![sprite](https://i.stack.imgur.com/Ua5i6.png) This is the sprite with number `0`. The other sprites have the same script, except the number. Play with it [online](http://scratch.mit.edu/projects/20017533/). Code used for byte counting: (Using snippet to hide code) ``` when green flag clicked set [s v] to [0] delete (all v) of [a v] forever set [x v] to (pick random (0) to (3)) add (x) to [a v] set [i v] to [1] repeat (length of [a v] :: list) broadcast (item (i) of [a v] :: list) wait (0.3) secs change [i v] by (1) end set [i v] to [1] wait until <(x) = [4]> end when I receive [0 v] play sound [0 v] next costume wait (0.3) secs next costume when this sprite clicked broadcast [0 v] wait (0.3) secs if <[0] = (item (i) of [a v] :: list)> then change [i v] by (1) else stop [all v] end if <(i) > (length of [a v] :: list)> then set [x v] to [4] change [s v] by (1) end when this sprite clicked broadcast [3 v] wait (0.3) secs if <[3] = (item (i) of [a v] :: list)> then change [i v] by (1) else stop [all v] end if <(i) > (length of [a v] :: list)> then set [x v] to [4] change [s v] by (1) end when I receive [3 v] play sound [3 v] next costume wait (0.3) secs next costume when I receive [1 v] play sound [1 v] next costume wait (0.3) secs next costume when this sprite clicked broadcast [1 v] wait (0.3) secs if <[1] = (item (i) of [a v] :: list)> then change [i v] by (1) else stop [all v] end if <(i) > (length of [a v] :: list)> then set [x v] to [4] change [s v] by (1) end when this sprite clicked broadcast [2 v] wait (0.3) secs if <[2] = (item (i) of [a v] :: list)> then change [i v] by (1) else stop [all v] end if <(i) > (length of [a v] :: list)> then set [x v] to [4] change [s v] by (1) end when I receive [2 v] play sound [2 v] next costume wait (0.3) secs next costume ``` Note: Code automatically generated using [scratchblocks generator](http://scratchblocks.github.io/generator/), modified as somehow the generator doesn't correctly handle decimal numbers (treating 0.3 as 0). Screenshot: ![screenshot](https://i.stack.imgur.com/bd5Q9.png) *Note: Please do not press two buttons within 0.3 seconds.* [Answer] # Bash ~~318~~ ~~297~~ ~~281~~ ~~273~~ ~~268~~ ~~244~~ 240-125=115 This is primarily a response to "Text probably won't work"; the following text-based bash script runs fine in `Konsole`, `gnome-terminal` etc. on my Ubuntu 14.04 machine. To create the regions of colour it sets the text background color. In fact, adding text makes the game more accessible to color-blind players. To make the game yet more accessible it reads the characters that the player needs to press (it assumes that `espeak` is installed). It also assumes that the only file matching `/d*/ur*/` is `/dev/urandom`. For the regions of color to be of non-trivial size you probably want to set the text size to be quite large. Also if you want the regions of color to be quadrants, you have to run it in a terminal that is two characters wide. To play press y, r, g or b as appropriate. ``` cat <<"EOF"|sed s/E/`echo -e '\E'`/>simon_golf.sh;bash simon_golf.sh;wc simon_golf.sh d(){ echo Ecx1r09mRx2g10mGx3y11mYx4b14mBx0m$s|sed s/.$1"// s/[rgyb]..//g s/x/E[48;5;/g";};x(){ d $c;espeak $c;d j;};l(){ for c in $o;{ eval $1;x;};};f(){ o=$o\ `tr -dc yrgb</d*/ur*|head -c1` l;l 'read -n1 i;[ $c = $i ]||exit;let s++';f;};f EOF ``` This solution contains two non-printable ESC characters. Although these ESC character appear in the preview, they seem to get deleted after submission, so the code above is a wrapper that generates and runs the golfed `simon_golf.sh`. See also the original [ungolfed version](https://github.com/gmatht/joshell/blob/master/golf/simon_game.sh), and the slightly more playable [256 byte version](https://github.com/gmatht/joshell/blob/master/golf/simon2.sh). The screenshots below are when the yellow light is on and the player's score is 7. The screenshot on the right has been desaturated to simulate colour-blindness. ![screenshot](https://i.stack.imgur.com/heNhm.png)![BlackandWhite](https://i.stack.imgur.com/RgrKE.png) [Answer] ## Mathematica, 409 - 125 = 284 ``` k = 2; p = Tuples[{0, 1}, 2]; f[c_, p_] := EventHandler[{c, Rectangle[p]}, "MouseClicked" :> (AppendTo[x, p]; Beep[]; g)] h[R_] := (i = 1; RunScheduledTask[ H = If[OddQ@i, Beep[]; {EdgeForm[{Thickness[0.02], Black}], FaceForm[], Rectangle@R[[Ceiling[i/2]]]}, {}]; i++, {.3, 2 Length@R}]) s := (m = 0; x = {}; h[R = RandomChoice[p, k]];) g := (m++; If[Take[R, m] != x, k = 2; s, If[m == k, k++; s]]) Dynamic@Graphics[{MapThread[f, {{Yellow, Red, Blue, Green}, p}], H}, PlotLabel -> k] s ``` ![enter image description here](https://i.stack.imgur.com/Ul7iV.png) [Answer] ## Windows PowerShell (CLI), 272 - 100 - 25 = 147 ``` $d={param($c)cls;sleep -m 99;'R','Y','Blu','Gre'| %{Write-Host '#' -N -F "$(if($i%4-ne $c){'Dark'})$_"; $i++}};$b={param($c)&$d $c;[console]::Beep(($c+1)*99,700);&$d}; $m=@();$s=0;for(){$m+=0..3|Get-Random;$m|%{&$b $_};$m|%{ if((read-host)-ne $_){$s;exit}&$b $_};$s++;sleep 1} ``` I've added newlines here to avoid side-scrolling, but it works as one line so the character count is without newlines. Screenshot: ![Screenshot of game playing](https://i.stack.imgur.com/NBjOV.gif) To play: * Open PowerShell ISE (v3), paste script into text editor, press F5 to run. * Game will light up a color, play a sound, then wait for input * Press a number (0=red, 1=yellow, 2=blue, 3=green) then Enter. * If you are wrong it prints the score and quits. (NB. it might exit your console). * If you are right it goes for two notes. * You have to press Enter between each note when playing the sequence back. Comments: * "divide the screen into 4 regions" - you didn't say they had to be quarters, so they aren't. * It's hard to see blue light up on the blue background, but it does. * Please run in PowerShell ISE - in the normal prompt "DarkYellow" shows as white. * You could arguably golf another 28 characters off by removing some of the timing (still making the game playable), and by interpreting the rule "sound (a note played when pressing and when the game shows you the colors)" to mean "they can all be the same sound - default error DING", but I think that's too far against the spirit of it. [Answer] ZXBasic: 422 - 100 - 25 = 297 This definitely counts as a nostalgic urge for the '80s... ZXBasic uses a combination of FreeBASIC type commands and ZX Spectrum BASIC to allow loops and repeats which then turn into TZX format to load into a Spectrum emulator. This version changes the border (although a legend on screen says which key to press). It plays the same notes as original Simon game (<http://en.wikipedia.org/wiki/Simon_%28game%29>). ``` d=0.5:s=0:l=1:t=1:n$="4261":dim m(4)=>{-8,9,1,4} border 7 while l>0 cls:a$="":print at 1,1;"Level: ";t;at 2,1;"Score:";s::for i=1 to 4:print at 0,i;paper val(n$(i));ink 0;i:next for i=1 to t c=1+int(rnd*4) border val(n$(c)):beep d,m(c):border 7 a$=a$+str(c) next print at 10,1;"your turn" p$="":i=1 do pause 100:k$=inkey:print at 6,i;k$ if k$=a$(i) then s=s+1:print at 2,7;s:beep d,m(val(k$)):i=i+1 else l=l-1:i=t+1:print "bad luck!" end if loop until i>t t=t+1:pause 25 end while ``` ![Best score](https://i.stack.imgur.com/4N21r.png) ![In play](https://i.stack.imgur.com/qV1BA.png) [Answer] ## HTML5 and Javascript, 1118-100-25=993 bytes ![enter image description here](https://i.stack.imgur.com/A03i1.png) Way too bloated HTML+Js version. Plays sounds through the [Web Audio API](http://webaudio.github.io/web-audio-api/). Frequencies of the notes should be the original Simon's ones, colours and colour placement too. There is an online demo here: <http://www.dantonag.it/miniSimon.html>. Works in Web Audio compliant browsers (at least Chrome and Firefox, IE doesn't support it, AFAIK). ``` <html><script> var hc=["#0f0","red","#ff3","blue"],lc=["#090","#930","#cc0","#33c"],nt=[391,329,261,195],ln=[],qpos=0,pm=0,x,ct=new AudioContext;function ps(a,d){var b=ct.createOscillator();b.frequency.value=d;b.connect(ct.destination);var c=ct.createGain();b.connect(c);c.connect(ct.destination);c.gain.value=-.5;x[a].style.backgroundColor=hc[a];b.start(0);setTimeout(function(a,b){a.stop(0);x[b].style.backgroundColor=lc[b]},500,b,a)} function w(a){2==pm&&(a!=ln[qpos]?(pm=3,document.getElementsByTagName("span")[0].innerHTML="game over!",ps(a,156)):(qpos++,ps(a,nt[a]),qpos>=ln.length&&(pm=qpos=0)))}function ml(){if(0==pm)document.getElementsByTagName("div")[0].innerHTML=ln.length,ln.push(Math.floor(4*Math.random())),pm=1;else if(1==pm){var a=ln[qpos];qpos<ln.length?(ps(a,nt[a]),qpos++):(qpos=0,pm=2)}setTimeout(ml,500)}window.onload=function(){setTimeout(ml,1);x=document.getElementsByTagName("td")};</script><div>0</div><table cellpadding=40><tr><td bgcolor=#090 onmousedown=w(0)><td bgcolor=#930 onmousedown=w(1)><tr><td bgcolor=#cc0 onmousedown=w(2)><td bgcolor=#33c onmousedown=w(3)></table><span></span> ``` My record is 15 (I'm pretty bad at this game). What's yours? ]
[Question] [ ## Exposition In this challenge, I am talking about ARM assembly language. [ARM](https://en.wikipedia.org/wiki/ARM_architecture_family) is a 32-bit RISC processor; I'll use instruction set up to architecture v6. To load a constant ("immediate") value into a register, use the `MOV` instruction: ``` MOV r8, #42 ``` To load negative values, use the `MVN` instruction, with a bit-complement of the operand: ``` MVN r8, #41 ``` You can't load any 32-bit value with this instruction. Acceptable values are: * Any 8-bit value: 0...255 * Any 8-bit value, rotated right by an even number of bits, 2...30 * A bit-complement of any value as described above (a good assembler will accept such operands and turn `MOV` into `MVN`) ## Challenge Make code which determines if the given input is a valid operand for a `MOV` instruction. ### Input A number in the range 0...232-1 or -231...231-1, whatever is easier. If you represent the number as a string, use decimal notation. ### Output True or false, [as usual](https://codegolf.meta.stackexchange.com/q/2190/25315). ### Examples (some of them taken from [this nice site with explanations](https://www.davespace.co.uk/arm/introduction-to-arm/immediates.html)). True: ``` 0x000000FF 0xffffd63f 0xFF000000 0b1010101100000000 (8 arbitrary bits, followed by even number of zeros) 0b11110000000000000000000000001111 (11111111 rotated right by 4 bits) ``` False: ``` 0x000001FE 0xF000F000 0x55550000 0xfffffe01 0b10101011000000000 (8 bits but followed by odd number of zeros) 0b11110000000000000010000000001111 (too many spread-out 1-bits) ``` [Answer] # [Rust](https://www.rust-lang.org), ~~52~~ 49 bytes ``` |n|(0..16).any(|i|(n<<33^n<<32^n*2^n)<<i*2>>41<1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jVFLbsIwFFS3OcUj6sJGCbITGqEQ6KrZ9gAIqlBsyVL6goIjUZGcpBsW7R16g56BnqZxokIKLDqWn-V5H488b-95sdGfM9t1xUppleHEYx63HbDdR3t-uJUIL4lCQmFnpUKDDEEiKYIhBXcKyyxLYfJRaOmODrzEkrDBgAd0kOArKVVJMIp8f2Git8B-vWkUqb43nQ55xGnb-H3zNbZklgNBB8R2LZ61WFFQCDOLsC1rEMdPhe85oPNCUMfwssYq8GWXi-O2usMtOWsWZ-xKjp_4c5jcsfYohMcPDsgk3fy-aLQ1UzvkXQ12Thq9UjDeJS_Esb_ZC3mnayuvLbbmtTsA61yhTrFH7F3IRtsKQtiF9xUQE2ntaf2_kiAkGzAGdj57_J_uXtNOekivTqisqvVzv2_PHw) A closure that takes an unsigned 32-bit value of type `u64` and returns a bool. -3 thanks to corvus\_192. * A 32-bit value `n` is acceptable * \$\Leftrightarrow\$ `n` has a run of 24 equal bits at an even offset, when viewed cyclically * \$\Leftrightarrow\$ `n | n << 32` has a run of 24 equal bits at an even offset, between 0 and 30 inclusive * \$\Leftrightarrow\$ `(n | n << 32) ^ ((n | n << 32) << 1)` has a run of 23 zero bits at an even offset between 0 and 30 inclusive, counting from the high end * \$\Leftrightarrow\$ `n<<33^n<<32^n<<1^n` has a run of 23 zero bits at an even offset between 0 and 30 inclusive, counting from the high end * \$\Leftrightarrow\$ `(n<<33^n<<32^n<<1^n)<<i>>41` is zero for some even `i` between 0 and 30 inclusive [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` Nθ⊙ 3№×²◧⍘θ 123¹⁶×¹²ι ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjdTPPMKSkv8SnOTUos0CjWtuQKKMvNKNBzzKjWUFIyVdBSc80uB_JDM3NRiDSMdhYDEFJ_UtBINp8Ti1OASoNp0jUIdBSUFQyNjJU0dBUMzTSAJUW0IVJ6pCQTWS4qTkouhNi6PVtIty1GKXWxqaAARAQA) Will accept input in decimal by default, but also hex with `0x` prefix and binary with `0b` prefix. Outputs a Charcoal boolean, i.e. `-` for valid, nothing if not. Explanation: ``` Nθ First input as a number 3 Literal string ` 3` ⊙ Any character satisfies θ Input number ⍘ Converted to custom base 123 Literal string ` 123` ◧ (Left) Padded to length ¹⁶ Literal integer `16` × Repeated by ² Literal integer `2` № Contains ι Current character × Repeated by ¹² Literal integer `12` ``` [Answer] # [Python](https://www.python.org), 52 bytes ``` f=lambda n:n>4**32or 0<n%~-4**16>>8<8**8-1and f(n*4) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZBNSsQwGIZx21N8GyENrSROHeow0509xYAkJHEKbVLSVKcuvIibAdE76WlM0sKguPAN5D9PnuT1o5_cwejTm9rt30en8vKzULuWdVww0BtdFRivro0FstWXL7kf0XVVldsS4zKnTAtQSOMiXc7eKr-1zfA9NBo61qPB2auhbxuXmV5qRNJ0kwBAbxvtkEKhbjM_uwBOXxd7ciQxdZ2Qo_IR65Xy3bqe5xPCKYmFkiWASmCWN84yO4FvhwyUaVvzJAXwCeSj1KDHjksLRsGztGZIA4eeGb8T1gDRJWCNY87TbPNwcIFZxHs8Zdal9V1wDN7R8XjjM-vGRyhJ6B_mUT2AgI_uh7MR4n_K5-Gs7IzxX68nGHormciNB9N8lp1_-Rs) Returns False for True and True for False. ## How? Uses `mod 0xffffffff` to get from a linear left shift to a cyclic left shift. Advantages of linear being 1) Python actually has it. 2) easier stopping criterion. [Answer] # [Go](https://go.dev), ~~157~~ 147 bytes ``` import."math/bits" func f(n uint32)(r bool){F:=uint32(0xFF) for k:=2;k<31;k+=2{j:=RotateLeft32(n,k) if r=j<=F||^j<=F;r{return}} return n<=F||^n<=F} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lZHdSsMwFIDxtk9xLBRSrC7dUKRbBMEVL0Rkzgvxj3Q2s-uajjSFQten8NKbIfgQvoc3-jS2iTKUXuhJ4JycE8j3kafnabp6XdBJTKchJDTiRpQsUiF3TJZI8yWXbHv__fG7l1D50AkimZkGy_kEGOKQR1z2ujYSEKTp3C59j-gWwoXv2wZLBcQe6fbjQc_tx1ukW848MkolleFJyJqL3IltI2IgyGxA_OXytkl9UYpQ5oJXlaEL4HrapEqjfWy8KZCGHNlQGmeifnvOkUkIGY8uxseXdWFqijsnA4-AoLx2vbrRlCUusArfd3DB6rjf6zGnYdd9BwcuVsvFeN1y18ff0cyqmoV6hKFMmW1SKBUaQyYurAI6gAMrAHIAlgRkSfuamw5kalMHpMhDsKEyqh9G_uHJ-fCvRq4_bDQaNcVc7Nah8ZUnC7HbItdutz622P1TjtF51mY3PD3Sal-fu1rp_Ak) Input is an unsigned 32-bit integer. * -10 bytes: use a comparison rather than an equality and bitwise-and. ### Explanation ``` import."math/bits" func f(n uint32)(r bool){ F:=uint32(0xFF) for k:=2;k<31;k+=2{ // rotation check j:=RotateLeft32(n,k) // rotate left an even number of times if r=j<=F||^j<=&F;r{return}} // if 8-bit or its complement is 8-bit, return true return n<=F||^n<=F} // return if 8-bit or its complement is 8-bit ``` ## [Go](https://go.dev), 121 bytes ``` func f(n,k uint32)int{F:=uint32(0xFF) if n&^F>0{k-- if k<1{return 0} j:=n*4|n>>30 if k&1>0{j=^n} return f(j,k)} return 1} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lZHfSsMwFIfxtk9xLHSkkumJU5FiCoILXoiIzgtRJ92fjK4uG10LHbVP4s0QfAifRPRpTNPhUCfoaUj7Ownk-5rHp8F4_jIJulEw6MMoCJUVjibjONm05Sixn9NE1vffZjJVXZBE0QjSUCWNbVfPufB4lQhmQrhWKEHV2sLHPKrXyxQdsDzuJ2msAAtr6HG1sfOgfL-BZrXG9NYhb6vCWuySZEgj9zOyogJ4X3s1BCUfcSG3zmJ97r0iNue8dX7ZOr7SH7ZryXEMd3QKHoc4UNro-rYizDFDU0JQzKSu3l5D0pK76lPsMDQPQ1y22DJ-r3Kt0CyBxyWZUv1PSqlgnTPIDZ8kNmZOBluAHacD3AenB8TpuTfKpjA1I6DAXCis4ouSODy5aP5ViYlm6VG6GehsV1fFb0RlH9kKu9V6y_irHv5PD-GnX_P0qJJb3O98Xr0_AA) A direct port of [@Arnauld's JS answer](https://codegolf.stackexchange.com/a/269870/77309). [Answer] # ARMv2, ~~32~~ 28 bytes Input is in `R0`, output is in `R1` which is zero if the input is an invalid constant. `CMN` trick stolen from [Notlikethat's answer](https://stackoverflow.com/questions/27963312/armv5-and-earlier-mov-and-mvn-operands/27973178#27973178) to the Stack Overflow question linked by @PeterCordes. ``` VALID: MOV R1, #-16 LOOP: MOV R0, R0, ROR#2 CMP R0, #256 CMNCC R0, #256 @ compare with -256, predicated on Carry Clear ADDSCC R1, R1, #1 @ Add and Set flags if Carry Clear BCC LOOP MOVS R15, R14 @ return ``` This is ARM mode so each instruction is 4 bytes, unlike Thumb or Thumb 2. `movs r15, r14` copies the return address to the program counter, `mov pc, lr`, returning from the function like `bx lr` in modern ARM code. Alternative version using @Bubbler's trick of XORing the input with itself rotated left one bit, which still works with `CMP` (but not my original 32-byte `TST` version, which is why I didn't use that approach at the time). Input is in `R0`, output is in `ZF` which is set or `R0` which is zero if the input is an invalid constant. ``` VALID: EOR R1, R0, R0, ROR#31 MOV R0, #-16 LOOP: MOV R1, R1, ROR#2 CMP R1, #512 ADDSCC R0, R0, #1 @ Add and Set flags if Carry Clear BCC LOOP MOV R15, R14 @ return ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 101 bytes ``` .+ $.(23283064365386962890625** 16{`.+$ $.(4** )r`(.?)(.{1,32})$ $.($1*)¶$2 A`$ ¶ $ $` 0`0{12}|3{12} ``` [Try it online!](https://tio.run/##JY47DsIwEET7PYeRkoCs/duuEBXXMAUFDUVEF3KtHCAXCw5pVm9mZzU7Pj@v94O2U3evWzxDiB0LZ0FXcZPsxTkXdLZhAPKpxnPYQ9pkP9YuXvsuTnQRnvv/ItDQr0tguNUA6wLQ3ApYcSKev7LPbWMD5aLF3DE1TJkKYkZQSclBkVs3ZbMDS/sIgVTIRQrjceyeskFOZnzEFFHTDw "Retina – Try It Online") Link includes test cases. Outputs `1` for valid, `0` for invalid. Explanation: ``` .+ $.(23283064365386962890625** 16{`.+$ $.(4** )r`(.?)(.{1,32})$ $.($1*)¶$2 A`$ ``` Convert the input to 16 base `4` digits. (This method is required for very large integers or even for large integers where the traditional method would cause the process to run out of memory.) ``` ¶ $ $` ``` Join the digits together and then duplicate the string. ``` 0`0{12}|3{12} ``` Check for 12 repeated `0`s or `3`s. (If any non-zero output is acceptable, the `0`` can be removed to save two bytes.) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 43 bytes ``` f=n=>++i&31&&n>>8==n>>31|f(n>>>2|n<<30);i=0 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1k5bO1PN2FBNLc/OzsLWFkgaG9akaQBpO6OaPBsbYwNN60xbg//J@XnF@Tmpejn56RppGgYVBmDg5qapyYUulQYEKWbGaVik3Nwg@rBJQU1Ek8JUCFZm6OaKwww37MabAgEOm0HuTUs1MNTU/A8A "JavaScript (Node.js) – Try It Online") Note: This function will not be reusable after about 248 invokes. I would argue that should be fine according to the spirit of code-golf though. And fix the limit may [cost 2 more bytes](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7TVls7U83YUE0tz87OwtYWSBob1qRpAGk7o5o8GxtjA03rTFuD/8n5ecX5Oal6OfnpGmkaBhUGYODmpqnJhS6VBgQpZsZpWKTc3CD6sElBTUSTwlQIVmbo5orDDDfsxpsCAQ6bQe5NSzUw1NT8DwA). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 4B16°+¦2×30S12×åà ``` Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/269883/52210), so make sure to upvote that answer as well. Input as an integer. [Try it online](https://tio.run/##yy9OTMpM/f/fxMnQ7NAG7UPLjIwOTzc2CDYEUoeXHl7w/7@poQEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVnlo2ZF29YrAzFKPw6uda10qlQ7vV9A4vF9T4VHbJAUl@/8mToZmhzZoH1pmdHi6sUGwIZA6vPTwgv86/w0qDMDAzY3LoCINCFLMjNOATDc3iDiXQZKhARgaGhgghAwRXHQAkuOCGmvo5goyC2Q@WGOFKRBAzABblpZqYIjFBuxWGKJYAQA). **Explanation:** ``` 4B # Convert the (implicit) input-integer to base-4 16° # Push 10**16 + # Add it to the base-4 number (as base-10 addition) ¦ # Remove the leading 1 2× # Repeat this string two times 30S # Push [3,0] 12× # Repeat both 12 times å # Check if the earlier string contains a substring of 12 3s or 0s à # Check if either of the two is truthy # (after which the result is output implicitly) ``` [Answer] # Ada/GNAT, 152 bytes ``` type T is mod 2**32;function G(X:T;C:T:=0) return Boolean is (C<30 and then ((((X and 255)=X or (X or not 255)=X) or else G((X mod 4)*2**30+X/4,C+1)))); ``` G is a recursive function that: 1. Takes a type T, which is a mod. Mod types are like Integers, except they wrap around when they overflow and you can do bitwise operations on them. 2. Defaults C to 0 and uses it to check for too many recursions. This was way fewer bytes than writing a loop structure, not just because of the verbose loop syntax in Ada but also because the inline subprogram syntax couldn't be usable with a loop. I picked 30 because it was no more bytes than more sensible values like 15 or 16 that I'd have to do more testing on. 3. Does bitwise logic between the input X and 255/not 255. I honestly didn't expect "not 255" to work, but as it turns out, this does a logical inverse as if it were a variable. These two comparisons basically enforce the rule that all the meaningful data must be within a range of eight contiguous bits. 255 being 00000000000000000000000011111111, and not 255 being 11111111111111111111111100000000. 4. Does the arithmetic equivalent of rotating by 2 and uses this with an incremented C to call its next iteration. There is a builtin for rotations, but using it required a with and a function call, so doing this turned out to be less verbose. [Answer] # JavaScript (ES6), 47 bytes Returns **0** or **1**. ``` f=(n,m=~255)=>n&m&&~n&m?m%96&&f(n,m*4|m>>>30):1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfXts7I1FTT1i5PLVdNrQ5I2ueqWpqpqaWBJLVManLt7OyMDTStDP8n5@cV5@ek6uXkp2ukaRhUGICBm5umJhe6VBoQpJgZp2GRcnOD6MMmBTURTQpTIViZoZsrDjPcsBtvCgQ4bAa5Ny3VwFBT8z8A "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input m = ~255 // m = mask, initialized to ~255 (note that this gives // the signed value -256 rather than 0xFFFFFF00, which // is important for the modulo 96 test) ) => // n & m && // if n & m is not 0 ~n & m ? // and ~n & m is not 0: m % 96 && // if m is not equal to 0x3FFFFFC0 (the last rotation // which is the only one to be a multiple of 96): f( // do a recursive call: n, // pass n unchanged m * 4 | // rotate m by 2 positions to the left m >>> 30 // (the result is still signed) ) // end of recursive call : // else: 1 // success: return 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` +Ø%BḊṙ⁴ḶḤ¤;¬$ḄṂ<⁹ ``` [Try it online!](https://tio.run/##AUsAtP9qZWxsef//K8OYJULhuIrhuZnigbThuLbhuKTCpDvCrCThuIThuYI84oG5/zvigJwgLT4g4oCdO8OHCuG7tMWSVuKCrMOH4oKsWf8 "Jelly – Try It Online") A monadic link taking an integer and returning 1 for valid and two for invalid. ## Explanation ``` +Ø% | Add 2**32 B | Convert to binary Ḋ | Remove first digit ṙ⁴ḶḤ¤ | Rotate left by each of (0 to 15 doubled) ;¬$ | Concatenate to binary not of this Ḅ | Unbinary Ṃ | Max <⁹ | < 256 ``` ]
[Question] [ For a 2 dimensional array we will call the elements in either the first row or the last column the "J-Bracket" of the array. For example in the following array elements in the J-bracket are highlighted: \$ \begin{bmatrix} \color{red}{\underline 1} & \color{red}{\underline 2} & \color{red}{\underline 4} & \color{red}{\underline 8} \\ 9 & 3 & 6 & \color{red}{\underline 7} \\ 3 & 3 & 2 & \color{red}{\underline 9} \end{bmatrix} \$ The J-bracket is given in order starting from the first element of the first row and going clockwise. The element that is in both the row and the column is not repeated. So for the above that is: \$ \left[1, 2, 4, 8, 7, 9\right] \$ Your task is to take as input a 2 dimensional array of positive integers, and repeatedly remove J-brackets from it until the remaining array has no more elements. Your output should be all the J-brackets removed in this process in the order they were removed. The input will always be perfectly rectangular, and both dimensions will be at least 1. You may take input in any reasonable format. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. ## Test cases ``` [[2]] -> [[2]] [[1,2],[3,4]] -> [[1,2,4],[3]] [[1,2,4,8],[9,3,6,7],[3,3,2,9]] -> [[1,2,4,8,7,9],[9,3,6,2],[3,3]] [[1,2],[3,4],[5,6]] -> [[1,2,4,6], [3,5]] [[1,2],[3,4],[5,6],[7,9]] -> [[1,2,4,6,9], [3,5,7]] ``` [Answer] # [Haskell](https://www.haskell.org/), ~~(53)~~ 47 bytes *Fixed and golfed 6 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)* ``` f((a:b):c)=(a:b++(last<$>c)):f(init<$>c) f x=[] ``` [Try it online!](https://tio.run/##dYuxDoIwFEX3fsUbGNrwYiIgCLH@hONLh0poaCyVWIj@fQVcTIzbuefm9DrcOudiNJzr5iqaVsgV0pQ7HaZTcm6FaAy33n4GM/CSpOKgrQcJ4zxdpkcye2d9F5JBj8BDf3/ujABiAESZUrjBHjOFlGPxJbDA4yJrzLHEarvzxda/DdIBy38aqVobBiq@AQ "Haskell – Try It Online") [Answer] # [R](https://www.r-project.org), 37 bytes ``` \(m)split(m,pmin(row(m),rev(col(m)))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZBNCsIwFIRx21MEREhguuh_C-op3NUspFgoGFti_bmLmwp6KD2NL8ZFUYtZZB7DzJdHzhfdXUs2dW_7tnTT-2TJldg1m6rlCo2qtlzXR7Kg1wde1Bsa6djwYwSuZmrV6urEC-4LeMBCiDFz5yzPfSmdkvJOP-TBR4BQkPSixg0l8mCoEiJFRsUYCd0BOZkg-URQKkFGIJv1DRKDUNoDEeKfoFiCUTf60zXPCRq_-2aNFwHJm2E_reusPgE) Working on the [related challenge](https://codegolf.stackexchange.com/questions/245748/find-the-j-twin) led me to this approach. Test harness taken from [pajonk's answer](https://codegolf.stackexchange.com/a/245700/67312). In an \$m\times n\$ matrix \$A\$, each element \$A\_{ij}\$ is in the \$p^\text{th}\$ J-bracket if and only if \$\min(i,n+1-j)=p\$. R has some odd built-ins that return the matrix \$R=\text{row}(M)\$ where \$R\_{ij}=i\$ and similarly for \$C=\text{col}(M)\$. Reversing the column matrix luckily performs the right operation, and we take the `p`arallel `min`imum of these matrices to obtain a matrix of J-brackets, which `split` helpfully breaks into groups of the right order. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 11 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` ⌊⌜⟜⌽○↕´∘≢⊸⊔ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oyK4oyc4p+c4oy94peL4oaVwrTiiJjiiaLiirjiipQKCuKImOKAvzHipYogRuKImD7CqCDin6gK4p+o4p+oMuKfqeKfqQrin6jin6gxLDLin6ks4p+oMyw04p+p4p+pCuKfqOKfqDEsMiw0LDjin6ks4p+oOSwzLDYsN+KfqSzin6gzLDMsMiw54p+p4p+pCuKfqQ==) ``` ⊔ # Group the values by: ≢ # The shape of the matrix ´ # Reduce the shape by: ○↕ # Convert both integers to a range [0, n) ⟜⌽ # Reverse the right range ⌊⌜ # Minimum table ``` [Answer] # [R](https://www.r-project.org), ~~117~~ ~~88~~ ~~86~~ ~~76~~ 72 bytes *Edit: **-~~29~~ 31 bytes** thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe); -10 bytes thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder); another -4 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` f=\(M)"if"(1%in%dim(t(M)),M,list(c(M[1,],M[-1,n<-ncol(M)]),f(M[-1,-n]))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZGxCsIwEIZx7VMURcjBnyFtbS2os0s3t5hBKoGAraAVfBcXHXwofRqvrYKoxSUX_vv_L0fudNmdz9dDZeX4NrfTpcio72xfqKErh2tXiIoVQoaN21ciF5lWMMi0VCgnssy3G-4bghWNJktDRC3v3oMopsWq2rkjJwOCAhZEA1_OfK0DYzwrCvLeTQoBQkTE5c1aq5GBDrsiEcZIORgj4TNkJSUunwh2JUgZ1HqDGolOKM-BEeKfoNjA5-zoT7Z-jvj6na_HaAhInoz2017LeAA) Recursive approach with some clever tricks by [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) and [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder). [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` a=input() while[[]]<a:print a.pop(0)+map(list.pop,a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dY5NDoIwFIT3PUXDBtCn4U8Eoid5aUhDSmiipcEScek53LgxXsCdJ-E2IsSN0eV8M_PeXO76ZKpaBddnWTc0p1JZuTWLM0JNc8pEJwrbtm-tKRdJH_GtVLo1jkuOldwJRMY2PNONVIbypa6147nzPdfOTh7MWwN3p-5juEKo6AqhTeYTOnYm69qfEQPGCKIPAQMMIfooiCAZSAohxLAevXCg6VcacAXxTwa4_pOeHEBv-MCmJS8) -4 bytes thanks to @ovs [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ßest Friends Forever?! ``` Ḣ;Ṫ€W;ßFF? ``` A monadic Link that accepts a rectangular list of lists and yields a list of lists. **[Try it online!](https://tio.run/##y0rNyan8///hjkXWD3euetS0Jtz68Hw3N/v/h9uPTnq4c8b//9HRhjpGOiY6FrE60ZY6xjpmOuZAljGQZaRjGRsLAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjkXWD3euetS0Jtz68Hw3N/v/h9uPTnq4c4Zm5P//0dHRRrGxXDrR0YY6RrE60cY6JnCujomOBVDIUsdYx0zHHCxpDBS1RFevE22qY4ZdUCfaHKw@FgA "Jelly – Try It Online"). ### How? ``` Ḣ;Ṫ€W;ßFF? - Link: list of lists, X Ḣ - head -> top row of X (mutates X) € - for each of (the remaining rows of) X: Ṫ - tail -> last element of the row (mutates X) ; - concatenate these together W - wrap that list in a list -> Z ? - if... F - ...condition: flatten (the mutated) X (falsey once empty or only empty rows) ß - ...then: call this Link with (the mutated) X F - ...else: flatten (the mutated) X -> an empty list ; - Z concatenate that ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 44 bytes ``` {,'/(&/d)#'(-1 1*!'d:#'1*:\x)_''1(1_'|+:)\x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJyr1lHX11DTT9FUVtfQNVQw1FJUT7FSVjfUsoqp0IxXVzfUMIxXr9G20oypqAUA0QcKLQ==) Solved in my worst attempt at [find-the-j-twin](https://codegolf.stackexchange.com/questions/245748/find-the-j-twin). It seems a shame to let it go to waste... [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` λ[ḣƛt;J,ḢƛṪ;x¤ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwizrtb4bijxpt0O0os4biixpvhuao7eMKkIiwiIiwiW1sxLDIsNCw4XSxbOSwzLDYsN10sWzMsMywyLDldXSJd) ## Explanation ``` λ[ḣƛt;J,ḢƛṪ;x¤ λ Open a lambda (for recursion) [ If statement (check if truthy) ḣ Separate the first item, push both sides to stack ƛt; Map to last item of each J Join both lists , Pop and print (the J bracket) Ḣ All but the first item ƛṪ; Map to all but the last item of each x Recurse ¤ Empty space (so that it won't output an empty list at the end, since stack is implicitly output) ``` [Answer] # [Python](https://www.python.org), 49 bytes ``` f=lambda a,i=0:a and[*a.pop(i),*f([*zip(*a)],~i)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dY9BDoIwEEX3nqLLlowEBVFI2HiNSRdVaJwE2wbRRBcmnsMNG72Tt7EKboyuJv_9P38y17s7thtruu62b_V48ZjoolbbVamYAiqi3E9TYqBCZx0nAYHmGJzI8UAJCWcSclhcatswYmSYdZXhkQibSpU1mWrHRT5ijFFRHVTtS17CNWRaTqA5hWvrjlwI0Td1jwviVMoR4gSmEjCG5KMggYUnGcSQwvztxZ5mX2nAGaQ_GeD8T7p3ACN_YfjpCQ) Loosely based on @pxeger's Python 2 answer. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 51 bytes ``` f(m)=m&&print(concat(m[1,],m[^1,#m]~))*f(m[^1,^#m]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN43TNHI1bXPV1AqKMvNKNJLz85ITSzRyow11YnVyo-MMdZRzY-s0NbWAykC8OCBXE6o1OrGgIKdSI1dB104BolvJM88qJk9JIVdBKSbPv7TESknTWgFkgY5CtC_QWCMQw1DHyNpYxyQWwtQx0bGwttAx1jHTMQcKGwNFLGNhVsBcCQA) [Answer] # APL+WIN, 47 bytes Prompts for 2 dimensional matrix ``` m←⎕⋄⍎∊(⌊/⍴m)⍴⊂'m[1;],1↓,m[;1↓⍴m]⋄m←1 0↓0 ¯1↓m⋄' ``` [Try it online! Thanks to Dyalog APL Classic](https://tio.run/##XYxBCoJQFEXnfxVv9guM/F@zxBUERQsQB2IYgZ8CR00jTCwliNbRpBW0lLcRu4JENLnvvnPfffE@G60PcbbbjJIszvNt0nLzWC64uDkCbr6CU4LLc9oaWCC@nLhuuKwGfK3GXL/MEMLVUZpQBZGluLhbJgy62aURCl1VkQ1i0/vZJQZUtvgr2lQoUrjUQpIUqdCksSnS5JDbM7ieuTQjH4lHU6gD4n9vfno0Ia/n7j9H0/8A "APL (Dyalog Classic) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [ćs©€θ«,®€¨Wg_# ``` [Try it online](https://tio.run/##yy9OTMpM/f8/@kh78aGVj5rWnNtxaLXOoXVA1qEV4enxykCpaEMdIx0THYtYnWhLHWMdMx1zIMsYyDLSsYyNBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3loeVR61qHdOlxK/qUlMMH/0Ufaiw@tfNS05tyOQ6t1Dq0Dsg6tCE@PV/5fe2ib/f/o6Gij2FgdhehoQx2jWJ1oYx0TOFfHRMcCKGSpY6xjpmMOljQGilqiq9eJNtUxwy6oE20OUh8LAA). **Explanation:** ``` [ # Loop indefinitely: ć # Extract head; pop and push first row and remainder-matrix s # Swap so the remainder-matrix is at the top © # Store it in variable `®` (without popping) €θ # Pop and only leave the last value of each row « # Merge it to the extracted first row , # Pop and output this list with trailing newline ® # Push matrix `®` again €¨ # Remove the last integer from each row W # Push the flattened minimum of the matrix (without popping) g # Pop and push the length of it _ # If this length is 0: # # Stop the infinite list ``` [Answer] # Java 8, 109 bytes ``` m->{for(int i=0,j;;){var t=m[j=i++];for(;++j<m.length;)t.add(m[j].pop());if(t.size()>0)System.out.print(t);}} ``` Input as an array of Integer-Stacks; output prints directly to STDOUT. [Try it online.](https://tio.run/##7VXNTgIxEL77FBNPbbY0KgqSAgkHDybqhSPhUEuBLvuXdkBxs1cfwEf0RbCwSogQDmYPJnpp0szMN983M5kJ5ULWwtFspSLpHNxLk@QnACZBbcdSaXhYfwEWqRmBIqF353M0Ee@jVLP2rfebaNsdDCGmgFObPjm4eVY6Q5MmwocWJ/5xKNEoeIAEOrCKa918nFrik4DpnLFQCJovpAXsxIOwY4JgKNZ2EQRhO@aRTiY4FRS5HI2I9xjyLM0IpcKMCXJnXjSh3TPaXzrUMU/nyDPrsQlSURQrsSaQzR8jT@CTx0ZM7KWSPnrPiWcvaakTtUNyRCaFRD/BN/tgWAbDIeM2mNA89wp6UbSD37NWLh2X7s74xBd0TXmDVVDxCwids5ISqwauzi5/oUJ2ya6rVNliddZgzWoLV/c8W39kPCqCu2KN/4L9pGAVwTX3B3b3Gmy28KYdR69KWfm95b6XFNNymZOYBqfw/voGp18tt8s84cobRKEkqinZXijQzzQvDmaIEvJJuVh9AA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ≔⮌AθW›θEθυI⟦⁺⊟θE⮌θ⊟κ ``` [Try it online!](https://tio.run/##NUy7CsIwFN39ioz3wnWwFbV0Kg7iIATXkCGUYIMhbfOonx8TxOm8zzgpP87K5jyEYF4OnnrTPmi4uyVFQCS2Yr/7TMZqBjevVdQeVmIPtVRIiMi4Ny7CVYUIgtsUgM8lxF/pf1h19d9lIRH7nIUQB2roSBdJoqOWTnQurC2soU5Kmfeb/QI "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @pxeger's Python solution. ``` ≔⮌Aθ ``` Reverse the input as Charcoal can only pop from the end of a list. ``` W›θEθυ ``` Repeat until the input has no rows or columns. ``` I⟦⁺⊟θE⮌θ⊟κ ``` Remove the now last row and the last column of the remaining rows reversed back into their original order and output those values. [Answer] # [Ruby](https://www.ruby-lang.org/), 46 bytes ``` f=->m{[m.shift+m.map(&:pop),*m*"">""?f[m]:[]]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y63OjpXrzgjM61EO1cvN7FAQ82qIL9AU0crV0tJyU5JyT4tOjfWKjo2tva/QkFRZl6JgkKaXnJiTo5GdLRRbKwmF1RUKSZPiQtDhaGOUaxOtLGOCTEqdUx0LICqLXWMdcx0zMH6jIGiliTYohNtqmNGsnqdaHOwLf8B "Ruby – Try It Online") Takes advantage of *shift* and *pop* which modifies object in place and return what we needed. Checking the updated *m* was a bit difficult because pop and shift may return *nil* which is *truthy* in Ruby [Answer] # [Factor](https://factorcode.org/), 69 bytes ``` [ [ 1 cut flip 1 short cut* rot prepend concat . flip ] until-empty ] ``` [Try it online!](https://tio.run/##RYy9CsIwFEb3PsU3CxZsxd8HEBcXcSodQrzFYprEm1uwlD57THWQbzkcDl@jtDiOt@v5cjog0Ksnqyn8Kae3sAp4Elsy8Ewig@fWCo5ZNmLECgXW2GFKvEeJDbZfLtOKZCZMsUKVOt0LGtP6hOHhWGaxADuZbz3ZO7SzWgnyX1ajt9KaJXVeBtRRK2PiBw "Factor – Try It Online") ## Explanation It's a quotation (anonymous function) that takes a matrix as input and prints its J-brackets, one per line. * `[ ... ] until-empty` Repeatedly call a quotation on an input until it is empty. ``` ! { { 1 2 4 8 } { 9 3 6 7 } { 3 3 2 9 } } 1 cut ! { { 1 2 4 8 } } { { 9 3 6 7 } { 3 3 2 9 } } flip ! { { 1 2 4 8 } } { { 9 3 } { 3 3 } { 6 2 } { 7 9 } } 1 short ! { { 1 2 4 8 } } { { 9 3 } { 3 3 } { 6 2 } { 7 9 } } 1 cut* ! { { 1 2 4 8 } } { { 9 3 } { 3 3 } { 6 2 } } { { 7 9 } } rot ! { { 9 3 } { 3 3 } { 6 2 } } { { 7 9 } } { { 1 2 4 8 } } prepend ! { { 9 3 } { 3 3 } { 6 2 } } { { 1 2 4 8 } { 7 9 } } concat ! { { 9 3 } { 3 3 } { 6 2 } } { 1 2 4 8 7 9 } . ! { { 9 3 } { 3 3 } { 6 2 } } flip ! { { 9 3 6 } { 3 3 2 } } ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 91 bytes ``` (l=Length@#&@@#;Flatten@Pick[#,MapIndexed[Min[#,l-#2+1]&@@#2&,#,{2}],i]~Table~{i,Tr[1^#]})& ``` [Try it online!](https://tio.run/##dY9Ba8IwGIbv/RWFQNnYO0pbbRUJ5CQMFDx4Kx1kNc5gDaPNYRDiX@@@RTYsbJeQPN/z5k0u0p7URVrdyvHIx4eOb5R5tyfBEiHYat1Ja5URO92ea4at/HgxB/WpDvVWGwLdM8ufsubbzRMwuNw30M11L986dXUa@77OXlnjH5PRqsG2clADd5GLHakeYY09AsiQEykwo8HtSFsCEwMzLAguUaBEFfyC6PIugwUqAj/S7dLirx64Ocr7ZBkG8/9duGraVYYmytBjKBX5KDqmYq37wabi98sx5/FGTlGa7npt7PgF "Wolfram Language (Mathematica) – Try It Online") Feels too long but I couldn't find anything shorter [Answer] # JavaScript (ES6), ~~66 63~~ 59 bytes *Saved 4 bytes thank to @l4m2 (on both versions)* Returns a list. ``` f=m=>[[...m.shift(),...m.map(r=>r.pop())],...m>'0'?f(m):[]] ``` [Try it online!](https://tio.run/##jZHLDoIwEEX3fgU72@RaRZSHCfghzSyIimKAEjD@Pg5VFigau@vtmTM36TW9p@2hyevbojLHU9dlcRknWiulStVe8uwmJOylTGvRxEmjalMLKcmmyXw132eilDtN1B1M1ZripApzFpnQek3kfD1SOsulY6HZ@6CLNUF72EwJhkGGGGBsWoANQn6N4MFHYHUepxHRSIAQAYcD@Nzr/ewEvYU/bjZW@gSHye0fFuh@O01a@lrWw/X/NcHm9GHq4ZcLLn/VAw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = // f is a recursive function taking m => // a matrix m[] [ // [ ...m.shift(), // extract the first row and split it ...m.map(r => // for each row r[] in m[]: r.pop() // extract the last element of r[] ) // end of map() ], // ...m > '0' ? // if there's still at least one number in m[]: f(m) // append the result of a recursive call : // else: [] // stop the recursion ] // ``` --- # [JavaScript (V8)](https://v8.dev/), ~~65 62~~ 58 bytes Prints the results. ``` f=m=>print([[m.shift()],...m].map(r=>r.pop()))|m>'0'&&f(m) ``` [Try it online!](https://tio.run/##dZAxD4IwEIV3fkUnaZOzKihiCGwuDjo4Nh2ISRWTSlMIiVF/Ox6gwSh2urz73nvNndMqLQ42M@W4CutaxTpOjM0uJRVC8@KUqZIyCZxzLblODbVxYrnJDWWM3XXiTt3RSFHN6kg4hAjhSQnk/5tMOqZlZ@BJED7Mhz0tiwzukeo9MIcQlRX4EMCyTfBRXTUpvQdCWKL25rom/6cZxAKC7/6PlABXCC7@GEE0JXLI2JS3VvyjdKTDVW7X6eFENYkTciPdmTf73ZYXJc7HTF3xkCwizT2j1x6HB6uf "JavaScript (V8) – Try It Online") [Answer] ## PHP 5.4 (93 chars) The function **j** take a *$m* PHP [array](https://www.php.net/manual/en/language.types.array.php) and return the answer as a PHP array. ``` function j($m){for(;$k=array_shift($m);$j[]=$k)foreach($m as&$z)$k[]=array_pop($z);return$j;} ``` Variant using **105 characters** : The function **j** take a *$m* matrix and print the answer as [JavaScript Object Notation](https://www.json.org) array. ``` function j($m){for(;$k=array_shift($m);$j[]=$k)foreach($m as&$z)$k[]=array_pop($z);echo json_encode($j);} ``` [Try it online](https://tio.run/##lVLtToMwFP1Nn@Jm6QSSxqjbmAuiD1LJ0kAJZROatsTpsmfHO8Bl0xj1V2/POffc0w9d6u7hSZeaUCets5DwNB5rnkICHDi/S1MGfr/6DL7zt@wuZXzG5qjz@y2WCKAcftCzObtHyYrNWMSWffcM0dU4aVSwJSKfqmHG7NcMjC9YdOET9czij52ML7/kiPoU6IBJB4@uaOvMqaaGKqAv4b5oTBDTTSKMEW9rW6rCHfGYVjxN6CZEXoqsRAyEvaLvId0gMah1owNEYiNda9DQNvVa1lmTy4BWYXwg3al7eCJhgebCiZDsibdVFkepWreOAZU7LTMn8xDP1msgJh5tWoc0QtWoDBFVBQQnJjlrJZ6njapdEUy0sFbmMF3c4Md4hKl9rifsMuHgh6MHq6Oz3FpJvP2ZjzSmMfCqXPlfL0/ulMP1QA6E5EoG/pipv4prP4y7Dw) ]
[Question] [ ### Task A *reverse checkers* position is a chess position where every piece for one player is on one colour and every piece for the other player is on the other colour. Your task is to find if the given (valid) position meets these criteria. For example, this position does (click for larger images). Every white piece is on a light square, while every black piece is on a dark square: [![reverse checkers 1](https://i.stack.imgur.com/F989pm.jpg)](https://i.stack.imgur.com/F989p.jpg) This position is also a reverse checkers position. Every white piece is on a dark square, while every black piece is on a light square: [![reverse checkers 2](https://i.stack.imgur.com/716Nbm.jpg)](https://i.stack.imgur.com/716Nb.jpg) ### Input Your input will be a ***valid*** chess position. You choose whether it'll be a [FEN](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) (for the purpose of this challenge, we'll only consider the first field, [piece placement](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation#Definition)), or an 8x8 grid (with spaces or not between). If the latter, mention in your answer what characters you used to denote empty squares and the pieces. --- The examples below will use upper-case letters for white pieces and lower-case for black. Empty squares are represented by dots (`.`). 1. The first position above: ``` 5r1k/2p3b1/1p1p1r2/p2PpBp1/P1P3Pp/qP1Q1P1P/4R1K1/7R . . . . . r . k . . p . . . b . . p . p . r . . p . . P p B p . P . P . . . P p q P . Q . P . P . . . . R . K . . . . . . . . R ``` *is* a reverse checkers position. 2. The second position above: ``` r3r3/5pBk/p3nPp1/1p1pP2p/2pPb1p1/P1P1N1P1/1P3R1P/R5K1 r...r... .....pBk p...nPp. .p.pP..p ..pPb.p. P.P.N.P. .P...R.P R.....K. ``` is a reverse checkers position as well. 3. The starting position: ``` rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR bbbbbbbb bbbbbbbb ........ ........ ........ ........ wwwwwwww wwwwwwww ``` *is **not*** a reverse checkers position. ### Rules * The chess position will *always* be valid. * You may use two characters for the pieces, one for white pieces and one for black pieces (i.e. you don't have to use a different character for every piece). * You can receive input through any of the standard IO methods. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # [Python](https://www.python.org), 34 bytes ``` lambda p:{*p[::2]}<{*p}>{*p[1::2]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=tVM9T8MwEB3Y_CssT0mhJ1E6VBVl6FqETBjTDEk_hKlxjiQlqlB_CUslBP8Jfg1nJ6kAFUSFOOt07z3n3p2HPL7gqrhOzeZpPhg_L4t5u_cqdHybTGOO_YcWhv1-J1qfElqfWXrsePXl28GVHIixEXCTKuOFIgHR6kat7mEoSguPBJRO6fiMYaZM4Um_BnOCpO40OCEDQr3ob0bUlVRdv_epsDhfThZKr7hJCx7z-1irKcc0V0VqQHw7Dfad9slHNBXKRIQTUPkScZZ5fttinZYWR3yeZnzCleEactSq8Hzfadpqgkx4czLKBbMIayXhwCqG9T2w6k6SMrQqk45Bo7I7xy5rVbLGPaAcOb-PJ7AbuL20MrPc8__n6V-ebAOHC4ZUjURaCgElaYxSJsSYBAkXlIwSIADJAtc2ArbPykIkdbAtgDp-AmUdW0BOu8dU_9ZmU9V3) Accepts a single string. Works for any distinct 4 characters for empty,black,white,newline. ### How? Uses the fact that including the linebreak lines have odd length, hence going over the entire string skipping every other character separates black and white squares. Both subsets must contain newlines and empty squares (we can't legally put all 32 initial pieces on the same colour squares because of the bishops). Iff there are pieces of both players on the same kind of square that subset will be the full set and the corresponding inequality fail. #### Old [Python](https://www.python.org), 40 bytes ``` lambda p:{*p[::2]}<{*"bw.\n"}>{*p[1::2]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=tZOxTsMwEIYHNj-F5SkJ9CQKQ1VRhq5FyIQxzRC3jTA1jklSoqrqk7BUQvBO8DScnaQCVBAV4qyT__su_n0e8vhiluVNpjdP6WD8vCjTTu_VU8mdmCbU9FeBifr9brw-WwVMVDDWbH1u4bGj9fdvB9d8wLAFt5nUXsQEsOA0Dk4PI1ZZecSgcqTrE2JyqUuP-41IUSLdaXCCBqh68d-M8JSoT_3ep9bsYjGZS7WkOitpQh8SJafUZIUsMw3s29tg39s--bB2h0qwaAKyWBgzyz2_Y7XKKqtjmmY5nVCpqYLCKFl6vu-YsoyhCW1XjjknVpmGCAqkrkzTB1L3OJKhpYS7ClpK7l111VBOWvcQc-T8Pq7QTuDmUlLPCs__n6d_ebINM5wTg7vmBocyYDgygskFVoQDh0tMggkQAiehOzYCss_IjIkmyFZAEz-JqomtQKfd19T_1mZT7-8) Accepts a single string. ".bw\n" for empty,black,white,newline. #### Wrong [Python](https://www.python.org), 36 bytes ``` lambda p:len({*p[::2]}&{*p[1::2]})<3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pZLBSsNAEIbB45x9gGURSYQOqBcJ9tJrQdZc2x6aNqFr182YpAQRn8RLQPSd9Gmc3WyKiAjFWYb55t9k9l_Yl3d6bDal7V6L8fxt1xSjq48Ts7zP1ktBiclt9HRGsyS5WDyfOjr3GF9f9t9-Hh2DGsu5lXhXahvJoWKbydkKdb0jyqsoHjk2Zet4IYqyEiuhrTBYk9FNFMdeM06TPEQMq-LcgiMKSiYQ-o7CPkK_p1iZOBWU73BQ4cF3t0FVMExPOad-3veVOgfel9E2r9kcAFXaNpGKAxSMrP7r6j-u7IImWyCuVhGbIiTFGnCqjDtQqPCGEzgRU1SQ-t-mCIdYljILAXvAEH9BG2IPPOn3Y_rH0XV9_QI) Accepts a single string. Works for any distinct 4 characters for empty,black,white,newline. [Answer] # [R](https://www.r-project.org/), ~~68~~ ~~50~~ 40 bytes ``` function(x)sd((z=rbind(x,0)*.5:-1)[!!z]) ``` [Try it online!](https://tio.run/##fVDBboMwDL37K2hOyZRGRdoq2ik77DbtwqrdOlQBpSsqJCwJK@vPswCh6mHMlpX3nhXLz6oV0uxU9p0es/TE20MtUpNLgRui9xhfuEpysccNXZA79rCe@2Q7m10i0pYcMW9MZesEHaqckngMBla5PoOhF1rluVMh7BkbVfjq2ZtTQxinb2y99vNuc4NA8DI2Km9wVmBtlK6K3OD0GCujMPoQiCIP0ZJ0DyE0ICDHDwsaWP4otzququIHC1qbQ/AuX4QhT8v7iPsTvdUy4nMfbo@GJQGw50hcwBUwF/@Bs4srmLD1qevEmRo8TVoS3O6CBgsdPqM/V25/AQ "R – Try It Online") Input is 8x8 matrix with `1`s and `-1`s representing black and white pieces (or the other way around), and `0`s representing empty positions. Outputs zero (falsy) for not-reverse-checkers positions, non-zero (truthy) for reverse-checkers positions (or [+2 bytes](https://tio.run/##fVDBboMwDL37K2hOyZRGZdoq1ik77DbtwqrdOjQBpS0qJCwJK@vPswCh6mHMlpX3nhXLz6oV0nyq7Ds9ZOmRt7tapCaXAjdEbzE@c5XkYoubuU8X5Ibdr@Y@2cxm54i0JUfMG1PZOkKHKqckHoOBVa7PYOiFVnnuVAh7xkYVvnr25tQQxulrW6/9vOtcIxC8jI3KG5wVWBulqyI3OD3EyiiMPgSiyEO0JN1DCA0IyPGDTwPLH@VGx1VV/GBBa7ML3uWLMORpeRfxxUTvYRnxW7i@GpYEwF4jcQEXwFz8B04uLmDC1V7XifM0WJp0JLjdBQ0OOnxCf23c/gI) for single-character input `0`, `2` & `1` as black, white & empty). Multiplies black squares by `-0.5` and white squares by `0.5`, and then uses the standard deviation (`sd`) to check if all the resulting nonzero `[!!z]` values are the same (in which case the standard deviation is zero). In many challenges, the `sd` approach could fail for inputs with zero or one items (which would yield a standard deviation of `NA`), but luckily this can't happen here for a valid chess position. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ŒJ§ḂṬƙFṀḊ ``` [Try it online!](https://tio.run/##y0rNyan8///oJK9Dyx/uaHq4c82xmW4PdzY83NH1/3D70UkPd87QjPz/P5orOtpIR8EAhhDsWB0uhWgDJCmIrCGQBEsZYYoj6TJCEoeqQTIQoR5JF0QlOgnTZYhkHVQWSZcBmmwsUA7oM0znYzoERRbD@Qg1qJ42xPA0ssMRamC6sHgOI4AxPY2JDKE@MwLbjI5gtuGSwmqkAW2kDMFeQUf4pGgaZ4bYEip944xynxnhTo0GA5wa0WyjXbqilxRyPjNE89yQ91ksAA "Jelly – Try It Online") Takes input as an \$8 \times 8\$ matrix, with `0` being empty space, `1` being white and `2` being black. Outputs an empty list `[]` for truthy, and a non-empty list `[1]` for falsey. Additionally, if we *really* want to stretch the output format, we can have this 8 byter ``` ŒJ§ḂṬƙFṀ ``` [Try it online!](https://tio.run/##y0rNyan8///oJK9Dyx/uaHq4c82xmW4Pdzb8P9x@dNLDnTM0I///j@aKjjbSUTCAIQQ7VodLIdoASQoiawgkwVJGmOJIuoyQxKFqkAxEqEfSBVGJTsJ0GSJZB5VF0mWAJhsLlAP6DNP5mA5BkcVwPkINqqcNMTyN7HCEGpguLJ7DCGBMT2MiQ6jPjMA2oyOYbbiksBppQBspQ7BX0BE@KZrGmSG2hErfOKPcZ0a4U6PBAKdGNNtol67oJYWczwzRPDfkfRYLAA "Jelly – Try It Online") which outputs `[1]` for truthy, and `[1, 1]` for falsey. ## How it works ``` ŒJ§ḂṬƙFṀḊ - Main link. Takes a matrix M on the left ŒJ - 8x8 grid of coordinates [x, y] between 1 and 8 § - Sum of each coordinate Ḃ - Bit F - Flatten M ƙ - Over the lists formed by grouping the flattened M by the bit of the coordinate: Ṭ - Yield a boolean list, with 1s at the indices in the list Ṁ - Maximum Ḋ - Dequeue, remove the first element ``` [Answer] # [Factor](https://factorcode.org/), 43 bytes ``` [ 2 group unzip [ cardinality 3 = ] both? ] ``` [Try it online!](https://tio.run/##fZDPTgMhEIfv8xS/J@Cgtxqjid2ol5poPDU9AGIlRXaF2ZD68itTSBoT4xDg4898Q3jXlse0vL48bu5XyO5rdtG6jH0a58nHPXTOo831hDMOLkUX8DkH9sFHhyk55uOUfGRcET0Mz8P66W6FYbMmJWGUIRmlk6yEqfZiSt0pqihhMkK1nbKEWnplEtdvc9OpfsdIeptbiao8FS1SjLq4HpWmptLE6i9zjzP0Z6j/oPQ4g7iWLS7aN2KO337CFlanNx918HzEJa6xgxn54wa7hZO/hcqwwem0/AA "Factor – Try It Online") Takes input as a string with any three distinct values representing black pieces, white pieces, and empty spaces and relies on the trick from @loopy walt's [Python answer](https://codegolf.stackexchange.com/a/240572/97916): namely, that because of newlines, even and odd indices of the string correspond to black and white squares. However, all we need to do is check if the cardinality of both groups is three. [Answer] # [J](http://jsoftware.com/), 23 22 21 16 15 bytes ``` 6 e.]*.//.~2|#\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/zRRS9WK19PT19eqMapRj/mtypSZn5CukKRgpGIIhjEaGRgrGYHEjND5MPYhviEUewjdGw4ZoNLI4VAzmKGQnGGI40QhNDlXcGMmZqFYjnIzDehQ@XBwRUqjQEIsItaAxGsQQoTykjFEilKohRYqjjDCiz5DKjvoPAA "J – Try It Online") Test cases taken from caird's Jelly answer *Input:* Single list with space & newline = 1, black = 2, white = 3. *Output:* 0 for valid, 1 for invalid. ## how * `2|#\` Creates list `1 0 1 0 1 0 ...` to length of input. * `]*.//.~` Partitions input according to that, taking LCM of each partition. Only an invalid board will have a partition containing both `2` and `3`, and hence an LCM of `42`. * `6 e.` Is `6` an element of that? Only possible on invalid boards. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 66 bytes ``` a=>a.map(t=r=>r.map(c=>t|=5+(g=-g)*(c>{}?-1:c>'@'),g=-g),g=3)^15^t ``` [Try it online!](https://tio.run/##fZDBboMwDIbvfgpuJOtwVU29rAqbkHaqhFKuY1VDBoxBQxqiXbo@O0uA7ThLSb7Y@X8r/hRfYpCm0TZS/Xs5VmwULBZ4FppYZlhsJpQstt9suyI1i2p6R2R8vT1Fm0cZh88hvZ@ybn@gx832aEdbDlaKoRwCFpwAfRhsHWhHBYI7tcsguDvXiUbgyNEzXDgeHPNJleEeZ7ljADP54JLSSev1qLieHZ2D9j14gYtj6hZMzplzzCaZcwSjiktbKAN6id8m@B/wJSBLk8M@STM44aC7xpJ1rnK1WtN5bAGLA4vWNGdClwdhrsK5anz11X/kjVKAv0lh1ZsXIT9m@RWCQPZq6LsSu74mFbGU7uBGd@MP "JavaScript (Node.js) – Try It Online") Input 2d array of characters in `rnbqpRNBQP.`. Output truthy vs falsy. 52 bytes if input as 2d array of `+1, 0, -1`. [Answer] # Python3, 245 bytes: ``` lambda b:g({(x,y):b[x][y]for x in r(8)for y in r(8)}) r=range g=lambda p:len(set(w:=[(x%2==0 and y%2==0)or(x%2 and y%2)for x,y in p if p[(x,y)]==1]))==1 and len(set(b:=[(x%2==0 and y%2==0)or(x%2 and y%2)for x,y in p if p[(x,y)]==0]))==1 and w!=b ``` [Try it online!](https://tio.run/##pZHBauMwEIbPO08xDRRJkA5NcikGXXItFDVX1yzWRs6q9cpa2SUxyz57Kil26KHsZUeMPPPN6B8j@XH42bnNgw/nRr6c2/qX3teoiwP/w0/LURS6PFXlWDVdwBNah4E/iJSMc/JXQJChdgcDBzmd90VrHO/NwI@FLPnpdi3lPdZuj2MORRcSnEkWjNOSpEfboC/z8ErKVSVE3HPnrKn/U/P@k@bxRuqzXsnFYkE4rxD9DVLkJ6KR4JL5qU5wqalItomCyhnNFH7n7HmiCmb1XfTHrPd57eIfgF6jxBgEIkoOlMxv38DHr1M@Ek9eRRZLXumYgSJFT9EhOtGOFOzysUfKkpuLpJ4MrgFN9q/gONk1SPcUjG/rH4YzzZZsywTsTYND9113ddjzXhTwLZjhPTgsy7tVunsrJSOGpu0NWrL9u/cmcIHpjWx6odfchTcSGbIq89fEG9sOsfOpc2aJPfW@tQNnL44JUQH4YN3AG36drVdCiC/w@mu8ifj8AQ) [Answer] # [Perl 5](https://www.perl.org/), 48 bytes ``` y,/2468,1,d;$_=/^(([w\d][b\d])+|([b\d][w\d])+)$/ ``` [Try it online!](https://tio.run/##lU9dS8NAEHzPrzhpoQltWC4ftVhFDOhLIFzzaK2Sa04bEi/bu0hQQn@68WwLin1yh71bZnYGFoWqwn6ASqCq10JrcnebuIXEt@bC0rDM3I8VcHiZkwGvsnWpCRfr@lWY/1u@ce9X0O7ldlM04kdureHT1U539vXlGTjDDjqzk@W5JlK0VSEFGcGI1JJUmW6IqltSPJOiGRm9bkizEUr07xPwgulsQif53KTBo20v24d8teTmccadvR/2lDN2htD3oaIleOhzChQNlAfoMYyQAqPMZwhbRhfUzBCkNKZwnlrKVz6EGJWAvmR4cDIPTQ7j9OCkiWkwCalxpmFMLSX5tuRSAR4LZkewY0GaRIs4SlJrBr8RxLSkp1x8ypXeH2paxhYG/7/xs8amqKXuXay@AA "Perl 5 – Try It Online") Takes preprosessed FEN-input: blacks becomes `b` and whites `w`. Deletes 2, 4, 6 and 8 empty squares since they don't change the result, odd empties 1, 3, 5 and 7 are treated as 1 (no difference in result). Flattens the board so the newlines `/` become one invisible empty square. The regex tests if all 36 pairs (9x8/2) of the flattened board consist of either white|empty then black|empty or the opposite. Returns `1` for truthy and `""` (empty string) for falsey. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes ``` a->sum(n=0,1,!matrix(8,,i,j,(i+j+n+t=a[i,j])%2*t)) ``` [Try it online!](https://tio.run/##lY7BCsMgEER/xQYK2mzAeCosyY8ED15SDE2Q1EL79dZobDW3siw6M@I8o1bd3IwbSedU0z@eM106Di2cZmVX/aJXAA0TUF1P9VLbTg1eSnYWF8uYU8bc31SRpidm1Yv112oTFRmpYgzIMHBI026L6bafuPvJxZgJr0TIRVA8udhCcsIi/2Zh8dcXXOkZsrpQkSPFLzOVIcXahCwSJBYA4b3IIGKeYUWEYvCoS2r@txZQzFFLydwH "Pari/GP – Try It Online") Takes input as an 8x8 matrix of `0`s (empty), `1`s (black), `2`s (white). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~35~~ 32 bytes ``` T`L`0 T`l`1 s`(\d).(..)*(?!\1)\d ``` [Try it online!](https://tio.run/##PYxBC8IwDIXv/R0Kc7CFtI55tdfCyHp0DraiBymMrHoS/3vt3PA9EkIe3wv312Ma4z4brjexy@Nz6M7FpS@zsjzk3Vi8@89vb48li7EK6EGycgjIyUECS2LNCISkiGEmbDHdcLRoEGorggoKKtYeWE3EK0mSUw85XEls0kBqsIm0lUERJjd7NwXgTXDaTJvANro1urHC1/9wcW2@ "Retina 0.8.2 – Try It Online") Takes input as a board but link is to test suite which converts from FEN to a compatible board, so if you want to test board input then delete the contents of the header first. Outputs `0` for a reverse draughts position and non-zero if not (+1 byte to always output `1`). Explanation: Maps pieces to `0` or `1` depending on their colour (-12 bytes for a custom input format) and then checks whether opposite colour pieces are on two squares of the same colour. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` F²⊞υ⟦⟧F⁸UMS⊞O§υ⁺ιλ⁻№ακ№βκ⊙υ×⌈ι⌊ι ``` [Try it online!](https://tio.run/##LU2xbgIxDN3zFRkd6eqBCYmJMqHqwIJuVYcA117EJbFySUW/PnWOWnqy3/N79nW06RrtVOtXTBpWRlOZRyid/vg0G7WIa6N7y7vovQ032Acu@ZyTC99gusV@5CHZHBNs8z7chkeL01RmcJ2ejJh6F4TtYgkZbKfvIj3JpREjj0juZdiG35Z9d36YobcP54sH9zzwPzd3rQkRGxS24te7YumBWBRGJtFkxXQRpggJDwIlQDwhqdMSe8P68jP9AQ "Charcoal – Try It Online") Takes input as a board and outputs nothing for a reverse draughts position and `-` if not. Explanation: ``` F²⊞υ⟦⟧ ``` Start collecting the colour of pieces on squares of each colour. ``` F⁸ ``` Loop over the rows. ``` UMS⊞O§υ⁺ιλ⁻№ακ№βκ ``` Push `1`, `0`, or `-1` to the appropriate square colour list depending on the colour of the piece or `0` if there is no piece. ``` ⊙υ×⌈ι⌊ι ``` See whether any square colours contain pieces of both colours. Since there can only be 15 pieces of the same colour on squares of one colour, there will be at least one zero in the array, but this will not be the minimum or the maximum if this is not a reverse draughts position. ]
[Question] [ # The rundown Create a program that generates an array of random length with random numbers, then apply a series of rules that alter the array. After the rules have been applied, print the sum of the array unless specified otherwise # Array setup The array must be a random length between **5 and 10** inclusive, with random integers between **1 and 20** inclusive. Each array length should have equal probability of happening and each integer should have an equal probability of being picked per element. # The 7 rules The rules should act as if they were applied in sequence (eg: rule 1 acts before rule 2) and are only applied once. **For proof of rule application, the array must be printed to console after each rule application and once before any rules are applied.** 1. If the array contains a 7, subtract 1 from every element 2. If rule 1 is applied and the array now contains a 0, add 1 to each element 3. If the array contains a 13, exclude the 13, and all elements that follow, from the array 4. If the array contains a 2, exclude all odd numbers 5. If the array contains a 20, and the third element is even, return 20 as the sum then terminate. If a 20 is present and the third element is odd, return 20 times the length of the array as the sum then terminate. 6. If the sum is greater than 50, remove the last element repeatedly until it is less than or equal to 50 7. If the array contains a 16, print the sum in both decimal and hexadecimal. # Example Here is an initial array, ``` [20, 2, 5, 7, 14, 8] ``` Rule 1 can be applied: ``` [19, 1, 4, 6, 13, 7] ``` Rule 3 is applied next: ``` [19, 1, 4, 6] ``` No other rules are needed, so the program returns **30** as the sum. # Notes * I'm not an experienced code golfer, although I can say my personal record is in Python 3 with **369 bytes**. * The rules don't have to actually be applied in order, but have to act as if they did. [Answer] # Python 3, ~~294~~ ~~301~~ ~~287~~ 356 bytes ``` import random as r r=r.randint k=[r(i)+1for i in[20]*r(5,11)] p=print if 7in k:k=[i-1for i in k] p(k) if 0in k:k=[i+1for i in k] p(k) i=k.find(13) if not~i:k=k[:i] p(k) if 2in k:k=[i for i in k if~i%2] p(k) a=0 z=len(k)>2and k[2]%2 if 20in k:a=20*len(k)**z if~z:p(k) while sum(k)>50:k=k[:-1] if~z:p(k) if a:p(a) else:a=sum(k);p(a,hex(a)*(16in k)) if~z:p(k) ``` I don't know how you're going to prevent people circumventing the rules, but this one uses the procedure specified. +7 bytes; thanks to @YamB for saving a few bytes; added a lot more to fix a previous error. -14 bytes thanks to @RootTwo and myself and also corrected the error. +83 bytes; this is getting horribly long because OP keeps changing the rules. -some number of bytes thanks to @ZacharyT [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 91 bytes ``` 5TŸ.RF20©L.R})=D7åi<=D0åi>=}}D13åiD13k£=}D2åiDÈÏ=}D®åiDgs2èÉ®si*},q}[DO50›_#¨=]D16åiDOH,}O, ``` [Try it online!](https://tio.run/nexus/05ab1e#@28acnSHXpCbkcGhlT56QbWati7mh5dm2ti6GAApO9vaWhdDYyALSGYfWmxb62IE4hzuONwPZB9aB@KkFxsdXnG489C64kytWp3C2mgXf1ODRw274pUPrbCNdTE0Ayny99Cp9df5//9rXr5ucmJyRioA) or [With input](https://tio.run/nexus/05ab1e#@2/rYn54aaaNrYsBkLKzra11MTQGsoBk9qHFtrUuRiDO4Y7D/UD2oXUgTnqx0eEVhzsPrSvO1KrVKayNdvE3NXjUsCte@dAK21gXQzOQIn8PnVp/nf//ow3NdRRMdRSMdRQMgchMR8EIxARioLihYezXvHzd5MTkjFQA) [Answer] # JavaScript, ~~344~~ ~~342~~ ~~340~~ ~~342~~ ~~335~~ ~~331~~ ~~333~~ ~~313~~ ~~311~~ ~~305~~ ~~298~~ ~~297~~ ~~290~~ ~~289~~ ~~283~~ ~~279~~ ~~271~~ ~~265~~ 263 bytes Following [this exchange](https://codegolf.stackexchange.com/questions/116318/the-tedious-array-of-7-rules/116406#comment285409_116318)\* in the challenge's comments and after much deliberation I opted to use `new Date` as the seed for the random number generator instead of `Math.random()`. Doing so means that all the integers in the array will be of the same value. Now a full programme, rather than a function ``` D=new Date P=print I=n=>~a.indexOf(n) C=(n,c)=>I(n)&&P(a=+c?a.map(x=>x+c):a.filter(c)) P(a=[...Array(D%6+5)].map(x=>D%20+1)) C(7,-1) C(s=0,1) C(13,(_,x)=>x<~I(13)) C(2,x=>x%2) P(I(t=20)?a[2]%2?t*a.length:t:P(a.filter(x=>s+x<51?s+=x:0))|I(16)?[s,s.toString(16)]:s) ``` [Try it online!](https://tio.run/##NY9Pa8MwDMXv@RS7pFizaxKP/sFUCaO55LTCjiEMkaVdRueF2HQejH71zC70JD3x03vSJ13IdtMwuuVlO88Vmv7noSLXJwccp8G4pEaDxZXkYN57/3JkBpI9MiM6wKIOarE4MELelSS/aGQeC8870CSPw9n1E@sAkkg0UsrnaaJfVqVrvoL2jlepyngeqD3biGUeq8VM3Jr8SbA34UOU313rIG@YEjElVdG4Zg5VBiU1qk1V6R5Jnntzch/a6RB7vyIsWO53q7y0HL3OAP6C3RrKxgor3ferC8@e4qTVFub5Hw) or [with `Math.random`](https://tio.run/##NY9Bi8IwEIXv/R9KYmJos@guwWkRvfSwrLDHUpYhVu2isSRBsiD@9W4ieJp5j5n3zfziDZ22/eDnt49x3MIn@pOwaPbXS7aDwfbGZzUYKB8oerPvwteBGJptgBiuKZR1VNPpjiAwXaG44EAClIFpqlAc@rPvLNGUZmmiEUKsrcU/siV0tmSLe07b10qyZM6K6MV48s7nRaoOcv5sijdOfniIyLB61FE@xyRPtIlMgJp4kDmtsJHtRFZ@huLcmaM/Ka8i/nVNXHAsrBZF5RgEFXH3GLekVeO4E/767ePTx@S0ytFx/Ac) --- \*Screenshot, in case it's deleted: ![](https://i.stack.imgur.com/IgQ9S.png) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~621~~ ~~619~~ ~~593~~ ~~585~~ ~~570~~ ~~562~~ ~~557~~ ~~552~~ ~~529~~ ~~517~~ ~~500~~ ~~482~~ ~~461~~ ~~444~~ ~~442~~ ~~441~~ 438 bytes There's a whole lot of golfing needed here... Fixed a bug where it would print the hexidecimal once for each 16 in the list... Special thanks to ZacharyT with the golf help ``` #define R r[i] #define P printf("%d " #define L for(d=i=0;i<l;i++) d,i,j,l,r[11];p(i){L P,R);puts("");}main(){srand(time(0));for(l=5+rand()%5;i<l;R=1+rand()%20,i++);for(p();i--;)if(R==7){L--R;j=i=1;}for(p();j&&i<l;i++)if(!R){L++R;j=i=l;}p();L if(R==13)l=i;p();L if(R==2)for(d=1;d;)L if(R&1)for(d=1,--l;i<=l;i++)R=r[i+1];p();L if(R==20)return P,r[3]&1?20*l:20);for(j=i=0;i<l&&j+R<51;j+=R,i++);l=i;p();P,j);L if(R==16)printf("0x%x",j,i=l);} ``` [Try it online!](https://tio.run/##TZHNasMwEITveQrVJUZbSWAlpIWuRV/Ah6BryCH4p13hOEZxIBDy2D27io1KjvoYjWZGpfouy3F8reqGuppZ5ne0X8TjlvWeuqHhybJiyT8uWHPyvDJkMqS8RRICFpUk6WQr/U7rPfac4FawrbSA/WU48yQBvB8P1HG4nf2hq/hAx5pnAPgwa81GTBSWm8nTGh3BKpOPFyZdzwFJKQRquDXmIzyilEUXsmi8R4VL05gr6F5sUAkxq1q8PxQFmw30GlpD@IxWMLfTWCHMMNWRSaWCb25mc2vCXGKq@3Q/A18PF9@F9n633qf6a5W9tZ@BTxVc3C1NnbD5RqMTxs4VY5atdE8Z3yF@Q3ZdXpMwc@gR5hzH3@6kykP5U/8B "C (gcc) – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~160~~ ~~147~~ 139 bytes -13 from consolidating `0N!` prints/other tweaks -8 by converting to `ngn/k` ``` {0N!'|(a@:&(~2!a)|^a?2;a:(a?13)#a;a+:|/~a;a-:|/a=7;a:1+(*5+1?6)?20);$[^a?20;;:20*(1;#a)2!a 2];0N!a@:&51>+\a;(+/a),$[^a?16;!0;,`hex@`c$+/a]} ``` [Try it online!](https://ngn.bitbucket.io/k/#eJxtjU1rwkAQhu/5FeMHdddtyc6mSWCHGnvorXgo9KSRDHUlguag9gOa+tu7we2lepkZeJ/nnbX91rPeqBU8tTfiZHos2yUXhtgKLjCRAyZWto1Pft/5zQ+5z1CJcaqwyGRhtKThvHM0kTV6LJAGLH0TmJJ8edec4kQt+MxhRipmEt2oavc1rd6G/pblTxRVoC30oeYDYALi5fX5CRLZj9bz8i9cNHB438EEUh2A7ALo/DykeE4hhn+ACcD9hT6LH681YhaM/OpDo2/hc3OswX24BpL9CtzW7VxzDFYarF9u0Vt1) From the beginning to the end... * `0N!'|` print each of the following in reverse order (when building lists, `ngn/k` executes the right-most/last list item first, the second-to-last item second, etc. For ease of explanation, the below are listed in the order they are executed) + `a:1+(*5+1?6)?20` generate 5-10 random numbers between 1 and 20, storing in `a` + `a-:|/a=7;` decrement `a` if it contains a `7` + `a+:|/~a;` increment `a` if it contains a `0` + `a:(a?13)#a;` take elements occurring before the first `13` + `a@:&(~2!a)|^a?2;` if a `2` is present, remove odds from `a` * `$[^a?20;;:20*(1;#a)2!a 2];` if `20` is present, check the third value `a 2` and early return from the function (otherwise do nothing) * `0N!a@:&51>+\a;` remove values where the cumulative sum up to that point is >50 * `$[^a?16;+/a;(+/a;`hex@`c$+/a)]` return either the sum of `a` (if no `16` is present), or return the sum as both an integer and in hexadecimal representation (the latter as a string) [Answer] ## JavaScript (ES6), ~~296~~ ~~295~~ ~~290~~ 289 bytes A full program that logs the initial array, the intermediate results and the final sum to the console. ``` f="z=[...Array(5+6j)]Z1+20jw7`-1w0`+1w13_qi+1<-kw2_qn&1^1w20_z[2]&1?a.length*20:20);else{q(s+=n)<51,s=0w16_b.toString(16_;b)}zconsole.log(aw_;if(k=~a.indexOf(v((n,i)=>qz=a.filtervj*Math.random()|0bz.reducevn+i,0)`_z=aZn_))Z.mapv";for(g of "Z_`bjqvwz")e=f.split(g),f=e.join(e.pop());eval(f) ``` ### How it works This was compressed using [this JS packer](http://js1k.com/2012-love/demo/1189). Breakdown: * Packed string: ~~226~~ 225 bytes * Unpacking code: ~~69~~ 64 bytes Below is the original source code with some additional whitespace and line feeds for readability. Rather than applying standard golfing tricks, it was written in a way that produces as many repeating strings as possible in order to please the packer. For instance, the syntax `if(k=~a.indexOf(N))` is duplicated everywhere although `k` is only used in the 3rd rule. ``` console.log(a=[...Array(5+6*Math.random()|0)].map((n,i)=>1+20*Math.random()|0)); if(k=~a.indexOf(7)) console.log(a=a.map((n,i)=>n-1)); if(k=~a.indexOf(0)) console.log(a=a.map((n,i)=>n+1)); if(k=~a.indexOf(13)) console.log(a=a.filter((n,i)=>i+1<-k)); if(k=~a.indexOf(2)) console.log(a=a.filter((n,i)=>n&1^1)); if(k=~a.indexOf(20)) console.log(a[2]&1?20*a.length:20); else { console.log(a=a.filter((n,i)=>(s+=n)<51,s=0)); if(k=~a.indexOf(16)) console.log(a.reduce((n,i)=>n+i,0).toString(16)); console.log(a.reduce((n,i)=>n+i,0)) } ``` ### Unpacking methods The original unpacking code is: ``` f="packed_string";for(i in g="ABCDEFGHI")e=f.split(g[i]),f=e.join(e.pop());eval(f) ``` All the following ES6 variants have exactly the same size: ``` eval([..."ABCDEFGHI"].reduce((f,g)=>(e=f.split(g)).join(e.pop()),"packed_string")) [..."ABCDEFGHI"].map(g=>f=(e=f.split(g)).join(e.pop()),f="packed_string")&&eval(f) eval([..."ABCDEFGHI"].map(g=>f=(e=f.split(g)).join(e.pop()),f="packed_string")[8]) ``` The only way I've found so far to shave off a few bytes is to use `for ... of`: ``` f="packed_string";for(g of "ABCDEFGHI")e=f.split(g),f=e.join(e.pop());eval(f) ``` [Answer] First try at code golf! Already beat by other javascripters! Dangit! I will improve!!! =) ## **Javascript -> ~~550~~ 402 bytes** Could definitely be improved. Compressed Now: ``` f="ba=[];bl;yz5+5`^=0;i<y;i++)a[i]z20+1|~7j-1|~0j+1|}}~13_l=indexOf(13`ql,y-l-Y_^ in a)if(a[i]%2)qi,Y0)&&(!a[3]%2_k'20'`throw new Error(`}do{l=Vreduce((X,num)=>X+num`ifW)qy-1,1`}whileW|kl`~16))kl.toString(16)`~if(Vincludes(|`ka`z=Zound(Zandom()*yVlengthqVsplice(kalert(j_Vmap((i)=>ibvar `);_)){^for(biZMath.rY1|}~2XtotalW(l>50Va.";for(i in g="VWXYZ^_`bjkqyz|~")e=f.split(g[i]),f=e.join(e.pop());eval(f) ``` Originial: ``` var a=[];var l;a.length=Math.round(Math.random()*5+5);for(var i=0;i<a.length;i++)a[i]=Math.round(Math.random()*20+1);alert(a);if(a.includes(7)){a.map((i)=>i-1);alert(a);if(a.includes(0)){a.map((i)=>i+1);alert(a);}}if(a.includes(13)){l=indexOf(13);a.splice(l,a.length-l-1);alert(a);}if(a.includes(2)){for(var i in a)if(a[i]%2)a.splice(i,1);alert(a);}if(a.includes(20)&&(!a[3]%2)){alert('20');throw new Error();}do{l=a.reduce((total,num)=>total+num);if(l>50)a.splice(a.length-1,1);}while(l>50);alert(a);alert(l);if(a.includes(16))alert(l.toString(16)); ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 525 413 bytes ``` filter a{"$a"};0..(4..9|random)|%{$a+=@(1..20|random)};a;if(7-in$a){$a=($a|%{$_-1});a;if(0-in$a){$a=($a|%{$_+1});a}}$b=$a;$a=@();foreach($z in $b){if($z-ne13){$a+=@($z)}else{a;break}}if(2-in$a){$a=($a|?{$_%2-eq0});a}if(20-in$a){if($a[2]%2){20*$a.count;exit}else{20;exit}}while(($h=$a-join'+'|iex)-gt50){$a=$a[0..($a.count-2)];a}if(16-in$a){$l=0..9+'a b c d e f'-split' ';$q=[math]::floor($h/16);"$q"+$l[$h%16]};$h ``` [Try it online!](https://tio.run/nexus/powershell#ZZDRToMwFIZfpSGH0EqKperM1hD3HgsxhRWpdq1jGJexPrbXs4xxYbxs/@/838m5NNr0qkNyiEBGXrAsw49Ztjx30m7djpzjAWRarHGeZZzNv15IoRv8TLUFSQJRYJAj@kpzT6aQ/Q/Ta@g9VAVIEYI1JqJxnZJ1i@GEtEVQkSEMw4lalT@QmxxOxCtzUIMUVaA/vA8M/yt4CYKYU7VnV8kIzCuMhXLDy5iTgbM7kFntvmwv1FH3Uy9n08N/t9oojKENG9J3p22SJmetjoS@9U/sKgtV45XmFspJOfnyxbyRKQKxTBOJKlSjLVKoSejh0@g@QYmAfbHZyb4tV6vGONcF232@ICKCfZSC2UAb54vSC2gvlx/raB3Oo34B "PowerShell – TIO Nexus") I wanted to attempt this one although I figured I wouldn't beat the answers already here :P I have been attempting to golf this down still, I'm sure it's possible with less bytes. Found a better method for hex, but could probably still improve. Had to cast `$a` to a string so many times it was better to create a filter for it... There were quite a few easy golfs I missed such as parentheses and spaces. Might still be some out there? Somewhat easier to read code: ``` filter a{"$a"};0..(4..9|random)|%{$a+=@(1..20|random)};a; if(7-in$a){$a=($a|%{$_-1});a;if(0-in$a){$a=($a|%{$_+1});a}} $b=$a;$a=@();foreach($z in $b){if($z-ne13){$a+=@($z)}else{a;break}} if(2-in$a){$a=($a|?{$_%2-eq0});a} if(20-in$a){if($a[2]%2){20*$a.count;exit}else{20;exit}} while(($h=$a-join'+'|iex)-gt50){$a=$a[0..($a.count-2)];a} if(16-in$a){$l=0..9+'a b c d e f'-split' ';$q=[math]::floor($h/16);"$q"+$l[$h%16]};$h ``` [Answer] # Ruby 2.4, 260 bytes Ruby 2.4 is required for `Enumerable#sum`. ``` p a=(1..s=5+rand(5)).map{1+rand(19)} a.map!{|i|i-1}if a.index 7 p a a.map!{|i|i+1}if a.index 0 p a a.pop s-(a.index(13)||s) p a a.reject! &:odd?if a.index 2 p a a.index(20)?p(20*[1,s][(a[2]||1)%2]):((a.pop;p a)while a.sum>50 p m=a.sum;puts"%x"%m if a.index 16) ``` [Try it online!](https://repl.it/HwCO) (Neither repl.it nor tio.run support Ruby 2.4 yet, so this online version replaces `sum` with `inject(:+)`, which has the same behavior.) [Answer] # Java 10, ~~622~~ ~~619~~ ~~618~~ ~~613~~ ~~576~~ 575 bytes ``` v->{var L=new java.util.Stack<Integer>();String r="",N="\n";int c=(int)(Math.random()*6+5),i=c;for(;i-->0;L.add((int)(Math.random()*20+1)));r+=L+N;if(L.contains(7)){for(;++i<c;L.set(i,L.get(i)-1));r+=L+N;}if(L.contains(i=0)){for(;i<c;L.set(i,L.get(i++)+1));r+=L+N;}if((i=L.indexOf(13))>=0){L.subList(i,c).clear();r+=L+N;}if(L.contains(2)){for(i=0;i<L.size();)if(L.get(i)%2>0)L.remove(i);else++i;r+=L+N;}if(L.contains(20))return r+20*(L.get(2)%2<1?1:L.size());i=0;for(var x:L)i+=x;for(;i>50;)i-=L.remove(L.size()-1);return r+L+N+(L.contains(16)?Byte.valueOf(i+"",16)+N:"")+i;} ``` -1 byte thanks to *@Poke* -6 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##dZJRT9swFIXf@RVWpEm@uLGSTIBU10Ha26SQPSDtBfZgHLdzSR3kOFlZ1d/eXUPKAMFLLDv3fOfa96zVqNJ1c3/Qrep7cqWs250QYl0wfqm0IXXcEnIdvHUrounPzjZkBIGn@xP81MQRSQ5jWu5G5UklnflD1kjlQ7Atvw5K3y@@I25lfElBTCAvk2RWy@TWJQLNiJYUF6BXKvzmXrmm21A4PWdnMLNSi2XnqbBpWmai4qpp6EfVRcZyABCeyYrVwi5pxXXnAt6ppxcAuycKY3ahkdKbQO2s4qu4Qpr/F@7fKq3MjtoPlIwBe6dFRcWta8z2x5LmXwFKJOxQN9xVto9aDVy3Rnn6mWcxOaI3mqLU/jVYDE9Vzx1/KcoMKu7NphsN7oVpe4OX@4yIl/AmDN4Rz4rsdOIUyFnkl/n86AEiekbvOM7tvALL5HYaQHmWYQ@pfLE9qvD5xAsd3dlr6/wcLr89BsNH1Q4G38QyHD6esnqeJIAt7w8iZulhuGutJn1QAZcxJm2DBPqcmZtfRAGZ4vjYB7Ph3RD4A/4LraMxdzG@FLjjmrqhbWGK6f7wDw) **Explanation:** ``` v->{ // Method with empty unused parameter and String return var L=new java.util.Stack<Integer>(); // Integer-list, starting empty String r="", // Result-String, starting empty N="\n"; // Temp-String `N`, containing a newline int c=(int)(Math.random()*6 // Get a random integer in the range [0,6] +5), // And add 5 i=c;for(;i-->0; // Loop that amount of times: L.add((int)(Math.random()*20+1))); // Add a random integer in the range [1,20] to the list r+=L+N; // Append the current list + newline to the result-String if(L.contains(7)){ // If the list now contains a 7: for(;++i<c;L.set(i,L.get(i)-1)); // Decrease each value by 1 r+=L+N;} // And append the current list + newline again if(L.contains(i=0)){ // If the list now contains 0: for(;i<c;L.set(i,L.get(i++)+1)); // Increase each value by 1 r+=L+N;} // And append the current list + newline again if((i=L.indexOf(13))>=0){ // If the list now contains a 13: L.subList(i,c).clear(); // Remove all values from that 13 onward from the list r+=L+N;} // Append the current list + newline again if(L.contains(2)){ // If the list now contains a 2: for(i=0;i<L.size();) // Loop over the list: if(L.get(i)%2>0) // If the current value is odd: L.remove(i); // Remove it else // Else: ++i; // Skip it, and go to the next value r+=L+N;} // Append the current list + newline again if(L.contains(20)) // If the list now contains a 20: return r // Return the result-String +20* // And append 20 multiplied by: (L.get(2)%2<1? // If the third item is even: 1 // Multiply the 20 by 1 so it'll remain 20 : // Else (it's odd instead): L.size()); // Multiply the 20 by the list-size i=0;for(var x:L)i+=x; // Set `i` to the sum of the list for(;i>50;) // Loop as long as the list-sum is larger than 50: i-=L.remove(L.size()-1); // Remove the last item of the list return r // Return the result-String +L+N // Appended with the current list + newline again +(L.contains(16)? // If the list now contains a 16: Byte.valueOf(i+"",16)+N // Append the sum as hexadecimal : // Else: "") // Append nothing +i;} // And append the sum (as regular base-10 integer) ``` **Sample outputs:** *Comments behind the sample outputs aren't printed, but I added them as clarification.* ``` [17, 5, 3, 1, 16, 17, 11, 7, 13] // Initial print (size 9) [16, 4, 2, 0, 15, 16, 10, 6, 12] // Rule 1 (contains a 7) [17, 5, 3, 1, 16, 17, 11, 7, 13] // Rule 2 (contains a 0) [17, 5, 3, 1, 16, 17, 11, 7] // Rule 3 (contains a 13) [17, 5, 3, 1, 16] // Rule 6 (sum must be <= 50) 66 // Rule 7 (contains a 16 -> print as Hexadecimal) 42 // Print sum as integer [4, 18, 17, 12, 11, 8] // Initial print (size 6) [4, 18, 17] // Rule 6 (sum must be <= 50) 39 // Print sum as integer [4, 14, 6, 14, 7, 20, 2, 2] // Initial print (size 8) [3, 13, 5, 13, 6, 19, 1, 1] // Rule 1 (contains a 7) [3] // Rule 3 (contains a 13) [3] // Print is always done after rule 6 3 // Print sum as integer ``` [Answer] # R (3.3.1), 325 bytes Pretty naive implementation; I think I can probably make it a bit shorter. ``` s=sample(1:20,sample(5:10,1));print(s);if(7%in%s){s=s-1;print(s);if(0%in%s)s=s+1;print(s)};if(13%in%s){s=s[1:(which(s==13)-1)];print(s)};if(2%in%s){s=s[!(s%%2)];print(s)};if(20%in%s){if(s[3]%%2){20*length(s);print(s)}else{20;print(s)}};while(sum(s)>50){s=s[-length(s)];print(s)};if(16%in%s){print(as.hexmode(sum(s)))};sum(s) ``` [Answer] ## MATLAB, 275 bytes I originally planned on maybe a one-liner Octave answer, but requiring output of all applied rules thwarted my plans. Instead, a fairly straightforward MATLAB answer with a few interesting optimisations, e.g. the use of `cumsum` instead of the obvious `while` for rule 6. Still, a lot of the byte count is wasted on `if`s to prevent output if a rule is not applied. ``` A=randi(20,1,randi(6)+4) if any(A==7) A=A-1 if any(~A) A=A+1 end;end q=find(A==13,1);if q A=A(1:q-1) end if any(A==2) A=A(2:2:end) end if any(A==20) if mod(A(3),2) 20*length(A) else 20 end;return;end q=cumsum(A)<51;if any(~q) A=A(q) end q=sum(A) if(any(A==16)) dec2hex(q) end ``` [Try it online!](https://tio.run/nexus/octave#ZY7PCoMwDIfvfYod21nB1M2Broc@itg6Ba3UP7Bd9tY7u9gqDHYIhF@@5Muq5Fha3VKRcOChzVh0YaStT6V9USXljRElVQxH9FY@iIAYqwss4mTdWr2xkHJgBYJuQyjkLga2cT/3hF@nIhc5Dv6miXf3A96jKeNIi@TcGfuYG4pm000GE@8ezbyMdn@hWvpp6RG5X6E4XnXB5YLFyUCggO46yBgj2lSiMc8dW9ePHeKqrBrzBQ "Octave – TIO Nexus") [Answer] # Scala 587 bytes one liner ``` import scala.util.Random;object A{def main(args:Array[String])={val s=5+Random.nextInt(6);var a=new Array[Int](s);for(i<-1 to s){a(i-1)=1+Random.nextInt(20)};p(a);if(a.contains(7)&& !a.contains(1)){a.map(a=>a-1);p(a)};if(a.contains(13)){if(a(0)==13)a=new Array[Int](0)else a=a.slice(0,a.indexOf(13));p(a)};if(a.contains(2)){a=a.filter(pred=>pred%2==0);p(a)};if(a.contains(20)){if(a(2)%2==0)println(20)else println(20*a.length)}else{while(a.sum>50)a=a.dropRight(1);val u=a.sum;if(a.contains(16))println(Integer.toHexString(u));println(u)}};def p[T](a: Array[T])=println(a.mkString(","))} ``` # Scala, 763 bytes as is ``` import scala.util.Random object TA { def main(args:Array[String])={ val s=5+Random.nextInt(6) var a=new Array[Int](s) for (i<-1 to s) a(i-1)=1+Random.nextInt(20) p(a) if(a.contains(7) && !a.contains(1)){ a.map(a=>a-1) p(a) } if(a.contains(13)){ if (a(0)==13) a=new Array[Int](0) else a=a.slice(0,a.indexOf(13)) p(a) } if(a.contains(2)){ a=a.filter(pred=>pred%2== 0) p(a) } if(a.contains(20)){ if (a(2)%2==0) println(20) else println(20*a.length) }else{ while(a.sum>50) a=a.dropRight(1) val u =a.sum if (a.contains(16)) println(Integer.toHexString(u)) println(u) } } def p[T](a: Array[T])={ println(a.mkString(",")) } } ``` [Answer] # MATLAB, ~~228~~ 241bytes ``` a=randi(20,1,randi(6)+4) b=@any; a=a-b(a==7) a=a+b(a==0) a(find(a==13,1):end)=[] a(and(mod(a,2),b(a==2)))=[] if b(a==20) a=[a 0 0 0]; s=20*(1+mod(a(3),1)*(numel(a)-4)) else a(cumsum(a)>50)=[] s=sum(a) if b(a==16) h=['0x' dec2hex(s)] end end ``` This will apply all rules in order, printing the array value after each step. ~~The program will crash on rule 5 if the resulting number of elements is less than three. There is currently nothing to say what should happen if there is no third element, so I am assuming that a crash is acceptable.~~ The program will now print 20 if there are less than 3 elements and one or more is a 20. Interestingly step 2 can be applied regardless of whether step 1 was. This is because the input array will never have a 0 in it meaning that if there are any 0's in the array it must be as a result of step 1 having occurred. All rules are applied in turn, up until 5, even if there are no changes made. As a result the array will be printed at the start and then after each step up until 5. After step 5 you will either get the sum if it is applied, or no output until after step 6. An extra line containing `a` could be added after the else statement to ensure that the array value is printed after step 5 at the cost of 2 bytes. --- I'd also like to mention that I didn't look at the other answers until after I had written this. I see now that there is another MATLAB answer with some similarities - all of which are coincidental. [Answer] # Python 3, ~~297 293 289~~, 278 bytes As Arnauld spotted, you can't get 0 unless rule 1 was applied, which saved on indenting. Thanks to everyone else who commented with suggestions too. ``` from random import* p=print a=b=sample(range(1,20),randint(5,10)) p(a) if 7in a:a=[i-1for i in a];p(a) if 0in a:a=b;p(a) if 13in a:a=a[:a.index(13)];p(a) if 2in a:a=[i for i in a if~i%2];p(a) if 20in a and~a[2]%2:a=[20] while sum(a)>50:a=a[:-1] b=sum(a) p(b) if 16in a:p(hex(b)) ``` [Try it online](https://tio.run/##TU9LCsIwEN3nFLMREmklSVFBqRcpXUw1tQNtEmJF3Xhr1zWt39XA@4@/9Y2z2TDUwXUQ0B7ioc670M@Zz30g2zPMq/yEnW8Nj4qj4SrRUiSjOtJ8mSgpBPMcBaMa1mQBN5gXlKraBSAYgXL74eWbr76Iyt4QFhtckD2YK1eZ@Fn0NxJ@iUD1nWb6TzUlQ1x1x0KXMz06tCzZpaHWwOncReFuKV9FqSpZfGsC4/bqtWQ1NXnexAmVEMPwsC7d474xTw) [Answer] # [Perl 6](http://perl6.org/), 246 bytes ``` my&f={.grep($^a)};my&s=->{.say};$_=[(1..20).pick xx(5..10).pick];s;$_»-- if f 7;s;$_»++ if f 0;s;.splice(.first(13):k//+$_);s;$_=[f*%%2]if f 2; s;say(20*(.[2]%%2||$_)),exit if $_>2&&f 20;s;.pop while .sum>49;$/=f 16;$_=.sum;s;.base(16).say if $/ ``` Ungolfed: ``` my &f = { .grep($^a) }; # Helper function: search $_ for something my &s = -> { .say }; # Helper function: print $_ $_ = [ (1..20).pick xx (5..10).pick ]; # Generate the initial array s; # Print the array $_»-- if f 7; # Decrement all elements if it contains a 7 s; # Print the array $_»++ if f 0; # Increment all elements if a zero is found s; # Print the array .splice(.first(13):k // +$_); # Splice out everything from the first 13 onward s; # Print the array $_ = [ f *%%2 ] if f 2; # Remove all odd elements if a 2 is found s; # Print the array say(20*(.[2] %% 2 || $_)), exit if $_ > 2 && f 20; # Print and exit, maybe s; # Print the array .pop while .sum > 49; # Remove elements from the end until sum is below 50 $/ = f 16; # Save in $/ whether $_ contains a 16 $_ = .sum; # Set $_ to its own sum s; # Print the sum .base(16).say if $/ # Print the sum in hexadecimal if the last array contained a 16 ``` [Answer] # Common Lisp, 490 bytes Here the array is represented as a Common Lisp list. ``` (let((a(loop for i from 1 to(+ 5(random 5))collect(1+(random 19)))))(flet((p()(format t"~a~%"a))(m(x)(member x a))(h(x)(map-into a x a)))(p)(and(m 7)(h'1-))(p)(and(m 0)(h'1+))(p)(let((p(position 13 a)))(and p(setf a(butlast a (-(length a)p)))))(p)(and(m 2)(setf a(remove-if'oddp a)))(p)(or(and(m 20)(or(and(third a)(oddp(third a))(* 20(length a)))20))(p)(and(setf a(loop for x in a sum x into s while (<= s 50) collect x)) nil)(p)(let((s(reduce'+ a)))(print s)(and(m 16)(format t"~x"s)))))) ``` As usual, large use of `and` and `or` as control structures. ``` (let ((a (loop for i from 1 to (+ 5 (random 5)) ; create initial list collect (1+ (random 19))))) (flet ((p () (format t "~a~%" a)) ; auxiliary functions: print list (m (x) (member x a)) ; check membership (h (x) (map-into a x a))) ; operate on elements (p) (and (m 7) (h '1-)) ; if 7 is present decrement all values (p) (and (m 0) (h '1+)) ; if 0 is now present increment all values (p) (let ((p (position 13 a))) ; remove from 13 (if exists) (and p (setf a (butlast a (- (length a) p))))) (p) (and (m 2) (setf a (remove-if 'oddp a))) ; if 2 is present remove odd values (p) (or (and (m 20) ; if 20 is present (or (and (third a) ; when third is present (oddp (third a)) ; and it is odd (* 20 (length a))) ; return 20 times the length 20)) ; otherwise return 20 (p) ; otherwise (20 is not present) (and (setf a (loop for x in a sum x into s ; compute sum of elements while (<= s 50) ; limited to 50 collect x)) ; and return those elements nil) ; (to execute the rest of the code) (p) (let ((s (reduce '+ a))) ; compute the final sum (print s) ; print the result in decimal (and (m 16) (format t "~x" s)))))) ; if 16 is present print also in hexadecimal ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=sum`, 256 bytes ``` $,=$";say$_="@{[map{0|1+rand 20}1..5+rand 6]}";/\b7/&&s/\d+/$&-1/ge&&(say)&&/\b0/&&s/\d+/$&+1/ge&say;s/ ?13.*//&&say;@a=/\d+/g;/\b2\b/&&say@a=grep$_%2-1,@a;/20/&&(say$a[2]%2?20*@a:20)&exit;$t=pop@a while($_=sum@a)>50;$t&&say@a;say;"@a"=~/16/&&printf"%x",$_ ``` [Try it online!](https://tio.run/##TY/LasMwEEV/xQhZxPFDj@IELJzoA9plV3EwClFdgWMLS6UpafrpdaUki66GO2fmwDVq6st5hlkNAbfyC7Y1EJfdSZoL@abpJIdjxMiVFkV5D6v9FXDcHNYYIYubY4ohyinuFEIL/58g5CH5B9Mb9IhbHG3pU7HEgfosZH276YKPNYf72m@7SRnYxiynmZAcs6ALcih3bB@zLSNLIStGEqTO2nHoajMaIaPPd92rha9gP05CJpuSePaQhnIcCAnqH0xXXmgmPbg3EJ9BBtt5/h2N0@Ng5/ylLAglfj5r66rq1ek@CP8A "Perl 5 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 82 bytes ``` 6℅4+ƛ20℅;…:7c[‹…:A¬[›…}1J:13ḟẎ…:2cß~₂…D20c[2i₂[20|L20*],Q}1J:¦‡50>ǑẎ…:16c[∑₌,H,|∑, ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI24oSFNCvGmzIw4oSFO+KApjo3Y1vigLnigKY6QcKsW+KAuuKApn0xSjoxM+G4n+G6juKApjoyY8OffuKCguKApkQyMGNbMmnigoJbMjB8TDIwKl0sUX0xSjrCpuKAoTUwPseR4bqO4oCmOjE2Y1viiJHigowsSCx84oiRLCIsIiIsIiJd) ## Explained ``` 6℅4+ƛ20℅;…:7c[‹…:A¬[›…}1J:13ḟẎ…:2cß~₂…D20c[2i₂[20|L20*],Q}1J:¦‡50>ǑẎ…:16c[∑₌,H,|∑, 6℅4+ƛ20℅;… # Generate the original array with randint(1, 6) + 4 items, each being randint(1, 20). Print it without popping. :7c[‹… # If the array contains a 7, subtract 1 from everything :A¬[›…} # If there's 0s after doing that, add 1 to everything 1J:13ḟẎ… # Find the first occurance of `13` in the array with a 1 appended, and keep everything up to that index. If `13` is not in the array, this will return -1, and will keep everything except the appended 1. Basically, the appended 1 is always removed. 2cß~₂… # If the array contains a 2, keep only even numbers D20c[2i₂[ # If there's 20 in the array and the 3rd item (0 if < 3 items) is even: 20 # Push 20 |L20* # else, push len(array) * 20 ,Q} # print and terminate 1J:¦‡50>ǑẎ… # find the first item in the cumulative sums of the array where the sum is > 50 and keep until that index. Same logic as the 13 check. :16c[ # If 16 is in the array ∑₌,H, # Print the sum as dec and hex |∑, # else, just print the sum ``` ]
[Question] [ ## Background In the sport of Table Tennis (aka Ping-Pong or Whiff Whaff), two opponents play a sequence of rounds, where each round consists of players hitting a ball back and forth until one player (may or may not be the server) gains a point. Table Tennis has some [official rules](https://www.pongfit.org/official-rules-of-table-tennis) that make for a good game, but we will use a different set of rules for a better challenge. The modified rules are as follows: 1. The score is announced directly before each serve as a pair `(current server's score, other player's score)`. 2. Person `A` serves for 5 points, then Person `B` serves for 5 points, then back to `A`. Hence, `A` serves whenever the total score `A+B` is `0-4` mod 10. 3. After each serve, either `A` scores a point or `B` scores a point. `A` and `B` both start with `0` points. 4. For simplicity, games never end. Following is an example game: ``` (A starts serving, so the scores are read as (A,B)) 0,0; A scores a point 1,0; B scores a point 1,1; A scores a point 2,1; A scores a point 3,1; A scores a point (B is now serving, so the scores are read as (B,A)) 1,4; A scores a point 1,5; B scores a point 2,5; B scores a point 3,5; B scores a point 4,5; B scores a point (A is now serving, so the scores are read as (A,B)) 5,5; B scores a point 5,6 … (game continues) ``` ## Task Given a pair of unique score readouts, determine if they can be announced in the same game. Your program/function may take input as any reasonable way equivalent to an ordered pair of numbers. The output can follow your language's convention for truthy/falsey or use any two distinct values to represent true/false. ## Examples Given `(4,5), (1,4)`, the output should be truthy. The example game is one where this score set occurs. Given `(4,2), (3,5)`, the output should be falsey. They occur at point totals `6` and `8` respectively, so `B` is serving in both readouts, so both are reported as `(B,A)`. It is impossible for `B`'s score to decrease from `4` to `3` while `A`'s score increases from `2` to `5`, so this situation is impossible. Given `(3,1), (1,5)`, the output should be truthy. `(3,1)` is reported as `(A,B)`, while `(1,5)` is reported as `(B,A)`, so the game can transition from `(3,1)` to `(1,5)` if `A` scores `2` points. ## Test Cases ``` Truthy: (4,5), (1,4) (3,1), (1,5) (0,0), (0,1) (0,0), (45,54) (6,9), (11,9) Falsey: (12,5), (11,6) (4,2), (3,5) (3,3), (5,2) (2,1), (4,1) (17,29), (17,24) ``` [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` lambda a,b,A,B:(A-a)*(B-b)<(a-b)*(A-B)*((a+b)/5+(A+B)/5&1) ``` [Try it online!](https://tio.run/##PYzBDoIwDIbve4qdTAslsrFhJHJgz@FlRAkkiMRgjE8/OyBe@vf7037zd@mfkw5dfQ2jf7Q3Lz211JCroMk8JuCyFi/geSbcOJ7g0xaPNoUmdZwHheHTD@NdqkpI4HckYAHWwzS/F0Ah59cwLbKDXY0ygCGLJEGRQQEFqQ0sQ055hJy7PxhLNh6WdF4PFacApXeJopLRkI5UrJaCigiWOwF685tVqU6kNwsvBn8 "Python 2 – Try It Online") Outputs True/False reversed **59 bytes** ``` lambda a,b,A,B:A*B+a*(b-A-B)<(b-a)*[A,B][(a+b)/5+(A+B)/5&1] ``` [Try it online!](https://tio.run/##PYzLDoJADEX38xWzMi2UyAwzGIksmN9AFkOUQIJIDMb49VgecXV72tszfqf2Oei5ya9z7x/1zUtPNRXksiJwoQ@gjorI4YXTY1DyoSrBhzUebQhF6DgPqpo/bdffpcqEBP5HAi5i3g3jewIUcnx1wyQb2N0oZzBkkSQoMiggIbWBZYgpXiDm3R@MJbsUUzqvRcUpQOldoihlNKQXSlZLQskClncC9OY3q1KdSG8WHgz@AA "Python 2 – Try It Online") **59 bytes** ``` lambda a,b,A,B:A*B+b*a<[A*b+B*a,a*A+b*B][(a+b)/5+(A+B)/5&1] ``` [Try it online!](https://tio.run/##PYzLCsIwEEX3@YqsZJIM2KSJougi@Y3aRYKWFrQWqYhfH6cPXN05lztn@I7tsze5OV/yPT7SNfKICT2Go5dBJRlPlZdJBRkxSk9FqCuIKomtU@BVoNzoOn/a7n7j@sg40L9AIIM4d/3wHkEwPry6fuQNrG7BM1h0AjlotIJBiXoBR1BgMUFB3R@sQzcNd3iYh5qSgTarROOO0KKZqJwtJZYTOOoYmMVvZ6Xeo1ksdFjxAw "Python 2 – Try It Online") **62 bytes** ``` a,b,A,B=input() if(a+b)/5+(A+B)/5&1:a,b=b,a print(A-a)*(B-b)<0 ``` [Try it online!](https://tio.run/##JYzLCsIwFET39ytCF5LYKfbmUWmxi/ZPEqkYkFqkon59TXQ1B2bOLJ/1ep/19rrG2yS4m97TuSiKzSNgwNjHeXmuUlG8SF8GdXClHMox5Y67tOkDPC2POK9yqLzay7EK6lRv@cLCQTAsGXAGRzVqiBr8B@vgLDVoU8loifVPYDRkoSFMMgwMhIMmnT9sUvkInY0U9gs "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p` `-Minteger`, ~~77~~, 73 bytes ``` / (.*) (.*) /;$_=($`-$2)*($1-$')>=(($`+$1)/5+($2+$')/5)%2*($`-$1)*($2-$') ``` [Try it online!](https://tio.run/##JYxRCsIwEET/c4r5WDFpiXE3SaVIvYFnUD@KFEpbas9vTCoLb2B4s0u/jjElB32qzB/uSo9O09OSmEoTWzqaW6dzUxMbF2tNUufORXOQahe5iFLElAIiGEH5TEZUZ5TjPUNEDKpBC2a0iqW4jEYFCHyWfSFESXmRR3yBZDkzfOdlG@bpk@xrXJK9D9PWv/v1Bw "Perl 5 – Try It Online") 2 bytes saved using xnor approach, and 2 other bytes using integer division, explanation is (renaming: $` -> a, $1 -> b, $2 -> c, $' -> d), first answer was: * `(a-B)(b-A)>=0` if scores are in reversed order (`(a+b)/5%2^(A+B)/5%2==1`) * `(a-A)(b-B)>=0` otherwise as `(a-B)(b-A)>=0` is equivalent to `(a-A)(b-B)>=(a-b)(A-B)` * `(a-B)*(b-A)>=0` <=> `ab+AB-aA-bB>=0` <=> `ab+AB-aB-Ab>=aA+bB-aB-bA` <=> `(a-A)(b-B)>=(a-b)(A-B)` answer can be * `(a-A)(b-B)>=0` if `(a+b)/5%2^(A+B)/5%2==1` * `(a-A)(b-B)>=(a-b)(A-B)` if `(a+b)/5%2^(A+B)/5%2==0` or * `(a-A)(b-B)>=(a-b)(A-B)*((a+b)/5%2^(A+B)/5%2)` or with integer division * `(a-A)(b-B)>=(a-b)(A-B)*((a+b)/5+(A+B)/5)%2` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~14~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εDO5÷FR]`-Pd ``` -2 bytes thanks to *@Neil*. [Try it online](https://tio.run/##yy9OTMpM/f//3FYXf9PD292CYhN0A1L@/4@ONtExjdWJNtQxiY0FAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/3NbXfxND293C4pN0A1I@a@kF6bzPzo62kTHNFYn2lDHJBZIRRvrGIJ5pmCegY4BkDIAiiF4JqY6phC1ZjqWILWGQArENTSCmGSoYwbmm@gYASljqFHGOsZAyhQoBuIZga0xgRpsaK5jBDYKSAONjgUA). **Explanation:** ``` ε # Map both pairs in the (implicit) input to: D # Duplicate the pair O # Pop this duplicate and calculate its sum 5÷ # Integer-divide it by 5 F # Loop that many times: R # Reverse the pair every iteration # (the pair is reversed for odd sums; and remains unchanged for even sums) ] # Close both the loop and map # (all pairs are now in the order [A,B]) ` # Pop and push both pairs separated to the stack - # Subtract the values of the pairs from one another at the same indices P # Take the product of those two values d # And check that it's non-negative / >=0 (thus no score is decreasing) # (after which the result is output implicitly) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 15 bytes ``` ≡⍥⍋∘⌽⍨⌊⍤+.÷∘5⌽⊢ ``` [Try it online!](https://tio.run/##dY@/TsMwEId3P0VGR3GI/8RFzCywUl6gUlKWChg6FAETUtWGuIIBwUpJRTYGkDohpPZN7kXC2alSEGGx/bv77ju5dz4Ik4ve4OwkTEfD9DRJk4rDtJDrxwiyeQj5F5gC8k8wpca64FdBRGD6DGYB5hYmT3UP2b9Q4aZfpG1OXls9DZJn2F8vUajxEUTbgWz@g6MIasRMGfj/McHOxrPdubD@X5DtYN@tbQacqWr5XRvWh/EdmBlkN6s3BeN7mD10j/bxPD447FaXfU96uOUDC9erEsy74ITGTPvMo4LFPqGKiTpoDJxxGzjWmhBrpi3YYXsOFHgTKuRGIljHt0ppk3IWxZQNGmuEytofO6XYZbK24CP2q28 "APL (Dyalog Extended) – Try It Online") ``` ≤⌿⍣2⍤∧⌊⍤+.÷∘5⌽⊢ ``` [Try it online!](https://tio.run/##dY6/TsMwEId3P0VGR3GI/xYxs8BKeYFKSVkqYGAAARNS1Ya4ggHBSklFNgaQmBBS@yb3IuHsVGmllsX27@6779w7H8TpVW9wdhJnlxfZaZqlNYdxKRfPCeTTGIpfsCUUP2Arg3XBb6KEwPgV7AzsPYxemh6ym1Dpp9@ka47et3papMixv/hGocFHlKwG8ukaRxE0iNkqCv9jop2lZ7Vz5vwe2vi4X9yOeFe99i8UoGYb1IfhA9gJ5HfzDwXDR5g8dY/28Tw@OOzW1/1ABjj@hYXbeQX2U3BCNTMhC6hgOiRUMdEEg4Ez7gLHWhu0YcaBHbbnQYE3oUIuJYJ1QqeULilvUUy5YLBGqGz82ivFLpONBR86rP8A "APL (Dyalog Extended) – Try It Online") It took a long time to shave one byte from 16. You can see a long history of alternative solutions in the TIO link. Both solutions take a 2×2 matrix as single input, where each row is a score readout. The first one would also work in Dyalog APL 18.0, since it only uses 17.x features plus `⍥⍤`. ### How it works ``` ≡⍥⍋∘⌽⍨⌊⍤+.÷∘5⌽⊢ ⍝ Input: 2×2 matrix ⌊⍤+.÷∘5 ⍝ For each row, divide each number by 5, sum, then floor ⌽⊢ ⍝ Rotate each row by that amount ∘⌽⍨ ⍝ Check for the above and its horizontal reverse... ≡⍥⍋ ⍝ Is the sorting order equal? ≤⌿⍣2⍤∧⌊⍤+.÷∘5⌽⊢ ⍝ Alternative solution ⌊⍤+.÷∘5⌽⊢ ⍝ Same as above up to here ⍤∧ ⍝ Ascending sort the rows ≤⌿⍣2 ⍝ 1st axis reduce by ≤ twice; ⍝ Since the rows are sorted, first ≤⌿ gives [1 x] ⍝ where x is 1 iff the 2nd column is also increasing ⍝ Then the second ≤⌿ tests if x is 1 ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/) 18.0, ~~19 18~~ 17 bytes ``` 0≤×.-⍥(⌊⍤+.÷∘5⌽⊢) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v/f4FHnksPT9XQf9S7VeNTT9ah3ibbe4e2POmaYPurZ@6hrkeb/tEdtEx719j3qaj603vhR28RHfVODg5yBZIiHZ/B/DRMdU02FNAUNQx0TTS4NYx1DKM8UyDPQMQDzDICiCJ6JqY4pSK2ZjiVErSGQwaVhaAQzyVDHDMg30TECc43BRhnrGIN5pkBRLg0jqDUmYIMNzXWMoEYBWSaaAA "APL (Dyalog Classic) – Try It Online") This makes use of the new operators over (`⍥`) and atop (`⍤`), both of which are very good for golfing. TIO is still on 17.0, so this doesn't work, but I've tested it locally for the given test cases. Takes the two inputs as the left and right parameters. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` UMθEι§ι⁺÷Σι⁵쬛⁰ΠE²⁻§§θ⁰ι§§θ¹ι ``` [Try it online!](https://tio.run/##bY0/C8IwEMV3P0XGK0RoFadOolA6KAXHkCEkAQ@aRGNS/PbxonTzwXF/Hvd7@q6iDmou5aIep@Cc8gaenNEGyNkxjd7Ydx2nOb9g9OmMCxoLt@wAG84OVK4h9Zspok9wDQmGaFWyEVp6i8FknaACd8RFT5gVu3YKbIlTeX@s7mv91JcihNjTUXImOsqXUpbtMn8A "Charcoal – Try It Online") Link is to verbose version of code. Takes a pair of pairs of integers and outputs a Charcoal boolean, i.e. `-` for possible, nothing for impossible. Explanation: ``` UMθEι§ι⁺÷Σι⁵μ ``` Cyclically rotate each pair by one fifth of its sum. ``` ¬›⁰ΠE²⁻§§θ⁰ι§§θ¹ι ``` Check that the product of the differences between the pairs is not negative. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṚS:5Ɗ¡€Ṣ>/E ``` A monadic Link accepting a list of the to pairs which yields a `1` if valid, or a `0` if not. **[Try it online!](https://tio.run/##ASoA1f9qZWxsef//4bmaUzo1xorCoeKCrOG5oj4vRf///1tbNSwwXSxbMCwxXV0 "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##TY47DsIwEET7nILSkUbCa@8GQUHHCSgtlzQoF6ClQeIIdFDnAmlB4h7hIsafRHK180a7O3M@9f0lhGl8HHfyvb@fv@swja/9@hA@t6hDcE4xpMVKEbj1DZyyoMJSWEMn1tGumQUyX3TY5guKMxku7no4gfYZk0A2fZP2ycyRhK58YJhk2CXTwiaWaGc2pRMvHWgDUzKj4DpUQ@pQyh38Hw "Jelly – Try It Online"). ### How? ``` ṚS:5Ɗ¡€Ṣ>/E - Link: list, S e.g. [[17,29],[17,24]] € - for each (pair in S): ¡ - repeat... Ṛ - ...what: reverse Ɗ - ...number of times: last three links as a monad: S - sum 46 41 5 - five 5 5 : - integer division 9 8 -> [[29,17],[17,24]] Ṣ - sorted [[17,24],[29,17]] / - reduce by: > - is greater than? ([17>?29, 24>?17]) [0,1] E - all equal? 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ ~~23~~ 20 bytes Thanks to fireflame241, I was able to shave off a few bytes already. ``` S€%⁵:5E¬µ³U⁸¡Ðo_/ṠIỊ ``` Original: ``` S€%ȷ1<5E¬©µ³Ṛ€®¡Ðo_/ṠIA=2¬ ``` [Try it online!](https://tio.run/##y0rNyan8/z/4UdMa1RPbDW1MXQ@tObTy0NZDmx/unAUUPLTu0MLDE/Lj9R/uXODpaGt0aM3///@jow3NdYwsY3XAtElsLAA "Jelly – Try It Online") Here's my Jelly solution. It's my first Jelly program, so it can definitely be improved a lot, especially at the part where I use the register. I don't quite understand how argument flow works yet. Here's how it works: ``` S€%⁵:5E¬µ³U⁸¡Ðo_/ṠIỊ - Example input: [[4,5],[1,4]] S€%⁵<5 - Figure out who is serving each time S€ - Calculates sum of each inner list: [9, 5] %⁵ - Modulo 10: [9, 5] <5 - Vectorized less than 5?: [0, 0] E¬µ³U⁸¡Ð - If server is different, reverse list 1 E - Checks if all elements are equal: 1 ¬ - Logical not: 0 µ - Start a monadic chain ³ - Get first input: [[4,5],[1,4]] U - Reverse order of inner lists Ðo - At odd indices (ie. the first list) ⁸¡ - {left argument, ie. 0} times: [[4,5],[1,4]] _/ṠIỊ - Calculate difference in score per player. If one decreased and the other increased, it's not a possible score _/ - Vectorized subtract: [3, 1] Ṡ - Get sign: [1, 1] I - Difference between elements: 0 Ị - abs(x) <= 1: 0 ``` ``` [Answer] # [R](https://www.r-project.org/), ~~65~~ ~~59~~ 57 bytes (or [56 bytes](https://tio.run/##dY/RCoIwFIbvfQ0RdvCI29yMpG57gu6iizmLBNNwGvT0tmUX4ezq/PD9/Hynn56qqSuju/5i9tN1bPVQdy1RWMKj7yqikvJEaMFiM96JglQmLpQQpZGEKOIxO8OOTuGxH4fbqwh@5ogmAiWgJgwFwAJlyGYkPUSROkRt4w8SEqU/meP2M8nshSAID6oxF8@J8a8Uw9ybEMgdy1asMswckraxRHz@RawIsw3y2coGpzy9AQ) by outputting FALSE for Truthy and TRUE for Falsey) ``` function(a,b)prod(a-b[(0:1+sum(a)/5-sum(b)%/%5)%%2+1])>=0 ``` [Try it online!](https://tio.run/##dY/LCoJAFIb3voYIc/CIczUSbNkTtIsW4yUSTMNL0NNPM9ki1Fbnh@/n5zu9eeqmLoei66shM9epLca6a4nGHB59VxId5WdCUxYO051oiFXkQg5BHCgIAh6yCxwyavxTP423V@r97JGCSFSABWEoARZIIJuRWiGK1CFqG3@QVKjWkwnuP5PMXvA8/6iboVo5Mf6VYpisJiRyx8SGlUDhkLKNJeLzL3JDmO2Qz1Y2OGXzBg "R – Try It Online") *Edit: -6 bytes by flipping b elements using indexing, instead of using if-else* *Edit 2: -2 bytes by not bothering to do integer division for both a and b, since indexing will only use the integer part anyway.* Commented version: ``` validscores=function(a,b){ b=b[ # Select elements from b (0:1+ # with index of: zero or 1, plus sum(a)%/%5 # changes of serve until first score -sum(b)%/%5) # minus changes of serve until second score %%2+1] # modulo 2, plus 1. # This will flip the elements of b if there # have been an odd number of changes of serve, # & otherwise leave b as it was). prod(a-b)>=0 # a-b now gives changes in each players points: } # so if the second score came after the first, # both changes must be >=0, otherwise both must be <=0. # So, either way, the product must be >=0 ``` [Answer] # Java 8, ~~116~~ ~~63~~ 54 bytes ``` (a,b,A,B)->(A-a)*(B-b)<((a+b)/5+(A+B)/5)%2*(a-b)*(A-B) ``` Whopping -53 bytes thanks to *@NahuelFouilleul* as a port from [his Perl answer](https://codegolf.stackexchange.com/a/207157/52210), so make sure to upvote him!! Additional -9 bytes by porting [*@xnor*'s first Python answer](https://codegolf.stackexchange.com/a/207160/52210). Takes the inputs as four loose integers. Outputs `false` for truthy; and `true` for falsey. [Try it online.](https://tio.run/##fZHfa4MwEMff@1eEwiCppzP@6Ni6DfR9fenexIdo7bDTWDTtKMG/3V2isLeFcB@@l@O@l@QsbsI9H7@nshHDQD5ELfWKkFqqqj@JsiJ7Iwkpuq6phCQlxSMiwMTCxsTGlO2wblxhGJRQdUn2RJK3iQooIIGUue80cQXb0NQt2CulwinYY@zQxEmR7CHYUIEnG6xK2bQzjS7XosFGS79bVx9Ji/PRg@pr@ZXlRLB5uFPXm7GyHHMteSGy@iGLznKtdQTxCJpDNCJ0CNyq2CoffISPuT8VxRDPtVt4NrUcMYL1@n9pzYPZjMPWdoggQISLWwghIsacUYGdJFq8@RME1g2J7iNb/A73QVWt112Vd8GLq0bSM/6ad1V14yV9L@6Dd6yqy2c3PwxtmbPGV1g70itpm/k5brDkhnzR3Gi2/Ns4/QI) **Explanation:** ``` (a,b,A,B)-> // Method with four integer parameters and boolean return-type (A-a)*(B-b) // Get the difference between the values of the two pairs, // and take the product of those two differences < // And check that this is smaller than: ((a+b) // The sum of the first pair /5 // integer-divided by 5 + // Plus: (A+B)/5) // The sum of the second pair, integer-divided by 5 as well %2 // Check if these two added together are odd (1 if odd; 0 if even) *(a-b) // Multiplied by the reduced by subtraction of the first pair *(A-B) // Multiplied by the reduced by subtraction of the second pair ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 58 bytes ``` f(a,b,A,B){a=(A-a)*(B-b)<(a-b)*(A-B)*((a+b)/5+(A+B)/5&1);} ``` [Try it online!](https://tio.run/##bZLbboMwDIbv@xQWUqekGLWcOlW0k8i0p1irKpw2LkYr4AIN8ezMBNK1FYSEOP/n38hKbH3Fcd9nTGKEIQreygMLLclXTFgR3zNJ64pOBK1MmhFf@yYLTUHfF5sHXZ8XNfzIvGB80S6AnvhblisoP09wgNY4Nh/Osdm90/QNhPvYNbpAZQwWdVrVZzkmeejihsYWbQeHwEH79ZmNRtZHW7E79AlzKXJ2z2g4orZCPcqwh9elDG/GWOifGKx9j5y3ypucvTs2ba5pU6eJoqHdoB62HhOcXUpgQ0ZeJGlD8CaYtnuo8t/0kjHtxdfTAeE8ANNUHIexsbqyJI@pXUo/BQ9ypOVoVg61HM7KQstiVq5I/r8sj1pK2q0rz8nXkpCMGWzpJEiTI9y21hssE1hWx4JuiESIEEIEgVAh3SMqSb6nqVi36Po/ "C (gcc) – Try It Online") Port of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [Python answer](https://codegolf.stackexchange.com/a/207160/9481). Outputs \$0\$ if they can be announced in the same game and \$1\$ otherwise. [Answer] # Javascript , 70 bytes ``` (a,b,c,d)=>(~~((a+b)%10/5)==~~((c+d)%10/5)?(c-a)*(d-b):(d-a)*(c-b))>=0 ``` Input: is 4 numbers representing two pairs in order. Output: true/false [Try it online](https://tio.run/##bY/BDoIwDIbvvIfJJj9CB8NIMr35BL7AGKgoCgE18eKr45Z4cqRJ035Nm68X/dKjGZr@EY19U9XDrbtf6/d0VBPTKGFQcbVlnw9jOiz5gpJYcqVcb8Lq1@@YiTRfsioqeWGzq42t@VYlUxDHh@H5OL@LwHT3sWvrVdud2JFlkCBknP/x1FKC9HgCFzTLMwnpX8qxARE2dmAt9roda8@ChNMg5N52BoF0xiN1FMLjwn0z40drCOthszWcvg) ]
[Question] [ This problem is about separating a string representing a product identifier into three components. * The first part consists of upper and lower letters of arbitrary length which represents the warehouse. * The second part is digits which represents the product number. This part is also of arbitrary length. * The last part is qualifiers as size and colours, and this part continues to the end of the string. The qualifiers are guaranteed to start with a capital letter and consist of alphanumeric characters. Each part should be printed clearly separated. It is guaranteed that each part is non-empty. The winner is the one who uses least bytes to solve this problem. **Example:** *Input:* UK7898S14 *Output:* UK 7898 S14 Here UK is United Kingdom, 7898 is the product code, and S14 is size 14. **Example 2:** *Input:* cphDK1234CYELLOWS14QGOOD *Output:* cphDK 1234 CYELLOWS14QGOOD Here cphDK is Copenhagen, Denmark, 1234 is the product code, CYELLOWS14QGOOD represents yellow colour, size 14, and good quality. [Answer] ## Perl, 12 bytes 11 bytes of code + 1 byte for `-p` flag. ``` s/\d+/ $& / ``` To run it : ``` perl -pe 's/\d+/ $& /' <<< "CYELLOWS14QGOOD" ``` [Answer] ## APL, 18 ``` {⍵⊂⍨3⌊+\1,2≠/⍵∊⎕D}'UK7898S14' UK 7898 S14 ``` Works by searching the first 2 points where there is a change from character to digit or vice-versa, and using those to split the string. [Answer] # [Retina](http://github.com/mbuettner/retina), ~~28~~ ~~14~~ ~~10~~ 8 bytes Saved 4 bytes thanks to *Dom Hastings*. Saved 2 bytes thanks to *Martin Ender*. ``` S1`(\d+) ``` [Try it online!](http://retina.tryitonline.net/#code=UzFgKFxkKyk&input=Y3BoREsxMjM0Q1lFTExPV1MxNFFHT09E) [Answer] ## Haskell, 36 bytes (no regex) ``` d c='/'<c&&c<':' (span d<$>).break d ``` This gives the result in the format `("UK",("7898","S14"))`. The idea is to split at the first digit, and then split the rest at the first non-digit. [Try it on Ideone](http://ideone.com/liXE8z). [Answer] # JavaScript, ~~38~~ 36 bytes ``` s=>/(\D+)(\d+)(.+)/.exec(s).slice(1) ``` ### Example ``` const f = s=>/(\D+)(\d+)(.+)/.exec(s).slice(1) console.log(f("UK7898S14")); console.log(f("cphDK1234CYELLOWS14QGOOD")); ``` [Answer] ## JavaScript (ES6), ~~28~~ 26 bytes ``` s=>s.replace(/\d+/,` $& `) ``` Saved 2 bytes thanks to @Grax ### Examples ``` let f = s=>s.replace(/\d+/,` $& `) console.log(f('UK7898S14')); console.log(f('cphDK1234CYELLOWS14QGOOD')); ``` [Answer] # Gema, ~~17~~ 12 characters (The trick of not handling the country code explicitly shamelessly borrowed from [Dada](https://codegolf.stackexchange.com/users/55508/dada)'s [Perl solution](https://codegolf.stackexchange.com/a/98950). Appreciation should be expressed there.) ``` <D>*=\n$1\n* ``` Sample run: ``` bash-4.3$ gema '<D>*=\n$1\n*' <<< 'UK7898S14' UK 7898 S14 bash-4.3$ gema '<D>*=\n$1\n*' <<< 'cphDK1234CYELLOWS14QGOOD' cphDK 1234 CYELLOWS14QGOOD ``` [Answer] # Python 2, 40 Bytes I don't know much Regex, but thankfully this problem is simple enough :) Seperates the input string into a list of length 3 which contains each part. ``` import re lambda k:re.split('(\d+)',k,1) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~39~~ ~~37~~ 16 bytes Saved a lot of bytes thanks to Emigna. It uses CP-1252 encoding. ``` TvDSdykF¬?¦}¶?}? T push "10" v for each element (i.e., 1 and 0). Element is stored in 'y' DS split string (input during the first iteration) d for each character, 1 if digit or 0 otherwise yk get index of the first occurrence of 'y' F for 0 <= i < string.firstIndexOf(y) ¬? print the first character of the string ¦ remove it from the string } end inner for ¶? display a newline } end outer for ? display the remaining string ``` [Try it online!](http://05ab1e.tryitonline.net/#code=VHZEU2R5a0bCrD_Cpn3Ctj99Pw&input=Y3BoREsxMjM0Q1lFTExPV1MxNFFHT09E) (This is my first post here!) [Answer] ## JavaScript (ES6), 36 bytes ``` s=>/(.+?)(\d+)(.*)/.exec(s).slice(1) ``` ### Examples ``` let f = s=>/(.+?)(\d+)(.*)/.exec(s).slice(1) console.log(f('UK7898S14')); console.log(f('cphDK1234CYELLOWS14QGOOD')); ``` [Answer] # Java 7, ~~200~~ ~~185~~ ~~174~~ 167 bytes ``` import java.util.regex.*;String c(String s){Matcher m=Pattern.compile("(.*?)(\\d+)(.*)").matcher(s);s="";for(int i=0;i<3;)if(m.matches())s+=m.group(++i)+" ";return s;} ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/z6inUN) ``` import java.util.regex.*; class M{ static String c(String s){ Matcher m = Pattern.compile("(.*?)(\\d+)(.*)").matcher(s); s = ""; for(int i = 0; i < 3;){ if(m.matches()){ s += m.group(++i) + " "; } } return s; } public static void main(String[] a){ System.out.println(c("UK7898S14")); System.out.println(c("cphDK1234CYELLOWS14QGOOD")); } } ``` **Output:** ``` UK 7898 S14 cphDK 1234 CYELLOWS14QGOOD ``` [Answer] # C#, ~~191~~ 177 bytes Golfed: ``` void F(string s){var a=s.ToList();int i=a.FindIndex(char.IsDigit);int n=a.FindIndex(i,char.IsUpper);Console.Write($"{s.Substring(0,i)}\n{s.Substring(i,n-i)}\n{s.Substring(n)}"); ``` Ungolfed: ``` void F(string s) { var a = s.ToList(); int i = a.FindIndex(char.IsDigit); int n = a.FindIndex(i, char.IsUpper); Console.Write($"{s.Substring(0, i)}\n{s.Substring(i, n - i)}\n{s.Substring(n)}"); } ``` EDIT1: @Link Ng saved 14 bytes. [Answer] # PHP, 48 bytes ``` print_r(preg_split('/(\D+|\d+)\K/',$argv[1],3)); ``` With its `$limit` parameter, and the fantastically useful `\K`, `preg_split()` is perfect for this challenge. [Answer] # MATLAB, ~~81~~ 73 bytes ``` function y=f(x) [~,~,~,m,~,~,s]=regexp(x,'(?<=^\D+)\d+');y=[s(1) m s(2)]; ``` Function that accepts a string and returns a cell array of three strings. Tested in version R20105b. Example use: ``` >> f('UK7898S14') ans = 'UK' '7898' 'S14' >> f('cphDK1234CYELLOWS14QGOOD') ans = 'cphDK' '1234' 'CYELLOWS14QGOOD' ``` ### Explanation The regular expression `(?<=^\D+)\d+')` matches a group of digits preceded by non-digits from the start of the string; the latter are not part of the match. The fourth output of [`regexp`](https://es.mathworks.com/help/matlab/ref/regexp.html) is the `'match'`; and the seventh output is the `'split'`, that is, the two parts of the string before and after the match. [Answer] # Ruby, 28 bytes ``` ->s{puts s.sub(/\d+/,"\n\\&\n")} ``` This surrounds the first cluster of digits with newlines. [Answer] # jq, 47 characters (43 characters code + 4 characters command line options.) ``` match("(\\D+)(\\d+)(.+)").captures[].string ``` (Again the old story: fairly elegant at the beginning, then becomes painfully verbose.) Sample run: ``` bash-4.3$ jq -Rr 'match("(\\D+)(\\d+)(.+)").captures[].string' <<< 'UK7898S14' UK 7898 S14 bash-4.3$ jq -Rr 'match("(\\D+)(\\d+)(.+)").captures[].string' <<< 'cphDK1234CYELLOWS14QGOOD' cphDK 1234 CYELLOWS14QGOOD ``` [On-line test](https://jqplay.org/jq?q=match%28%22%28%5C%5CD%2b%29%28%5C%5Cd%2b%29%28.%2b%29%22%29.captures[].string&j=%22cphDK1234CYELLOWS14QGOOD%22) (Passing `-r` through URL is not supported – check Raw Output yourself.) [Answer] # PHP, 61 59 5655 bytes ``` preg_match('/(\D+)(\d+)(.+)/',$argv[1],$a);print_r($a); ``` This does output the initial code as well: ``` Array ( [0] => cphDK1234CYELLOWS14QGOOD [1] => cphDK [2] => 1234 [3] => CYELLOWS14QGOOD ) ``` ### Edit Thanks to @manatwork for saving a few bytes for me Thanks to @RomanGräf for another few bytes saved [Answer] # JavaScript without regex, 84 81 79 bytes `p=>{for(i=n=o='';i<p.length;){if(n==isNaN(c=p[i++])){o+=' ';n++}o+=c}return o}` [Answer] # Mathematica, 39 bytes ``` StringSplit[#,a:DigitCharacter..:>a,2]& ``` Anonymous function. Takes a string as input, and returns a list of strings as output. [Answer] ## Racket 274 bytes ``` (let((g 0)(j'())(k'())(l'())(m list->string)(r reverse)(n char-numeric?)(c cons))(for((i(string->list s))) (when(and(= g 0)(n i))(set! g 1))(when(and(= g 1)(not(n i)))(set! g 2))(match g[0(set! j(c i j))] [1(set! k(c i k))][2(set! l(c i l))]))(list(m(r j))(m(r k))(m(r l)))) ``` Ungolfed: ``` (define (f s) (let ((g 0) (j '()) (k '()) (l '()) (m list->string) (r reverse) (n char-numeric?) (c cons)) (for ((i (string->list s))) (when (and (= g 0) (n i)) (set! g 1) ) (when (and (= g 1) (not (n i))) (set! g 2) ) (match g [0 (set! j (c i j))] [1 (set! k (c i k))] [2 (set! l (c i l))])) (list (m (r j)) (m (r k)) (m (r l))))) ``` Testing: ``` (f "UK7898S14") (f "cphDK1234CYELLOWS14QGOOD") ``` Output: ``` '("UK" "7898" "S14") '("cphDK" "1234" "CYELLOWS14QGOOD") ``` [Answer] # R, 63 52 bytes Edit: Saved a bunch of bytes thanks to @JDL Takes input from stdin and prints to stdout: ``` gsub("([a-z]+)(\\d+)(.+)","\\1 \\2 \\3",scan(,""),T) ``` Example output: ``` [1] "UK 7898 S1" [1] "cphDK 1234 CYELLOWS14QGOOD" ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` O<65ITḣ2‘ṬœṗµY ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=Tzw2NUlU4bijMuKAmOG5rMWT4bmXwrVZ&input=&args=IlVLNzg5OFMxNCI)** ### How? ``` O<65ITḣ2‘ṬœṗµY - Main link: productIdentifier e.g. "UK7898S14" O - cast to ordinals e.g. [85,75,55,56,57,56,83,49,52] <65 - less than 65? e.g. [ 0, 0, 1, 1, 1, 1, 0, 1, 1] I - incremental difference e.g. [ 0, 1, 0, 0, 0,-1, 1, 0] T - truthy indexes e.g. [2, 6, 7] ḣ2 - head to 2 e.g. [2, 6] ‘ - increment e.g. [3, 7] Ṭ - set truthy indexes e.g. [0, 0, 1, 0, 0, 0, 1] œṗ - split y at truthy indexes of x e.g. ["UK", "7898", "S14"] µ - monadic chain separation Y - join with line feeds ``` [Answer] # C, 107 bytes ``` #define p(x) printf("%c",x); f(char*s){for(;*s>64;s++)p(*s)p(10)for(;*s<58;s++)p(*s)p(10)for(;*s;s++)p(*s)} ``` Call with: ``` int main() { f("UK7898S14"); return 0; } ``` [Answer] # Python 2, ~~103~~ ~~94~~ 88 bytes Solution without using regex ``` a,b=input(),"" for f in a: if ord(f)<58:b+=f elif b"":c,d=a.split(b);print c,b,d;break ``` Simply extracts the numbers from the middle then slices the input using the number as an index. Requires quotes around the input but I didn't see anywhere that quotes are disallowed. -9 by splitting a on the middle number then print the components with b in the middle -6 Thanks to @Shebang Test Cases ``` D:\>python codes.py "UK7898S14" UK 7898 S14 D:\>python codes.py "cphDK1234CYELLOWS14QGOOD" cphDK 1234 CYELLOWS14QGOOD ``` [Answer] # C#, 74 bytes ``` v=>new System.Text.RegularExpressions.Regex("\\d+").Replace(v,"\n$&\n",1); ``` Replace 1st set of digits with carriage return, set of digits, and another carriage return, as Johan Karlsson did for JavaScript. ]
[Question] [ # Background The [Copeland–Erdős constant](https://en.wikipedia.org/wiki/Copeland%E2%80%93Erd%C5%91s_constant) is the concatenation of "0." with the base 10 representations of the prime numbers in order. Its value is ``` 0.23571113171923293137414... ``` See also [OEIS A033308](https://oeis.org/A033308). Copeland and Erdős proved that this is a [normal number](https://en.wikipedia.org/wiki/Normal_number). This implies that every natural number can be found at some point in the decimal expansion of the Copeland-Erdős constant. # The challenge Given a positive integer, express it in base 10 (without leading zeros) and output the index of its first appearance within the sequence of decimal digits of the Copeland–Erdős constant. Any reasonable input and output format is allowed, but input and output should be in base 10. In particular, the input can be read as a string; and in that case it can be assumed not to contain leading zeros. Output may be 0-based or 1-based, starting from the first decimal of the constant. The actual results may be limited by data type, memory or computing power, and thus the program may fail for some test cases. But: * It should work in theory (i.e. not taking those limitations into account) for any input. * It should work in practice for at least the first four cases, and for each of them the result should be produced in less than a minute. # Test cases Output is here given as 1-based. ``` 13 --> 7 # Any prime is of course easy to find 997 --> 44 # ... and seems to always appear at a position less than itself 999 --> 1013 # Of course some numbers do appear later than themselves 314 --> 219 # Approximations to pi are also present 31416 --> 67858 # ... although one may have to go deep to find them 33308 --> 16304 # Number of the referred OEIS sequence: check 36398 --> 39386 # My PPCG ID. Hey, the result is a permutation of the input! 1234567 --> 11047265 # This one may take a while to find ``` [Answer] # Python 2, 64 bytes ``` f=lambda n,k=2,m=1,s='':-~s.find(`n`)or f(n,k+1,m*k*k,s+m%k*`k`) ``` Returns the 1-based index. Test it on [Ideone](http://ideone.com/hDwIIu). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 14 bytes Uses **0-indexed output**. Prime functions in osabie are *very* inefficient. Code: ``` [NØJD¹å#]¹.Oð¢ ``` Explanation: ``` [ ] # Infinite loop... N # Get the iteration value Ø # Get the nth prime J # Join the stack D # Duplicate this value ¹å# # If the input is in this string, break out of the loop ¹.O # Overlap function (due to a bug, I couldn't use the index command) ð¢ # Count spaces and implicitly print ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=W07DmEpEwrnDpSNdwrkuT8OwwqI&input=OTk5). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆRDFṡL}i Ḥçßç? çD ``` Returns the 1-based index. [Try it online!](http://jelly.tryitonline.net/#code=w4ZSREbhuaFMfWkK4bikw6fDn8OnPwrDp0Q&input=&args=MQ) or [verify most test cases](http://jelly.tryitonline.net/#code=w4ZSREbhuaFMfWkK4bikw6fDn8OnPwrDp0QKxbzDh-KCrEc&input=&args=MTMsIDk5NywgOTk5LCAzMTQsIDMxNDE2LCAzMzMwOCwgMzYzOTg). I've verified the last test case locally; it took 8 minutes and 48 seconds. ### How it works ``` çD Main link. Argument: n (integer) D Decimal; yield A, the array of base 10 digits of n. ç Call the second helper link with arguments n and A. Ḥçßç? Second helper link. Left argument: n. Right argument: A. Ḥ Unhalve; yield 2n. ? If... ç the first helper link called with 2n and A returns a non-zero integer: ç Return that integer. Else: ß Recursively call the second helper link with arguments 2n and A. ÆRDFṡL}i First helper link. Left argument: k. Right argument: A. ÆR Prime range; yield the array of all primes up to k. DF Convert each prime to base 10 and flatten the resulting nested array. L} Yield l, the length of A. ṡ Split the flattened array into overlapping slices of length l. i Find the 1-based index of A in the result (0 if not found). ``` ## Alternate version, 11 bytes (non-competing) ``` ÆRVw³ ḤÇßÇ? ``` The `w` atom did not exist when this challenge was posted. [Try it online!](http://jelly.tryitonline.net/#code=w4ZSVnfCswrhuKTDh8Ofw4c_&input=&args=OTk5) ### How it works ``` ḤÇßÇ? Main link. Argument: n (integer) Ḥ Unhalve; yield 2n. ? If... Ç the helper link called with argument 2n returns a non-zero integer: Ç Return that integer. Else: ß Recursively call the main link with argument 2n. ÆRVw³ Helper link. Argument: k (integer) ÆR Prime range; yield the array of all primes up to k. V Eval; concatenate all primes, forming a single integer. ³ Yield the first command-line argument (original value of n). w Windowed index of; find the 1-based index of the digits of the result to the right in the digits of the result to the left (0 if not found). ``` [Answer] ## Actually, 19 bytes ``` ╗1`r♂Pεj╜@íu`;)╓i@ƒ ``` Takes a string as input and outputs the 1-based index of the substring [Try it online!](http://actually.tryitonline.net/#code=4pWXMWBy4pmCUM61auKVnEDDrXVgOynilZNpQMaS&input=IjEzIg) Explanation: ``` ╗1`r♂Pεj╜@íu`;)╓i@ƒ ╗ push input to register 0 `r♂Pεj╜@íu`;) push this function twice, moving one copy to the bottom of the stack: r♂Pεj concatenate primes from 0 to n-1 (inclusive) ╜@íu 1-based index of input, 0 if not found 1 ╓ find first value of n (starting from n = 0) where the function returns a truthy value i@ flatten the list and move the other copy of the function on top ƒ call the function again to get the 1-based index ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` €ṁdİpd ``` [Try it online!](https://tio.run/##yygtzv7//1HTmoc7G1OObChI@f//v7GhCQA "Husk – Try It Online") Prime number infinite list babyyyyy [Answer] # Julia, 55 bytes ``` \(n,s="$n",r=searchindex(n|>primes|>join,s))=r>0?r:3n\s ``` Returns the 1-based index. Completes all test cases in under a second. [Try it online!](http://julia.tryitonline.net/#code=XChuLHM9IiRuIixyPXNlYXJjaGluZGV4KG58PnByaW1lc3w-am9pbixzKSk9cj4wP3I6M25ccwoKZm9yIG4gaW4gKDEzLCA5OTcsIDk5OSwgMzE0LCAzMTQxNiwgMzMzMDgsIDM2Mzk4LCAxMjM0NTY3KQogICAgQHByaW50ZigiJTh1IC0tPiAlOXVcbiIsIG4sIFwobikpCmVuZA&input=) [Answer] # Pyth, 17 bytes ``` fhJxs`MfP_YSTz2J ``` Leading space is important. [Test suite.](http://pyth.herokuapp.com/?code=+fhJxs%60MfP_YSTz2J&test_suite=1&test_suite_input=13%0A997%0A314&debug=0) [Answer] # [J](http://jsoftware.com), 37 bytes ``` (0{":@[I.@E.[:;<@":@p:@i.@]) ::($:+:) ``` Input is given as a base 10 integer and the output uses zero-based indexing. ## Usage ``` f =: (0{":@[I.@E.[:;<@":@p:@i.@]) ::($:+:) f 1 4 f 13 6 f 31416 67857 ``` ## Explanation This first call treats the verb as a monad, however subsequent calls which may occur recursively treat it as a dyad. ``` 0{":@[I.@E.[:;<@":@p:@i.@] Input: n on LHS, k on RHS ] Get k i.@ Get the range [0, 1, ..., k-1] p:@ Get the kth prime of each ":@ Convert each to a string <@ Box each string [:; Unbox each and concatenate to get a string of primes [ Get n ":@ Convert n to a string I.@E. Find the indices where the string n appears in the string of primes 0{ Take the first result and return it - This will cause an error if there are no matches (...) ::($:+:) Input: n on RHS, k on LHS (...) Execute the above on n and k ::( ) If there is an error, execute this instead +: Double k $: Call recursively on n and 2k ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-rprime`, 48 bytes 0-based. ``` ->n{s="" Prime.find{s<<_1.to_s=~/#{n}/} $`.size} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7CI326WlJWm6FjcNdO3yqottlZS4AkBSemmZeSnVxTY28YZ6JfnxxbZ1-srVebX6tVwqCXrFmVWptRB9qwoU3KKNDU0MzWIhAgsWQGgA) [Answer] # [Raku](https://raku.org/), 45 bytes ``` {{$~={$_ x.is-prime}(++$)}...*~~/$_/;$/.from} ``` [Try it online!](https://tio.run/##DcpLCoAgFAXQrVziEX3oSRSFlG1FGiQESWGTQnTr1uDMzrW5Y0j2RW6gkvcUlSeNh/e7udxut1DUNZWBmasYBWkxkWDjThvSvb7I/qwWeAPSIYM5Hea2g5TjT6Jr@yV9 "Perl 6 – Try It Online") Really had to dig deep to bring the byte count way down here. The code generates a warning, but oh well! The first bracketed expression generates strings consisting of the concatenation of successive primes. `++$` increments an anonymous state variable, and that number is passed to an anonymous function `{ $_ x .is-prime }`, which replicates the stringified number once if it's prime, and zero times (ie, to an empty string) if it isn't. That string is appended to another anonymous state variable that keeps the concatenation of all primes seen so far with `$ ~=`. The sequence looks like `2, 23, 23, 235, 235, 2357, 2357, 2357, 2357, 235711, ...`, with a repeated element whenever there isn't a prime. Very inefficient! The sequence terminates when the ending condition `* ~~ /$_/` is met; that is, when the concatenated string of primes matches the input number interpolated into a regex. That has the side effect of storing the resulting Match object into `$/`. Then the function just returns `$/.from`, the starting position of the match in the string of primes. [Answer] ## PowerShell v2+, 90 bytes ``` for($a="0.";!($b=$a.IndexOf($args)+1)){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){$a+=$i}}$b-2 ``` Combines the logic of my [Find the number in the Champernowne constant](https://codegolf.stackexchange.com/a/66884/42963) answer, coupled with the prime generation method of my [Print the nth prime that contains n](https://codegolf.stackexchange.com/a/80446/42963) answer, then subtracts `2` to output the index appropriately (i.e., not counting the `0.` at the start). Takes input as a string. Finds the `999` one in about seven seconds on my machine, but the `33308` one in quite a bit longer (*edit - I gave up after 90 minutes*). Should theoretically work for any value up to index `[Int32]::Maxvalue` aka `2147483647`, as that's the maximum length of .NET strings. Will likely run into memory issues long before that happens, however. ]
[Question] [ A sequence of integers is a one-sequence if the difference between any two consecutive numbers in this sequence is -1 or 1 and its first element is 0. More precisely: \$a\_1, a\_2, ..., a\_n\$ is a one-sequence if: $$\forall k \::\: 1\le k<n, |a\_k-a\_{k+1}| = 1 \\ a\_1 = 0$$ **Input** * \$n\$ - number of elements in the sequence * \$s\$ - sum of elements in the sequence **Output** * a one-sequence set/list/array/etc of length \$n\$ with sum of elements \$s\$, if possible * an empty set/list/array/etc if not possible **Examples** For input `8 4`, output could be `[0 1 2 1 0 -1 0 1]` or `[0 -1 0 1 0 1 2 1]`. There may be other possibilites. For input `3 5`, output is empty `[]`, since it cannot be done. **Rules** This is a code golf, shortest answer in bytes wins. Submissions should be a program or function. Input/output can be given in any of the [standard ways](http://meta.codegolf.stackexchange.com/a/1326/14215). [Answer] # JavaScript (E6) 79 ~~82~~ ``` F=(n,t, d=n+n*~-n/4-t/2, l=1, q=[for(x of Array(n))d<n--?++l:(d+=~n,--l)] )=>d?[]:q ``` No need of brute force or enumeration of all tuples. See a sequence of length *n* as *n*-1 steps, each step being increment or decrement. Note, you can only swap an increment for a decrement, sum varies by 2, so for any given length the sum is always even or always odd. Having all increments, the sequence is 0, 1, 2, 3, ..., n-1 and we know the sum is (n-1)\*n/2 Changing the last step, the sum changes by 2, so the last step weighs 2. Changing the next to last step, the sum changes by 4, so the last step weighs 4. That's because the successive step builds upon the partial sum so far. Changing the previous step, the sum changes by 6, so the last step weighs 6 (not 8, it's not binary numbers). ... Changing the first step weighs (n-1)\*2 *Algorithm* ``` Find the max sum (all increments) Find the difference with the target sum (if it's not even, no solution) Seq[0] is 0 For each step Compare current difference with the step weight if is less we have an increment here, seq[i] = seq[i-1]+1 else we have a decrement here, seq[i] = seq[i-1]-1. Subtract we current weight from the current diff. If remaining diff == 0, solution is Seq[]. Else no solution ``` **Ungolfed code** ``` F=(len,target)=>{ max=(len-1)*len/2 delta = max-target seq = [last=0] sum = 0 weight=(len-1)*2 while (--len > 0) { if (delta >= weight) { --last delta -= weight; } else { ++last } sum += last seq.push(last); weight -= 2; } if (delta) return []; console.log(sum) // to verify return seq } ``` **Test** In Firefox / FireBug console ``` F(8,4) ``` *Output* ``` [0, -1, 0, -1, 0, 1, 2, 3] ``` [Answer] ## CJam, ~~56 47 44~~ 34 bytes A lot of scope for improvement here, but here goes the first attempt at this: ``` L0aa{{[~_(]_)2++}%}l~:N;(*{:+N=}=p ``` Credits to Dennis for efficient way of doing the `{ ... }%` part. Prints the array representation if possible, otherwise `""` [Try it online here](http://cjam.aditsu.net/) [Answer] ## GolfScript (41 39 bytes) ``` [][1,]@~:^;({{.-1=(+.)))+}%}*{{+}*^=}?` ``` [Online demo](http://golfscript.apphb.com/?c=Oyc4IDQnCgpbXVsxLF1AfjpeOyh7ey4tMT0oKy4pKSkrfSV9Knt7K30qXj19P2A%3D) Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for 41->39. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ’Ø-ṗÄS=¥ƇḢŻ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw8zDM3Qf7px@uCXY9tDSY@0Pdyw6uvv/4eX63iqPmtZE/v8fbaFjEqsTbaxjCiQtgWwA "Jelly – Try It Online") Although I originally had `’2*ḶBz0Z-*ÄS=¥ƇḢŻ`, this is close enough to caird's solution in principle now that I'm almost tempted to just suggest it in the comments. In the case that you really really want `[]` over `0`, [maybe it's just +3 bytes?](https://tio.run/##AS8A0P9qZWxsef//4oCZw5gt4bmXw4RTPcKlxofhuKLFu@G5luG5lj//w6fhuZj//zP/NQ), [maybe it's +5](https://tio.run/##AS8A0P9qZWxsef//4oCZw5gt4bmXw4RTPcKlxofhuKLFu@G5luG5lj/FkuG5mP///zP/NQ). ``` Ø- [-1, 1] ṗ to the Cartesian power of ’ n - 1. Ä Cumulative sums. Ƈ Keep only those for which S ¥ the sum = is equal to s. Ḣ Take the first survivor Ż and slap a 0 on the start of it. ``` [Answer] ## Mathematica, 73 bytes ``` f=FirstCase[{0}~Join~Accumulate@#&/@Tuples[{-1,1},#-1],l_/;Tr@l==#2,{}]&; ``` Simple brute force solution. I'm generating all choices of steps. Then I turn those into accumulated lists to get the one-sequences. And then I'm looking for the first one whose sum is equal to the second parameter. If there is non, the default value is `{}`. [Answer] ## Haskell, 56 bytes ``` n%s=[x|x<-scanl(+)0`map`mapM(\_->[1,-1])[2..n],s==sum x] ``` Explanation: * Build a list with the permutations of `1,-1` and length n-1: `replicateM n-1[-1,1]` Example: `replicateM 2 [-1,1]` == `[[-1,-1],[-1,1],[1,-1],[1,1]]` * Build the one-sequence out of it. `scanl` has poor performance, but it does the right job here. * Filter all possible one-sequences with length `n` where the sum is `s` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ 16 bytes ``` ḟo=⁰ΣmΘm∫π←²fIṡ1 ``` [Try it online!](https://tio.run/##ASoA1f9odXNr///huJ9vPeKBsM6jbc6YbeKIq8@A4oaQwrJmSeG5oTH///8z/zU "Husk – Try It Online") Same idea as Unrelated String's answer. ~~I'll add in a version that returns `[]` once I can find a way to make `if` work properly.~~ Now works as advertised! [Answer] # Python, 138 ``` from itertools import* def f(n,s): for i in[list(accumulate(x))for x in product([-1,1],repeat=n-1)]: if sum(i)==s:return[0]+i return[] ``` [Answer] # [Python 3](https://docs.python.org/3/), 80 bytes ``` f=lambda l,s,a=[0]:l>1and max(f(l-1,s,a+[a[-1]+x])for x in(1,-1))or(sum(a)==s)*a ``` [Try it online!](https://tio.run/##NctNCsIwEEDhfU@R5Uw7AYcqSCFeJGQxpQQL@SlJhXj6qAuXj493vM9nTnPv3gSJ6yYqUCUx9uKW8GBJm4rSwEPQ/IPJitXspubQ56Ka2hMwaUbMBeorgqAxFUfpR9nT@R3vdEUc/jXTDbF/AA "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 16 bytes ``` ’Ø-œċŒ!€ẎÄS=¥ƇḢŻ ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//4oCZw5gtxZPEi8WSIeKCrOG6jsOEUz3CpcaH4biixbv///84/zQ "Jelly – Try It Online") Returns `0` if no such list exists. If you insist on returning `[]`, [+5 bytes](https://tio.run/##AT0Awv9qZWxsef//4oCZxZPEi0DDmC3FkiHigqzhuo7Fu@KCrMOEUz3CpcaH4biib@KAnOKAncWS4bmY////M/81). -2 bytes [thanks to](https://codegolf.stackexchange.com/questions/38444/make-a-one-sequence/215637?noredirect=1#comment503811_215637) [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) ## How it works Rather than generating all possible lists of length \$n\$ and comparing to specific parameters, this instead generates all possible partial differences, then filters sequences on that ``` ’Ø-œċŒ!€ẎÄS=¥ƇḢŻ - Main link. Takes n on the left and s on the right ’ - n-1 Ø- - [-1, 1] œċ - Combinations with replacement Œ!€ - Get the permutations of each Ẏ - Tighten into a list of partial differences Ä - Compute the forward sums Ƈ - Filter; Keep those sequences k where the following is true: ¥ - Group the previous 2 links into a dyad f(k, s): S - Sum of k = - Equals s Ḣ - Take the first sequence or 0 if there are none Ż - Prepend a 0 if a list ``` [Answer] ## CJam, ~~65~~ ~~58~~ 54 bytes Barely shorter than my Mathematica solution, but that's mostly my fault for still not using CJam properly: ``` 0]]l~:S;({{_1+\W+}%}*{0\{+_}%);}%_{:+S=}#_@\i=\0>\[]?p ``` It's literally the same algorithm: get all `n-1`-tuples of `{1, -1}`. Find the first one whose accumulation is the same as `s`, prepend a `0`. Print an empty array if none is found. [Answer] # CJam, 40 Another approach in CJam. ``` ri,W%)\_:+ri-\{2*:T1$>1{T-W}?2$+\}/])!*p ``` [Answer] **Ruby(136)** ``` def one_sequences(n) n.to_s.chars.map(&:to_i).each_cons(2).to_a.select{|x|x[0] == 0 && (x[1] == 1 || x[1] == -1)}.count end ``` [Answer] # J, 47 chars Checks every sequence like many other answers. Will try to make a shorter O(n) solution. ``` f=.4 :'(<:@#}.])(|:#~y=+/)+/\0,|:<:2*#:i.2^<:x' 8 f 4 0 1 2 1 0 1 0 _1 3 f 5 [nothing] ``` [Answer] ## APL 38 ``` {⊃(↓a⌿⍨⍺=+/a←+\0,⍉1↓¯1*(⍵⍴2)⊤⍳2*⍵),⊂⍬} ``` Example: ``` 4 {⊃(↓a⌿⍨⍺=+/a←+\0,⍉1↓¯1*(⍵⍴2)⊤⍳2*⍵),⊂⍬}8 0 1 2 1 0 1 0 ¯1 ``` This one as many others just brute forces through every combination to find one that matches, if not found returns nothing. Actually it tries some combinations more than once to make the code shorter. ]
[Question] [ Given a positive integer `n`. Generate a JSON array (can be a string, or your language's built-in JSON representation as long as we can get valid JSON, (your code does not need to include outputting the string, you can just use the built-in JSON representation)) containing two empty JSON arrays, then, add a set of 2 empty JSON arrays to each existing set of 2 empty JSON arrays up to `n` deep. `n` can be 0 or 1 indexed. # Rules 1. The shortest code wins the challenge (as this is code-golf). 2. All output JSON must be RFC8259 compliant. # Examples ``` Input: 0 Output: [[], []] Input: 1 Output: [[[], []], [[], []]] Input: 2 Output: [[[[], []], [[], []]], [[[], []], [[], []]]] ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~12~~ 6 bytes −6 thanks to OP now allowing 1-indexing and results that *can* be converted to JSON, rather than the JSON itself. Full program; prompts for 1-indexed `n` and prints APL nested array equivalent of the required JSON. Adding an print handler which just converts output to JSON shows the required result. ``` ⍮⍨⍣⎕⊢⍬ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfkfUJSZV/KobUL1o76pQApIegX7@z3q3VXLBWQHu@rl5wWnFhdn5ufBVKqDGepcjzraC/4/6l33qHfFo97FIO1dix71rvkPFP@vAAYFXIZcMJYRnGUMZ5kAAA "APL (Dyalog Extended) – Try It Online") `⍬` empty list (`[]`) `⍣⎕⊢` on that, apply the following function `n` (prompted-for) number of times:  `⍮⍨` pair up with itself The print handler: `Print←{`…`}` assign a function as follows:  `⎕JSON⍺` convert output array to JSON  `⎕←` print that Setting up the JSON printing callback on output: `⎕SE.` for the current session:  `onSessionPrint←` set the event handler for printing to  `Print` call the above handler function [Answer] # [GNU sed](https://www.gnu.org/software/sed/), ~~36~~ 35 bytes I believe numeric input is allowed to be in unary format for sed. For ex. `3` becomes `@@@` and `0` becomes the empty string (no @s). The nameless label `:` is supported by older versions of sed. ``` s:$:@[]: : s:@:: s:\[]:[&, &]:g /@/b ``` [Try it online with sed 4.2.2!](https://tio.run/##K05N@f@/2ErFyiE61orLiqvYysEKRMYAudFqOgpqsVbpXPoO@kn//3M5cDmAkAMA) In each loop iteration one character is removed from the unary number as one depth is introduced in the array. A small trick is used in the first line, where the initialization is only `[]` (shorter than `[[], []]`), like a "-1 based indexing". As such the input number is incremented by one with the extra `@`. This helps also with not checking up front for the empty string (input 0). **EDIT:** with 1-based indexing now allowed, the incrementing from first line isn't needed,thus saving one byte: `s:$:[]:` Thanks to Adám for the heads-up. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` ›(W: ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oC6KFc6IiwiIiwiMVxuMlxuMyJd) One-indexed. Returns a nested list. ``` › # increment ( # repeat for n+1 times (n+1 is popped): W # wrap stack into single list (initially []) : # duplicate # implicit output ``` --- ### [Vyxal](https://github.com/Vyxal/Vyxal) `W`, 3 bytes ``` (W: ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyJBVyIsIiIsIihXOiIsIiIsIjFcbjJcbjMiXQ==) Here, it repeats `n` times, and before outputting implicitly, the `W` flag wraps the stack into a single list. [Answer] # [sclin](https://github.com/molarmanful/sclin), 15 bytes ``` []"dup ,";1+ *# ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) I've been thinking about having code that took input from the next line rather than the previous. Surprisingly useful, gonna have to use it more often... For testing purposes: ``` []"dup ,";1+ *# f>o 2 ``` ## Explanation Prettified code: ``` [] ( dup , ) ; 1+ *# ``` * `[]` empty list * `(...) ; 1+ *#` execute (next line) + 1 times... + `dup ,` duplicate and pair into list [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~25~~ ~~23~~ 22 bytes *Saved 2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)! Saved 1 byte by changing to 1-indexed.* ``` f=n=>n--?[a=f(n),a]:[] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1q4uT1fXPiFapTo60TZNI09TJzG2NjbBKiE6NuF/cn5ecX5Oql5OfrpGmoaBpqY1F6qQIaaQEVDoPwA "JavaScript (Node.js) – Try It Online") Arnauld's observation of testing for 1-indexed as `~n--` saves 1 byte over `n--+1`. Returns an array of arrays, which, when printed, will output JSON compliant arrays. If a string output is mandatory, then we have, using the same method: # [JavaScript (Node.js)](https://nodejs.org), ~~34~~ ~~32~~ ~~31~~ 29 bytes *Saved 2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)! Saved 2 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)! Saved 1 byte by changing to 1-indexed.* ``` f=n=>`[${n--?[a=f(n),a]:[]}]` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i4hWqU6T1fXPjrRNk0jT1MnMdYqOrY2NuF/cn5ecX5Oql5OfrpGmoahpqY1F6qQEaaQMVDoPwA "JavaScript (Node.js) – Try It Online") [Answer] # TI-Basic, 32 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541) ``` Prompt N "[] For(I,0,N "["+Ans+","+Ans+"] End Ans ``` [![enter image description here](https://i.stack.imgur.com/7d72u.png)](https://i.stack.imgur.com/7d72u.png) [Answer] # ><>, 58 bytes ``` e0i1+:?v"]["oo~. 3[r]40.\"["o:1-20 .","o:1-303[r]40 ."]"o~ ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiZTBpMSs6P3ZcIl1bXCJvb34uXG4zW3JdNDAuXFxcIltcIm86MS0yMFxuLlwiLFwibzoxLTMwM1tyXTQwXG4uXCJdXCJvfiIsImlucHV0IjoiXHUwMDAwIiwic3RhY2siOiIiLCJtb2RlIjoibnVtYmVycyJ9) Offsetting the number by 1 would save 2 bytes, since I can skip the 1+. ## Explanation [![enter image description here](https://i.stack.imgur.com/AaTPL.png)](https://i.stack.imgur.com/AaTPL.png) Top row: Main function. Check if the recursion level is 0, if so print `[]` and return, else go down. Second row: print `[`, then recurse. Third row: print `,` then recurse Print `]` and return. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 22 bytes ``` K`[] "$+"+`\[] [[],[]] ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zshOpZLSUVbSTshBsiKjo7ViY6N/f/fGAA "Retina – Try It Online") No test suite due to the way the program uses history. Explanation: ``` K`[] ``` Replace the input with an empty array. ``` "$+"+` ``` Repeat `n` times... ``` \[] [[],[]] ``` ... replace each empty array with a pair of empty arrays. Previous 0-indexed version was 27 bytes: ``` K`[[],[]] "$+"+`\[] [[],[]] ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zshOjpWJzo2lktJRVtJOyEmOpYLKvL/vxEA "Retina – Try It Online") No test suite due to the way the program uses history. Explanation: Starts with the first pair of empty arrays thus reducing the number of iterations needed by 1. [Answer] # [FunStack](https://github.com/dloscutoff/funstack) alpha, 23 bytes ``` Pair self iterate "" At ``` You can try it at [Replit](https://replit.com/@dloscutoff/funstack). Takes the depth (1-indexed) as a command-line argument and the program on stdin. ### Explanation At the core of this solution is the following infinite sequence: ``` [] [[],[]] [[[],[]],[[],[]]] ... ``` We start with the empty list, and each subsequent element is two copies of the previous element wrapped in a list. `Pair self` does exactly that, and we get the desired infinite list by `iterate`ing that function starting from `""` (empty string / empty list). This creates a bare value at the left end of the program, so it is appended to the program's argument list. Then `At` takes the first argument as an index into the second argument and returns the corresponding element. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` F⊕N≔E²υυ⭆¹υ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzMvuSg1NzWvJDUFyC4oLfErzU1KLdLQ1NRUcCwuzkzP0/BNLNAw0lEo1QRha66Aosy8Eo3gEiCVDpIyBAlrWv//b/RftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of Adám's APL answer. ``` F⊕N ``` Loop `n+1` times... ``` ≔E²υυ ``` ... replace the predefined empty list with a list of two copies of it. ``` ⭆¹υ ``` Pretty-print the final list (needed because Charcoal doesn't normally output anything for empty lists). [Answer] # [Python](https://www.python.org), 29 bytes ``` g=lambda n:n*[0]and[g(n-1)]*2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhZ7021zEnOTUhIV8qzytKINYhPzUqLTNfJ0DTVjtYwgam4qFxRl5pVopGsYampywdhGSGxjTU2IUpixAA) 1-indexed. Returns Python's native array representation. # [Python](https://www.python.org), 45 bytes ``` g=lambda n:n and f'[{g(n-1)},{g(n-1)}]'or'[]' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3ddNtcxJzk1ISFfKs8hQS81IU0tSjq9M18nQNNWt1YIxY9fwi9ehYdagm5YKizLwSjXQNQ01NLhjbCIltrKkJUQqzBwA) Returns a string, also 1-indexed. I found three different 45-byte functions for this, so I chose the simplest. [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 8+2=10 bytes Takes `n` as 1-indexed argument on TIO. ``` .+ [&,&] ``` Initial input: ``` [] ``` [Try it online!](https://tio.run/##KyxNTCn6/19PmytaTUct9v//6Nj/RgA "QuadR – Try It Online") `.+` match everything (any number of any characters) `[&,&]` replace with open-bracket, match, comma, match, close-bracket [Answer] # [PHP](https://php.net/), 64 bytes ``` for($a=[],$b=[&$a,&$a];$argn--;)$a=[$a,$a];echo json_encode($b); ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFQSbaNjdVSSbKPVVBJ1gDjWWiWxKD1PV9daEyQHFASJpSZn5CtkFefnxafmJeenpGqoJGla//9v9C@/oCQzP6/4v64bAA "PHP – Try It Online") I thought this solution by reference elegant enough to be posted, I wish we could use a reference to a variable while initializing it, but unfortunately it's not the case. Too bad for the output format, almost a third of the code is lost to formatting.. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¯IƒD‚ ``` [Try it online](https://tio.run/##yy9OTMpM/f//0HrPY5NcHjXM@v/fCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W98bJKfvZLCo7ZJCkr2/w@t9zs2yeVRw6z/tTr/AQ). **Explanation:** ``` ¯ # Push an empty list: [] Iƒ # Loop the input+1 amount of times: D # Duplicate the current list ‚ # Pair the two lists together # (after the loop, output the result implicitly) ``` [Answer] # [Julia 1.0](http://julialang.org/), 21 bytes ``` !x=1:2(x>0).|>_->!~-x ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/X7HC1tDKSKPCzkBTr8YuXtdOsU634n9afpFCpkJmnoKBlSmXAhAUFGXmleTkaWQq2NopKGZqcqXmpfwHAA "Julia 1.0 – Try It Online") returns a nested array **Explanation** * `a .|> f` applies `f` on each element of `a` * when `x=0`, `1:0` is (kinda) an empty list, so the result is an empty list * when `x>0`, `1:2` acts like a 2-element list, and each element of this list will be `!(x-1)` [Answer] # [R](https://www.r-project.org), ~~57~~ 53 bytes *Edit: saved 4 bytes by copying [MarcMush's approach](https://codegolf.stackexchange.com/a/255519/95126)* ``` \(n){s="[]";for(i in 1:n)s=paste0("[",s,",",s,"]");s} ``` Returns JSON string. [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGGotTk0qLizLLU-MSiosRK26WlJWm6FjdNYzTyNKuLbZWiY5Ws0_KLNDIVMvMUDK3yNIttCxKLS1INNJSilXSKdZR0wGSskqZ1cS1UswWaoRqGmlzoQkaYQsaaEP0LFkBoAA) --- # [R](https://www.r-project.org), ~~41~~ 37 bytes ``` f=\(n,s={})`if`(n,f(n-1,list(s,s)),s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY5BCsIwEEX3PUWICAlEUFdSyCXcqtRQkxoJk5JJBRFP4qYu3Lv0Kt7G1NZNF8MM7__5_PsjtK-gyyagPetChaAu8tlEM1t9pkZuGQiU1xvfW7NPt2EwWwhnMTIUyHmawfxWgHIUxJY8mxAFZE1AY9QH0n3mGcbAkr0TSw9nHSKJnihyQg8kiRaqPBuUIvqi47JKZRyvVcqZM7qhwhrmNFTxmPCfo6prd2FOVFyU3jlVo5ZUUC7ojvJx5q9E379t-_0F) Returns R nested list, which can be converted into a json string. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 21 bytes ``` {(@,{$_,$_}...*)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1uplmb7v1rDQadaJV5HJb5WT09PSzNaJT629n9xYqWCnlqaQlp@kYKhnp7pfwA "Perl 6 – Try It Online") [Answer] # [jq](https://stedolan.github.io/jq/), 36 bytes ``` def n:try(.<0//(.-1|[n,n]))+[]//[];n ``` [Try it online!](https://tio.run/##yyr8/z8lNU0hz6qkqFJDz8ZAX19DT9ewJjpPJy9WU1M7OlZfPzrWOu//fwMuQy4jAA "jq – Try It Online") Thanks to [ovs for the `try(A//C)+[]//B`](https://codegolf.stackexchange.com/a/235138/86147) hack! Our recursive function has a base case of `-1`, which yields `[]`. Otherwise, our input is decremented, and `[n,n]` recurses into the function twice. [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$7\log\_{256}(96)\approx\$ 5.76 bytes ``` ls{KDZP ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbLc4qrvV2iAiA8qOCChUYQBgA) Port of Kevin Cruijssen's 05AB1E answer. #### Explanation ``` ls{KDZP # Implicit input ls # Push an empty list and swap {K # Repeat (input) times: DZP # Duplicate and pair # Implicit output ``` [Answer] ## Batch, 76 bytes ``` @set s=[] @for /l %%i in (0,1,%1)do @call set s=%%s:[]=[[],[]]%% @echo %s% ``` Explanation: Port of the 1-indexed version of my Retina answer, but looping from `0` to `n` to convert back to 0-indexed. `call set` is needed because otherwise the variable gets expanded before the `for` loop executes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ’ßWƊR‘?;` ``` A recursive, monadic Link that accepts a non-negative integer (0-indexed) and yields the nested list. (Replace `‘` with `¹` to use 1-indexed input.) **[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4oCZw59XxopS4oCYPztg/8OHxZLhuZj//zI "Jelly – Try It Online")** ### How? ``` ’ßWƊR‘?;` - Link: integer, n ? - if... ‘ - ...condition: increment (i.e. n != -1?) Ɗ - ...then: last three links as a monad - f(n): ’ - decrement (n) -> n-1 ß - call this Link with n-1 W - wrap that in a list R - ...else: range (n = -1) -> [] ` - use as both arguments of: ; - concatenate ``` [Answer] # [Factor](https://factorcode.org/), 33 bytes ``` [ { } swap [ dup 2array ] times ] ``` [Try it online!](https://tio.run/##HcuxCsIwFEDR3a@4X@DQUcG1uLgUp9LhUVOMTZPw8qSI9NsjdT9nktGS1nt3vbUnFrEns9PoAqIqn8KrpHhc1ZtTfOJ8aGrPl42ySqbn8c40f8uA@cUVhjpKCFz2SlYfrf4A "Factor – Try It Online") ]
[Question] [ # Background The monkeys need help organizing their defense and have asked you, [Benjamin](https://bloons.fandom.com/wiki/Benjamin_(BTD6)) the code monkey, to create a program that will list all tower upgrade options. Each tower has three unique upgrade "paths", each having a tier represented by a number between 0 and 5 inclusive, 0 meaning no upgrade. Up to two paths may be chosen for upgrading, that is contain an upgrade tier 1 or greater. Additionally, only one path can can contain a tier 3 or greater. # Task Output in some reasonable format all valid upgrade path triples in *any order* (the triples themselves are ordered). Triples can be represented in any reasonable way, such as 025 or 0-2-5. The triples must be distinguishable from each other in some way, so a flat list of numbers without triple delimiters is not allowed. Here is an example list of all 64 possible triples, as they appear in-game for your insta-monkey collection: ``` 5-2-0 5-0-2 5-1-0 5-0-1 5-0-0 2-5-0 0-5-2 1-5-0 0-5-1 0-5-0 2-0-5 0-2-5 1-0-5 0-1-5 0-0-5 4-2-0 4-0-2 4-1-0 4-0-1 4-0-0 2-4-0 0-4-2 1-4-0 0-4-1 0-4-0 2-0-4 0-2-4 1-0-4 0-1-4 0-0-4 3-2-0 3-0-2 3-1-0 3-0-1 3-0-0 2-3-0 0-3-2 1-3-0 0-3-1 0-3-0 2-0-3 0-2-3 1-0-3 0-1-3 0-0-3 2-2-0 2-0-2 2-1-0 2-0-1 2-0-0 0-2-2 1-2-0 0-2-1 0-2-0 1-0-2 0-1-2 0-0-2 1-1-0 1-0-1 1-0-0 0-1-1 0-1-0 0-0-1 0-0-0 ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~20~~ 18 bytes ``` ?,/+'!'1|3*<'+!3#3 ``` [Try it online!](https://ngn.codeberg.page/k#eJyz19HXVldUN6wx1rJR11Y0Vjbm4tJXcE0syslMLVJILClJzS0oKbYCitlDVJopGCsYOsDU6itUa+kbAoXM7LQrHNRt1CtqlUEyZkAZDbhUhYNNRa26JlwGaFR1hYO+FdSUWiAFNhYipQHlaTrEWMHVAABhOCP+) `+!3#3` All triples with values in `0 1 2`. `<'` Grade up each triple. This results in all permutations of `0 1 2` with some duplicates. `1|3*` Multiply by 3 and take maximum with 1 to generate all permutations of `6 3 1`. `+'!'` For each permutation, generate all triples where the each entry is a non-negative integer less than the number in the permutation at the same index. `?,/` Flatten into a matrix with three columns and take the unique rows. [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics`, ~~59~~ 58 bytes ``` 6 iota 3 selections [ natural-sort "\0"before? ] filter . ``` [Try it online!](https://tio.run/##JYy7DsIwDEUHfuSqOxUSEgMMjIiFBTEBgxscsJTGxXEHvj4EMZ9HpOBq9XI@ng5bFH7PnAMXjOSvPug4SKYmSCgoai75@UdqDzZMxu6fySQ7dnUDUSes2yZxcNFccEXrZ6O0/OXobqtFN3BU4z3uiJK8bfpavw "Factor – Try It Online") -1 byte from a tip by @ovs. Note the string `"\0"` has literal control character `3` embedded as well as the `0`; you can see it on TIO. This string is equivalent to the longer (but clearer) sequence `{ 0 3 }`. * `6 iota 3 selections` Generate all 3-selections of \$[0..5]\$: `{ { 0 0 0 } { 0 0 1 } ... { 5 5 5 } }` * `[ natural-sort { 0 3 } before? ] filter` Select those that when sorted are less than `{ 0 3 }`. * `.` Print them. [Answer] # Python 2, ~~82~~ 80 bytes ``` from itertools import* print[k for k in product(*[range(6)]*3)if[0,3]>sorted(k)] ``` -2 bytes thanks to *@ovs*. [Try it online.](https://tio.run/##DcsxDoAgDADA3Vd0BOJgJHH0I4TBCGiDUFLr4OvR26@9clKde09MBVAiC9F1A5ZGLGZojFVchkQMGbBCYwrPLso43uoR1aK9sRqTm0br1/tPMaisfe8f) **Explanation:** * `from itertools import*`: Import `itertools` for the cartesian `product` builtin * `range(6)`: Push list `[0,1,2,3,4,5]` * `[^]*3`: Repeat it three times: `[[0,1,2,3,4,5],[0,1,2,3,4,5],[0,1,2,3,4,5]]` * `product(*^)`: Use the cartesian product builtin to get all triplets * `k for k in ^`: Loop over these triplets * `^if`: And filter to only keep the triple-tuplets `k` that are: + `sorted(k)`: When sorted and converted to an array + `[0,3]>^`: are smaller than `[0,3]` * `[^]`: Wrap all these tuplets into an array * `print^`: And print it as result [Answer] # [Python](https://www.python.org), 71 bytes ``` for x in range(521):max(s:='%03d'%x)<'6'!=['0','3']>sorted(s)==print(s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY33dPyixQqFDLzFIoS89JTNUyNDDWtchMrNIqtbNVVDYxT1FUrNG3UzdQVbaPVDdR11I3VY-2K84tKUlM0ijVtbQuKMvNKgCyIcVBTYaYDAA) I took the `['0','3']>sorted(s)` idea from ovs. [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` uΣmPΠmŀ∫ḣ3 ``` [Try it online!](https://tio.run/##yygtzv7/v/Tc4tyAcwtyjzY86lj9cMdi4///AQ "Husk – Try It Online") Similar to my K answer. ``` ∫ḣ3 -- cumulative sums of [1..3] -> [1,3,6] mŀ -- lowered range of each -> [[0],[0,1,2],[0,1,2,3,4,5]] Π -- cartesian product of the three lists mP -- for each triplet, get all permutations Σ -- flatten into a list of triplets u -- get the unique ones ``` [Answer] # [JavaScript (V8)](https://v8.dev/), ~~75~~ 67 bytes *Saved 8 bytes thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)* Prints one comma-separated triplet per line. ``` for(i=216;i--;)[...a=[i/36%6|0,i/6%6|0,i%6]].sort()<'0,3'&&print(a) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPT1sjQzDpTV9daM1pPTy/RNjpT39hM1azGQCdTH0qrmsXG6hXnF5VoaNqoG@gYq6upFRRl5pVoJGr@/w8A "JavaScript (V8) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 5Ý3ãʒ{₆1š‹P ``` -2 bytes thanks to a tip of *@ovs* using `136`. Outputs as a list of triplets. [Try it online.](https://tio.run/##yy9OTMpM/f/f9PBc48OLT02qPrY1KvhRw86A//8B) **Explanation:** ``` 5Ý # Push a list in the range [0,5] 3ã # Cartesian power of 3: get all triplets using these [0,1,2,3,4,5] ʒ # Filter this list by: { # Sort the triplet from lowest to highest ƵZ # Push compressed integer 136 S # Convert it to a list of digits: [1,3,6] ‹ # Check for sorted triplet [a,b,c] whether [a<1,b<3,c<6] P # Check if all three are truthy # (after which the filtered list of 64 triplets is output implicitly) ``` `ƵZS` could alternatively be `₆1š` for the same byte-count: [try it online](https://tio.run/##AR0A4v9vc2FiaWX//zXDnTPDo8qSe@KChjHFoeKAuVD//w). ``` ₆ # Push 36 1š # Convert it to a list of digits, and prepend 1 ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ƵZ` is `136`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes ``` 520$*¶ 00$.` .+(...) $1 G`0 A`[3-5].*[3-5]|[6-9] ``` [Try it online!](https://tio.run/##K0otycxL/P@fy9TIQEXr0DYuLgMDFb0ELj1tDT09PU0uFUMu9wQDLseEaGNd01g9LTBVE22maxn7P8aJS/c/AA "Retina 0.8.2 – Try It Online") Link includes footer that prettifies the output. Explanation: ``` 520$*¶ 00$.` .+(...) $1 ``` List all the integers from `0` to `520` inclusive, padded to 3 digits. ``` G`0 ``` Only keep those integers with at least one `0` digit. ``` A`[3-5].*[3-5]|[6-9] ``` Discard those with more than one digit greater than `2` or with a digit greater than `5`. [Answer] # [Python 3](https://docs.python.org/3/), 75 bytes ``` print([r for r in[(x//36,x//6%6,x%6)for x in range(216)]if[0,3]>sorted(r)]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EI7pIIS2/SKFIITMvWqNCX9/YTAdImqkCKVUzTZBUBVBKoSgxLz1Vw8jQTDM2My3aQMc41q44v6gkNUWjSDNW8/9/AA "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` ΦEφ﹪%03dι∧№ι0∧›6⌈ι›²ΣEι‹2λ ``` [Try it online!](https://tio.run/##NYzBCsIwEER/JSwIG1ghVvDiSQS9GBD8gqUJuJA2kjbi38et1DnOvDf9k0ufObV2LzLOeJE0x4KeX7hzzpHxOdSUETZuH4CMWEvmNAY856q4kAEHa3UtkRcZDgp6/shQB/wJ/6Uj89BueVfzFqcJoVM42TXH1tr2nb4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` φ Predefined variable `1000` E Map over implicit range ι Current value ﹪%03d Formatted to 3 0-filled digits Φ Filtered where ι Current value № Contains 0 Literal string `0` ∧ Logical And 6 Literal string `6` › Is greater than ι Current value ⌈ Maximum character ∧ Logical And ² Literal integer `2` › Is greater than ι Current value E Map over digits 2 Literal string `2` ‹ Is less than λ Current digit Σ Take the sum Implicitly print ``` 28 bytes for the prettier version: ``` ΦEφ⪫﹪%03dι-∧№ι0∧›6⌈ι›²ΣEι‹2λ ``` [Try it online!](https://tio.run/##NY3RCsIwDEV/pQSEFDqoE3zxSQQFWUHwC8paMNC1o1tlf19TmHkJnHtPMn5sHpMNtb4yxRXvFFaf0dgZj1prJZ6JIprkSkgIB31yoARJJaADyesaHd5SYZOYadjRI3vb7sCZ68ZuNJUJqQn/pFfizaw9YnPwy4LQcznIfS611u4bfg "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Ruby](https://www.ruby-lang.org/), 62 bytes ``` p (z=*0..5).product(z,z).select{|x|x.min<1&&(x-[3,4,5])[1]}|[] ``` [Try it online!](https://tio.run/##KypNqvz/v0BBo8pWy0BPz1RTr6AoP6U0uUSjSqdKU684NSc1uaS6pqKmQi83M8/GUE1No0I32ljHRMc0VjPaMLa2Jjr2/38A "Ruby – Try It Online") [Answer] # [Rust](https://www.rust-lang.org), 106 bytes ``` for i in 0..6{for j in 0..6{for k in 0..6{let mut t=[i,j,k];t.sort();if t<[0,3,6]{print!("{i}{j}{k} ")}}}} ``` Actually using nested loops is barely shorter than my attempt using itertoools. [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMHqtDyF3MTMPA1NheqlpSVpuhY3s9LyixQyFTLzFAz09MyqQbwsFF42nJeTWqKQW1qiUGIbnamTpZMda12iV5xfVKKhaZ2ZplBiE22gY6xjFltdUJSZV6KooVSdWVudVVudXculpFkLBBAbF0LpBQsgNAA) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` f>,Z3ST^U6 3 ``` [Try it online!](https://tio.run/##K6gsyfj/P81OJ8o4OCQu1EzB@P9/AA "Pyth – Try It Online") Port of Kevin Cruijssen's [Python answer](https://codegolf.stackexchange.com/a/249354/65425) ``` f>,Z3ST^U6 3 U6 Range up to 6 = [0,1,2,3,4,5] ^ 3 Cartesian product with itself 3 times = [0,1,2,3,4,5] * [0,1,2,3,4,5] * [0,1,2,3,4,5] f Filter for elements T such that: >,Z3ST [0,3] > sorted(T) ``` [Answer] # [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `-a`, ~~73~~ 64 bytes ``` [345]([12]0|0[012])|[12]([1-5]0|0[0-5])|0([012][0-5]|[345][012]) ``` [Attempt This Online!](https://staging.ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboWNx2ijU1MYzWiDY1iDWoMog2AtGYNiAcU0jWFiAFpzRoDDbAkmFcD1gRRDDEHatwCKA0A) Surprised nopony did this yet. Probably golfable! EDIT: -9 thanks to [math junkie](https://codegolf.stackexchange.com/users/65425/math-junkie) for reminding me of the shorter output format. Now it's 1 byte per combination :P I still think it can be golfed further, possibly with a new approach :-)c [Answer] # [Python 3](https://docs.python.org/3/), ~~161~~ ~~146~~ ~~141~~ 135 bytes ``` from itertools import* for u in product(*[range(6)]*3): i,j,k=u if 0not in u or i>2and j>2or j>2and k>2or k>2and i>2:1 else:print(u) ``` [Try it online!](https://tio.run/##JcsxDsMgDIXhnVN4DChDm0gdkJqLVBmiBlogsZFjhp6e0mZ7n/S//JE34VirZ9ohiGMh2g4IeyYWozwxFAgImWktT@nMgxd8ue6mZzNqqyD0sU/30oaHC5L84gLtFqZhwRXiNDTEE@mPdKIF9qrAbYezmQNKV3StXw "Python 3 – Try It Online") -5 thanks to [qwr](https://codegolf.stackexchange.com/users/17360/qwr) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` 6p3’Ż€Œ!€ẎQ ``` [Try it online!](https://tio.run/##y0rNyan8/9@swPhRw8yjux81rTk6SRFIPtzVF/j/PwA "Jelly – Try It Online") A niladic link that returns the 64 triples. This is [my answer to the follow-up question](https://codegolf.stackexchange.com/a/268857/42248) but with the sorting code removed. [Answer] # Batch, 271 bytes ``` @!! 2>nul||cmd/q/v/c%0&&exit/b&for /l %%i in (0,1,5)do @(for /l %%j in (0,1,5)do @(for /l %%k in (0,1,5)do @(set s=%%i%%j%%k&set p=!s:0=!&if !p:~!==~ set p=0 if !p!. neq !s!. set/af=!p!/10&set/al=!p!%%10&if !f! lss !l! (if !f! leq 2 echo !s!)else if !l! leq 2 echo !s!))) ``` ]
[Question] [ You are [Odysseus](https://en.wikipedia.org/wiki/Odyssey), and are finally free from Calypso (who has kept you captive for many years) after you drugged her while she was sleeping1. You wish to return to your homeland of Ithaca, but the ship you've stolen is a bit damaged and cannot steer. However, you have also stolen a map which contains the location of Calypso’s island as well as the locations of Ithaca and the small islands that lie in between, as well as information about the wind currents of the area. Your ship can only sail by the wind currents, but you get to choose the direction you start in (north, south, east, west). If the currents bring you to another island, you also get to choose the direction in which you depart that island. Can you get home to Ithaca? [1] Because that definitely happens in the epic. ## Input Format The input consists of: * positive integers w and h * a w-by-h grid of characters representing the map, where: + `~` denotes calm sea + `^` denotes a wind blowing north + `v` denotes a wind blowing south + `<` denotes a wind blowing west + `>` denotes a wind blowing east + `c` denotes Calypso's island, your starting point + `i` denotes Ithaca, the destination + `*` denotes an intermediate island Each “wind” character moves you one cell in the direction of the wind, and winds never form loops (i.e. there is no way to get trapped in a cycle of winds). You may take input however you want (reading a file, from STDIN, as function parameters etc.) ## Output Output a truthy value if it is possible to get to Ithaca, and a falsy value if that is not possible. ## Test Cases ``` w=10, h=5 ~^~~~~~~~~ ~c>>*>>v~~ ~v~~v~~v~~ ~>>*<~~*>i ~~~v~~~~~~ Expected Output: True Explanation: Go east, then east again, then east again ``` ``` w=8, h=5 ~~~~~~~~ ~~>>v~~~ <<c~~~~~ ~~>~i~~~ ~~~~~~~~ Expected Output: False Explanation: There are two paths that lead to cells neighboring Ithaca, but there is no wind on those cells. ``` ``` w=5, h=2 <c>>> ~v~~i Expected Output: False Explanation: Although you can get to a distance of one cell away from Ithaca, the wind on that cell is eastward which pushes Odysseus off the map instead of to Ithaca. ``` ``` w=20, h=6 ~~~~~~~~~~~~~~~~~~~~ ~~v<<<<<<*<<>>>v>~~~ ~~i~<<*<<<<c~~~*~~~~ ~~~~~~^~~~~v~~~^~~~~ ~~~~~~<<*>>>>>>^~~~~ ~~~~~~~~~~~~~~~~~~~~ Expected Output: True Explanation: North, then West ``` ``` w=20, h=6 ~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~*<<>>>v>~~~ ~~i<v<*<<<<c~~~*~~~~ ~~~~v~^~~~~v~~~^~~~~ ~~~~v~<<*>>>>>>^~~~~ ~~~~v~~~~~~~~~~~~~~~ Expected Output: False Explanation: Although there is a wind leading to Ithaca, it is inaccessible. ``` Standard loopholes are prohibited. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes in each language wins. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 176 bytes ``` lambda w,h,b:b.find('i')in(r:={b.find('c')})|{r.update(*([{(d:={'<':i-1,'>':i+1,'^':i+~w,'v':i-~w}).get(b[i],i)},{*d.values()}][b[i]in'*c']for i in r if-1<i<len(b)))for _ in b} ``` [Try it online!](https://tio.run/##hVLBbqMwED3XX@GebFM3arrqqkLG0l76Bb2laQXGNJZYgjAxqij@9dQ2IZBVpB0hZvTe@M0by/VXu9tXv57r5thK3X6IVEsNE7gBeP1AnyhC6A3Yd3sKYAXnEefGl@43fsA6kFkbcQVsQHy4o/S1OUhCAX4@S52FbFCxgDFxRqwai1ngJS11UHiij6MCcw54GK4uGh4f6O/LGctwoGEhIsacgOEjqGxARhORnceHlc1UnEDXy0MswctYbv1fS6f4xxIz1yyZa5bMNUvmiqX5mqZ7FApwvnC7BaBI3o5l@jfLU9jRHc3ibFWoKsdIIaIq3MRJPyECkYF8983qUOdpK3GENz3OXQNiKFb3a4q4y3cuv/tsO4qMJ2w3kNWnbHG2UVuqyED7KF@ZtDxIjcmw3XhcVSgSaFvsG6igqqBLxf2aKVbKCmeEEM98eCYbjvoghNT@zfpF3BKOC@6p8B3zq47BjSpggQNJ4G0ChYM8Vu1beJKJYd2oqsXEMWOFXp0CfElVKfNbNOMF6pK@GyjcJf3OpV4MCzbz5WwtXD9wo6YxYFL/U5bBo4Z1qnUYcfwB "Python 3.8 (pre-release) – Try It Online") Ungolfed ``` def f(w,h,b): r = {b.find('c')} for _ in b: for i in list(r): if 0 <= i < len(b): d = {'<':i-1,'>':i+1,'^':i-w-1,'v':i+w+1} if b[i] in '*c': r.update(d.values()) r.add(d.get(b[i],i)) return b.find('i') in r ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~178~~ ~~173~~ ~~171~~ 168 bytes ``` s=>!/i/.test(s.map((_,i)=>_.map((_,j)=>_=='c'&&g(j,i,668)),g=(x,y,w)=>w--&&g(x,y,w>>3,w%=8,x+=--w%2,b=s[y+=--w%2]||0,b[x]=c='*<^>v'.indexOf(b[x]),~c&&g(x,y,c||668)))+s) ``` [Try it online!](https://tio.run/##hU/tboIwFP3PW@yHUrDUZUuMyXrvK@wBnIJWMDUOzEoKJqSvzkrBj6nJTprm3nN77jndr/VaiR95LKO82KZtBq0CfJnKKStTVRLFvtdHQmIqA8D43Oy7BsAX/ni8I3sq6Ww2DwK6A1LTE63suIqibuZaxHdajWBO6wlEUTV6oxtQi9PQLJvmlW4W9RIE@CFfofaZzLdp/ZmRjg6oEedVommcUzBRQfvhdRGhBhRFropDyg7FjmSkZup4kGXylScucAy4YIzFS6vrNSQxKzPAMwIxRNRdaa/@eMaS3JgQpWcc0yG56i9q46TG41xcGCP74l7FrRU6F/m46hZWq7lDyLnVaOxJaRzTe4Xm6uK@o8/FQNq36HBL/sW/MQbcxeD6WQz9LIZ@FkM/xmh/AQ "JavaScript (Node.js) – Try It Online") Treat destination as glory hole [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes ``` WS⊞υιυW№KAiFLυFL§υ⁰«Jλκ¿⁼iKK«UMKV⎇№⁺c*§v<^>νμiμ~»»≔¬№KAcθ⎚θ ``` [Try it online!](https://tio.run/##bVDLasMwEDzbXyF0kowLvdcITOghpQ2Ghh4DwlFsEVlyZMltKfGvuys/SgnZg9gZzc6sVNbcloarcfyspRKIbHXr3buzUleEUlT4riY@RZI@xQWQjnjoFu3GeCAKIc65UoSmCEsMMydjEXkVunIweoNzt9VH8RUsHync/cTRi2/avSEqRWewjuQJkeeL56ojYJeiYE8WafTG241pGq6PU@yH0TvhAeqQvhdWc/u9rqU8OJQJWKyhuM8ODLCmoG7mfUMTYqP5dXjAAV3ja5x3naw02Rl356ElDh4X0G6U4Jb8fQ9Q4zjcqXgY@myqJMsYYz2bSTlMTJaVgJNFGeoQjn5tFhK0bKr/5E3Q@NCrXw "Charcoal – Try It Online") Link is to verbose version of code. Doesn't bother with the dimensions, just takes a newline terminated list of strings for the map. Explanation: ``` WS⊞υιυ ``` Input the map and print it to the canvas. ``` W№KAi ``` Repeat while there are still potential source squares. ``` FLυFL§υ⁰« ``` Loop over all squares of the map. ``` Jλκ¿⁼iKK« ``` If the current square is a potential source square, then... ``` UMKV⎇№⁺c*§v<^>νμiμ ``` ... mark adjacent squares that can move to the current square as potential source squares, and... ``` ~»» ``` ... mark this square as seen. ``` ≔¬№KAcθ ``` Record whether the initial square was found to be a potential source square. ``` ⎚θ ``` Clear the canvas and output the result. [Answer] # [Python 3](https://docs.python.org/3/), 361 bytes ``` e=enumerate d={"^":(0,-1),"v":(0,1),"<":(-1,0),">":(1,0),"~":(0,0)} def f(g,x=e,y=0,V=[]): if x==e:x,y=[(x,y)for y,r in e(g)for x,c in e(r)if c=="c"][0] if(x,y)in V or x<0 or x>=len(g[0])or y<0 or y>=len(g):return 0 v=g[y%len(g)][x%len(g[0])] if v in d:a,b=d[v];return f(g,x+a,y+b,V+[(x,y)]) return v=="i"or any(f(g,x+j,y+k,V+[(x,y)])for j,k in d.values()) ``` [Try it online!](https://tio.run/##dVDdboMgGL0uT2FMlkDLGpfdOeAxeuNcYpV2bJYatUSzjFfvPj/c2jTdF6OHw/kBm7F/P9rn81lLbU8H3Ra9JpX8it/ilCb88Ynx2CGckAD0@MQTgApgQB63E/ZNKr2LdnTPB6n5KBO@kVnOUrIwu2iQUqcDsBmFN9sd22jkbWRspOkelwMvw7JloC@ljMs4z5J8sqMHNjfRJBQJfpSstaV7kLApLbDjzLK01f2ptVFCFk7us/Eh0Hk2PPzZMDtyU22VFnwrq8zlL7MRL7Iq@Lja8s0qHDtnZDFvOzigiaGxsCMN2g/Qfl5pp1t98E@MX7uiPumOMnY2h@bY9lE3doRMkm19LFEEzLrrK2PXrS4qytZdU5uexq/21cbTf2xaY3soq03X00PRIOAhIIhrY7EE5uzf/DzEl0otlXIThFd4iAdSeL9UhnhkUEsuLo8WT4Qo/xhvAvhVC4hWmGou1usB0gmcpRCgdSqQxiMTspf@korHdr9gJkGrcK7Jm6L/6ue5qRfuXr27V@/u1buboh8 "Python 3 – Try It Online") -26 bytes thanks to l4m2 [Answer] # JavaScript (ES6), 114 bytes As suggested by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh), we can save many bytes if we take the grid as an array of characters (with line-feeds) along with its width. Expects `(width)(grid)`. Returns `0` or `1`. ``` w=>g=(m,p=m.indexOf('c'),c=m[p])=>c=='i'|[m[p]=0,1,2,3].some(i=>"<^>v"[i]==c|c=='*'|c=='c'&&g(m,--i%2+p-~-i%2*~w)) ``` [Try it online!](https://tio.run/##nZDRaoMwFIbvfQoprEmchq67zckr7AGcpSVVl2FUqqS7KOfVXYyuK8VB2U/IOfk5@fORz4M9dOqk2z6pm2M@FDCcQZZATdyC4bo@5l9vBSWKsFiBSduMgVQARJNLOh5hE7/E2/g1411jcqpBrsRO2lWqMwB1GUcj4osi63XpcpNEP22f2wTHGuGZsaHPuz6E0IQgw4Ia3rWV7il5rwlLNxmv8rrsPxhNOecmY4Fq6q6pcl41JR2v0n2AO5wVoJIyktKOrdumFaAzBWIkdYDe8bN73p@0oYwth14j0edhIIS6Oqin5qEo4aCk59EPPnorZ1rhFQnhgqycTI3emagi/OXxv2F/mtl0s9Lr1rx76F9ss@7YhF1is0tsdonN/s02fAM "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~ 148 ~~ 143 bytes *Saved 5 bytes thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects a matrix of characters. The dimensions [are ignored](https://codegolf.meta.stackexchange.com/a/12442/58563). Returns `0` or `1`. ``` f=(m,y=m.findIndex(r=>i=~r.indexOf('c')),x=~i,c=(r=m[y]||0)[x])=>c=='i'|[r[x]=0,1,2,3].some(i=>"^<v>"[i]==c|c<'+'|c=='c'&&f(m,y+--i%2,x+~-i%2)) ``` [Try it online!](https://tio.run/##pVHRaoMwFH33K4qwJtEYuu41N@972geIhRJ13FF16AgWJL/uonbDOlsKOwSSe85Nzj3k42iOja7x8ysqqzTr@xxowc9QiBzL9LVMs5bWoBBsLXCo3nJKNGGMt2CRa3BqEZ@TrtuxuE0YKA1AkHRx7UrY8We@5y@JaKoiowjKP0ij/BgTAN1pSULSDRc02W7zwTiMInza8za0w85Yr6uyqU6ZOFXvNKext9nEQgjfHuwFfsJ/Sa1UoJS5Jl05rTnpGqW1gcI5OXZNb3oJY94t7xVnO9rOKSn1SpfFJfWIo3TB1CITPjbkHFe@Ro4IpHRvG7WU0Y7alCKwa1OPX2B@Dn9kd1@NWJeXo/0rzAU3w0hzP4y5H8bcD2NWw/Tf "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: m, // m[] = input matrix // (x, y) = current position with: y = m.findIndex(r => // y initialized to the index of the row r[] ... i = ~r.indexOf('c') // ... which contains 'c' at position ~i ), // x = ~i, // x initialized to ~i c = ( // c = character at (x, y), r = m[y] || 0 // or undefined if we're out of bounds )[x] // ) => // c == 'i' | // success if c == 'i' [r[x] = 0, 1, 2, 3] // invalidate r[x] .some(i => // for i = 0 to i = 3: "^<v>"[i] == c | // if c is equal to the character for this direction c < '+' | // or c is '*' (intermediate island) c == 'c' && // or c is 'c' (starting point): f( // do a recursive call: m, // pass m[] y + --i % 2, // add dy to y x + ~-i % 2 // add dx to x ) // end of recursive call ) // end of some() ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~234~~ ~~201~~ 198 bytes Full program, outputs by exit code. Started out as a golf of [hyper-neutrino's answer](https://codegolf.stackexchange.com/a/224384/64121). -9 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)! ``` g=input() W=len(g[0]) a=[divmod(`g`.find("c")-2,W+4)] for y,x in a:A,B,C,D,E,F=map(((g+["~"*W])[y]+"~")[x].__eq__,"><v^~i");a+={(y+a%3+1/~-F,x+a/3-1)for a in{3+3*A-3*B-~C-D}-{4-E}or[3,5,1,7]}-set(a) ``` [Try it online!](https://tio.run/##dVDtbpswFP0dP4WFNGGDoU3pNImBpX6kr5AflKYu0MwaMQw8CxTFr545Jm2qKDuy0PXh3HOubzvKX4242RdNWcEUuq67X6dctH8lwmCZ1pVA6@w6x4ClWcnVpinR6/o1fOeiRE7h4OCGLP1bnIP3poMjGSAXkMV35J48kEeyIE/phrUIobWfOdrxljnOxtw3Jc6GPFytqj@rFXFool40d/BP5qdbNPrsW@TPr3TwRAafXUXBHB/smTHfRn7k3QWRdx/oh@BxF2xvg8Wu6bKIfCdz8iPfBX0lEcN78xTAN23TSdiPPbADvtVN8fswomHCXpZchF3FSoTDvq25RM6zeBYOjsHMrsAspGabt5LFU@ekqrmoerMdeITsxvjzMquGqoCHbYLZrO24kNBdDFxaCl67wAiKqpXxpd9zd69f9BFAF5R6lKpDaT7TAdqQidYe5UBbxmrBqUvbFg2SpPhkNJ@KD3VirKl15afWrzCkSiy8JDFaRSeSa8tM3p4@udqx1UdxJI2WWnwlz4L@F3/EWXyiLsWrS/HqUrw6C/oH "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~232~~ ~~230~~ ~~203~~ 198 bytes ``` f=function(m,p=which(m=="c",T))`if`(sd(!p|p>dim(m)),F,{x=regexpr(m[p],"><^v*c~i",f=T) m[p]="~" d=matrix(c(1:-1,0,0,-1:1),2) `if`(x>6,x-7,`if`(x>4,any(apply(d,2,function(e)f(m,p+e))),f(m,p+d[,x])))}) ``` [Try it online!](https://tio.run/##tVHPT8MgGL33r5h4gcoSuxhNFiDx4E6edJ6W/ai03UjajZSKXVT@9cpot7nNHvu1Cd97BL73HnklN0qJ9zSeF5v5Mi52iyhWIQ9pldDkY80LsVnDDEv6uRJ8BTNKAQd4jNBCJAuoInglvyWLRAYzhPAIf5U0j5dxKXOYTeQUA0Zm2udGAJzQMfJ2JAUGeBHNwiIXJeQwGPYDfGu/fjAMEB4gz11esntc9h9wA@5wuN7CUMp0CyM8wAd1MUp2Cm9iZBXUbTTB5dTCH1RloaQcesDMTFMAW8QZ8xnTDbJr/Ttkt4gxPhMOOd6ds@qpqgXYW48CFIpTqIpcyVQUUGEA7GivNVqbVO@6N355e/K8Wh04kWacLtcTwv/yRhz6LiSNHp9fj5qIjYjt0xFdTjL/VO1SE1c@IVaLZgdeGEfW8fjmJBX3znrfHHl7grk648/mdv/IlzaburRJdItN3WJTt9jUndqsn7P6BQ "R – Try It Online") Recursive function expecting the map as a character matrix. **How?** ``` possible_to_get_to_ithaca= f=function(m, # recursive function f, m=map as a matrix p=which(m=="c",T)){ # p=current position, initialized to position of 'c' if(any(p<1|p>dim(m))) # if p is off the map, return FALSE return(F) x=m[p] # set x to contents of current position m[p]="~" # and set the current position to "~" to stop backtracking if(x=="i")return(T) # if x is "i" then we've arrived: return TRUE if(x=="~")return(F) # if x is "~" then we're becalmed: return FALSE if(x=="*"|x=="c"){ # if x is an island, try all 4 directions return(any( apply(cbind(a<-c(0,0,1,-1),rev(a)), # matrix of all 4 possible offsets 1,function(b) # try each offset b f(m,p+b)))) # recursive call to f with new position p } else # else move with the wind return( # recursive call to f with p offset by wind f(m,p+c((x==">")-(x=="<"),(x=="v")-(x=="^")))) } ``` [Answer] # [Scala](https://www.scala-lang.org/), 319 bytes It can be golfed more. A port of [@gsitcia's answer](https://codegolf.stackexchange.com/a/224427/110802). [Try it online!](https://tio.run/##lVRha9swEP2eX3ENpZZS17SFjZHagjI2GKz0Q7dP2zpkRU40XCdIirOSxn89O8mxnTRZxg5jfO9JevdOlozgOV@rp9lUWzAuicQ0z6WwalpET3PL01z2etP0F0LwRRr7nhtpYNkDKHkOwmcJfFbGEsQAyNVlCG9C6Pf73z0A8FI9VptoEcHYgLFyC8Hv@mkRHBJX1YCpFvG8C1w9Mlar2R3XY1WEYPVc0rCu4N1@Aa/lK6/d5nEsXvOV2sn/Ipvx3LS6KHq9qxujTbbtUB1f4Rp79/Zw6dvRcWXsYxDHKFSyHU5Vnqi9Dao9O35TyuZjl8OZzMcBbjeO7sR/@9nEYT9xecRPecRPecRP@S8/uxu0t8Wi/TsZO9wL5Glv1R6iO64KWK5HMoOMLIafChtO/DsdPuDcYkyTpTtaOtkcv@hBWpJGqhjJ3/cZCURA6U0aZVMtuZiQnwnT5@eJjuzUncIoU7mVmqiEwWWcKDg7AxWnUS6LsZ3QKMu5veMzoiBhXmeEx9cBQRzABQMkLuCKhhCwJj@v88eOXzRjym7Mwo@jN6AyIClRFJIEgkEALy/gUpdh6TCKUHWOt4bEvtYXxygaS3uvPyDgZ4aK0hUupfEyKiz2y2z7V@h/tQZwHXxCkmCzzRButebP3@oW/qBD@Fooi9aWfntKrsHMhZDG3VZuW3oexyYCIYsQJiGkIQgK8UV3zUX@eqObNcA7y5rRFE4SN6Eha/pko0JhhoXYvCC05Ruk7wTgI1e5HJ3093nTXySnTiU5RaFTcWBI2kGdLf@nbvBVr3u7utqymnLbYm7zHCwWZGDGjekqcnNX@N@u/wA) ``` def f(w:Int,h:Int,b:String)={val r=mutable.Set(b.indexOf('c'));b.foreach(_=>r++=r.toList.filter(i=> 0<=i && i<b.length).flatMap(i =>{val d = Map('<' -> (i - 1), '>' -> (i + 1), '^' -> (i - w - 1), 'v' -> (i + w + 1)); if (b(i) == '*' || b(i)== 'c') d.values else List(d.getOrElse(b(i),i))}));r.contains(b.indexOf('i'))} ``` Ungolfed version: ``` import scala.collection.mutable object TestCases { val cases = List( (10, 5, """\ |~^~~~~~~~~ |~c>>*>>v~~ |~v~~v~~v~~ |~>>*<~~*>i |~~~v~~~~~~""".stripMargin, true), (8, 5, """\ |~~~~~~~~ |~~>>v~~~ |<<c~~~~~ |~~>~i~~~ |~~~~~~~~""".stripMargin, false), (5, 2, """\ |<c>>> |~v~~i""".stripMargin, false), (20, 6, """\ |~~~~~~~~~~~~~~~~~~~~ |~~v<<<<<<*<<>>>v>~~~ |~~i~<<*<<<<c~~~*~~~~ |~~~~~~^~~~~v~~~^~~~~ |~~~~~~<<*>>>>>>^~~~~ |~~~~~~~~~~~~~~~~~~~~""".stripMargin, true), (20, 6, """\ |~~~~~~~~~~~~~~~~~~~~ |~~~~~~~~~*<<>>>v>~~~ |~~i<v<*<<<<c~~~*~~~~ |~~~~v~^~~~~v~~~^~~~~ |~~~~v~<<*>>>>>>^~~~~ |~~~~v~~~~~~~~~~~~~~~""".stripMargin, false), (2, 2, """\ |ci |>>""".stripMargin, true) ) } object Main { def f(w: Int, h: Int, b: String): Boolean = { val r = mutable.Set(b.indexOf('c')) for (_ <- b) { for (i <- r.toList) { if (0 <= i && i < b.length) { val d = Map('<' -> (i - 1), '>' -> (i + 1), '^' -> (i - w - 1), 'v' -> (i + w + 1)) if (b(i) == '*' || b(i) == 'c') { r ++= d.values } r += d.getOrElse(b(i), i) } } } r.contains(b.indexOf('i')) } def main(args: Array[String]): Unit = { var success = true for ((w, h, b, c) <- TestCases.cases) { if (f(w, h, b) != c) { if (!success) println() println("Test Failed!") println(s"w=$w, h=$h, $c") println(b) success = false } } if (success) { println("All tests passed!") } } } ``` ]
[Question] [ ## Lucky dice rolls In pen and paper roleplaying games dice are used for various chance calculations. The usual way to describe a roll is \$n\textbf{d}k\$ where \$n\$ is the number of dice and \$k\$ is the number of faces on a die. For example \$3d6\$ means that you need to roll the classical 6-sided die 3 times (or roll 3 dice at the same time). Both \$n\$ and \$k\$ are positive integers. Each die's output value ranges from 1 to \$k\$. Usually the values are then summed and they are used for various game mechanics like chance to hit something or damage calculations. A lucky roll will mean that you have Fortuna's favor on your side (or against you). Luckiness is an integer number that increases (or decreases) the sum in the following way. The roll is modified to \${(n+|luck|)}\textbf{d}{k}\$ and the sum will be the \$n\$ best (or worst) values. Each die is fair, so they will have the same probability for the outcome of the possible values per die. The \$luck\$ can be a negative number, in this case you need to get the \$n\$ worst values for the sum. ### Input The integer values for \$n,k,luck\$ in any way. ### Output The expected value for the sum of the (un)lucky roll. The [expected value](https://en.wikipedia.org/wiki/Expected_value#Finite_case) is \$\sum{x\_{i} p\_{i}}\$ where \$x\_{i}\$ is the possible outcome of the sum and \$p\_{i}\$ is the probability for \$x\_{i}\$ occuring, and \$i\$ indexes all possible outcomes. The output value can be float or rational number, at least 3 decimal places of accuracy or a fraction of two integer numbers, whichever suits your program better. ### Examples ``` n,k,luck expected value 1,6,0 3.5 2,6,0 7 2,6,-1 5.54166 2,6,1 8.45833 2,6,-5 3.34854 2,10,-1 8.525 2,10,1 13.475 6,2,15 11.98223 6,2,-15 6.01776 ``` ### Scoring Shortest code in bytes wins. ### Other With this mechanic you essentially create fake dice using only fair dice. I wonder if there is a nice formula to calculate this mathematically. Good luck! ;) [Answer] # [AnyDice](https://www.anydice.com), 82 bytes ``` function:l N K L{ifL<0{result:[lowestNof(N-L)dK]}else{result:[highestNof(N+L)dK]}} ``` [Try it online!](https://anydice.com/program/1c3a6/export/summary) For the output, check the "export" view and "summary" data and take the first value next to the output name (normally the link brings you there, but if you encounter issues, you know). ## Ungolfed for readability ``` function: l N K L { \ function with 3 parameters \ if L<0 { \ if L is negative \ result: [lowest N of (N-L)dK] \ return the lowest N dice among (N-L) rolls of a K-sided die \ } else { \ else \ result: [highest N of (N+L)dK] \ return the highest N dice among (N-L) rolls of a K-sided die \ } \ end if \ } \ end function \ ``` [Answer] # [R](https://www.r-project.org/), ~~106~~ ~~96~~ 88 bytes ``` function(n,k,l)n*mean(apply(expand.grid(rep(list(NA,1:k),n+abs(l))),1,sort,l>0,T)[1:n,]) ``` [Try it online!](https://tio.run/##TcixCsIwEAbg3afoeKd/JefgUETwBZzcxCHaRErjNSQR9Omjg4rbx5eqbzZtU/1dL2WYlBQjAuv85qySjTE8yT2i1X55TUNPyUUKQy6030G6kaELe84UmBmCPKWCsDU48FE6xYmrJ8EahmeeVv9o5asPxPzuTeH6Ag "R – Try It Online") Credit to Dominic van Essen for the `l>0` for the `descending` argument to `sort`, and for golfing down a lot of other bytes! [Answer] # [MATL](https://github.com/lmendo/MATL), 24 bytes ``` |+i:Z^!S1G0>?P]2G:Y)XsYm ``` Inputs are: `luck`, `n`, `k`. ### How it works ``` | % Implicit input: luck. Absolute value + % Implicit input: n. Add. Gives n+|luck| i: % Input: k. Range [1 2 ... k] Z^ % Cartesian power. Gives a matrix with n+|luck| columns, where each % row is a Cartesian tuple ! % Transpose S % Sort each column in ascending order 1G % Push first input (luck) again 0> % Is it positive? ? % If so P % Flip vertically: the order within each column becomes descending ] % End 2G: % Push second input (n) again. Range [1 2 ... n] Y) % Row-index. This keeps the first n rows Xs % Sum of each row Ym % Mean. Implicit display ``` [Try it online!](https://tio.run/##y00syfn/v0Y70yoqTjHY0N3Azj4g1sjdKlIzojgy9/9/Qy4jLkMDAA) Or [verify all test cases](https://tio.run/##y00syfmf8L9GO9MqKk4x2NDdwM4@INbI3SpSM6I4Mve/S1RFyH8DLkMuMy4DLiMgqWsIpiCkrilCzNCAC0aZAsWMgKJgGgA). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L²³Ä+ãε{³.$O}ÅA ``` Inputs in the order \$k,n,luck\$. [Try it online](https://tio.run/##ASYA2f9vc2FiaWX//0zCssKzw4Qrw6POtXvCsy4kT33DhUH//zYKMgotMQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaNh/n8iIwy3ahxef21odoafiX3u41fG/zv/oaDMdQx2DWB0FIMMIwdA1hLHADEMDuBiYCZU1hmkwRogAVcUCAA). **Explanation:** ``` L # Push a list in the range [1, (implicit) input `k`] ² # Push the second input `n` ³Ä+ # Add the absolute value of the third input `luck` ã # Take the cartesian product of the list and this value ε # Map each inner list to: { # Sort the list ³.$ # Drop the third input amount of leading items, # `luck` = 0: no items are removed # `luck` = 1: the first item is removed # `luck` = -1: the last item is removed O # Sum the remaining list of values }ÅA # After the map: calculate the average of this list of sums # (after which it is output implicitly as result) ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=sum -ap`, 116 bytes ``` @r=1..$F[1];$_=(sum map{(sort{$F[2]<0?$a-$b:$b-$a}/\d+/g)[0.."@F"-1]}@g=glob join$"=',',("{@r}")x("@F"+abs$F[2]))/@g ``` [Try it online!](https://tio.run/##HY7BCsIgAEB/RUSYY9PpoMtK8rRTHTutEY5CjG2KGgRjv56tro/H47mHH3cpSS84pajteL9HN4HDawKTcgsO1sdl43V/YEekCBoaNBCk1up6Lyqdd4xSKFtIeL9KLfRoB/C0ZkZQZGVWYrhIv8L8jX9SoYbwb@V5JXVKNeAM8I910dg5JHI@mRCb5hLNKLaDDewo4ywR5b4 "Perl 5 – Try It Online") Enumerates all possible rolls, selects the top (bottom) entries from each list, adds all of those up, and divides by the number of combinations. [Answer] # [J](http://jsoftware.com/), 45 bytes Takes input as `k` on the left side and `n, luck` on the right side. ``` [:(+/%#){:@]+/@}.&|:1+[:/:~"1[#.inv(i.@^+&|/) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600tPVVlTWrrRxitfUdavXUaqwMtaOt9K3qlAyjlfUy88o0MvUc4rTVavQ1/2v@N1NIUzBUMOAC0UZw2hBKxxtyGRqgsQwB "J – Try It Online") ### How it works ``` [:(+/%#){:@]+/@}.&|:1+[:/:~"1[#.inv(i.@^+&|/) i.@^+&|/ 0..k^(|n| + |luck|) [#.inv to base k 0 0 0..5 5 5 /:~"1 sort each roll 1+ 0 0 0 -> 1 1 1 {:@] }.&|: transpose and drop luck rows negative values drop from end +/ sum each roll (+/%#) average of all rolls ``` [Answer] # [R](https://www.r-project.org/), ~~152~~ ~~127~~ 109 bytes ``` function(n,k,l,w=n+abs(l))n*mean(apply(cbind(NA,mapply(rep,list(1:k),e=k^(w:1-1),l=k^w)),1,sort,l>0,T)[1:n,]) ``` [Try it online!](https://tio.run/##bc3BCoJQEAXQfV8yUzdwWrQQDPqBVu2i4mkG8sZR9In49fagjaC7uYfLnW7WofDTOzTBaTZ/BytC1RgZPBRjZgeX96TMtq9LZ@TaVicq8so@dLui/ueubKFVH0hSzygz/6IxlaMwNN4jMwR90wXoJcGdH5Ianrx8TYIzEt4t6bRNcXZlK5Jkoxcx2vwD "R – Try It Online") *Edit: -18 bytes thanks to Giuseppe for a really nice bit of programming! Note that this solution avoids a key `R` built-in function `expand.grid`, but Giuseppe's improvement manages to close-the-gap on his own solution (that uses the function) quite a lot.* Commented: ``` lucky_total=function(n,k,l){ m=n+abs(l) # number of rolls including lucky rolls a=matrix(NA)) # initial (empty) matrix of roll results for(r in 1:m){ # do all the rolls & combine results in matrix a=cbind(a[rep(seq(d<-k^(r-1)),k),],rep(1:k,e=d)) } mean( # get the mean result of... apply(a,1,function(b) # all the rolls, but only keeping # the highest/lowest 'lucky' dice # (using luck>0 to decide whether to sort # increasing or decreasing) sum(sort(b,l>0)[1:n]) ) ) } ``` [Answer] # [Python 2](https://docs.python.org/2/), 131 bytes ``` from itertools import* n,k,l=input() w=n+abs(l) print sum(sum(sorted(x)[l>0and-n:][:n])for x in product(*[range(1,k+1)]*w))*1./k**w ``` [Try it online!](https://tio.run/##PY4xb4MwFIR3/4q3YTtOijN0QKJbumbphhgIvDQW5tl6GEF@PYVE6nD33Uk3XHymR6Dz2oYOoYQsy9Y7hwFcQk4h@BHcEAMnLcj0xpeO4pSkEnNJh@Y2Sq9EZEcJxmmQL21j7OSiKv@VN9Qdqairgmp1DwwLOILIoZvaJHXFDf2itKY/WFXrWSltTx@91vO6/RBifjiP8MMTFgIg8XMHAC7Ywv5X7LnFmOBy/b4wB34PboxNv1rzaXJx/vejfWF3m7/bRvsH "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~131~~ 119 bytes ``` function(Z,Y,l,E=Z*(1+Y)/2,`[`=pbinom)(sum(1:Y*((K=rep(1:Z-1,e=Y))[X<-abs(l)+Z,J<-1-1:Y/Y]-K[X,J+1/Y]))-E)*(-1)^(l<0)+E ``` [Try it online!](https://tio.run/##DcqxCoMwEADQX3G8S@6wJ7RDSUYX/QGT0GItCoJG0fr9abY3vCNNheEiTVf8/uYtgidHC9XWKxDtsKyoD73dhzluK8J5rSBPpwBae4x7tmeh0TrE0Bn@DCcsqD01hoVzLN2L29BRoyUTkWtUwIJvWMwNdZ0meFBFLHdMfw "R – Try It Online") Quite a fast implementation; calculates the value directly. It's binomials all the way down. The key is the identity found [here](https://math.stackexchange.com/a/3568061/243672), for the expected value of a rolling \$X\$ d\$Y\$ and keeping the highest \$Z\$ of them. I rearranged it slightly to $$\sum\_{j=1}^{Y}j \sum\_{k=0}^{Z-1} \sum\_{l=0}^k \binom{X}{l}\left(\left(\frac{Y-j}{Y}\right)^l\left(\frac{j}{Y}\right)^{X-l} - \left(\frac{Y-j+1}{Y}\right)^l\left(\frac{j-1}{Y}\right)^{X-l}\right). $$ Recognizing the innermost sum as the difference of two binomial CDFs, it's implemented as ``` sum(1:Y*(p(K<-rep(1:Z-1,e=Y),X,J)-p(K,X,J+1/Y))) ``` for maximum (ab)use of R's recycling rules. There is then an adjustment for the fact that we may wish to keep the *lowest* `n` dice, but that's easy due to the symmetry of the binomial distribution. [Answer] # perl -alp -MList::Util=sum, 144 bytes ``` @,=map{@;=sort{$a<=>$b}/\d+/g;pop@;for$F[2]..-1;shift@;for 1..$F[2];sum @;}glob join",",("{".join(",",1..$F[1])."}")x($_+abs$F[2]);$_=sum(@,)/@, ``` [Try it online!](https://tio.run/##PYxPC4IwAMXvfYoxdlCc0wl1cBk7dapjpxJRSltMN9yCQPzqLf9Al/f4Pd57@tHLrXMcZ22pB84yo3o7oHKfHVA1Rrd7EDVMK81ZrXp0vCY5ISFl5ilqu2SAErLkzLxbwNnYSFWBlxIdxBB7cIBkBm@mtUpzn8AR@h8PFUFZmWXtM1Rk04PHsR9x7BwFOxBvkr@GdLFZabzS5PSrtBWqMy6UpXbh@SSMTdOLFXJ@@wE "Perl 5 – Try It Online") More readable written: ``` use 5.026; use strict; use warnings; no warnings 'syntax'; my ($n, $k, $luck) = @F; my @a = map { # Iterate over all possible rolls my @b = sort {$a <=> $b} /\d+/g; # Grab the digits, sort them. pop @b for $luck .. -1; # Remove the -luck best rolls. shift @b for 1 .. $luck; # Remove the luck worst rolls. sum @b; # Sum the remaining pips. } glob # Glob expansion (as the shell would do) join ",", # Separate the results of each die in a roll. # Almost any character will do, as long as it's # not special for glob expansion, and not a digit ( "{" . # "{" introduces a set of things glob can choose from join (",", 1 .. $k) . # 1 to number of faces "}" # matching "}" ) x ($n + abs $luck); # Number of dice in a roll $_ = sum (@a) / @a; # Sum the results of each different roll, # and divide by the number of rolls; $_ is # printed at the end of the program. __END__ ``` Reads space separated numbers from `STDIN`. Writes results to `STDOUT`. [Answer] # JavaScript (ES10), 143 bytes A naive, straightforward approach. ``` (n,k,l)=>eval([...Array(N=k**(t=l<0?n-l:n+l))].flatMap((_,v)=>[...Array(t)].map((_,i)=>-~(v/k**i%k)).sort((a,b)=>(a-b)*l).slice(-n)).join`+`)/N ``` [Try it online!](https://tio.run/##bczRToMwFMbxe5@iNyanrD3QQTdiROMDuBcwxnUIpuPYLtCQeOOrY5OpaMa57O/f72hGM9S9PQXp/GsztdUETnSCeHXXjIbgCREf@t58wK7qkgRCRbfZvZN041bE@TO2ZMKjOQG8iDF@mvsQ8f0MNoL8hDGNC/a64xwH3wcAIw5RwMgDTyg@kq0bkC760Vu3X@15uptq7wZPDZJ/gxaUYBvBMs5ZmrIc9dV/Xv/l7RJKdUaNulCb@RZj9h2XWOgyn6@4iFX2u1yiXuul4GdN5Vhs9fQF "JavaScript (Node.js) – Try It Online") ### How? We generate \$N=k^{n+|l|}\$ arrays of length \$n+|l|\$ corresponding to all possible rolls, keeping only the \$n\$ best or \$n\$ worst die in each array. We turn that into a single flat list of values, compute its sum and divide it by \$N\$. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 116 bytes ``` k=>l=>g=(n,w=[],h=i=>i&&g(n-1,[...w,i])+h(i-1),L=l<0?-l:l)=>n+L?h(k)/k:eval(w.sort((a,b)=>(a-b)*l).slice(L).join`+`) ``` [Try it online!](https://tio.run/##fc5NDoIwEEDhvQchM9JWcOFCnXIBbkBIKMhPYdIaIHB8ZOMOXX/Jy@vNYqZqtO9ZOv@qt4a2gTSTbgmcWCnLRUeWtA2CFpyMRaaUWoXNMezAyhhFSvyMEsl3RtIuTJMOBrwM93oxDKua/DgDGFHuCkaWeGZUE9uqhhRV760rwgK3x6nybvJcK/YtNHBDiBBixGO4HsK@80OOIY7@ybe2fQA "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes ``` NθNηNζ≧⁺↔ζθ≔XηθεFε«≔⊕…⮌↨⁺ιεηθδF↔ζ≔Φδ⁻μ⌕δ÷⌊×δζζδ⊞υΣδ»I∕Συε ``` [Try it online!](https://tio.run/##XY/LSsNAFIbXzVOc5QmM0Lp1VSOFLCqh@gJp5tgZmEucS8SKzx7PxCDFzYH/Mt/PDKoPg@/NPLduzOk52zMFfK8fqlut/ukr62M/7mPUF3fSF5WwMzkK2J@jNzkRNwQUym8FO/9RMMUTQOy/@QBINXxVm7XSuiGQJZdIYvM5GGqUH/FEE4VI@NjzKRuoC0CAqpcFPpJxm4V3s17Dij1ok3haCjhqx8@tgIN2shitS0960pKQI22zxVdtKZboWsB8/vhdjgqzgBduyZqd76oL2iVs@phwxZQwLx/kxjzfw24Lu/luMj8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNηNζ ``` Input `n`, `k` and `l`. ``` ≧⁺↔ζθ ``` Add `|l|` to `n`. ``` ≔Xηθε ``` Calculate the number of possible outcomes of rolling `n+|l|` `k`-sided dice. ``` Fε« ``` Loop over each outcome index. ``` ≔⊕…⮌↨⁺ιεηθδ ``` Generate the next outcome by converting to base `k` padded to length `n+|l|`. ``` F↔ζ ``` For each element of luck, ... ``` ≔Φδ⁻μ⌕δ÷⌊×δζζδ ``` ... remove the lowest or highest value from the outcome. ``` ⊞υΣδ ``` Save the sum of the remaining dice. ``` »I∕Συε ``` Output the average sum. 41 bytes if `l` is limited to `-1`, `0` or `1`: ``` NθNηNζ≧⁺↔ζθ≔XηθεI∕ΣEEε⊕…⮌↨⁺ιεηθ⁻Σι×⌊×ιζζε ``` [Try it online!](https://tio.run/##XY69DsIwDIR3niKjIwUJWJmgLAygCniBUCxiKUlLforg5YNTFsTgk@50/uzO6ND12pay90NOx@yuGOAh17Nfb/78m/1BD5sY6e5PdDcJWpujEptr7G1OyA0lKuVbgbZ/VkzNlEDO20A@QaNjgh2NdEM4ZwfMnAaV2PsuoEOf8AbNq7PYmH6AE44YIsJWs9STQJWnhJHTwaoH8pxXHLG7kMMInJHj5Ot4512bLHL6R8p1KSuxXIhlmY/2Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNηN ``` Input `n`, `k` and `l`. ``` ≧⁺↔ζθ ``` Add `|l|` to `n`. ``` ≔Xηθε ``` Calculate the number of possible outcomes of rolling `n+|l|` `k`-sided dice. ``` I∕ΣEEε⊕…⮌↨⁺ιεηθ⁻Σι×⌊×ιζζε ``` Generate all the possible outcomes, but if the luck is `-1` or `1` then subtract the largest or smallest entry from the sum, finally calculating the average sum. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~61~~ ~~58~~ ~~57~~ ~~64~~ 61 bytes[SBCS](https://en.wikipedia.org/wiki/SBCS) Full program, input order is `k`, `luck` and `n`. ``` (⊢⌹=⍨){w←1∘/⍵⋄1⊥w[⍒w]↑⍨n×(¯1*<∘0)l}¨(,∘.,)⍣(¯1+(n←⎕)+|l←⎕)⍨⍳⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtEzQedS161LPT9lHvCs3qcqCA4aOOGfqPerc@6m4xfNS1tDz6Ue@k8thHbROBKvIOT9c4tN5QywaoxkAzp/bQCg0dIFNPR/NR72KQjLZGHtAIoMma2jU5UBZQ36PezUDW//9mXAZcRgA "APL (Dyalog Unicode) – Try It Online") (with two extra bytes to print in TIO) or [check all test cases](https://tio.run/##SyzI0U2pTMzJT///P03hUdsEhWqNbIU8hRxNIPtR71aFR90tChqPuhY96tlp@6h3hWZ1OVDC8FHHDH2gLFDS8FHX0vLoR72TymMftU0Eqsg7PF3j0HpDLRugGgPNnNpDKzR0gEw9Hc1HvYs1NGpyNLXzdA2BnBWPejdn14KsNVMwVDDgAtFGcBpoBJQFog0N4EJgpiEA)! ]
[Question] [ # The system Assume [the Earth is flat](https://xkcd.com/1318/) and that it extends infinitely in all directions. Now assume we have one infinitely long train railway and `n` trains in that railway. *All* trains have different speeds and *all* trains are going in the same direction. When a faster train reaches a slower train, the two trains connect (becoming a single train) and the new train keeps going at the speed with which the slower train was going. E.g., if we have two trains, one going at speed 1 and another at speed 9, the lines below "simulate" what would happen on the railway: ``` 9 1 9 1 11 11 11 ``` whereas if the trains start in a different order, we'd have ``` 1 9 1 9 1 9 1 9 etc... ``` With that being said, given a train/position/speed configuration there comes a time when no more connections will be made and the number of trains on the railway stays constant. # Task Given the number `n` of trains in the railway, your task is to compute the *total* number of trains there will be on the railway, after all the connections have been made, summing over all `n!` possible arrangements of the `n` trains. A possible algorithm would be: * Start counter at 0 * Go over all possible permutations of the train speeds + Simulate all the connections for this permutation + Add the total number of remaining trains to the counter * Return the counter **Note** that you can assume the train speeds are whatever `n` distinct numbers that you see fit, what really matters is the relationships between train speeds, not the magnitudes of the differences in speeds. # Input You must take `n`, a positive integer, as input. # Output An integer representing the total number of trains that there will be on the railway, summed over all possible permutations of the trains. # Test cases ``` 1 -> 1 2 -> 3 3 -> 11 4 -> 50 5 -> 274 6 -> 1764 7 -> 13068 8 -> 109584 9 -> 1026576 10 -> 10628640 11 -> 120543840 12 -> 1486442880 13 -> 19802759040 14 -> 283465647360 15 -> 4339163001600 16 -> 70734282393600 17 -> 1223405590579200 18 -> 22376988058521600 19 -> 431565146817638400 20 -> 8752948036761600000 ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` !:RS ``` **[Try it online!](https://tio.run/##y0rNyan8/1/RKij4////pgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/1/RKij4f9DRPYfbHzWtcf//38gAAA "Jelly – Try It Online"). ### How? When we introduce an \$n^{\text{th}}\$ train it allows: * \$(n-1)!\$ states - by being placed behind none of the \$n-1\$ existing trains and being faster than all of them. * all the previous end states, each in \$n\$ different ways - by being placed behind at least one existing train and being faster than \$[0,n-1]\$ of the \$n-1\$ existing trains We know \$a(1) = 1\$ so... ``` n a(n) 1 1 2 1! + 1*2 3 2! + 1!*3 + 1*2*3 4 3! + 2!*4 + 1!*3*4 + 1*2*3*4 5 4! + 3!*5 + 2!*4*5 + 1!*3*4*5 + 1*2*3*4*5 ... etc ``` Which is: ``` n a(n) 1 1 2 1 + 2 3 1*2 + 1* 3 + 2*3 4 1*2*3 + 1*2* 4 + 1* 3*4 + 2*3*4 5 1*2*3*4 + 1*2*3* 5 + 1*2* 4*5 + 1* 3*4*5 + 2*3*4*5 ... n n!/n + n!/(n-1) + n!/(n-2) + ... + n!/1 ``` Hence the code: ``` !:RS - integer, n ! - (n) factorial n! R - range (n) [1,...,n-2,n-1,n] : - integer division [n!/1,...,n!/(n-2),n!/(n-1),n!/n] S - sum a(n) ``` [Answer] # JavaScript (ES6), 34 bytes ``` f=n=>n>1?(n+--n)*f(n)-n*n*f(n-1):n ``` [Try it online!](https://tio.run/##FcZNCoMwEAbQq8wyozNC6k9V0B5EXAQ1YtEvoqXXT@lbvbf7unu6tvOjCPMSo@/Q9ejtyyBVBSfegBUJ/lHLLeIUcId9yfawmsEKPYRyoUKoFKqEnkK1UDNmhzuNZ44/ "JavaScript (Node.js) – Try It Online") This is an implementation of the recurrence relation: $$\cases{ a(0)=0\\ a(1)=1\\ a(n) = a(n-1) \times (2n - 1) - a(n-2) \times (n - 1)^2,\:n>1}$$ [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 5 bytes ``` +/!÷⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBG19xcPbH/VuBvIOrVAAMhSMDAA "APL (Dyalog Classic) – Try It Online") Calculates the sum of (`+/`) the factorial of \$n\$ (`!`) divided by (`÷`) the range 1 to \$n\$ (`⍳`). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` !IL÷O ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f0dPn8Hb///9NAA "05AB1E – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 57 bytes ``` f=lambda n:n and n*f(n-1)+math.factorial(n-1) import math ``` [Try it online!](https://tio.run/##RVLLahwxELzrKzo67Sb2ovfDYEMOySfkFAiKZ8Yr0GqGkdYQwn77Ri0RPBd1VbWqS81sf@p5zfJ@X55TuPyeAuSnDCFPkD8vh/zIj18uoZ5PS3it6x5D6hyJl23dK6B0r3Opv15DmQs8A6WUw@MLcCLwkER2xInCUzOi8RRWEdMFaxSxvZLMOOJ6ybx2ivhRC6OtIZwNZIQzihE@hgimlXSI@zSumqiEc40Yc71jwmrPsKUnEE4qo42y0jSqh1FSem4kY9ywxvVcllnZjIT0spMjohBSMd3stPUC6R63sdb4NlQ7LYaHH75cG82Vce2VmJIR0V/hrBZeOSaNNdjfvrY2QpZ1B1wmxAwfSz2VLcV6oD8zPT4RgPwA67W2VWPLfxFt6RHVJsRcDxnBMhqXgeIyiE@jo5XdD2APsczwI6Tr/G3f1/2w0O8hpnkaaTAF/M23Byjn9ZomeIvvjWj3b/1HeQsI0frWIsypzGi77TiEfk3pw6XAFkqZpxM93v8B "Python 3 – Try It Online") Implements the recurrence relation given by $$\begin{cases}a(n) = n\times a(n-1) + (n-1)! \\ a(0) = 0 \end{cases}$$ **How**: If you have \$n\$ trains on the railway, consider removing the faster one from the railway and take the \$(n-1)!\$ permutations of the remaining \$n-1\$ trains. For each permutation of the \$n-1\$ trains, there are \$n\$ places where you can put the \$n\$th train, the fastest one. * If you put it in the front, then the connections made by the other \$n-1\$ trains remain exactly the same, and those never catch up with the faster train. So placing it in the front adds a new train to the total sum. * If you put it in any other of the \$n - 1\$ positions, it will just connect to the train in front and then we are back at the case when we had \$n - 1\$ trains on the railway, so the total number of trains stays the same. [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~50~~ 49 bytes -1 thanks to Surculose Sputum (using walrus in 3.8 to save some `~-`s) ``` f=lambda n:n>1and(2*n-1)*f(n:=n-1)-n*n*f(n-1)or n ``` **[Try it online!](https://tio.run/##HYuxCsMwEEP3fsVt8ZmkYHcpB8m/uCRuA41i3FtKyLe7djVITyClr7523O4plxLHd9gecyAIJhcwG28xOLbRQMZGAyxaq7hnQonVdfkoraAc8FyM68k7lgtVpbxCTXfI5E@h4@yudb8FNe3SU/wnM5cf "Python – Try It Online")** --- A **52** using a different approach: ``` f=lambda n,k=2:n*k and~-n*f(n-1,k)+f(n-1,k-1)or n==k ``` [Try it online!](https://tio.run/##LYtBDsIgFET3nuLvyq9gAksSvAumRRvstMG/aZp6dUTj28xbzFs3eSxwtabwjPNtiASdg/PoM0UMb4M@KRirM5//YiwvhRBCrqmJjC@hCVQi7qOympxlf6LGWiaI6nZ/dYen/egu7T9HUd9EU/otM9cP "Python – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes ``` Tr[#!/Range@#]& ``` *-1 byte from @Greg Martin* [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6QoWllRPygxLz3VQTlW7X9AUWZeiYK@Q7q@A0TQyOD/fwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` ≔…·¹NθIΣ÷Πθθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DMy85p7Q4syw1KDEvPVXDUEfBM6@gtMSvNDcptUhDU1NHoVDTmiugKDOvRMM5sbhEI7g0F6ipxCWzLDMlVSOgKD@lNLlEoxCsEAis//@3/K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔…·¹Nθ ``` Create a range from `1` to `n`. ``` θ Range `1`..`n` Π Product i.e. `n!` ÷ Vectorised divide by θ Range `1`..`n` Σ Sum I Cast to string Implicitly print ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~57~~ ~~52~~ 50 bytes *-2 bytes thanks to @JonathanAllan !* ``` i=x=0 f=1 exec"i+=1;x=i*x+f;f*=i;"*input() print x ``` [Try it online!](https://tio.run/##LY7NDoMgEITvPMWGXvCnSfGo2b4LVdBN2sUQjPTpqWLn@GW@zKzfuHju8ugni1LKTJjwIRxqYZMdJTWoh4RUp8YNrkYaZE28blFVYg3EEVI@NOF8AAZiCIZnq3QLna56AUduEGiGvwTRQ7BxCwxxsReF3cJuOJZ2Ifg2n9dkeuDCriFu5f0p20LOb@r8XOUf "Python 2 – Try It Online") --- **If the sequence is 0-indexed, we can cut down 2 more bytes** ## [Python 2](https://docs.python.org/2/), 48 bytes ``` i=x=f=1 exec"i+=1;x=i*x+f;f*=i;"*input() print x ``` [Try it online!](https://tio.run/##LY5LDoMwDET3OYWVbvh1AUuQuUsKCVhqHRQZkZ4@hdBZPs3TzPaV1XOXJj9b1FonwogOW2WjnTTV2A4RqYq1G1yFNOiKeNulKNUWiAViOiXlfAAGYgiGF1t0bdkrOPOAQAv8DRAPwcoeGGS1N4XDwmFYcjsTfJvPazY9cGb3Cjf6Oeomk@tYcd0t0w8 "Python 2 – Try It Online") --- **How:** This solution uses the `exec` trick, which repeats the code `n` times, then `exec` the repeated code. `f` is the current factorial. `x` (the solution function) is defined by the recurrent relation: $$x(i)=ix(i-1)+(i-1)!$$ and $$x(0)=0$$ [@RGS's answer](https://codegolf.stackexchange.com/a/201085/92237) has a really nice explanation for this formula. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 22 bytes ``` {sum [*]($_)X/$_}o^*+1 ``` [Try it online!](https://tio.run/##JU/LSkNRDNznK86iiFa85p0cRL9DEC0u7Kql0uKiiN9@PY9skpmEmcn31/ng6/Fabvbluay/l59jedu@3252d6@Pm93f6WN7T@sTXD6vZWk3@9O50LIwrlQeXgoB9yYgAxFo74ZgvXMo@FiEK8SYBD0hx4jVUqHOmd3CgXAi53RFoGnCaCrZ8XAjbUvlzEZM35rIYRX7yUjAKermGuKNGmFUpJILIjk2buQKDGlCLFUGOSMyi6I1OYvKnR5xGxtem6ml8dSoU5fMjdSzfdlTIvD4IsO4aqJ4eL9v9Q8 "Perl 6 – Try It Online") Returns the sum of the factorial of \$n\$ divided by the range 1 to \$n\$. [Answer] # [W](https://github.com/A-ee/w) `j`, ~~5~~ 4 [bytes](https://github.com/A-ee/w/wiki/Code-Page) After scanning through the source, I realized an undocumented feature - the `j` flag can actually sum the output at the end! ``` 7Uëÿ ``` Uncompressed: ``` *rak/ ``` ## Explanation ``` *r % Reduce via multiplication % (Contains implicit range) ak % Range from input to 1 / % Division (integer division when % none of the operands are floating-points) Flag:j % Sum the resulting list ``` [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` a 0=0 a n=n*a(n-1)+product[1..n-1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1HBwNaAK1EhzzZPK1EjT9dQU7ugKD@lNLkk2lBPD8iP/Z@bmJlnW1CUmVeikqhg@h8A "Haskell – Try It Online") This implements the [OEIS definition](https://oeis.org/A000254). [Answer] # [C (gcc)](https://gcc.gnu.org/), 38 bytes ``` f(n){n=n>1?(n+n--)*f(n)-n*n*f(n-1):n;} ``` Port of Jonathan Allan's Python 3.8 answer. [Try it online!](https://tio.run/##HYqxDsIwDET3fIVVCclu8BBGQuFHWFCqIA9cUYVYqn57cLjlPd1d0WcprVWGbJhwTTdGhKqMvVKM6KJJzsh7M3zo9TDwd7FZwhbIU5eV@2A0UcqOi/PkEqP8Dz3v1S@Vh8N8x3CkyiaSw95@ "C (gcc) – Try It Online") [Answer] # [J](http://jsoftware.com/), 9 bytes ``` 1#.!%1+i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1FFUNtTP1/mtyKXClJmfkK2hYp2kqqNkpGCpoK2TqWUAEDQ2sFdKAZAWUawrmmkK5RmBZI4OK/wA "J – Try It Online") ``` 1#. the sum of (by conversion to base 1) ! n factorial % divided by 1+i. the list 1..n ``` # [K (oK)](https://github.com/JohnEarnest/ok), ~~16~~ 12 bytes -4 bytes thanks to ngn! ``` +/*/'1+&:'~= ``` [Try it online!](https://tio.run/##y9bNz/7/P81KW19LX91QW81Kvc72f5qC6X8A "K (oK) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Œ!«\€Q€FL ``` [Try it online!](https://tio.run/##y0rNyan8///oJMVDq2MeNa0JBGI3n////1sAAA "Jelly – Try It Online") this is the non-smart trivial approach # Explanation Observe that if we have a list of trains' speeds, moving left, then we can cumulatively reduce by minimum to get the final list of trains' speeds. ``` Œ!«\€Q€FL Main Link Œ! all permutations (defaults over a range) € For each permutation \ Cumulatively reduce by « minimum € For each permutation Q remove duplicate values F join all of the trains (flatten) L and get the final length ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÆÊ/°X ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=xsovsFg&input=MjA) [Answer] # [Racket](https://racket-lang.org/), 70 bytes ``` (λ(x)(let([a(range 1(+ 1 x))])(apply +(map(λ(y)(/(apply * a)y))a)))) ``` [Try it online!](https://tio.run/##NcwxDsIwFAPQvaewxGLTAYXrIIYvSFDVUEWhQ3M27sCVQoKoN1tPznab/VoP0ZYH8q8MvPswLR6h8vPmJka/8mLMzXg4jnDYpKtoKcWCkU9LnRbx9N@OMBXJ1FI1tM/plaIVdIuA/Qxn18UX "Racket – Try It Online") [Answer] # [Factor](https://factorcode.org/), 61 bytes ``` : f ( n -- n ) [1,b] dup [ product ] dip [ / ] with map sum ; ``` [Try it online!](https://tio.run/##LY27DsIwFEN3vsIjSKQ8xnQHdemCmKIOoU0hor0NyY0QXx9CxGIdy7I96p4Xn66Xpj1LPI0nM2HW/ChSeU13ExDMKxrqMzlvmD/OW2LUq6aVOJUFqyfBXltKEiPWIAiRZQN12N46DNFB5fIyxJ6Rvf35Xaa3LV8OIc6o03H/b6g805WgSl8 "Factor – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~70~~ \$\cdots\$ ~~64~~ 63 bytes Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Saved a byte thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!! ``` l;c;i;t;f(n){l=0;for(c=i=1;i<n;l=c,c=t)t=-l*i*i+c*(i+++i);n=c;} ``` [Try it online!](https://tio.run/##FY5LCoNAEET3nqIRhPmJMxo/oZ2cJJvQYmgwnSDuxLObcVOPWryiqHwTneeChIwbzkr0vkSP83dVFDkG5FFwieQobnqL5WLYsCWj2FrLGiUSHufnxaL0nl0aywaSRBlDQGtFQ2UgOGgchITWO6j7Wyp9d2XjuyHB39vhqr7u2r4DU2W/NS3NKi8mKB9QTE/JHYiD66PG7Dj/ "C (gcc) – Try It Online") Uses [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [formula](https://codegolf.stackexchange.com/a/201081/9481). [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ╒k!╠Σ ``` [Try it online.](https://tio.run/##BcFLDYAwFEXB/XGBg96W/uSwARIgbFBC0j0JfhBRI4@ZY7rW5dxns97ubejt@V4z4QmMRBKZQkUOCXkU0IgiSiijgire/Q) Or ``` !k╒/Σ ``` [Try it online.](https://tio.run/##BcFLDYAwFEXB/XGBAnr7rxw2lAQIG5SQoAA/iMDIY2afzqUf22w2rN99je9jJjyBSCJTqDTkkJBHAUWUUEYFVdTw7gc) **Explanation:** ``` ╒ # Push a list in the range [1, (implicit) input-integer] k! # Push the input-integer again, and pop and push its factorial ╠ # Divide the factorial by each value in the list (b/a builtin) Σ # And sum that list # (after which the entire stack joined together is output implicitly as result) ! # Push the factorial of the (implicit) input-integer k╒ # Push the input-integer again, and pop and push a list in the range [1, input] / # Divide the factorial by each value in the list Σ # And sum that list # (after which the entire stack joined together is output implicitly as result) ``` ]
[Question] [ Let \$A\$ be a positive integer consisting of \$n\$ decimal digits \$d\_1,d\_2,...,d\_n\$. Let \$B\$ be another positive integer. For the purpose of this challenge, we call \$A\$ a **copycat** of \$B\$ if there exists at least one list of positive integers \$p\_1,p\_2,...,p\_n\$ such that: $$\sum\_{i=1}^{n}{{d\_i}^{p\_i}}=B$$ \$A\$ and \$B\$ are called **reciprocal copycats** if \$A\$ is a copycat of \$B\$ and \$B\$ is a copycat of \$A\$. ## Example \$526\$ and \$853\$ are reciprocal copycats because: $$5^3 + 2^9 + 6^3 = 853$$ and: $$8^3 + 5^1 + 3^2 = 526$$ ## The challenge Given two positive integers \$A\$ and \$B\$, your task is to print or return a truthy value if \$A\$ and \$B\$ are reciprocal copycats or a falsy value otherwise. ## Clarifications and rules * You may take \$A\$ and \$B\$ in any reasonable, unambiguous format (e.g. integers, strings, lists of digits, ...) * \$A\$ and \$B\$ may be equal. If a number is a reciprocal copycat of itself, it belongs to [A007532](https://oeis.org/A007532). * Instead of truthy/falsy values, you may return two distinct **consistent** values. * For \$1\le A<1000\$ and \$1\le B<1000\$, your code must complete in **less than one minute**. If it's taking too much time for higher values, it must however be able to solve them in theory. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). ## Test cases ``` Truthy: 1 1 12 33 22 64 8 512 23 737 89 89 222 592 526 853 946 961 7 2401 24 4224 3263 9734 86 79424 68995 59227 32028 695345 Falsy: 1 2 3 27 9 24 24 42 33 715 33 732 222 542 935 994 17 2401 8245 4153 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes ``` ẹ{∧ℕ₁;?↔^}ᵐ².+ᵐ↔?∧≜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GundWPOpY/apn6qKnR2v5R25S42odbJxzapKcNpIBce5Bs55z//6MtzHTMLU2MTGL/AwA "Brachylog – Try It Online") Outputs `true.` or `false.` ### Explanation ``` ẹ Split the numbers into lists of digits { }ᵐ² For each digit ∧ℕ₁ Let I be a strictly positive integer ;?↔^ Compute the digit to the power I (which is unknown currently) . Call . the list of those new numbers .+ᵐ Their mapped sum results… ↔? …in the reverse of the input ∧≜ Find if there effectively are values for the numbers in . to satisfy these relationships ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 17 bytes ``` Λλ€⁰mΣΠTṪ^ḣ√⁰d)De ``` [Try it online!](https://tio.run/##JYsxCgIxEEX7OcUv3TIzSTbTiyewtlIQJI0i1ruVZ9BG2E4srESx8wC5w@YiMWj1@e/x1vvdpsTJLPdd3B6az6Okc3rn/pa7e0xDuszH13UxPod8PFW0bKarUoqBIcMQIWZ4SwHOMLGglZaCImgVDKdMjj2CE1Lrob5mYBJwSwq2xBa2/hoa9xvhf1mpioOq/QI "Husk – Try It Online") Finishes all test cases under 1000 in about 11 seconds. ## Explanation ``` Λλ€⁰mΣΠTṪ^ḣ√⁰d)De Implicit inputs, say 12 and 33. e Put into a list: [12,33] D Duplicate: [12,33,12,33] Λ Does this hold for all adjacent pairs: (12,33 is checked twice but it doesn't matter) For example, arguments are 33 and 12. λ ) Anonymous function with arguments 33 (explicit) and 12 (implicit). d Base-10 digits of implicit argument: [1,2] ḣ√⁰ Range to square root of explicit argument: [1,2,3,4] Ṫ^ Outer product with power: [[1,2],[1,4],[1,8],[1,16],[1,32]] T Transpose: [[1,1,1,1,1],[2,4,8,16,32]] Π Cartesian product: [[1,2],[1,4],...,[1,32]] mΣ Map sum: [3,5,...,33] €⁰ Is the explicit argument in this list? Yes. ``` ## Why it works If we have \$B = d\_1^{p\_1} + \cdots + d\_n^{p\_n}\$ where the \$d\_i\$ are digits and \$p\_i\$ are positive integers, then \$d\_i^{p\_i} \leq B\$ for all \$i\$, or equivalently \$p\_i \leq \log\_{d\_i} B\$. We can ignore the case \$d\_i \leq 1\$, since exponentiating \$0\$ or \$1\$ does not change it. In my program the search space is \$1 \leq p\_i \leq \sqrt{B}\$ (to comply with the time restriction; I would use \$1 \leq p\_i \leq B\$ otherwise), so if we have \$\lfloor \log\_{d\_i} B \rfloor \leq \lfloor \sqrt{B} \rfloor\$, then everything is fine. If \$d\_i \geq 3\$, this holds for all natural numbers \$B\$, so the only dangerous case is \$d\_i = 2\$. We have \$\lfloor \log\_2 B \rfloor > \lfloor \sqrt{B} \rfloor\$ only for \$B = 8\$. In this case \$2^3 = 8\$, but the search only considers exponents \$1\$ and \$2\$. If the other number number \$A\$ contains the digit \$2\$, either it has other nonzero digits as well (so the exponent of \$2\$ cannot be \$3\$ in the sum), or \$A = 2 \cdot 10^k\$ for some \$k\$. In the latter case, \$A\$ is not a power of \$8\$, so it cannot be a copycat of \$B\$ anyway, and the program correctly returns a falsy value regardless of the other computation. [Answer] # [Python 2](https://docs.python.org/2/), 102 bytes ``` lambda a,b:g(a,b)*g(b,a) g=lambda a,b,e=1:b==a<1or(b>0<=b-e>=0<a)and(g(a/10,b-(a%10)**e)or g(a,b,e+1)) ``` [Try it online!](https://tio.run/##XU/LbsMgELz7K7hUApe0sBg7RCZf0gs0xLUUP4TdQ77e3bRSvQrSIs3s7OzsfF@/phG2fpinvLLlvhRYb0tac/r8zks/jbd@6FduFT5RXP3HdgtDvAQWZDx1HH9RdjzKIIrO7y2ZvD5F70Orp8zjWbU@HtLZqzaIMF44Tr5rJeOBhxetRFkmMWX26yfTqxZim3M/ruzKtWRaFP8IJDNmx4C4rnZ8lMxqIH0jWWMaInCSHR01QAfryIiFGiWWLHEVMq4mMRrJoFKEgEqyCoAkMVDjbtcY5P7IgpxE9qEKSED3sH42JurHQdo@EQaeL6IzzlhM4tB1@wE "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εVтLIàgãεYSym}OIyKå}˜P ``` Takes the input as a list (i.e. `[526,853]`). [Try it online](https://tio.run/##ATAAz/9vc2FiaWX//861VtGCTEnDoGfDo861WVN5bX1PSXlLw6V9y5xQ//9bNTI2LDg1M10) or [verify most test cases in the range `[1,999]`](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVL6P9zW8MuNvlEHF6Qfnjxua2RwZW5tf4Rld6Hl9aenhPwX@d/dLShjmGsTrShkY6xMZA2MtIxMwHSFjqmhkYgvrGOubE5SMBSx8ISrMBIx9QSJGVqZKZjYQrSZGlipmNpBjRGAWgaSMpYxwikx1LHCGSWkYmOCVgUaJahKZRhbAQzDCxnaWyqY2lpEhsLAA). Similar as my old answer below, except that the `[1,n]` list is hardcoded to `[1,100]`, and it creates the cartesian list twice, once for each input-mapping, which is the main bottleneck in terms of performance. --- **Old 26 bytes answer that's better for performance:** ``` Z©bgL®gãUεVXεYSym}OsN>èå}P ``` In this version I traded in some bytes to make the performance a lot better so it can run `[1,1000]` with ease. Test cases containing numbers in the range `[1,9999]` are done in about a second on TIO. Test cases in the range `[10000,99999]` in about 10-15 seconds on TIO. Above that it will timeout. [Try it online](https://tio.run/##ATQAy/9vc2FiaWX//1rCqWJnTMKuZ8OjVc61VljOtVlTeW19T3NOPsOow6V9UP//WzUyNiw4NTNd) or [verify all test cases with numbers in the range `[1,9999]`](https://tio.run/##NU69agJhEHyVw3qKfLvfz22jjWVIAiFBc1zhgRwWkkIQrrD1AfIKIaBNUgnWd6VwD5EXOb/90GpnZ2Zn9nOzqFbLYdtMRtn//isbTZrpZT98tMeqfmx/6@77rT@9z/rT/LVZ757bv/78NO4O3c/uZcBQFAamRGEIzHESwds4czhDujMCByUEuSQDwYlKjjxyp0diPcRrTADZBwVkYYk0ickzJHDEWSzTSwZppCAZklXZWGXcDTDdu5Im7CCSHiPrYE3sLa8). **Explanation:** ``` Z # Push the max of the (implicit) input-list (without popping) # i.e. [526,853] → 853 © # Store it in the register (without popping) b # Convert to binary # i.e. 853 → 1101010101 g # Take its length # i.e. 1101010101 → 10 L # Pop and push a list [1, n] # i.e. 10 → [1,2,3,4,5,6,7,8,9,10] ® # Push the max from the register g # Take its length # i.e. 853 → 3 ã # Cartesian product the list that many times # i.e. [1,2,3,4,5,6,7,8,9,10] and 3 # → [[1,1,1],[1,1,2],[1,1,3],...,[10,10,8],[10,10,9],[10,10,10]] U # Pop and store it in variable `X` ε } # Map both values of the input list: V # Store the current value in variable `Y` Xε } # Map `y` over the numbers of variable `X` Y # Push variable `Y` S # Convert it to a list of digits # i.e. 526 → [5,2,6] ym # Take each digit to the power of the current cartesian product sublist # i.e. [5,2,6] and [3,9,3] → [125,512,216] O # Take the sum of each inner list # i.e. [[5,2,6],[5,2,36],[5,2,216],...,[125,512,216],...] # → [13,43,223,...,853,...] s # Swap to push the (implicit) input N> # Push the index + 1 # i.e. 0 → 1 è # Index into the input-list (with automatic wraparound) # i.e. [526,853] and 1 → 853 å # Check if it's in the list of sums # i.e. [13,43,223,...,853,...] and 853 → 1 P # Check if it's truthy for both both (and output implicitly) # i.e. [1,1] → 1 ``` [Answer] # [Haskell](https://www.haskell.org/), 77 bytes ``` a#b=a!b&&b!a a!b|a<1=b==0|b<1=b>1|1<2=or[div a 10!(b-mod a 10^e)|e<-[1..b+1]] ``` [Try it online!](https://tio.run/##PYxbasMwEEX/u4oxKUGiisno4URgdQdZgXGKlBhqGjvBbQoF792dESR/Z@6dez7j91d3uSxLXKUQi7RepyK@EMyxxpBC2M6J4R1nrHW4Ts25/4UIuC1E2gzXc@ZjJ@eu3jRYlukN23YZYj9CgCHeDh9wm/rxB0q@QNzH032a/kCspIRXaAQqQKkEagXGEGiCyhLsFTjUnBgFO7PjyCvY@/xEX85z63RFoeOpt4S@yjoFXNJS85B2mp3aKrC5YCe6Bxn9lObaG0cmb2W7/AM "Haskell – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~87 84~~ 69 bytes *-15 bytes thanks to nwellnhof!* ``` {!grep {!grep $^b,[X+] 0,|map (*X**1..$b.msb+1),$^a.comb},.[0,1,1,0]} ``` [Try it online!](https://tio.run/##LY3BaoNQEEX38xW3IEWjGN/Me0@n0G2/oItAkoK22ga0CdouQuq3p6@mzOLCOcy9p3bs/XU44757vF7u3sf2hP@IXppsu0n3KLKfoT4hXm1WK5PnUZMPU5OaJIte6vz1ODRzlm@LzIQr9vO1O46I@8NnOyW4EHDoMKzj3Vua7KYl1gsGpvqMLo7TqMjSyCRJgDPafmpxyYObab4@j99fH@cHMjBkGCLEDG@pgjNMLCilpEpRaRAMp0yOPSonpNZDvaESbAtDbGGZLQl7gZYSOjxKtQH5StX9/XIZdMEVvDqxjuip7qdlnUkQrIauWxNJ2DZuCeHbeKAqDqqhm62DNU5@AQ "Perl 6 – Try It Online") Anonymous code block that returns True or False. ### Explanation: ``` {!grep {!grep $^b,[X+] 0,|map (*X**1..$b.msb+1),$^a.comb},.[0,1,1,0]} { } # Anonymous code block !grep # None of: .[0,1,1,0] # The input and the input reverse {!grep # None of [X+] # All possible sums of 0,| # 0 (this is to prevent single digit numbers being crossed with themself) map ,$^a.comb # Each digit mapped to (*X** ) # The power of 1..$b.msb+1 # All of 1 to the most significant bit of b plus 1 # This could just be b+1, but time constraints... $^b, # Is equal to b ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~116~~ ~~92~~ ~~89~~ ~~86~~ ~~83~~ 77 bytes ``` a=>b=>(G=(c,g,f=h=g%10)=>g?c>f&f>1&&G(c,g,h*f)||G(c-f,g/10|0):!c)(a,b)&G(b,a) ``` [Try it online!](https://tio.run/##JY3LTsMwEEX38xVDVCob0hCPH4lBDivU37Ab4rQoaqK26qKPbw@GrmZ078w5P@Ecju1hN51W@/G7m6Obg2s2rmFrx9q8z6Pbuv5ZlNw1/WfbxGVsxHK5/u@2L5Hfbmlfxbx/E@Wt5O9PLWch3/B0sskDnz@8QAGCUEogQqOgRi0ISGIlK6gt1jYVhNoSaDJYawlWGbRGQIWkSgGkUBEpkGQk2komhsHKqhSZ2lr990tVqkuq0VgtlQaBBBJTahPjQQCZnEL/D0kPaUqt1GhtYpLSqETSi4fXF8dp2J08@CKOh6/QbtkFXYPtuD@OQ1cMY8/Y5Hxki@ulOHTTENqOZZjlGWcZv3PPXz06XFy7cxjYxO@e8/kX "JavaScript (Node.js) – Try It Online") Expect input as `(A)(B)`. [Answer] # [J](http://jsoftware.com/), 56 bytes ``` h~*h=.4 :'x e.+/|:>,{x 4 :''<y&*^:(x&>)^:a:y''"+"."+":y' ``` [Try it online!](https://tio.run/##dZBPS8NAEMXv@RSPHLL2j9vs7L/MansRPHnyA7QEbQgiFGqFFMWvHmdTD714mGXmMfPej30bS606rBMUlqiRpG41Hp6fHsf@Z96vtUNSA/Z6sfpOm@XXgCyo@3M136abodrMtqlNZ6XKRamlpB1nxWRUFLOiOB129Noej@05h9RVqe/0jorT8fPUT9LVwuXKwBCI0AAgCzQsE8FTALuAiKw7eSwFiybkOTTMXoSaGrm3FsHBi020Md97FjtvwcHIaW3gSBw4WofITlpZoIjA3jov1F37/vEfnBDxBCApU2U4th4mkzUkBoIf84YTAOMFQuilZ3Z/6cZbSdm/9Ad0Zb3C5TeuhAlg/AU "J – Try It Online") Yay, nested explicit definition! ### How it works ``` powers =. 4 :'<y&*^:(x&>)^:a:y' Explicit aux verb. x = target, y = digit y Starting from y, y&*^: ^:a: collect all results of multiplying y (x&>) until the result is at least x < Box it. h=.4 :'x e.+/|:>,{x powers"+"."+":y' Explicit aux verb. x, y = two input numbers "."+":y Digits of y x powers"+ Collect powers of digits of y under x { Cartesian product of each item +/|:>, Format correctly and compute the sums x e. Does x appear in the list of sums? h~*h Tacit main verb. x, y = two input numbers Since h tests the condition in only one direction, test again the other way around (~) and take the AND. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~149~~ ~~147~~ ~~143~~ ~~139~~ ~~132~~ ~~118~~ ~~108~~ ~~107~~ ~~106~~ 105 bytes ``` lambda a,b:g(a,b)*g(b,a) g=lambda a,b:any(g(a/10,b-(a%10)**-~i)for i in(a*b>0)*range(len(bin(b))))or b==0 ``` [Try it online!](https://tio.run/##XVBNa8MwDL3nV@gysIPLbPkrGmS/ZBebNVmgdUvopZf99UwdYxXxwaCn96Snd73fvi4Nt2n82E7lXD8LFFPfZsW/7mdVTdHdPIpWaXfF7VdnTT2o8uKs7vvD96KnywoLLE2Vvr4zuJY2H9Xp2FRlsGp@zKjjaLfrurQbTMoZcLr7r9CA988auU7hWQ8GokPR9wayz4JABgaSA3hCJCGJmJgSxRIKjFASNrIBDFYAGAwEROHEY@LdlL10x3MyBUlLA1H8dYBZii3yKYmiD/EP7kQiwi4vkUp6ONv7EuxHHi7uAI/7QKSGPBskkndgYCg4Dmn7AQ "Python 2 – Try It Online") -4 bytes, thanks to Vedant Kandoi [Answer] # J, 68 bytes I thought J would perform quite well here, but it ended up being tougher than I expected and would love any suggestions for further golfing... ``` g=.#@#:@[ 1 1-:[:(([:+./[=1#.]^"#.1+g#.inv[:i.g^#@])"."0@":)/"1],:|. ``` [Try it online!](https://tio.run/##TU/bSsNAEH3PVxx2X1pqt9mZvWQWAvmPmIqISStSQasg@O9xkj4oc2PmzJw9@zLPU@tsZ0vXV2PrPPy@9GWz6cvOHfrWWzccjXV@N1l3vnz15eymo@2GrXGm7kzZHowf7sqPm6/vn9fTd@vwQBju4RcjMIMIKaBB1JYYmTMaWZwUiaJBCU1kSEiQ5JFBofaaEEgTU1Iss3IkZAk6So1IXG4pK1xTgySRQ6zGx9eP/xpUAHRHFrKVbxGUfVwL002CToUjRPQFChHBR66q56fTG0bjsXL@tbd/zr8 "J – Try It Online") *NOTE: we subtract 3 chars from the TIO count there since `f=.` on the main function doesn't count* ## ungolfed ``` 1 1 -: [: (([: +./ [ = 1 #. ] ^"#. 1 + g #.inv [: i. g ^ #@]) "."0@":)/"1 ] ,: |. ``` ]
[Question] [ [Palindromic dates](http://www.timeanddate.com/date/special-dates.html) are dates that appear as palindromes: the string of digits can be read the same way backwards as forwards. For the North American date format (MM/DD/YYYY), the next few palindromic dates are: `02/02/2020` `12/02/2021` `03/02/2030` ### The Challenge Create a function that returns all palindromic dates in a consistent, common date format (of your choosing) that fall within a range of dates (*edit: including the range itself*). ### Rules * To qualify as a palindrome, only the numeric characters of the date should be checked. * The date can be in any common format (`MM/DD/YYYY`, `DD-MM-YYYY`), as long as it uses two digits for both the month and day and four for the year, and it uses a character to separate parts of the date. The output must preserve seperating characters (`/`, `-`, etc.). Your function only needs to handle one distinct date format. Please include the format in your answer. * If there are more than one dates returned, they should be comma or new-line separated. * Shortest answer wins! ### Example ``` date_palindrome('05/02/2050', '12/12/2060') >>>['05/02/2050', '06/02/2060'] ``` [Answer] # MATL, ~~24~~ 23 bytes ``` YOZ}&:"@23XOtt47>)tP=?8M ``` Accepts input in the form of an array of string `{lower, upper}` where the date format is `'MM/DD/YYYY'`. Output is in the format `MM/DD/YYYY` as well. [**Try it Online**](http://matl.tryitonline.net/#code=WU9afSY6IkAyM1hPdDQ3Pil0UD0_OE0&input=eycwMS8wMi8yMDIwJywnMTIvMTIvMjAyMSd9Cg) **Explanation** ``` % Implicitly grab the two inputs YO % Convert to serial date format Z} % Push them onto the stack separately &: % Create an array from [lower...upper] incrementing 1 day " % For each day @23XO % Get the string version of the date (mm/dd/yyyy) tt % Duplicate twice 47>) % Get the numeric parts tP= % Compare numeric part with the flipped version of the numeric part ?8M % If they are the same push it to the stack % Implicitly display stack contents ``` [Answer] # Bash + GNU utilities, 116 84 Requires 64-bit version of date for the given testcase. ``` set date -uf- +% jot -w@ - `$@s` 86400|$@F|sed -r 'h : s/-|^(.)(.*)\1$/\2/ t /./d g' ``` I/O is in `YYYY-MM-DD` format. Input is taken from two lines of stdin, e.g. ``` printf "%s\n" 2050-05-02 2060-12-12 | ./palindate.sh ``` ### Explanation * `set` saves the date command template so it may be accessed using the `$@` parameter * `date -uf- +%s` converts endpoint dates to number of seconds since the Unix epoch * `jot` interpolates this to give a list of seconds-from-the-epoch, one per day, each prefixed with `@` * `date -uf- +%F` formats each list entry as `YYYY-MM-DD` * `sed` checks for palindromes: + `h` save the input line to the hold buffer + `:` define "unnamed" label + `s/-|^(.)(.*)\1$/\2/` if a dash is found, remove it or if the first and last characters match, remove them + `t` if there was a match above, jump back to the unnamed label + `/./d` if there are any characters left over, the line is not a palindrome - delete it and continue to the next line + `g` if we got here, then no line deletion happened, thus the line must have been a palindrome. Get the line back from the hold buffer and implicitly display it. [Answer] # Python 2, 197 bytes One byte saved thanks to @cat! ``` from datetime import* def g(a,b): for s in"ab":exec"%s=date(*[int(x)for x in %s.split('-')])"%(s,s) for d in range((b-a).days+1): x=str(a+timedelta(d));y=x.replace("-","") if y==y[::-1]:print x ``` [Try it here!](https://repl.it/C5Z9/2) Input and output format is `YYYY-MM-DD`. First intendation level is spaces, second one is tabs. Nothing too special going on here. Uses some `exec` abuse to convert the input to `date` objects by splitting the date string on `-` and splatting the list into the `date` constructor. Then we just iterate over all dates in their inclusive range and print the ones which are palindromic. [Answer] ## PowerShell v2+, 127 bytes ``` for($a,$b=[datetime[]]$args;$a-le$b){if(($c="{0:yyyyMMdd}"-f$a)-eq-join$c[$c.length..0]){"{0:MM/dd/yyyy}"-f$a}$a=$a.AddDays(1)} ``` Takes input as command-line arguments `$args` in `MM/DD/YYYY` (or similar) format and recasts as a `[datetime]` array, stores them in `$a` and `$b`. That's the setup step of the `for` loop. The conditional is so long as `$a` is less-than-or-equal-to `$b`. Each iteration, we set `$c` equal to a `-f`ormatted string of `yyyyMMdd` style, based on `$a`. We then compare if that's `-eq`ual to `$c` reversed (using an array-join trick). If so, we output `$a` in the proper format. Either way, we increment `$a` with `.AddDays(1)` to move to the next day. ### Example ``` PS C:\Tools\Scripts\golfing> .\forecast-palindromic-dates.ps1 '06/23/2016' '12/12/2020' 02/02/2020 ``` [Answer] # Julia, 132 bytes ``` f(a,b,t=s->DateTime(s,"mm/dd/y"),g=d->Dates.format(d,"mm/dd/yyyy"))=map(g,filter(d->(r=replace(g(d),"/",""))==reverse(r),t(a):t(b))) ``` This is a function that accepts two strings and returns an array of strings. Ungolfed: ``` function f(a, b) # Define a function to create a DateTime object from a string t = s -> DateTime(s, "mm/dd/y") # Define a function to create a string from a DateTime object g = d -> Dates.format(d, "mm/dd/yyyy") # Filter the range a:b to palindromic dates p = filter(d -> (r = replace(g(d), "/", "")) == reverse(r), t(a):t(b)) # Format all dates in the array m = map(g, p) return m end ``` [Try it online!](http://julia.tryitonline.net/#code=ZihhLGIsdD1zLT5EYXRlVGltZShzLCJtbS9kZC95IiksZz1kLT5EYXRlcy5mb3JtYXQoZCwibW0vZGQveXl5eSIpKT1tYXAoZyxmaWx0ZXIoZC0-KHI9cmVwbGFjZShnKGQpLCIvIiwiIikpPT1yZXZlcnNlKHIpLHQoYSk6dChiKSkpCgpwcmludGxuKGYoIjAyLzAyLzIwMjAiLCAiMDMvMDIvMjAzMCIpKQ&input=) [Answer] ## JavaScript (ES6), ~~159~~ 154 bytes ``` (s,e)=>{for(r=[],s=Date.parse(s),e=Date.parse(e);s<=e;s+=864e5){d=new Date(s).toJSON().slice(0,10);`${a=d.match(/\d/g)}`==a.reverse()&&r.push(d)}return r} ``` I/O in ISO format. Ungolfed: ``` function date_palindrome(start, end) { start = Date.parse(start); end = Date.parse(end); var result = []; while (start <= end) { var date = new Date(start).toISOString().slice(0, 10); var digits = date.match(/d/g); if (digits.join() == digits.reverse.join()) { result.push(date); } start += 24 * 60 * 60 * 1000; // ms } return result; } ``` [Answer] # TSQL, 88 bytes Using ISO8601 format for date(yyyy-mm-dd) ``` DECLARE @ date='2050-05-02',@t date='2060-12-12' a:IF stuff(reverse(@),3,1,'')=stuff(@,8,1,'')PRINT @ SET @=dateadd(d,1,@)IF @<=@t GOTO a ``` [Fiddle](https://data.stackexchange.com/stackoverflow/query/503725/forecast-palindromic-dates) [Answer] # Java 7, ~~436~~ ~~435~~ 416 bytes *\*sigh..\** ``` import java.text.*;import java.util.*;void c(String...a)throws Exception{DateFormat f=new SimpleDateFormat("dd-MM-yyyy");Calendar s=Calendar.getInstance(),e=Calendar.getInstance();s.setTime(f.parse(a[0]));e.setTime(f.parse(a[1]));for(Date d=s.getTime();s.before(e);s.add(5,1),d=s.getTime()){String o=f.format(d),x=o.replaceAll("\\W|_",""),w="";for(char c:x.toCharArray())w=c+w;if(x.equals(w))System.out.println(o);}} ``` **Input & Output format:** `dd-MM-yyyy` **Ungolfed & test code:** [Try it here.](https://ideone.com/wDlNL2) ``` import java.text.*; import java.util.*; class Main{ static void c(String... a) throws Exception{ DateFormat f = new SimpleDateFormat("dd-MM-yyyy"); Calendar s = Calendar.getInstance(), e = Calendar.getInstance(); s.setTime(f.parse(a[0])); e.setTime(f.parse(a[1])); for(Date d = s.getTime(); s.before(e); s.add(Calendar.DATE, 1), d = s.getTime()){ String o = f.format(d), x = o.replaceAll("\\W|_", ""), w = ""; for(char c : x.toCharArray()){ w = c + w; } if(x.equals(w)){ System.out.println(o); } } } public static void main(String[] a){ try{ c("05-02-2050", "12-12-2060"); } catch (Exception e){} } } ``` **Output:** ``` 05-02-2050 15-02-2051 25-02-2052 06-02-2060 ``` [Answer] **Oracle 11: SQL: 246 bytes** (hey, at least I beat Java :P lol ) ``` with d as(select to_date('&1','yyyy-mm-dd')s,to_date('&2','yyyy-mm-dd')e from dual),r as(select level-1 l from d connect by level<=e-s+1),x as(select s+l y,to_char(s+l,'yyyymmdd')w from d,r)select to_char(y,'yyyy-mm-dd')from x where w=reverse(w); ``` **Output:** ``` SQL> with d as(select to_date('&1','yyyy-mm-dd')s,to_date('&2','yyyy-mm-dd')e from dual),r as(select level-1 l from d connect by level<=e-s+1),x as(select s+l y,to_char(s+l,'yyyymmdd')w from d,r)select to_char(y,'yyyy-mm-dd')from x where w=reverse(w); Enter value for 1: 2000-01-01 Enter value for 2: 2021-01-01 TO_CHAR(Y, ---------- 2001-10-02 2010-01-02 2011-11-02 2020-02-02 SQL> ``` **In readable format:** ``` with d as (select to_date('&1','yyyy-mm-dd') s, to_date('&2','yyyy-mm-dd') e from dual), r as (select level-1 l from d connect by level <= e-s+1), x as (select s+l y, to_char(s+l,'yyyymmdd') w from d,r) select to_char(y,'yyyy-mm-dd') from x where w=reverse(w); ``` **Explained:** ``` d: get input for start/end r: generate rows needed, 1 per day. x: calculate the actual dates, and convert them to a minimal string. final: use REVERSE function to verify the palindroms, return in proper format. ``` Learned about the REVERSE function today :) [Answer] # C#, ~~97~~ 94 bytes ``` (a,b)=>{for(;a<b;a=a.AddDays(1))if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))a.Dump();}; ``` C# lambda (`Action`) where inputs are `DateTime` and the output is printed by using the `.Dump()` method (@EvilFonti's [trick](https://codegolf.stackexchange.com/a/33114/15214)). --- # C#, ~~115~~ 112 bytes ``` (a,b)=>{var r="";for(;a<b;a=a.AddDays(1))if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))r+=a+",";return r;}; ``` C# lambda (`Func`) where inputs are `DateTime` and output is a `string`. Code: ``` (a,b)=> { var r=""; for(;a<b;a=a.AddDays(1)) { if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse())) r+=a+","; } return r; }; ``` --- [Try them online!](https://dotnetfiddle.net/HcxgPg) [Answer] # VBA, 240 193 bytes ``` Function f(a, b) Dim j, g() For i = CDate(a) To CDate(b) If Format(i, "yyyy") = StrReverse(Format(i, "mmdd")) Then ReDim Preserve g(j) g(j) = Format(i, "yyyy-mm-dd") j = j + 1 End If Next f = g() End Function ``` That's it in a comprehensible format. Test case: ``` Sub e() MsgBox Join(f("5/2/2050", "6/2/2060"), ", ") End Sub ``` Without that much redundancy: ``` Function f(a,b) Dim j, g() For i=CDate(a) To CDate(b) If Format(i,"yyyy")=StrReverse(Format(i,"mmdd")) Then ReDim Preserve g(j) g(j)=Format(i,"yyyy-mm-dd") j=j+1 End If Next f=g() End Function ``` [Answer] ## Javascript (using external library) (158 bytes) ``` (a,b)=>_.RangeTo(a%1e20,b%1e20,864e5).Select(y=>new Date(y)).Where(x=>z=(_.From(x.toJSON()).Where(y=>!isNaN(y)).Take(8)).SequenceEqual(z.Reverse())).ToArray() ``` Link to lib: <https://github.com/mvegh1/Enumerable> Code explanation: Ok, I finally used some actual code golfing here for once. So the inputs a,b are Date objects. Create a range of integers from a to b, where a and b are coerced into integers, and the distance between values in the range is 86400000, i.e the amount of ticks in one day. Map each value in the range to a date object. Filter that range by the predicate that represents palindromic dates. The logic to determine that is simple...cast the JSON string representation of the current date object to a char array using the library and filter out the non-numeric entries, and only take the first 8 values (because the that would be yyyyMMdd) and store that into variable z, then check if z is equivalent to z Reversed. Finally, cast back to native JS array Edit: Shaved 2 bytes by removing unnecessary parens.. [![enter image description here](https://i.stack.imgur.com/LVvlJ.png)](https://i.stack.imgur.com/LVvlJ.png) [Answer] # Java, 269 bytes ``` import java.time.LocalDate;void q(String...a)throws Exception{LocalDate s=LocalDate.parse(a[0]);while(!s.isAfter(LocalDate.parse(a[1]))){String d=s.toString().replace("-","");if(d.equals(new StringBuffer(d).reverse().toString()))System.out.println(d);s=s.plusDays(1);}} ``` Ungolfed: ``` import java.io.IOException; import java.time.LocalDate; public class UnGolfedPalindromicDates { public static void main(String...a) throws IOException { LocalDate start = LocalDate.parse(a[0]), end = LocalDate.parse(a[1]); while (!start.isAfter(end)) { String d = start.toString().replace("-",""); if (palindrome(d)) System.out.println(d); start = start.plusDays(1); } } public static boolean palindrome(String s) { return s.equals(new StringBuffer(s).reverse().toString()); } } ``` ]
[Question] [ (This is a variation on [Print a Negative of your Code](https://codegolf.stackexchange.com/questions/42017/print-a-negative-of-your-code), which I enjoyed a lot! Thanks to [Martin Büttner♦](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) - almost all of this text is his.) Let's consider the *symbols* to be the following printable ASCII characters (note that space is included): ``` !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ``` And the *alphanumerics* to be these: ``` 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` Consider a square of printable ASCII characters for side length N, like the following: ``` ONE, {two} &3,+= !four f|ve. ``` We also require each row and each column to contain at least one symbol and one alphanumeric. (The above example satisfies this.) We define the *symbolic negative* of such a square to be a square of the same size where each symbol is replaced with an alphanumeric and vice versa. For example, the following would be a valid symbolic negative of the above example: ``` [&]OK a...b 1/100 i@#$% (R) z ``` The choice of specific characters is irrelevant as long as they are in the categories above. ### The Challenge Your task is to write a program with square source code with side length N > 1, which prints a symbolic negative of its source code to STDOUT. Trailing spaces must be printed. You may or may not print a single trailing newline. The usual quine rules also apply, so you must not read your own source code, directly or indirectly. Likewise, you must not assume a REPL environment which automatically prints the value of each entered expression. The winner is the program with the lowest side length N. In the event of a tie, the submission with the fewest *symbols* in the source code wins. If there's still a tie, the earliest answer wins. [Answer] # GolfScript, 3 × 3 (4 symbols) ``` 4,m `3/ n*o ``` Try it online on [Web GolfScript](http://golfscript.apphb.com/?c=NCxtCmAzLwpuKm8%3D). ### Output ``` [0 1 2 3] ``` ### How it works ``` 4, # Push the array [0 1 2 3]. m # Undefined token. Does nothing. ` # Push the string representation of the array. Pushes "[0 1 2 3]". 3/ # Split into chunks of length 3. Pushes ["[0 " " 1 " "2 3]"]. n* # Join the chunks, separated by linefeeds. Pushes the output. o # Undefined token. Does nothing. ``` [Answer] # CJam, 3 × 3 (5 symbols) ``` [5, S*3 /N* ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%5B5%2C%0AS*3%0A%2FN*). ### How it works ``` [ e# Unmatched [. Does nothing. 5, e# Push [0 1 2 3 4]. S* e# Join the integers, separating by spaces. Pushes "0 1 2 3 4". 3 e# / e# Split into chunks of length 3. Pushes ["0 1" " 2 " "3 4"]. N* e# Join the chunks, separated by linefeeds. Pushes the output. ``` ### Output ``` 0 1 2 3 4 ``` [Answer] # Pyth, 3x3, 4 Symbols ``` S]1 .5; S]1 ``` ### Output: ``` [1] 0.5 [1] ``` ### Explanation: * S sorts the one element list `]1` * The numeric literal `.5` gets printed as `0.5`, `;` terminates the statement (does nothing in this case) [Answer] # C++, 18 x 18 "Always choose the worst tool for the job." ``` #include<cstdio> int main(){ for ( int line = 0lu; 1lu*line < 18l; 1lu*line++){pri\ ntf(line == 0lu * 123*line? "\x41.\\ x2e\x02e...\x2e\\ x42\x02e...\x2e.\ CDE\x00a": 14l!= 1lu*line?".\x2e.\\ x46\x02e...\x47""\ HIJ\x02e..""KLM" /*O*/"\n": /*The bad code:*/"NOP.\ QRS\x054." "UVW\ XYZ\x02e" "\x2e\\ x2e\x00a"); 0lu;}} ``` Output: ``` A.......B......CDE ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM NOP.QRST.UVWXYZ... ...F....GHIJ...KLM ...F....GHIJ...KLM ...F....GHIJ...KLM ``` ]
[Question] [ In this challenge, you are given a map of a two-dimensional terrain, viewed from the side. Unfortunately, some parts of the terrain are floating in the air, which means they'll come crashing down. Your job is to predict where they land. # The Input Your input is one or more newline-separated strings of equal lengths, containing only the characters `#` (a number sign, signifying a rock) or `.` (a period, signifying empty space). # The Output Your output has the same format as the input, but with the following modification. Let us view the input string as a two-dimensional grid of rocks. Every rock in the input which is connected to the bottom of the grid by a path of adjacent rocks is *firm*; other rocks are *loose*. Diagonally adjacent rocks are not considered to be adjacent. All the loose rocks will fall straight down, and end up as a stack on top of either a firm rock or the bottom row. The loose rocks are not attached to each other, so they fall individually, not as big formations. The output is the resulting grid. # Examples * The input ``` ..###. .##.#. .#.... .##.#. ``` contains no loose rocks, so the output is identical to it. * The input ``` ...#.. .#..#. .#..## .#...# .##### .#...# ``` contains one loose rock at the top, which falls down on the firm rock under it. The output is ``` ...... .#..#. .#..## .#.#.# .##### .#...# ``` * The input ``` .#####.... .#....#### ###.###..# #.#...##.. .####..#.# ......###. ..#...#..# ..#...#..# ``` has a large group of loose rocks on the left. The group breaks down as the rocks fall, so the output is ``` .......... ....###### ..#.###..# . #...##.. .##....#.. .##...#### ####..#..# #####.#..# ``` # Clarifications * You can either take the input from STDIN and output to STDOUT, or write a function. * This is code-golf, so shortest program (in bytes) is the winner. * Standard loopholes are disallowed. [Answer] # Perl 5: 98 98 including 2 command line flags. ``` #!perl -p0 1while/ /,($x="($`)")=~y!#!.!,s/#(.* $)/%$1/+s/#$x?%|%$x?#/%$1$2%/s;1while s/#$x\./.$1#/s;y!%!#! ``` Explanation: ``` #!perl -p0 #read entire input to $_ and print at the end /\n/;($x="($`)")=~y!#!.!; #calculate pattern matching space #between two characters in the same column #looks like "(......)" 1 while s/#(.*\n$)/%$1/+s/#$x?%|%$x?#/%$1$2%/s; #flood fill solid rock with % 1 while s/#$x\./.$1#/s; #drop loose rock y!%!#! #change % back to # ``` [Answer] # CJam, ~~180 ... 133 101 ... 94 90~~ 87 bytes ``` qN/~'#/S*_,):L;]N*_,_,*{:A1$='#={[W1LL~)]Af+{W>},1$f=S&,{ASct}*}*}/N/z{S/{$W%}%'#*}%zN* ``` ~~There is definitely lots of golfing possible, but I wanted to post it first after getting it to work completely.~~ > > Look ma! No scrollbars! > > > Takes the rocks grid (made up of `.` and `#` without a trailing newline) from STDIN and prints the output to STDOUT *UPDATE* : Using an inefficient but shorter partial flood fill to figure out firm rocks. *UPDATE 2*: Changed the algorithm for making the rocks fall down. Much shorter now! *UPDATE 3*: Did several small optimizations and in the end I was able to bring down the byte count to half of the original code! **How it works**: ``` qN/~'#/S*_,):L;]N* "Preparations"; qN/~ "Read the input, split by new line and expand the array"; '#/S* "In the last row, replace # by space"; _,):L "Copy the last row and store length + 1 in L"; ;]N* "Pop the length, wrap everything in array and join by \n"; _,_,*{ ... }/ "Flood fill"; _, "Copy the array and calculate its length"; _, "Copy the length and calculate [0 - length] array"; * "Repeat the above array, length times"; { ... }/ "Run the code block on each element of the array"; :A1$='#={ ... }* "Process only #"; :A1$ "Store the number in A and copy the input array to stack"; = "Get Ath index element from input array"; '#={ ... }* "Run the code block if Ath element equals #"; [W1LL~)]Af+{W>},1$f=S&,{ASct}* "Flood fill spaces"; [W1LL~)]Af+ "Get the indexes of the 4 elements on the cross formed by" "the Ath index"; {W>}, "Filter out the negative values"; 1$f= "For each of the index, get the char from input string"; S&, "Check if space is one of the 4 chars from above step"; { }* "Run the code block if space is present"; ASct "Make the Ath character of input string as space"; N/z{S/{$W%}%'#*}%zN* "Let the rocks fall"; N/z "Split the resultant string by newlines and" "transpose the matrix"; { }% "Run the code block for each row (column of original)"; S/{ }% "Split by space and run the code block for each part"; $W% "Sort and reverse. This makes # come down and . to go up"; '#* "Join by 3, effectively replacing back spaces with #"; zN* "Transpose to get back final matrix and join by newline"; ``` For the floodfill, we iterate through the whole grid length(grid) times. In each iteration, we are guaranteed to convert at least 1 `#` which is directly touching a space to (space). Space here represents a firm rock group. Thus at the end of length(grid) iterations, we are guaranteed to have all firm rocks represented by spaces. [Try it online here](http://cjam.aditsu.net/) [Answer] # JavaScript (ES6) 232 ``` s=>{for(s=[...s+'1'.repeat(r=1+s.search('\n'))];s=s.map((c,p)=>c=='#'&(s[p+1]|s[p-1]|s[p-r]|s[p+r])?f=1:c,f=0),f;);for(;s.map((c,p)=>c=='#'&s[p+r]=='.'&&(s[p]='.',f=s[p+r]=c),f=0),f;);return s.join('').replace(/1/g,rok).slice(0,-r)} ``` As a function with a string parameter and returning a string. At first, add a bottom row of '1' to identify the ground line. The first loop search for the fixed rocks (that are near a '1') and marks them as '1' as well.The search is repeated until no more firm rocks are found. The second loop move the remaining '#' characters towards the bottom row. Again, this is repeated until no rock can be moved. At last, replace the '1' with '#' again and cut the bottom row. *Less golfed* ``` s=>{ r = 1+s.search('\n'); s = [...s+'1'.repeat(r)]; for (; s = s.map((c,p) => c=='#' & (s[p+1]|s[p-1]|s[p-r]|s[p+r])?f=1:c,f=0),f; ); for (; s.map((c,p) => c=='#' & s[p+r]=='.'&& (s[p] ='.', s[p+r]=c, f=1),f=0),f; ); return s.join('') .replace(/1/g,'#') .slice(0,-r) } ``` **Test** (You can have evidence of what rocks are firm and what have fallen) ``` F= s=>{for(s=[...s+'1'.repeat(r=1+s.search('\n'))];s=s.map((c,p)=>c=='#'&(s[p+1]|s[p-1]|s[p-r]|s[p+r])?f=1:c,f=0),f;);for(;s.map((c,p)=>c=='#'&s[p+r]=='.'&&(s[p]='.',f=s[p+r]=c),f=0),f;);return s.join('').replace(/1/g,rok).slice(0,-r)} var rok // using rok that is 3 chars like '#' function update() { rok = C.checked ? '@' : '#'; O.textContent=F(I.textContent) } update() ``` ``` td { padding: 5px } pre { border: 1px solid #000; margin:0 } ``` ``` <table><tr><td>Input</td><td>Output</td></tr> <tr><td><pre id=I>.#####.... .#....#### ###.###..# #.#...##.. .####..#.# ......###. ..#...#..# ..#...#..#</pre></td> <td><pre id=O></pre> </td></tr></table> <input type='checkbox' id=C oninput='update()'>Show firm rocks ``` [Answer] ## APL, ~~130~~ 119 ``` '.##'[1+⊖1↓⍉↑↑{,/{⍵[⍒⍵]}¨x⊂⍨2=x←2,⍵}¨↓ ⍉⊃⌈/(1,¨⍳⍴⊃↓x){x←⍵⋄(⍺⌷x)∧←2⋄x≡⍵:x⋄⊃⌈/((⊂⍴⍵)⌊¨1⌈(,∘-⍨↓∘.=⍨⍳2)+⊂⍺)∇¨⊂x}¨⊂⊖'#'=x←⎕] ``` Since it is not possible (as far as I know) to enter newlines when input is prompted, this program takes a character matrix as input. The algorithm used is first converting to a binary matrix (`0` is air and `1` is rock) then flood filling from the bottom row to mark firm rocks as `2`. Then partition each column into "spaces between firm rocks" and sort each partition to make the loose rock "fall through" the air. Edit1: Golfed some using a different flood fill algorithm --- ## Test runs **Run 1** Define a character matrix `A` and prints it: ``` A←↑('.#####....') ('.#....####') ('###.###..#') ('#.#...##..') ('.####..#.#') ('......###.') ('..#...#..#') ('..#...#..#') A .#####.... .#....#### ###.###..# #.#...##.. .####..#.# ......###. ..#...#..# ..#...#..# ``` Then feed `A` into the program: ``` '.##'[1+⊖1↓⍉↑↑{,/{⍵[⍒⍵]}¨x⊂⍨2=x←2,⍵}¨↓⍉(1,¨⍳⊃⌽⍴x){⍵≡y←⊃⌈/x←⍺{x←⍵⋄(⍺⌷x)∧←2⋄x}¨⊂⍵:y⋄((⊂⍴⍵)⌊¨1⌈,(,∘-⍨↓∘.=⍨⍳2)∘.+⍺/⍨x≢¨⊂⍵)∇y}⊖'#'=x←⎕] ⎕: A .......... ....###### ..#.###..# ..#...##.. .##....#.. .##...#### ####..#..# #####.#..# ``` **Run 2** ``` A←↑('#######')('#.....#')('#.#.#.#')('#.....#')('#######') A ####### #.....# #.#.#.# #.....# ####### '.##'[1+⊖1↓⍉↑↑{,/{⍵[⍒⍵]}¨x⊂⍨2=x←2,⍵}¨↓⍉(1,¨⍳⊃⌽⍴x){⍵≡y←⊃⌈/x←⍺{x←⍵⋄(⍺⌷x)∧←2⋄x}¨⊂⍵:y⋄((⊂⍴⍵)⌊¨1⌈,(,∘-⍨↓∘.=⍨⍳2)∘.+⍺/⍨x≢¨⊂⍵)∇y}⊖'#'=x←⎕] ⎕: A ####### #.....# #.....# #.#.#.# ####### ``` [Answer] # JS - 443 bytes ``` function g(b){function f(b,c,e){return b.substr(0,c)+e+b.substr(c+1)}function e(d,c){"#"==b[c][d]&&(b[c]=f(b[c],d,"F"),1<d&&e(d-1,c),d<w-1&&e(d+1,c),1<c&&e(d,c-1),c<h-1&&e(d,c+1))}b=b.split("\n");w=b[0].length;h=b.length;for(i=0;i<w;i++)"#"==b[h-1][i]&&e(i,h-1);for(j=h-2;-1<j;j--)for(i=0;i<w;i++)if(k=j+1,"#"==b[j][i]){for(;k<h&&"F"!=b[k][i]&&"#"!=b[k][i];)k++;k--;b[j]=f(b[j],i,".");b[k]=f(b[k],i,"#")}return b.join("\n").replace(/F/g,"#")}; ``` Flood fills rocks from the bottom, then brings un-flood-filled rocks down. Uses a lot of recursion with the flood fill so it may lag your browser for a bit. It's a function - call it with `g("input")` JSFiddle: <http://jsfiddle.net/mh66xge6/1/> Ungolfed JSFiddle: <http://jsfiddle.net/mh66xge6/> [Answer] # Python 3, 364 bytes I'm sure more could be squeezed out of this... but it's never going to compete with CJam and Perl anyway. ``` z="%";R=range def F(r,c,g): if z>g[r][c]:g[r][c]=z;[F(r+d%2*(d-2),c+(d%2-1)*(d-1),g)for d in R(4)] def P(s): t=s.split()[::-1];w=len(t[0]);g=[list(r+".")for r in t+["."*w]];[F(0,c,g)for c in R(w)] for c in R(w): for r in R(len(g)): while g[r][c]<z<g[r-1][c]and r:g[r][c],g[r-1][c]=".#";r-=1 return"\n".join(''.join(r[:w])for r in g[-2::-1]).replace(z,"#") ``` Similar to other answers. One quirk is that it turns the grid upside down first (to make the loop indices more convenient) and adds an extra row & column of `.` (to avoid problems with wrapping `-1` indices). Run by calling `P(string)`. ]
[Question] [ Finding primes is a programming rite of passage and very frequently the first serious program someone creates (usually with trial division). But primes alone are already worn out. A next far more interesting thing is to get the prime gaps: the so-far-longest gaps between consecutive primes. These are quite rare and "precious". A first few pairs and their differences are: ``` 2 3 1 3 5 2 7 11 4 23 29 6 89 97 8 113 127 14 ... ``` My father used to calculate these by hand for fun up to 10k. Let's see how short a code you can get. Write a program which goes through primes and produces a line of output every time the difference between two consecutive primes is bigger than that of any two previous consecutive primes. Your output can either be the two primes followed by their gap, or just the gap. If you choose the later add 10 to your overall score. For instance, between 3 and 5, there is a gap 2 units wide. The gap between 5 and 7 is also 2, but that's old news, we don't care any more. Only when you see a new biggest gap, you report it. This reflects how the primes are getting less and less frequent, as the gaps become wider and wider. Rules: * no builtin functions for prime testing, prime generation or prime gaps * no retrieving <http://oeis.org/A002386> or similar (I can smell you cheaters from far away :) ) * no precomputed arrays * keep printing until your internal integer type fails on you Answers are scored in characters, plus the potential 10 penalty. With lower scores being the goal. You can also show off versions with builtin functions if they are interesting. Be creative. --- *EDIT*: Most of the answers are brilliant and deserve more recognition. However, so far, a GolfScript entry with 48 characters is the shortest. [Answer] ## Python, ~~121~~ ~~110~~ ~~109~~ ~~108~~ ~~104~~ 103 characters ``` p,n,m=[2],3,0 while 1: if all(n%x for x in p): c=n-p[0] if m<c:m=c;print(p[0],n,c) p=[n]+p n+=1 ``` First time I tried to answer here, I hope I did it right... not sure I even counted the characters right. Hmmm, I could save another character on the print by downgrading to Python 2.x... [Answer] # JavaScript, 90 85 78 74 chars **Short Code** (Google Closure Compiler - Advanced Optimizations; some manual edits; more edits by [@MT0](https://codegolf.stackexchange.com/users/15968/mt0)) ``` for(a=b=2,c=0;b++;)for(d=b;b%--d;)d<3&&(c<b-a&&console.log(a,b,c=b-a),a=b) ``` **Long Code** ``` var lastPrime = 2, curNumber = lastPrime, maxDistance = 0, i; // check all numbers while( curNumber++ ) { // check for primes i = curNumber; while( curNumber % --i != 0 ) {} // if prime, then i should be equal to one here if( i == 1 ) { // calc distance i=curNumber-lastPrime; // new hit if( maxDistance < i ) { maxDistance = i; console.log( lastPrime, curNumber, maxDistance ); } // remember prime lastPrime = curNumber; } } ``` **Output** ``` 2 3 1 3 5 2 7 11 4 23 29 6 89 97 8 113 127 14 523 541 18 887 907 20 1129 1151 22 1327 1361 34 9551 9587 36 15683 15727 44 19609 19661 52 31397 31469 72 ... ``` Pretty inefficient test for primes, but that way it uses less characters. First post here, so please excuse any mistakes. [Answer] # GolfScript 66 59 57 49 48 ``` [2.0{:d{;\;.{).{(1$1$%}do(}do.2$-.d>!}do].p~.}do ``` Although I'm having trouble running it here <http://golfscript.apphb.com/> (maybe that site doesn't like the infinite loop?) but it works fine when I run it on my computer with golfscript.rb. I'm pretty new to GolfScript so this can probably be golfed down even further. UPDATE: I don't think this can be golfed down much more without changing the algorithm somehow. First few lines printed (If you do not like the "" being printed you can add ; at the beginning of the script, but that bumps it up to 49 chars) : ``` [2 3 1] ["" 3 5 2] ["" 7 11 4] ["" 23 29 6] ["" 89 97 8] ["" 113 127 14] ["" 523 541 18] ["" 887 907 20] ["" 1129 1151 22] ... ``` General human-readable idea of how this works (a few things slightly different since I'm not using a stack in this version) : ``` cur_prime = 2 next_prime = 2 gap = 0 do { do { cur_prime = next_prime do { next_prime = next_prime + 1 possible_factor = next_prime do { possible_factor = possible_factor - 1 } while (next_prime % possible_factor > 0) } while (possible_factor != 1) } while (next_prime - cur_prime <= gap) gap = next_prime - cur_prime print [cur_prime next_prime gap] } while (true) ``` [Answer] # Mathematica, 114 108 Allows infinite output, although after a certain point in the sequence the fan spins up and you begin to suspect that your CPU is playing Freecell while doing its best to look busy. ``` p@x_:=NestWhile[#+1&,x+1,Divisors@#≠{1,#}&];m=0;q=1;While[1<2,If[p@q-q>m,Print@{q,p@q,p@q-q};m=p@q-q];q=p@q] ``` Output sample (These are the ones it picks up in the first ~30s): ``` {1,2,1} {3,5,2} {7,11,4} {23,29,6} {89,97,8} {113,127,14} {523,541,18} {887,907,20} {1129,1151,22} {1327,1361,34} {9551,9587,36} {15683,15727,44} {19609,19661,52} {31397,31469,72} {155921,156007,86} {360653,360749,96} {370261,370373,112} {492113,492227,114} {1349533,1349651,118} {1357201,1357333,132} {2010733,2010881,148} ``` Ungolfed code: ``` p@x_ := NestWhile[ # + 1 &, x + 1, Divisors@# ≠ {1, #} &]; m = 0; q = 1; While[ 1 < 2, If[ p@q - q > m, Print@{q, p@q, p@q - q}; m = p@q - q]; q = p@q] ``` [Answer] # Haskell - 122 116 114 112 110 ``` q=[n|n<-[3..],all((>0).rem n)[2..n-1]] d m((p,q):b)|q-p>m=print(p,q,q-p)>>d(q-p)b|q>p=d m b main=d 0$zip(2:q)q ``` (Inefficient) prime list expression stolen from [Will Ness](https://codegolf.stackexchange.com/a/6940/17034). -edit- I never knew `x|y=z|w=q` would be valid. [Answer] ## MATLAB ~~104~~ 89 Just implemented the basic method by checking every possible division. ``` a=2;g=0;for n=3:inf;b=n*(sum(mod(n,1:n)<1)<3);h=b-a;if(h>g)g=h;[a,b,h] end;a=max(a,b);end ``` Output: ``` 2 3 1 3 5 2 7 11 4 23 29 6 89 97 8 113 127 14 523 541 18 887 907 20 ``` [Answer] # 76 chars, [dogelang](http://pyos.github.io/dg/tutorial/) Converted from my [Python version](https://codegolf.stackexchange.com/a/23924/4800): ``` g=0 i=l=2 while i+=1=>all$map(i%)(2..i)=>(i-l>g=>(g=i-l),print(l,i,g)),(l=i) ``` Output: ``` (2, 3, 1) (3, 5, 2) (7, 11, 4) (23, 29, 6) (89, 97, 8) (113, 127, 14) (523, 541, 18) (887, 907, 20) (1129, 1151, 22) ... ``` [Answer] # Golfscript, ~~59~~ ~~51~~ 50 chars Man each character is extremely difficult to lose: ``` 0[2.{).,2>{\.@%!},{.2$-.4$>{].p~\[}{;\;}if..}or}do ``` **Output**: ``` [2 3 1] [3 5 2] [7 11 4] [23 29 6] [89 97 8] [113 127 14] ... ``` **Explanation**: The stack is set up so each iteration starts with the stack like this, the top being to the right. The `[` indicates the current array marker, meaning when the interpreter encounters a `]`, everything on the stack from the mark to the top is put into an array. ``` g [ last | cur ``` `g` is the maximum gap so far. From the top down: ``` command | explanation -----------------+---------------------------------------- 0[2. | initialize vars g=0, last=2, cur=2 {...}do | loop forever... ``` Inside the loop: ``` ) | cur += 1 .,2>{\.@%!}, | put all divisors of cur into a list {...}or | if the list is empty, cur is prime, so | the block is executed. otherwise, | 'do' consumes the stack, sees it is truthy, | and loops again ``` How does it put all divisors into a list? Let's do it step by step ``` Command | explanation | stack -----------------+----------------------------------------------+---------------- | initial stack | n ., | make list of 0..n-1 | n [0,1,...,n-1] 2> | take elements at index 2 and greater | n [2,3,...,n-1] {...}, | take list off stack, then iterate through | | the list. on each iteration, put the current | | element on the stack, execute the block, and | | pop the top of the stack. if the top is | | true then keep the element, else drop it. | | when done, push list of all true elements | | So, for each element... | n x \. | Swap & dup | x n n @ | Bring x around | n n x % | Modulo | n (n%x) ! | Boolean not. 0->1, else->0. Thus this is 1 | | if x divides n. | n (x divides n) | So only the divisors of n are kept | n [divisors of n] ``` What does it do if the divisors are empty? ``` Command | explanation | stack -----------------+----------------------------------------------+---------------- | initial stack | g [ last | cur . | dup | g [ l | c | c 2$ | copy 3rd down | g [ l | c | c | l - | sub. This is the current gap, cur-last | g [ l | c | c-l . | dup | g [ l | c | c-l | c-l 4$ | copy 4th down | g [ l | c | c-l | c-l | g > | is cur gap > max gap so far? | g [ l | c | c-l | c-l>g {#1}{#2}if.. | #1 if c-l > g, #2 otherwise, and do ".." in | ... | g [ c | c | c | either situation | ``` Two paths: yes and no. If yes (note that `if` consumes the top value on the stack): ``` Command | explanation | stack -----------------+----------------------------------------------+---------------- | initial stack. note that now the old `g` is | XX [ l | c | g | garbage and `c-l` is the new `g`. | ] | close the array | XX [l, c, g] .p | duplicate it and print it, consuming the dup | XX [l, c, g] ~ | pump array back onto the stack. Note now the | XX | l | c | j | array marker [ is gone. | \ | swap. | XX | l | g | c [ | mark the array | XX | l | g | c [ . | this is the part after the if. dups the top, | XX | l | g [ c | c | but it does this in two steps, first popping | | c then putting two copies on top, so the | | array marker moves | . | dup again | XX | l | g [ c | c | c ``` If no: ``` Command | explanation | stack -----------------+----------------------------------------------+---------------- | initial stack. In this case g is still the | g [ l | c | c-l | max gap so far | ;\; | dump top of stack, swap, and dump again | g [ c .. | the part after the if. dup twice | g [ c | c | c ``` Note in either case, our stack is now in the form `... | g [ c | c | c`. Now the `do` pops the top value off the stack - always `c` - and loops if it is positive. Since `c` always increasing, this is always true, so we loop forever. Once popped, the top of the stack is `g [ c | c`, meaning last has been updated to `c`, the array mark is in the same place, and `g` is still where we expect it. These are the convoluted operations of GolfScript. I hope you enjoyed following along! [Answer] # Ruby, 110 Only for Ruby 2.0 due to the `lazy`method: ``` (2..1.0/0).lazy.select{|n|!(2...n).any?{|m|n%m==0}}.reduce([2,0]){|(l,t),c|d=c-l;p [l,c,d]if d>t;[c,d>t ?d:t]} ``` Output: ``` [2, 3, 1] [3, 5, 2] [7, 11, 4] [23, 29, 6] [89, 97, 8] [113, 127, 14] [523, 541, 18] [887, 907, 20] [1129, 1151, 22] [1327, 1361, 34] [9551, 9587, 36] [15683, 15727, 44] [19609, 19661, 52] [31397, 31469, 72] [155921, 156007, 86] [360653, 360749, 96] [370261, 370373, 112] [492113, 492227, 114] ... ``` [Answer] ## Perl, 105 bytes ``` $p=2;$d=0;L:for($i=2;++$i>2;){!($i%$_)&&next L for 2..$i-1;if($i-$p>$d){$d=$i-$p;print"$p $i $d\n"}$p=$i} ``` **Ungolfed:** ``` $p = 2; $d = 0; L: for ($i = 2; ++$i > 2; ){ !($i % $_) && next L for 2..$i-1; if ($i - $p > $d) { $d = $i - $p; print "$p $i $d\n" } $p = $i } ``` The algorithm is simple, `$p` remembers the previous prime number. Then `$i` goes from `3` up to, when the type $i "fails on me" or become negative because of overflow. `$i` is tested the crude way by checking all divisors from 2 to `$i-1`. A line is printed, if the current difference is larger than the previous printed difference `$d`. With some more bytes the run-time can be improved: ``` $p = 2; $d = 0; L: for ($i=3; $i > 2; $i += 2){ for ($j=3; $j <= sqrt($i); $j += 2){ next L if !($i%$j) } if ($i - $p > $d) { $d = $i - $p; print "$p $i $d\n" } $p = $i } ``` The **result** starts with: ``` 2 3 1 3 5 2 7 11 4 23 29 6 89 97 8 113 127 14 523 541 18 887 907 20 1129 1151 22 1327 1361 34 9551 9587 36 15683 15727 44 19609 19661 52 31397 31469 72 155921 156007 86 360653 360749 96 370261 370373 112 492113 492227 114 1349533 1349651 118 1357201 1357333 132 2010733 2010881 148 4652353 4652507 154 17051707 17051887 180 20831323 20831533 210 47326693 47326913 220 ... ``` [Answer] # Python, ~~93~~ 91 chars Naive prime checking (check if divisible by anything from 2 to `n` (less chars than to `n/2`)): ``` g=0;i=l=2 while 1: i+=1 if all(i%x for x in range(2,i)): if i-l>g:g=i-l;print l,i,g l=i ``` Second level of indent is one tab character. Output: ``` 2 3 1 5 7 2 7 11 4 23 29 6 89 97 8 113 127 14 523 541 18 ... ``` [Answer] # **Bash and some Perl for prime regex (167 157 143 112 bytes)** ``` n=2 c=2 while p=$c do perl -e\(1x$[++n]')=~/^(11+?)\1+$/&&exit 1'&&c=$n ((c-p>g))&&g=$[c-p]&&echo $p $c $g done ``` some output: ``` $./golfd.sh 2 3 1 3 5 2 7 11 4 23 29 6 89 97 8 113 127 14 523 541 18 887 907 20 1129 1151 22 ``` [Answer] # Perl 95 90 bytes ``` for($n=$c=2;$p=$c;$c-$p>$g&&printf"$p $c %d\n",$g=$c-$p){$c=$n if(1x++$n)!~/^(11+?)\1+$/} ``` old Non golf version: ``` $n=$c=2; while($p=$c){ $c=$n if (1x++$n)!~/^(11+?)\1+$/; if ($c-$p>$g) {$g=$c-$p;print "$p $c $g\n"} } ``` This is similar to my other submission, sans bash. [Answer] # C (100) My own contribution, no special algorithm, just golf: ``` i,g,r,p=2;main(){for(;r=p;p-r>g?printf("%d %d %d\n",r,p,g=p-r):0)for(i=0;i-p;)for(i=1,++p;p%++i;);} ``` [Answer] ## Haskell, 134C Golfed: ``` c n=null[x|x<-[2..n-1],n`mod`x==0]&&n>1 p=filter c[1..] g l(m:n:o) |(n-m)>l=do print(m,n,n-m);g(n-m)(n:o) |True=g l(n:o) main=g 0 p ``` Ungolfed: ``` -- c function checks if n is a prime number c n=null[x|x<-[2..n-1],n`mod`x==0]&&n>1 -- p is an infinite list of primes p=filter c[1..] -- g function prints a list of primes and differences. -- l is the maximum difference seen so far -- (m:n:o) is the list of unprocessed primes g l(m:n:o) |(n-m)>l=do print(m,n,n-m);g(n-m)(n:o) |True=g l(n:o) -- main starts the ball rolling with a default max-seen value of 0 main=g 0 p ``` [Answer] # C: 493 302 272 246 ``` int e(int j){for(int i=2;i<j;i++)if(j%i<1)return 0;return 1;}void f(int a,int b,int c){if(e(a)&e(b))if(c<b-a){printf("%d %d %d\n",a,b,b-a);f(a+1,b+1,b-a);}else f(a+1,b+1,c);if(e(b))f(a+1,b,c);if(e(a))f(a,b+1,c);f(a+1,b+1,c);}int main(){f(2,3,0);} ``` I used recursion not the usual loop of `for` or `while`. ``` int isPrime(int num){ for( int i=2; i<num; i++ ) if(num%i < 0) return 0; return 1; } void fun(int n1, int n2, int gap){ if( isPrime(n1) & isPrime(n2) ){ if( gap < n2-n1 ){ printf("%d %d %d\n", n1, n2, n2-n1); fun(n1+1, n2+1, n2-n1); }else{ fun(n1+1, n2+1, gap); } } if( isPrime(n2) ){ fun(n1+1, n2, gap); } if( isPrime(n1) ){ fun(n1, n2+1, gap); } fun(n1+1, n2+1, gap); } int main(){ fun(2,3,0); } ``` Output: ``` 2 3 1 3 5 2 7 11 4 23 29 6 89 97 8 113 127 14 523 541 18 887 907 20 1129 1151 22 1327 1361 34 9551 9587 36 15683 15727 44 19609 19661 52 ``` [Answer] # Oracle SQL, 216 202 196 172 + 10 = 182 Just noticed this in the question: > > Lowest character count wins. +10 characters if you only print the gaps without the primes. > > > As this is SQL and the keywords are so long it's actually better to take the penalty, giving the following. It's the same idea as the original. ``` with c as(select level+1n from dual connect by level<1e124)select lead(n)over(order by n) from(select*from c a where not exists(select*from c where n<a.n and mod(a.n,n)=0)) ``` which prettifies to: ``` with c as ( select level + 1 n from dual connect by level < 1e124 ) select lead(n) over ( order by n ) from ( select * from c a where not exists( select * from c where n < a.n and mod(a.n, n) = 0 ) ) ``` --- Old answer (196) ``` with c as(select level+1n from dual connect by level<1e124)select n,p,p-n from(select n,lead(n)over(order by n)p from(select*from c a where not exists(select*from c where n<a.n and mod(a.n,n)=0))) ``` and in a readable format: ``` with c as ( select level + 1 n from dual connect by level < 1e124 ) select n, p, p-n from ( select n, lead(n) over ( order by n ) p from ( select * from c a where not exists ( select * from c where n < a.n and mod(a.n, n) = 0 ) ) ) ``` This creates a number generator in `c`, the innermost sub-select creates the primes numbers using a Sieve of Eratosthenes, the outer works out the previous prime and finally the last select subtract one from the other. This won't return anything because it's performing 1 x 10 124 recursive queries... So, if you want it to work lower this number to something sensible. [Answer] ## D - 153 + 10 = 163 I'm willingly taking the +10 penalty here, because the char count is still lower than it would have been if I had printed the primes as well. **Golfed**: ``` import std.stdio;bool p(int l){int n;foreach(i;1..l+1)n+=l%i==0?1:0;return n==2;}void main(){int g;foreach(l;0..int.max)if(l.p){if(g>0)(l-g).write;g=l;}} ``` **Readable version**: ``` import std.stdio; bool prime( int number ) { int divisors; foreach( i; 1 .. number + 1 ) divisors += number % i == 0 ? 1 : 0; return divisors == 2; } void main() { int lastPrime; foreach( number; 0 .. int.max ) if( number.prime ) { if( lastPrime > 0 ) ( number - lastPrime ).write; lastPrime = number; } } ``` [Answer] # **JAVASCRIPT 174 char** ``` var p=[2],l=2,g=0; for(var n=3;n>0;n+=2){ var o=0; for(var t=0;t<p.length;++t){ if(n/p[t] == parseInt(n/p[t])){ o=1; } } if(o==0){ p.push(n); if(n-l>g){ g=n-l; console.log(l,n,g); } l=n; } } ``` short version: ``` var p=[2],l=2,g=0;for(var n=3;n>0;n+=2){var o=0;for(var t=0;t<p.length;++t){if(n/p[t] == parseInt(n/p[t])){o=1;}}if(o==0){p.push(n);if(n-l>g){g=n-l;console.log(l,n,g);}l=n;}} ``` [Answer] ## Javascript 138 ``` for(var a=2,b=0,c=0;a++;){var d;a:{for(var e=a,f=2;f<e;f++)if(0==e%f){d=!1;break a}d=!0}d&&(0!=b&&a-b>c&&(c=a-b,console.log(b,a,c)),b=a)} ``` Copy this code to your browser console. It will for like forever as the max number is something around `1.79*10^308`. Ungolfed: ``` var number = 2; var lastPrime = 0; var gap = 0; while(number++) { if (isPrime(number)) { if (lastPrime != 0) { if (number - lastPrime > gap) { gap = number - lastPrime; console.log(lastPrime, number, gap); } } lastPrime = number; } } function isPrime(n){ for (var i = 2; i < n; i++) { if (n % i == 0) return false; } return true; } ``` [Answer] ## C# 162 161 chars 151 chars + 10 penalty chars = 161 chars Short version: ``` using System;class P{static void Main(){int p=2,g=0;for(int i=3;;i++){for(int j=2;j<i;j++)if(i%j==0)goto e;if(i-p>g)Console.WriteLine(g=i-p);p=i;e:;}}} ``` Long version: ``` using System; class PrimeGaps { private static void Main() { int lastPrime = 2; int largestGap = 0; for (int i = 3; true; i++) { // Prime test for (int j = 2; j < i; j++) if (i%j == 0) goto nextI; // Skip to next iteration of i // Largest gap check if (i - lastPrime > largestGap) { largestGap = i - lastPrime; Console.WriteLine(largestGap); } // Remember last prime lastPrime = i; nextI: ; // Do nothing } } } ``` It was actually better to take 10 chars penalty, since it's shorter writing `g` (11 chars with penalty) than `p+" "+i+" "+g` (13 chars without penalty). [Answer] ## Ruby 90 86 84 83 chars ``` r,i,g=2,2,0;while i+=1 do(2...i).all?{|j|i%j>0}&&((i-r<=g||p([r,i,g=i-r]))&&r=i)end ``` Some boolean short circuits, abuse of expression evaluation, etc. [Answer] **C 248** Code compares consecutive prime numbers a, b and then checks if gaps are larger than g then finds next pair of primes. ``` #include <cstdio> void f(int* a, int* b){*a =*b;int t=1;while (*b += 2){t=1;for(int i=3;i<*b;i+=2){if(*b%i==0){t=0; break;}}if(t)break;}} int main(){int a=2,b=3,g=0;do{(b-a>g)?printf("%d %d %d\n",a,b,(g=b-a)): f(&a,&b);} while(b>=0);return 0;} ``` [Answer] ## Haskell, 154 144 137 123 The primes `p` are generated using the sieve of erasthotenes `#`, and then filtered and printed using `%`. ``` p=2:3#1 n#m|all((>0).mod n)$take m p=n:(n+1)#(m+1)|1<2=(n+1)#m (l:u@(o:_))%k|o-l>k=print(l,o,o-l)>>u%(o-l)|1<2=u%k main=p%0 ``` The output looks like ``` (2,3,1) (3,5,2) (7,11,4) (23,29,6) (89,97,8) ``` which I hope is okay. [Answer] ## Game Maker Language, 85 Assuming all uninitialized variables as `0` (this is the default with some versions of Game Maker). ``` a=2b=2for(d=2;b++;1)for(c<b-a;b mod --d;1)d<3&&(c=b-a&&show_message_ext("",a,b,c)a=b) ``` [Answer] ## Game Maker Language, 74 + 55 = 129 Assuming all uninitialized variables as `0` (this is the default with some versions of Game Maker). ``` n=2while(n++){if p(n){if l{if n-l>g{g=n-l;show_message_ext("",l,n,g)}}l=n} ``` Script `p` is below: ``` r=1a=argument0for(i=2i<a;i++){if a mod i=0r=0}return r} ``` [Answer] # Perl, 87 bytes (*using a module*) ``` use Math::Prime::Util":all";$l=2;forprimes{if($_-$l>$m){say"$l $_ ",$m=$_-$l}$l=$_}1e14 ``` I wrote the module, but we'd have to add an extra 565,000 characters to the tally. Mostly posting for fun, but also to give a performance alternative since I don't see any so far using builtins. 4.6s for gaps to 1e9, 36s for gaps to 1e10, 6.5min for 1e11. Pari/GP 2.8 can be done basically the same way, albeit over 2x slower: ``` l=2;m=0;forprime(p=2,1e14,if(p-l>m,print(l," ",p," ",m=p-l));l=p) ``` [Answer] # Perl 153 Short code: ``` $i=$a=2;while($a=$i++){if(p($i)){if($m<$m2=$i-$a){$m=$m2;print"$a $i $m$/"}}}sub p{$d=2;$s=sqrt$_[0];while(){return 0if!($_[0]%$d);return 1if$d>$s;$d++}} ``` easy to Read: ``` $i=$a=2; while($a=$i++){ if(p($i)){ if($m<$m2=$i-$a){ $m=$m2; print"$a $i $m$/" } } } sub p { $d=2; $s=sqrt$_[0]; while(){ return 0if!($_[0]%$d); return 1if$d>$s; $d++; } } ``` ]
[Question] [ Let \$p(x)\$ be a polynomial. We say \$a\$ is a **root of multiplicity \$k\$** of \$p(x)\$, if there is another polynomial \$s(x)\$ such that \$p(x)=s(x)(x-a)^k\$ and \$s(a)\ne0\$. For example, the polynomial \$p(x)=x^3+2x^2-7x+4=(x+4)(x-1)^2\$ has \$1\$ and \$-4\$ as roots. \$1\$ is a root of multiplicity \$2\$. \$-4\$ is a root of multiplicity \$1\$. ## Task Given a nonzero polynomial \$p(x)\$ and a root \$a\$ of it, find the multiplicity of \$a\$. The coefficients of \$p(x)\$ are all integers. \$a\$ is also an integer. You may take the polynomial in any reasonable format. For example, the polynomial \$x^4-4x^3+5x^2-2x\$ may be represented as: * a list of coefficients, in descending order: `[1,-4,5,-2,0]`; * a list of coefficients, in ascending order:`[0,-2,5,-4,1]`; * a string representation of the polynomial, with a chosen variable, e.g., `x`: `"x^4-4*x^3+5*x^2-2*x"`; * a built-in polynomial object, e.g., `x^4-4*x^3+5*x^2-2*x` in PARI/GP. When you take input as a list of coefficients, you may assume that the leading coefficient (the first one in descending order) is nonzero. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Testcases Here I use coefficient lists in descending order: ``` [1,2,-7,4], 1 -> 2 [1,2,-7,4], -4 -> 1 [1,-4,5,-2,0], 0 -> 1 [1,-4,5,-2,0], 1 -> 2 [1,-4,5,-2,0], 2 -> 1 [4,0,-4,4,1,-2,1], -1 -> 2 [1,-12,60,-160,240,-192,64,0], 2 -> 6 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` Ærċ ``` [Try it online!](https://tio.run/##y0rNyan8//9wW9GR7v@hh5cfWqr0/3@0oY6Rjq65jkmsjgIaW9dEx1RH10jHgDDXRMcAJGCiYwgSMoSqMDTSMQOKGwIJIxMQwxIoAFQa@99QRwGoXMFARwHIMgJyQBQA "Jelly – Try It Online") Takes input as a list of coefficients in ascending order. The Footer on TIO reverses each of the test cases to fit this. ## How it works ``` Ærċ - Main link. Takes a polynomial P on the left, and a root r on the right Ær - Calculate the roots of P, with repeats ċ - Count the number of times r appears in the list of roots ``` [Answer] # JavaScript (ES7), 62 bytes Expects `(root)(polynomial)`, where *polynomial* is a list of coefficients in ascending order. ``` (r,s=0)=>g=p=>s?-1:1+g(p.map((c,i)=>(s+=c*r**i,c*i)).slice(1)) ``` [Try it online!](https://tio.run/##lZHBasMwDIbveQod5VROI@N1dMPZaU8Rcgiek3qkdbBHXz@zYYPBto7pIMSvT78Eeh2vY7LRr2/yEl7cNpkNIyXTCtPNZjVdepL8wLsZ1@Y8roiWfG5h2hlbx7r2ZGsvRJMWbx2yENtjXwH00DMpkvekBwKGHyLr@z2ob7DUv8L8CUtNdyQVtVlv/wPzX2d8hdVtZ01twTVxGeByOt9yZkWHPME5KV2KYxb0x6YBCnyohqqZQnwe7Qmxh5UgwiDAdGDDJYXFNUuYccIo8j@iu7qYHIoc2zs "JavaScript (Node.js) – Try It Online") ### How? This simply recursively computes the successive derivatives of the polynomial: $$P\_{k+1}(x)=\frac{d}{dx}P\_k(x)$$ until \$P\_k(r)\neq 0\$ and returns the number of iterations. ### Commented ``` ( // outer function taking: r, // the root r s = 0 // the sum s of the polynomial evaluation ) => // g = p => // inner recursive function taking the polynomial p[] s ? // if s is not equal to 0: -1 // stop the recursion and decrement the final result : // else: 1 + // increment the final result g( // do a recursive call with the derivative of p[]: p.map((c, i) => // for each coefficient c at position i in p[]: ( // s += // add to s: c * // the coefficient multiplied by r ** i, // the root raised to the power of i c * i // set the new coefficient to c * i ) // ).slice(1) // end of map(); remove the leading term ) // end of recursive call ``` --- # 59 bytes A version without `slice()` suggested by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh). ``` (r,s=k=0)=>g=p=>s?~k:g(p.map(c=>(s+=0|c*r**i,c*i++),i=k--)) ``` [Try it online!](https://tio.run/##lZHBSsQwEIbvfYo5Ju2km4S4ojL15FOUHkpMu7XrJiSyJ/HVawIKgrrifxiGn2/@GZin8TwmG5fwIk7@0W0TbSxiopUkp26mQF26f1tvZxba5zEwSx1LDclXW8e6XtDWS9NwXGgVgvPtrq8AeugVahTXaAYEBT8o@7sd6G@wML/C6hMWBq9QaJTZl/@B1V9nfIX15WSDsuAGVRlQ5XR1KVlp3OcJlYs2pbnJhvnYNECB99VQtZOPD6M9MNZDQIgwcKAOrD8lf3Tt0c9sYpHnZ0R3djE5xrO2dw "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 65 bytes ``` f=lambda p,r,c=0:(q:=[c:=b+c*r for b in p])!=c==0and-~f(q[:-1],r) ``` [Try it online!](https://tio.run/##bY7BbsMgDIbveQqPE3SmAka7DYm@SJYDSRsViRJKo0m79NVTmDa1k@aDZX3@/Mvpaz5O8eUt5WUZbXCnfu8gYcbBCkPPxraDsf3zsMowThl68BFSx57sYK1wcc@vIz23hssOM1uqEqpCCGlaiQr5K@oOQQLfgfqDuK5MVsY1bpArFAWLf@n9/pGqH1ejqFyjrBtZwx8OpMJt2cvSlK7DewH6HrBtyrfry5x9omx9ScHPlHxEwkwDpTxOYOHkEj18uoDh1@A7wti3kbKPMx3pyjOc2HID "Python 3.8 (pre-release) – Try It Online") Divides by the linear factor X-root and recurses if the remainder is zero. [Answer] # [Factor](https://factorcode.org/) + `math.polynomials`, 58 bytes ``` [ [ 2dup polyval 0 = ] [ dup pdiff swap ] produce length ] ``` [Try it online!](https://tio.run/##lZHBTsQgEIbvfYrfB2CzkFqjxr0aL16Mp80eCKVusxQQqGbT7LPXgeweNE3UIZMhf@bjB6aTKrkwv748PT/e4aCD1QaDTPuVd@Zo3dBLExH1@6it0hEyRqcifNApHX3obcJ9VU0VKCZwyhrsBoK2J1oLcQW2gTgDrP6dKAA/A@uSTOA6s8vIN4D/FbhcSfzXgfFiw/IL6sysqfygFhwa6uW3AqImN96QkOvlGwrQVKdq3mIL0Y4eeSAf0hD6gB2JRWv7rkP8lJ4kH1w7Kg2j7VvaYzdPdFAZ2GaghhWU0TLMXw "Factor – Try It Online") Takes `root polynomial` where the polynomial is given as a sequence of coefficients in ascending order. Uses the method described in Arnauld's [JavaScript answer](https://codegolf.stackexchange.com/a/253297/97916). `polyval` evaluates a polynomial given a value and `pdiff` computes the derivative of a polynomial. `produce` creates a list of successive derivatives until one evaluates to nonzero. Then take the length of the list. [Answer] # [Rust](https://www.rust-lang.org/), 105 bytes ``` |a,r|{let mut j=0;while 0==(0..).zip(&mut*a).map(|(i,c)|{let d=*c*r.pow(i);*c*=i as i32;d}).sum(){j+=1}j} ``` [Try it online!](https://tio.run/##jY5Ra4QwEITf/RXTlyNrY4hWLNeQ/pGjlHAXaeS01igHp/52m9i@FroPy7DMfDvD5MctqTu0xnWMMCcIc7Uj6hfUHTu003hyT8UbR9iE7BWTd3cLjW0xfFjm6A0mNFqq24e7WkitmRSCxN31OyA1JFrTs4U5fqafyEWn53QQ/eeNOVJBawfj4xN1WUn4qWU0N486X5t1U8ley3hvh/Hdfj2wegfjVHJkzxwFRx4q5hQkqf@Zs5Ji4k@35KhiIj@GQFHKKKt43NUvpAiMKjDWZPsG "Rust – Try It Online") It's a `fn(&mut[i32], i32) -> usize`. Uses the same approach as Arnauld's JS answer. [Answer] # Mathematica, 19 bytes ``` #~Roots~x~Count~#2& ``` Takes inputs as equations: `polynomial == 0, x == root`. If this is not allowed: ## Mathematica, 27 bytes: ``` Count[Roots[#==0,x],x==#2]& ``` [View them on Wolfram Cloud!](https://www.wolframcloud.com/obj/22ebb3fe-5609-426e-aa37-3e17c5980f8a) [Answer] # [Maxima](http://maxima.sourceforge.net/), 29 bytes ``` f(p,a):=hipow(factor(p),x-a); ``` [Try it online!](https://tio.run/##hc9NCsIwEAXgvafoMslkoEmnKVq8SiEIwSxqQymY28ckKqggXb3F@5if2UY/25QcC9Ly0/nqw3Jnzl62ZWWBy4iWjyms/rYxx@LUgRZx0jiICCQbxfl4@NsifdeEJArqK8pUNu2uULtCf4rSmmoInvLlQOWDfoYNqMrBBkybo0dVk0BTyQ7Vsf4Dht570gM "Maxima – Try It Online") Factorises \$p(x)\$, taken as a built-in polynomial object, and returns the exponent of \$x-a\$. [Answer] # [SageMath](https://doc.sagemath.org/), 29 bytes ``` lambda p,a:dict(p.roots())[a] ``` [Try it online!](https://sagecell.sagemath.org/?z=eJxLs43h5cpJzE1KSVQo0Em0SslMLtEo0CvKzy8p1tDUjE6M5eXi5SpQsFWoiDPWNtKqiDPSNdeq0DYBChZl5pVopGkU6BhqagIAA-UUNA==&lang=sage&interacts=eJyLjgUAARUAuQ== "SageMath – Try It Online") Inputs a polynomial \$p\$ and a root \$a\$ of \$p\$. Uses `p.roots()` which returns the roots of \$p\$ along with their multiplicity as a list of \$2\$-element tuples. Turning this into a dictionary requires only a simple lookup of the root to find its multiplicity. [Answer] # [Desmos](https://desmos.com/calculator), 103 bytes ``` k=l.length L=[0...k-1] I=[n...k-1] f(l,R)=L[[0^{total(R^{[0...k-n]}I!l[n+1...]/(I-n)!)^2}forn=L]=0].min ``` [Try It On Desmos!](https://www.desmos.com/calculator/nsdbxpa3hv) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/gntg6ssytd) Function \$f(l,R)\$ takes in a list of coefficients in ascending order and the root \$R\$. Uses Arnauld's strategy of repeatedly taking derivatives, so go upvote his answer too! There's probably a way of shortening the `L=[...]` `I=[...]` part since they are so similar but I don't see it at the moment. Might post an explanation if I feel like it, though if you understand Desmos enough it shouldn't be too hard to decipher. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` W¬↨⮌θη≔ΦEθ×κλλθI⁻LALθ ``` [Try it online!](https://tio.run/##LYzLCsIwFET3fsVd3gsptKUUpCsVBMGKiLvSRSihDca0ebR@fkzEzczhMMwwcTvMXIXwmaQSgLfZ45E7gQ@xCRvbEIOJiODgnBw1nqXywmLLFzQMnvItHL4YKKIUDAw1u7uV2uOJO4@t1KvDq9Cjn/Cil9VjWv6FicfUhNB1OYO6YpAV@5JBWeUJ6yR/FF3RR9@HbFNf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses the same differentiation trick as @Arnauld's answer. ``` W¬↨⮌θη ``` While the root is a root of the current polynomial (defaulting to the input polynomial) (using base conversion of the reversed polynomial to evaluate it)... ``` ≔ΦEθ×κλλθ ``` ... differentiate the polynomial. ``` I⁻LALθ ``` Output the difference in degree of the input and final polynomial. [Answer] # [Raku](https://raku.org/), 51 bytes ``` {((|@^p,0),*[^(*-1)].produce(*×$^r+*)...*[*-1])-2} ``` [Try it online!](https://tio.run/##bczhCoIwFAXgVzmIxLbc2MYygpTeQzSklAJDsfoh6nP0QD3YmiFB4J/L5Tvn3qZoq9DeOqxKRLYnZDhkTSBpwJKMMK5oKpq2Pj9PBWHvl5@1a0aFECxxWUq5Hu097@CRXlyK/DzSAL145NdqRBSjLzH4x9FDWbcgewUNvoWJAyhX/ANuZuEGG3AN6VAumFow/TUDOamBmlxNT39lpRG6VLmhzbTsHJj52H4A "Perl 6 – Try It Online") This is an anonymous function that takes a polynomial as an array of coefficients in descending order, and a root. The arguments are stored in the placeholder variables `@^p` and `$^r` respectively. The outermost parenthesized expression is a list, where each element is a list of polynomial coefficients followed by a remainder. `(|@p, 0)` is the first element of the list, the input polynomial with a zero remainder appended. Each successive term is the previous polynomial divided by \$x - r\$. The iteration ends when the the remainder term, `*[*-1]`, is nonzero/truthy. `*[^(*-1)]` strips off the final remainder element of the previous coefficient/remainder list, and `.produce(* × $^r + *)` performs polynomial long division by \$x - r\$. Finally, the `- 2` coerces the entire list of polynomials to a number, its length, and subtracting 2 gives the multiplicity of the root. [Answer] # [GeoGebra](https://geogebra.org/calculator), 66 bytes ``` f=x InputBox(f k InputBox(k l=Flatten(Factors(f l(IndexOf(x-k,l)+1 ``` Input the polynomial in the first Input Box, and the root in the second Input Box. All the heavy lifting is done by the built-in `Factors`. [Try It On GeoGebra!](https://geogebra.org/calculator/qfzq8d9g) [Answer] # [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I don't understand the challenge! So a port of Arnauld's solution will have to do for now. ``` T?J:Òß¡T±X*VpY X*YÃÅ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=VD9KOtLfoVSxWCpWcFkgWCpZw8U&input=WzAsNjQsLTE5MiwyNDAsLTE2MCw2MCwtMTIsMV0KMg) ``` T?J:Òß¡T±X*VpY X*YÃÅ :Implicit input of array U & integer V T? :If T (initially 0) is truthy (not 0) then return J : -1 : :Else Ò : Negate the bitwise NOT of (i.e., increment) ß : Recursive call with argument (The unchanged V is implicit) ¡ : Map each X at 0-based index Y in U T± : Increment T by X*VpY : X multiplied by V raised to the power of Y X*Y : Return X*Y à : End Map Å : Slice off the first element ``` [Answer] # [J](https://www.jsoftware.com), ~~14~~ 11 bytes -3 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) ``` +/@E.1{::p. ``` Accepts a list of coefficients in ascending order [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxWlvfwVXPsNrKqkAPIrJbkys1OSNfId5QIU3BBKg-3gRIGSrEGykYQlQsWAChAQ) ``` +/@E.1{::p. 1{::p. NB. monadic fork p. NB. computes boxed result of multipler;roots 1{:: NB. fetches and lists contents of second box +/@E. NB. x E. y finds occurrences of x in y, returns boolean list @ NB. atop, executes E. dyadically and +/ monadically +/ NB. sum reduce ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr/), 23 bytes Naïve solution: ``` (P,r)->valuation(P,x-r) ``` [Answer] # [Scala](http://www.scala-lang.org/), 116 bytes Port of [@corvus\_192's Rust answer](https://codegolf.stackexchange.com/a/253300/110802) in Scala. --- Ungolfed version. [Try it online!](https://tio.run/##hZBBa8MgFIDv@RWPnrSzkoTQsgYLPe6w09hp9PCWmNRgbFDbspX89kyTHQd74PMpnx@@5yrUOF0@O1l5eEVl4JEA1LKBPhwI2tbt4Wgtfn28eatMe6J7eDfKgwhkckMNzR7IQrwYf2IQMgVxiHuApgdBZqk43NBCJ9LyflZaEpLC1XilAbmWpvVnyr/VQJDyHodHhU4Sxar5mYZaVOse/ZkPlzuxTFHuL8FeIlF0LVRZj9xdeyFS2j2JrOzGCUKgc9J60iyfIwWDzY5BziCjcYEQkNPkX3JTzGj2J5oy2EY8ew50XqSx3MbLufo15LNguwiGMESvDVkdtQYvnYfYrIMhmmu@itSYjNMP) ``` {(a,r)=>var j=0;while((0 until a.length).zip(a).map{case(i,c)=>val d=c*math.pow(r,i).toInt;a(i)*=i;d}.sum==0)j+=1;j} ``` Ungolfed version. [Try it online!](https://tio.run/##hY9NS8QwEIbv/RXvMVmzpS2lsoUKHj14Ek@yh7GfKf0izbqo9LfXJFuhB8FAMpOZZ968mXPqaF3H97bMNZ5JDvj2gKKs0JsLI1XPKR6Vos@3F63kUJ95itdBamSOBD6oQ5WC3aCnQZ8FzMmRPdhoOTASULbiJuyMQms6wXa/NrIrwViAy6BlB/K7cqh1w/0vOTHifk/T9pxdOc2GlgL5TvPXS2F0cxyMf93403hlSkByX4/GzA4lJjkOGeSuVmz54s@XHpnxx43Nuwzh1mhdXDwXaJ5LpVl1@zmLBY73ApFAyO228xH/nzzGDg3/RAOBxOLhydBRHNg0sUWXbQqRE0iswOIt6/oD) ``` object Main { def main(args: Array[String]): Unit = { val f: (Array[Int], Int) => Int = { (a, r) => var j = 0 while ((0 until a.length).zip(a).map { case (i, c) => val d = c * math.pow(r, i).toInt a(i) *= i d }.sum == 0) j += 1 j } assert(f(Array(4, -7, 2, 1), 1) == 2) assert(f(Array(4, -7, 2, 1), -4) == 1) assert(f(Array(0, 64, -192, 240, -160, 60, -12, 1), 2) == 6) } } ``` ]
[Question] [ I came across this picture the other day: (Credit to Josep M Batlle I Ferrer) [![N(f(x)=cosh(x)-1)](https://i.stack.imgur.com/0W6Yx.png)](https://i.stack.imgur.com/0W6Yx.png) Your job is to generate this picture. This graph is generated by repeatedly applying newton's method to the graph of: $$f(x)=\cosh(x)-1$$ In other words, repeatedly apply the following function to every point till the rectangular distance is less than some limit to a attractor: $$g(x)=\frac{x \cdot \sinh(x) - \cosh(x) + 1}{\sinh(x)}$$ The process is described in psuedocode below: ``` let n be the maximum number of iterations for every point (as a complex number) in the image: repeat n times: point = (point * sinh(point) - cosh(point) + 1) / sinh(point) if the rectangular distance between the point and any attractor is less than 0.01: break end if end repeat color the point in the image depending on the nearest attractor and the number of iterations required ``` The rectangular distance is defined as `max(abs(dx), abs(dy))`. We use rectangular distance instead of straight line distance so we get the wave shapes that make this graph so beautiful. There is a attractor at `0+n*2i*PI` for any integer N. Thus at even increments of 2 PI in the imaginary direction. # Rules * Your graph must include the area from `[-0.75, -0.75 + PI]` to `[0.75, +0.75 + PI]`. * Resolution over this needs to be at least 256 by 256. Either characters or pixels. If you decide to cover a larger area you need to increase the resolution in proportion. * Use at least 20 iterations. * Both adjacent iteration counts and adjacent attractors need to be drawn in distinct colors. You must use at least 3 different colors. Coloring should soley be based on the attractor and iteration count. * If any point causes a division by 0 or another math error, you may choose to render anything at this point. This is considered undefined behavior. * Displaying a image, saving a image, or drawing ASCII art are all acceptable, as long as the other rules are met. If you draw ASCII art characters need to be ANSI colored. * Please include a screenshot of the result in your answer This is code golf, shortest answer wins. ASCII art answers *do not* compete against graphical answers in the same language. # Background info * [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method) * [Newton's fractal](https://en.wikipedia.org/wiki/Newton_fractal) * [Hyperbolic Trignometry](https://en.wikipedia.org/wiki/Hyperbolic_functions) * [Julia set](https://en.wikipedia.org/wiki/Julia_set) [Answer] # [Desmos](https://desmos.com/calculator), ~~401~~ ~~375~~ ~~357~~ 353 bytes -26 bytes thanks to [@aiden-chow](https://codegolf.stackexchange.com/users/96039/aiden-chow) -18 bytes thanks to [flexabrotnt#1409](https://discordapp.com/users/339104210194792459) ``` H(u,v)=(u.xv.x-v.yu.y,u.xv.y+v.xu.y) F(u,v)=(u.xv.x+u.yv.y,u.yv.x-u.xv.y)/(v.x²+v.y²) E(z)=e^{z.x}(cos(z.y),sin(z.y)) C(z,k)=H((1/2,0),E(z)+kE(H((-1,0),z))) N(z)=F(H(z,C(z,-1))-C(z,1)+(1,0),C(z,-1)) G(z)=max(z.x²,z.y²) Y(z)=N(N(N(N(N(z))))) Z(z)=Y(Y(Y(Y(z)))) l=[0...2] O=hsv(l110,1,1) P=Z((x,y)) X=round(P.y/(2π)) G((0,2Xπ)-P)<0.01\{\mod(X,3)=l\} ``` [Try It On Desmos!](https://www.desmos.com/calculator/uskzayywop) [Before golfing](https://www.desmos.com/calculator/aei4dlbu0i) [![Rendered in desmos](https://i.stack.imgur.com/8FjSG.png)](https://i.stack.imgur.com/8FjSG.png) [Answer] # Rust + [Num](https://autumnai.github.io/cuticula/num/index.html) ASCII Art - ~~420~~ 413 bytes *-6 bytes thanks to @LF* ``` use{num::complex::*,std::f32::consts::*};(0..255).any(|y|(0..512).any(|x|if let Some(n)=(0..99).scan(Complex::new(x as f32/256.0-1.,y as f32/256.0-0.5+PI),|s,l|{*s=*s-(s.cosh()-1.)/s.sinh();Some((*s,l))}).filter(|s|s.0.re.abs().max(s.0.im-((s.0.im/(2.*PI)).round()*2.*PI).abs())<0.01).next(){print!("\x1b[{:0<2};{:0<2}m0",30+n.1%8,40+((n.0.im/PI/2. + 36.).round()%8.)as usize)}else{print!("0")}>())||print!(" ")>()); ``` [![enter image description here](https://i.stack.imgur.com/SwuRQ.png)](https://i.stack.imgur.com/SwuRQ.png) [Answer] # Python + Pygame, ~~410~~ 392 bytes (Example Submission) *-16 bytes thanks to wizzwizz4 and others* ``` from pygame import* from cmath import* w=256;s=Surface((w,w));f=lambda p:p-(cosh(p)-1)/sinh(p);g=lambda t:round(t.imag/pi/2)*pi*2j;h=lambda p:max(abs(p.real),abs(p.imag))>0.01 for x in range(w): for y in range(w): t=x/w-0.5+(y/w-0.5-pi)*1j for i in range(99): try:t=f(t);1/h(g(t)-t) except:break s.set_at((x,y),[0,[w-1,5,5],[9,w-1,9]][(round(t.imag/pi/2)+i)%3]) image.save(s,"f") ``` Result will be saved as a TGA file named `"f"`: [![enter image description here](https://i.stack.imgur.com/b4dYs.png)](https://i.stack.imgur.com/b4dYs.png) [Answer] ## JavaScript (ES6), ~~271~~ ~~260~~ ~~253~~ 251 bytes ``` c=>{z=c.getContext`2d`;for(i=384;i--;)for(j=384;i--;)with(Math){x=i/256-.75;y=j/256-.75+PI;for(k=10;k<30>(x*x<1e-4&abs(y-2*PI*(v=round(y/2/PI)))<.01);k++)w=cosh(x)+cos(y),x-=sinh(x)/w,y-=sin(y)/w;z.fillStyle=`#0${(k+v%10)*3%10}9`;z.fillRect(i,j,1,1)}} ``` Takes as parameter a 384×384 canvas on which to draw the result. Demo, with whitespace for readability and animation: ``` f = async c => { z = c.getContext`2d`; for (i = 384; i--; ) { for (j = 384; j--; ) with (Math) { x = i / 256 - .75; y = j / 256 - .75 + PI; for (k = 10; k < 30 > (x * x < 1e-4 & abs(y - 2 * PI * (v = round(y / 2 / PI))) < .01); k++) w = cosh(x) + cos(y), x -= sinh(x) / w, y -= sin(y) / w; z.fillStyle = `#0${(k+v%10)*3%10}9`; z.fillRect(i, j, 1, 1); } await new Promise(resolve => requestAnimationFrame(resolve)); } }; f(c); ``` ``` <canvas width=384 height=384 id=c> ``` Edit: Saved 11 bytes thanks to @Ausername. Saved 7 bytes thanks to @Steffan. Saved 2 bytes thanks to @Dingus. [Answer] # [Pyxplot 0.8.4](http://pyxplot.org.uk/), ~~190~~ ~~188~~ 186 bytes ``` se nu c su g(x,y){z=x+y*i fo n=1to20{z=z-coth(z)+csch(z) if(Re(z)**2<1e-4)*cos(Im(z))>cos(.01){ret ceil(Im(z)/pi-.5);} } } se sa gr 1e3x1e3 se colm hsb c2:c1:1 p[-1:1][2:4]g(x,y):n w col ``` Conveniently for code golf, most commands in Pyxplot may be abbreviated zealously. By default (empty `.pyxplotrc` config file), output is written to `pyxplot.eps`. [![enter image description here](https://i.stack.imgur.com/SEHFB.png)](https://i.stack.imgur.com/SEHFB.png) If the text and axis labels produced by default must be removed, replace the last line with ``` se ax xy in p[-1:1][2:4]g(x,y):n t''w col ``` at a cost of 15 bytes. Add `se s s` for a square aspect ratio. Some mathematical simplifications are used. Firstly, we write \$g\$ as \$g(z) = z-\coth(z)+\mathop{\rm csch}(z)\$. Secondly, we note that \$\max(\lvert\Delta x\rvert, \lvert\Delta y \rvert) < t\$ implies that both \$\lvert\Delta x\rvert < t\$ and \$\lvert\Delta y\rvert < t\$ and treat these two constraints separately: * \$\lvert\Delta x\rvert = \lvert x-0\rvert = \lvert x\rvert\$, so the first constraint becomes \$x^2<t^2\$, which is shorter in Pyxplot than \$\lvert x\rvert < t\$ (which would be `abs(Re(z))<.01`). * \$\lvert\Delta y\rvert = \lvert y-2k\pi\rvert\$ for some integer \$k\$. Observe that the attractors lie at points where the cosine function is maximal, i.e. \$\cos(2k\pi)=1\$. Thus the constraint on \$y\$ may be written as \$\cos(\lvert y-2k\pi\rvert) > \cos(t)\$, which simplifies to \$\cos(y) > \cos(t)\$ by the symmetry and periodicity of the cosine function. For the plot, an HSB colourmap is used. At each point the hue is determined by the number of iterations (`n` in the code), automatically rescaled to span the range from 0 and 1 (i.e. the full range of hues). The saturation is determined by the value of \$2k\$ (the return value of `g(x,y)`) for the point's attractor, again rescaled to span the full range of saturations. The brightness is fixed at maximum. An iteration limit of 20 is imposed. Red and orange hues become more predominant at the expense of green and blue as this limit is increased. In theory, it is possible to omit `[-1:1][2:4]` in the last line of the code (saving 10 bytes), have Pyxplot apply its default axis ranges (\$-10\le x,y\le 10\$), and increase the grid resolution (`1e3x1e3`) to compensate. In practice, setting the resolution to `4e3x4e3` exhausted the available memory (16 GB RAM plus 20 GB swap) on my machine. ### Ungolfed code ``` set numerics complex subroutine g(x, y) { z = x + y * i for n = 1 to 20 { z = z - coth(z) + csch(z) if Re(z)**2 < 1e-4 and cos(Im(z)) > cos(1e-2) { return ceil(Im(z) / pi - 0.5) } } } set samples grid 1e3 x 1e3 set colourmap hsb c2:c1:1 plot [-1:1] [2:4] g(x, y):n with colourmap ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 128 bytes ``` Image@Table[n=0;x+y*I//.z_/;Max@Abs@{Re@z,Mod[i=Im@z,Pi,n+=8t;-1]}>2t:>z-Coth@z+Csch@z;i~Hue~n,{y,-1+Pi,1+Pi,t=.005},{x,-1,1,t}] ``` [![enter image description here](https://i.stack.imgur.com/sw84K.png)](https://i.stack.imgur.com/sw84K.png) ]
[Question] [ # Background Famously, the acronym `GNU` stands for `GNU's Not Unix`. [1](https://en.wikipedia.org/wiki/GNU) It's recursive because, after expanding it once, it still contains the acronym `GNU`, and so must be exanded again: ``` (GNU's Not Unix)'s Not Unix ``` And so on, ad infinitum. Visualizing this, we get a kind of [Droste effect](https://en.wikipedia.org/wiki/Droste_effect): ``` ┌────────────────────────────────────────────┬───────────┐ │┌──────────────────────────────┬───────────┐│'s Not Unix│ ││┌────────────────┬───────────┐│'s Not Unix││ │ │││┌──────────────┐│'s Not Unix││ ││ │ ││││GNU's Not Unix││ ││ ││ │ │││└──────────────┘│ ││ ││ │ ││└────────────────┴───────────┘│ ││ │ │└──────────────────────────────┴───────────┘│ │ └────────────────────────────────────────────┴───────────┘ ``` Recursive acronyms need not recurse on the first word, or only once. For example: * `YOPY`: `Your Own Personal YOPY` * `PIPER`: `PIPER Is PIPER Expanded Recursively` Visualized: [![PIPER](https://i.stack.imgur.com/Xgf0e.png)](https://i.stack.imgur.com/Xgf0e.png) # Challenge ## Input You will be given two inputs: 1. A string whose space-delimited words form a recursive acronym. That is, if you form a string from the first letter of each word, that string is guaranteed to be either: * One of the words of the input string (it may occur more than once). * A prefix of one or more of those words (e.g. `GNU` is a prefix of `GNU's`) * The casing will match exactly 2. A non-negative integer -- the number of times to recursively expand. Given `0`, you'll return the input unaltered (or "framed" once, in its entirety). Given `1`, you'll expand once. Etc. ## Output The output is the input string with all instances of the acronym visually expanded, recursively, the specified number of times. You must use some visual effect to "frame" the nesting -- at minimum, distinct start and end delimiters like parentheses. Ascii boxing of some sort, as in the examples above, is also fine. As would be outputting an actual image that showed the nesting. I'm flexible as long as the nesting is in fact visualized. For clarity, parenthesized output would like this: ``` (((GNU's Not Unix)'s Not Unix)'s Not Unix)'s Not Unix ``` You are guaranteed that parentheses will never be part of acronym. Other than alphanumeric characters, the acronym will only contain apostrophes, commas, quotes, question marks and exclamation points, and those will only occur as valid punctuation (e.g., a question mark will not appear at the beginning of a word). This is code golf, fewest bytes wins, no loopholes. ## Test Cases This assumes you're using a parentheses visualization. Format for test cases: 1. Input string (the acronym) 2. Input integer (recursion) 3. Expected Output --- 1. `GNU's Not Unix` 2. `0` 3. `GNU's Not Unix` --- 1. `GNU's Not Unix` 2. `2` 3. `((GNU's Not Unix)'s Not Unix)'s Not Unix` --- 1. `YOPY Own Personal YOPY` 2. `1` 3. `(YOPY Own Personal YOPY) Own Personal (YOPY Own Personal YOPY)` --- 1. `YOPY Own Personal YOPY` 2. `2` 3. ``` ((YOPY Own Personal YOPY) Own Personal (YOPY Own Personal YOPY)) Own Personal ((YOPY Own Personal YOPY) Own Personal (YOPY Own Personal YOPY)) ``` --- 1. `YourYOPY Own Personal YOPY` 2. `2` 3. ``` YourYOPY Own Personal (YourYOPY Own Personal (YourYOPY Own Personal YOPY)) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~33~~ 32 bytes -1 byte thanks to Bubbler. Anonymous infix lambda. Takes count as left argument and string as right argument. ``` {('\b',⊃¨⍵⊆⍨≠⍵)⎕R(1⌽')(',⍵)⍣⍺⊢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v1pDPSZJXedRV/OhFY96tz7qanvUu@JR5wIgW/NR39QgDcNHPXvVNTWASkAivYsf9e561LUIyKn9n/aobcKj3j6g3ke9ax71bjm03vhR20SgruAgZyAZ4uEZ/N9AIU1B3d0vVF29WMEvv0QhNC@zQp3LiARRQ5BopH9ApIJ/eZ5CQGpRcX5eYo4CSASqBb9kfmkRDgUA "APL (Dyalog Extended) – Try It Online") `{`…`}` "dfn"; number is `⍺` and text is `⍵`:  `⊢⍵` on the text:  `⍣⍺` repeat given number of times  `(`…`)⎕R(`…`)` PCRE **R**eplace:   `')(',⍵` the text prefixed by `")("`   `1⌽` cyclically rotated one step left (puts `")"` at end)   … with:   `≠⍵` The mask of non-spaces in the text   `⍵⊆⍨` characters runs in the text corresponding to runs of 1s in that   `⊃¨` first character of each  `'\b',` prepend PCRE for word boundary [Answer] # JavaScript (ES9), ~~88 85~~ 82 bytes Takes input as `(string)(n)`. ``` s=>g=n=>n?s.replace(eval(`/\\b${s.match(/(?<=^| )./g).join``}/g`),`(${g(n-1)})`):s ``` [Try it online!](https://tio.run/##lcyxCsIwFEDR3a8IIvge2NQ6iqmjW9vFQRBJrGmsxBdpahW03151VhTXy@EeVKN8XpWnOiC3010hOi9iI0jENPe80iercg26URZkuF5vBzfPj6rO9xDCfCY2d4Y8NMgPriQp29BIHEkY3AxQEGGLEqe@yx15ZzW3zkAB/UWyHHqWuJotqbz2EcaIvV9m8m5WabZi6YVYpivvSFn2Kk8b/WE/fd25@ua7Bw "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = string g = n => // g is a recursive function taking the counter n n ? // if n is not equal to 0: s.replace( // replace in s: eval( // each word matching: `/\\b${ // a word boundary followed by s.match( // the acronym which consists of /(?<=^| )./g // the letters that are preceded by // either a space or nothing at all ).join`` // joined together }/g` // ), // with: `(${ // the result of g(n - 1) // a recursive call })` // surrounded with parentheses ) // end of replace() : // else: s // end of recursion: just return s ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ ~~25~~ 22 bytes ``` ðìÐ#€нJðìs" (ÿ )"Iи.:¦ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8IbDaw5PUH7UtObCXi8Qp1hJQePwfgVNJc8LO/SsDi37/9/dL1S9WMEvv0QhNC@zgssIAA "05AB1E – Try It Online") To make sure we only match the acronym at the beginning of a word, we match an extra leading space. This results in extra spaces in the output, which is allowed. ``` ðì # prepend a space to the input Ð # triplicate #€нJ # acronymize (split on spaces, head of each, join) ðì # prepend a space to the acronym s # swap " (ÿ )" # surround with parentheses Iи # repeat the following second-input times: .: # replace the acronym with the parenthesized string ¦ # remove the leading space ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 20 bytes ``` !→⁰Ṡ¡§¤σΘom←w`J"()"Θ ``` [Try it online!](https://tio.run/##yygtzv7/X/FR26RHjRse7lxwaOGh5YeWnG8@NyM/91HbhPIELyUNTaVzM/7//2/0Xykyv7Qo0j8gUsG/PE8hILWoOD8vMUcBJKIEAA "Husk – Try It Online") Takes the number followed by the string. Outputs with parentheses, prefixing each expansion with a space. ### Explanation ``` !→⁰Ṡ¡§¤σΘom←w`J"()"Θ (Let X and Y denote the arguments.) Θ Take Y prefixed with a space; denote this Y'. !→⁰ Take element X + 1 of Ṡ¡ the infinite list created by iterating this function on Y': σ Take the argument and substitute m← the string containing the first character of Ṡ § w each space-separated word of Y', ¤ Θ prefixed with a space, with Ṡ § `J the characters of Y' placed between "()" '(' and ')', ¤ Θ prefixed with a space. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 48 bytes ``` {($^s,{S:g/$([~] $s~~m:g/<<./)/($s)/}...*)[$^x]} ``` [Try it online!](https://tio.run/##FchBC4IwGAbgv/IyPmIL2Q5Bh7BzNxVCSMSFBw1Bt9iCFHN/fdXxeZ6dG49xWrDrcY4rJ@2T9Xp6KOJ1aEA@hOmnNJVKKE5eqE1KuRc16bnZom8X9PjQHb11YJes9MjsC6UZZpaAVXlRIX8bFJ3z1rQj/sNwgz7ELw "Perl 6 – Try It Online") ### Explanation ``` { } # Anonymous block ( , ...*) # Construct infinite sequence $^s # starting with input string. { } # Compute next item by S:g/ / / # globally replacing $( ) # interpolated $s~~m:g/<<./ # first letters of each word [~] # joined (the acronym) ($s) # with input string in parens [$^x] # Take nth item ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` û╟;±å↕êg╥σç ``` [Run and debug it](https://staxlang.xyz/#p=96c73bf186128867d2e587&i=%22GNU%27s+Not+Unix%22,0%0A%22GNU%27s+Not+Unix%22,2%0A%22YOPY+Own+Personal+YOPY%22,1%0A%22YOPY+Own+Personal+YOPY%22,2%0A%22YourYOPY+Own+Personal+YOPY%22,2%0A&m=2) Regex is pretty nice. ## Explanation ``` D.\bxjMh+x:{R X → input D do the following n times, with the first input on stack .\b push "\b" (word boundary) xj split X on spaces M transpose h take first row to get abbreviation + add that to the boundary x:{ push X, embedded in braces R replace matches of the created regex with "(X)" ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~104~~ 96 bytes -7 bytes thanks to [@DeathIncarnate](https://codegolf.stackexchange.com/users/91386/deathincarnate), and another -1 byte thanks to [@wastl](https://codegolf.stackexchange.com/users/78123/wastl) ``` import re f=lambda s,n:n and re.sub('\\b'+''.join(c[0]for c in s.split()),f'({s})',f(s,n-1))or s ``` [Try it online!](https://tio.run/##jYy9DoIwGAB3n@ILS9tYCehm4uwGLAxEHMpPYw18bdoSNcZnr7jpoHG9u5y5@ZPGTQhqNNp6sP1C7gYxNp0Ax3GLILCbaeymhpK6bsiSkPisFdL2kBylttCCQnCxM4PylDEuCb27ByNc0vmwShmbIxeMVeippNE@K4mDTHsoUV0jnjC2@CrX77LKiwryC0LRW6dRDPAiEU//iT5PerI/wvAE "Python 3 – Try It Online") Explanation: ``` re.sub( '\\b'+''.join(c[0]for c in s.split()), # match all acronyms that starts on a word boundary '('+s+')', # replace with the original string in parenthesis f(s,n-1) # on the result of the (n-1)th recursion ) ``` This is the acronym expanded n times. ``` return n and recursive_case or base_case ``` This returns `base_case` if n is 0, and `recursive_case` otherwise. This works because in Python, `0` is Falsy and non-empty string is Truthy. * If n is 0, `n and recursive_case` short circuits to `False`, then `False or base_case` is evaluated which returns `base_case`. * If n is not 0, `n and recursive_case` evaluates to `recursive_case` which is Truthy, so `recursive_case or base_case` is short-circuited to `recursive_case`. [Answer] # [Perl 5](https://www.perl.org/) `-apl`, ~~49~~ 43 bytes ``` /./,$p.=$&for@F;for$a(1..<>){s/\b$p/(@F)/g} ``` [Try it online!](https://tio.run/##dYpBC4IwGEDv@xUfNDIhNw08meHJTqkXD0KXJSuEsW9sk4Tor7fsB3R5h/eekVblIXDG99Swkm7vaKu6WEnFLmPseIpfjl9v1PBdVcf88Q4FNWUUFZtRSWEBZw/rDVouHrx0HkbhZDg3feSgQQ@9nhaSkqHtBmifGjppHWqh4GfIgQw423/xg8ZPqF1ILjlLszQkRokv "Perl 5 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 48 bytes ``` ~(`$ ¶($%`) (.).*? (?=.*¶) $1 ^(.+)¶ 1A`¶$1+`\b ``` [Try it online!](https://tio.run/##dYo9CsIwGED37xTfUDFtIDXuUhxK6dKGQoeCaKrNUCip9Efr4rFygFwsKm6C2@O9N6ip1TV3IaPWMBqeSCLdk0gP0BriraQPhPksiJBEOxZY44PH4UgY9a0BvpfWeJzKw9m5DSRZuR4x6ycsdbvA9ldwqHJRYX7XKNQw9rru8GPe5//Qz8PfKFIRF5iO@IV4uda6UQ0W6jIPY3tT3eMF "Retina – Try It Online") Takes the expansion count and acronym string on separate lines. Explanation: ``` ~(` ``` After performing the script, interpret the result as a new script to be evaluated on the original input. ``` $ ¶($%`) ``` Append a space to the string, and append a copy of the string wrapped in `()`s on a new line. ``` (.).*? (?=.*¶) $1 ``` Turn the string into the acronym. ``` ^(.+)¶ 1A`¶$1+`\b ``` Replace the count with a Retina repeat instruction, and also prefix an instruction to delete the count from the original input. For example, the result of evaluating the inner script on the input `2` `GNU's Not Unix` is ``` 1A` 2+`\bGNU (GNU's Not Unix) ``` This deletes the count from the original input, and then performs the acronym expansion twice. [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/), 180 bytes ``` h s/(.)[^ ]* */\1/g G s/$/\n/ G h N s/.*\n// tx :l s/^(.*)\n(.*)\b\1(.*)\n(.*)\n(.*)/\1\n\2\n(\5)\3\4\n\5/ tl s/\n(.*)\n(.*)\n/\n\1\2\n\n/ x tx :x s/.// x tl s/.*\n(.*)\n.*\n.*/\1/ ``` [Try it online!](https://tio.run/##dY7NCsIwEITveYo9CNqCDfHn4r2Il1oED8VVUBu0UBJpqsaXN25SDyJ6WebL7M7EyNK5MzN8kESbHWxjiDkKfmJzeutxVJzUmWVESUzEWWvZrCbcDZI4QhXmAcUHhUkpqHBEgNMIxzghmtK1P/3co0xyhN/0ZTbkW1/HA9Xv5m7XqyT80Ll5tu4byHQLa1VZxr5YCFboawPLu4JcNkarfQ3FMi/I8R6pX95fo4v77@aLPF3BwkAnUnvZq1KWsJLHa2Oqm6wfvvmpL22llXHD9AU "sed 4.2.2 – Try It Online") Well, finding one part of input in another part of input is not that simple in `sed`. Input is on two lines: first line is the acronym string; second line is number of expansions in unary. [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes ``` f=lambda s,n:n and re.sub('\\b'+''.join(zip(*s.split())[0]),'('+s+')',f(s,n-1))or s import re ``` [Try it online!](https://tio.run/##JY69rsIwDIVneAqri5PbUAEjEkjtUrEASwcEDKnaXoyKEyVB9@flS1Mm@3xHx8f2L9wNr4eh2/b6WTcavOINg@YGXJv5Vy3weq0xRcwehlj8kxVfPvO2pyCkvCxvUqHA1KcoUXVijC9WUhoHfk5Pa1wY7wxd1EAMl6Q8VOjhYAJUTL@JguR8PJ3h@MNwap03rHuIJDrlvsxh72Ga@bcmjrTQ96Iq8jHftA6m9ePdNvNZbKKpaalWah3RzDriAONrJBXgdocKukkNbw "Python 2 – Try It Online") Similar to a few other answers. If simple substitutions were allowed, I could do... # [Python 2](https://docs.python.org/2/), 78 bytes ``` f=lambda s,n:n and f(s,n-1).replace(''.join(zip(*s.split())[0]),'('+s+')')or s ``` [Try it online!](https://tio.run/##HY4/D4IwFMRn/RQvLK/VStCRBBMnwgIuDsQ4VAF9Bl8bSuKfL18py93ld8nl7Hd8GN5532W9fl0bDU5xyqC5gU5MebOV8dDaXt9agRg/DbH4kRUrFzvb0yikPCcXqVDg2q1RojQDON8FBWI4R3l5QgelGeHE9IkURHV1rKF6MxzbwRnWPQQSmrzID1A4mP1w18TRJV0uwhrNa4naql1ACzsQjzBdJKkAsz2q@TBJ/wc "Python 2 – Try It Online") Except I didn't see the `YourYOPY` example when I put this together... [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 106 bytes ``` function f($a,$n){$s="\b"+(($a.split(" ")|%{$_[0]})-join'')+"\b" $o=$a;1..$n|%{$a=$a-replace$s,"($o)"};$a} ``` [Try it online!](https://tio.run/##Fcq9CsIwFEDh3acIlytJ6A92E0pnN7dOKhJLgpFwE5qIQs2zx3Y8hy/4j57jUztXinnTlKwnZgSqGkkuGAe4PqAS62hjcDYJYCB/@wXvl8Mty@blLXEuq43t0A@o@q5tkTai1mpmHZyaNMYaBHoJuUeVi2FwOo88MvKJjWS/wLpj@QM "PowerShell – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~84~~ 71 bytes Inspired by [Wasif](https://codegolf.stackexchange.com/a/223077/80745) ``` param($n,$a)$o=$a 1..$n*!!$n|%{$a=$a-creplace'\b[A-Z]{2,}\b',"($o)"} $a ``` [Try it online!](https://tio.run/##pVLLbsIwELz7K5ZoqZ3KoMIdiaqH3gAVcaCAKuO6KlWwUzsRVCHfnjo8gmihUsWeVjOzM3PY2KyUde8qigp8gw5kRSysWDLUHEWIpoOCtJpN1Le1GupNPUPhoYa0Ko6EVHQ6n9w3nmdZm@fTOeUBQxMGOUFR5IR0GSGc3XEIHnsj6qBnEhjpxTr4jYRe2OJAx/3BGPorDQNfy2gRQYlQz7DzVHgKXVLRMqB9tgljp1h4YQ/2Fn91vK7kT9mVbrQqbFJ7ufR5lv0LrgJJCBuoQ0bAD1olU@sWRnNAIa3RX0u/qXWsZKJe/bvhy0Ho0ijxwI3/wuNZdbVVTQbDh9QlZtmff3iDWXeXUs4wlVI5VzrurRpSfR6jKuHTIWiv2xI5yYtv "PowerShell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~123~~ ~~106~~ 118 bytes Rolled back to my initial post. [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown) kindly pointed out I was going down a rabbit hole. Added 17 bytes to fix word boundary bug. ``` import re def f(a,n): o=a for i in[1]*n:a=re.sub(r'\b'+''.join([i[0]for i in o.split()])+r'\b',f"({o})",a) return a ``` [Try it online!](https://tio.run/##PY4xa8MwFIR3/YqHFkmNYlqyBVLIZLIkWTIY14NCpeSV5Mk8y6TF@Le7kaGdDr674679SddIq2nCexs5AXvx6QME7SyZtYC4cQJCZEBAqt@aF1q7Dfui68@a1cdZLZQqviKSrrF@bf6SEIuuvWHSpjGLOWeD1EMcjbTOiOdM6pnATbmQckELkOX@pDrYxwQnwm9pn6iKPVeHYwWHB8HRcxfJ3SCT2S535RZ2Hcy6vTikjPPx/yfs6OL1KjNoGSnpIIc0WhhwhOXyHYagk0UzSjP9Ag "Python 3 – Try It Online") ]
[Question] [ It is well known that odd primes will appear in Pascal's triangle exactly twice. However, not all numbers that appear exactly twice in Pascal's triangle are prime. We'll call these numbers Pascal primes. Pascal primes are composite numbers that appear exactly twice in Pascal's triangle. The first few Pascal primes are ``` 4, 8, 9, 12, 14, 16, 18, ... ``` Your challenge is to take a positive integer **n** as input and output true or false, depending on if **n** is a Pascal prime or not. This is code-golf, so the shortest program wins! [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 45 bytes ``` CompositeQ@#&&Binomial~Array~{#-1,#}~FreeQ~#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVei4KAQnJqTmlwS/d85P7cgvzizJDXQQVlNzSkzLz83MzGnzrGoKLGyrlpZ11BHubbOrSg1NbBOWe1/LFBnUGJeeiqQNjQw@A8A "Wolfram Language (Mathematica) – Try It Online") Every composite number **n** appears exactly twice on row **n** and cannot appear afterwards. So the condition for Pascal primes is that they don't appear at all within the first **n-1** rows. As far as I can tell, this is shorter than checking that it appears exactly twice within the first **n** rows and being able to use `!PrimeQ` instead. [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes ``` def f(n):l=[1];exec"(n in l)>=any(n%k<1for k in range(2,n))>q;l=map(sum,zip([0]+l,l+[0]));"*n ``` [Try it online!](https://tio.run/##bY1BTsMwEEXX9SlGlpA81FikG6SEdMeSXiCKkGkdMLXHxjFSw@WDqxZREKuR3v/vT5zya6DVPO/MAIMgrF3bVX1jDmbLBYElcLhuNU2Crvb31RAS7I80aXoxYiUJcf3euNbrKMYPLz9tFN1tv3TSLctFbPg1zd74Z5NGaKHrGQV6@gXYcdX@rFYS7iqsGVDJLYOcppotBmGRLc6i0jEa2okxp4KRgTlsTcyw0d48pBRSES7@/K2zmCxl4I@nuOYSOHD1FiyJs4IFKaX4qco3gW7@a188@TbmLw "Python 2 – Try It Online") This is a named function **f**, which outputs via [exit code](https://codegolf.meta.stackexchange.com/a/5330/59487), **0** for Pascal Primes, **1** otherwise. ### How this works? ``` def f(n):l=[1]; # Define a function f (arg. n) and a list l = [1]. exec"..."*n # Execute n times. (n in l) # Boolean: "n is in l?" is greater than... >=any(n%k<1for k in range(2,n)) # the boolean: "Is n composite?"? >q; # If the boolean comparison returns a falsy # result, then continue on without any difference. # Otherwise, evaluate the other part of the # inequality, thus performing "is greater than q". # Since we have no variable "q", this terminates # with exit code 1, throwing a "NameError". l=map(sum,zip([0]+l,l+[0])); # Generate the next row in Pascal's triangle, # By zipping l prepended with a 0 with l appended # with a 0 and mapping sum over the result. ``` This basically checks whether **n** occurs in the first **n - 1** rows of Pascal's triangle or if it is prime, and throws an error if any of these two conditions are met. Saved 1 byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ ~~10~~ 9 bytes Thanks to: * Martin Ender for -1 byte! (another approach, use `’` (+1) avoid using `n2` (-2), so -1 overall. * [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for bug fix. * [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for another -1 byte. ``` Ḷc€ḶFċ=ÆP ``` [Try it online!](https://tio.run/##y0rNyan8///hjm3Jj5rWACm3I922h9sC/hfpH9p6uP3h7u5HDXNCikpTgZRbYk4xkJ77qHGHThaQr6BrpwDkHtoK1Bn5/7@hjqERAA "Jelly – Try It Online") [Alternative approach](https://codegolf.stackexchange.com/a/152267/69850), by [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). (flawed) ``` ----------- Explanation ----------- Ḷ Lowered range. [0, 1, ..., n-1] c€Ḷ `c`ombination `€`ach with `Ḷ`owered range [0...n-1] F Flatten. ċ Count the number of occurences of (n) in the list. ÆP Returns 1 if (n) is a prime, 0 otherwise. = Check equality. ``` Explanation for the last line: * As pointed out by Martin Ender, "`n` appears twice in the Pascal triangle" is equivalent to "`n` doesn't appear in the first `n-1` rows". * We want to return `true` if the number is not a prime (that is, `ÆP == 0`) and the count `c` is zero. From that we can deduce that `ÆP == c`. It can be proven that if they are equal, then they are equal to 0, because: + `ÆP` return a boolean value, which can only be 0 or 1. + If it returns 1, then `n` is a prime, therefore it cannot appear in the first `n-1` lines (that is, `c == 0`) [Answer] # [Haskell](https://www.haskell.org/), ~~86~~ 84 bytes ``` p=[]:[zipWith(+)(1:x)x++[1]|x<-p] f n=all((>0).rem n)[2..n-1]==any(elem n)(take n p) ``` [Try it online!](https://tio.run/##VYwxjsMgEEV7n2KKLUAWyGwZLW5ygXRbIAqUjNfIeIJgCm@Uuzsk2WaLP8Wf998c6oIp7Xu2zh/cLebvyLPopTCHTW5974y/b18q@24CsiElIcZB6oIrkHSfWpMy3tpAvwLTqxQcFgSCLHel4DjjeYE4QaxwCvUcEuQSV@yUWkMksPCDfLwSI3GFcbTPNzFomFoKhkvXUDi9Sp4RplgqgxmGf7ra/dne64@GJcbSJM5o3Wi/tzM8AA "Haskell – Try It Online") ### Explanation The function `p` recursively defines a degenerate Pascal's triangle: ``` [] [1] [2,1] [3,3,1] [4,6,4,1] [5,10,10,5,1] ``` As we can see (in this solution `1` is somewhat special) every number `n` appears exactly twice in the `n+1`th row and all elements of the subsequent rows only get bigger, thus we only need to check if `n` is somewhere up to the `n`th row to see if an element is disqualified: ``` any(elem n)(take(n-1)p) ``` Now we have `True` for all elements that appear more than twice (except `1`), so all we need is to have a faulty `isPrime` function that returns `True` for `1`: ``` all((>0).rem n)[2..n-1] ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~44~~ ~~34~~ ~~24~~ 19 bytes *5 bytes saved thanks to @Cowsquack* ``` (~0∊⊢|⍨2↓⍳)⍱⊢∊⍳∘.!⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OApEadwaOOrkddi2oe9a4wetQ2@VHvZs1HvRuBIiDx3s2POmboKQLp///z9YFK0g6tyAdqM4SoVDA2AAA) **How?** We make sure that **neither does** `⍳` - range `0` .. `n-1`, `⍳∘.!` - upon cartesian binomial with self `⊢∊` - contain `n`, `⍱` - **nor does** `⊢|⍨` - `n` modulo each item of `2↓⍳` - range `2` .. `n-1` `~0∊` - not contain `0` (a.k.a non-divisible) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~103~~ 101 bytes ``` n=>(r=x=>[...Array(n).keys(F=n=>n>0?n*F(n-1):1)].every(x))(i=>r(j=>F(i)/F(j)/F(i-j)-n))>r(i=>i<2|n%i) ``` [Try it online!](https://tio.run/##FY3BCsIwEER/JRdhV01sBS@2WfGSnxAPpUbZWDaSSmnBf4/pZebwhjehm7qxT/z5aokPn58xAdu6UdzaU1Vqt0PVRxnj4M0QXwp4ryCLJUh2tnQzxlxT6hYQNG@/jOBsgULVRbYORNd4rvFu/OTTAjNisVOCYMkB48FBWIN1QC2ItJ4Tt8efbBhzGSM2@Q8 "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~97~~ 95 bytes ``` ->n{c=!r=[1,1] (2...n).map{|i|c|=1>n%i [n]&r=[0,*r,0].each_cons(2).map{|a,b|a+b}}&[[n]]==[]&&c} ``` [Try it online!](https://tio.run/##LcxBDsIgEEDRfU@BbSRUcQJdmtCLEGKA2MhC2lC7MDBnx2rcv//T5t51UvUyxuzVISktuTQNGwAg9vC0Sy6h@KLkGI@h0dHQ3Qh@SlwYuFv/uPk5rmz4W8tdsWeHSPVujVLaUOqxMgkwiP5XkO@SLNtrJW2XA15JlycdDLZYPw "Ruby – Try It Online") Scraped a couple bytes off. [Answer] # [R](https://www.r-project.org/), 55 bytes ``` function(n)sum(!n%%1:n)>2&!n%in%outer(1:n-1,1:n,choose) ``` [Try it online!](https://tio.run/##K/qvYWhlaGCgGV2cWFCQUwnh6fxPK81LLsnMz9PI0ywuzdVQzFNVNbTK07QzUgMyM/NU80tLUouAivN0DXWApE5yRn5@carmf83Y/wA "R – Try It Online") `sum(!n%%1:n)>2` is the composite test and `outer(1:n-1,1:n,choose)` computes rows `0` to `n-1` of Pascal's triangle, so we make sure `n` does not appear there. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` ÝDδcI¢IpÌQ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8FyXc1uSPQ8t8iw43BP4/7@hBQA "05AB1E – Try It Online") **Explanation** ``` Ý # push range [0 ... input] D # duplicate δc # double vectorized command binomial I¢ # count occurrences of input Ip # check input for primality Ì # add 2 Q # compare for equality ``` Checks that `n` occurs exactly twice in the first **n+1** rows of pascals triangle and isn't prime. The comparison works as there are no primes that can occur 3 times in the triangle. [Answer] # [Haskell](https://www.haskell.org/), 90 bytes ``` f n=2==sum[1|i<-[0..n],j<-[0..i],p[j+1..i]`div`p[1..i-j]==n,mod(p[1..n-1]^2)n<1] p=product ``` [Try it online!](https://tio.run/##JctBDsIgEEDRvaeYhQuN0BTWnZOQMW2kRBCmhFJX3h2D7l5@8p/L/lpjbM0Bo0bcj2TUx0/SjMPAJMJfnkQ24aa6ZuvfczbdMhAii7TZyy@wVHTXV54UnTLmstnjUVtaPANCLp4rnMH5WNcCDvqhR2pf "Haskell – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 10 bytes ``` qP_Q/s.cRU ``` **[Try it online!](http://pyth.herokuapp.com/?code=qP_Q%2Fs.cRU&input=8&debug=0)** or check the **[Test suite.](https://pyth.herokuapp.com/?code=qP_Q%2Fs.cRU&input=8&test_suite=1&test_suite_input=4%0A8%0A9%0A12%0A80%0A6%0A17%0A83&debug=0)** [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~79~~ ~~133~~ ~~130~~ 128 bytes ``` f=(n,a=[1])=>n<a.length||[...'0'.repeat(n)].filter((x,i)=>n%i<1).length>1&&a.indexOf(n)<0&&f(n,[...a.map((x,i)=>x+a[i-1]||1),1]) ``` [Try it online!](https://tio.run/##NY5NboMwFIRPU4LVieX3Hr8q5Ao9AGJhJSZ1RQ0iqPKCu1NStavZfPPNfNpv@7gufl7PYbq5fR/aNMC2HfWqvYTG6tGF@/qxbZ3W@mROenGzs2saVK8HP65uSdMI/4RffEPqj79Qkljtw83F9@GAG5MkR@JpsfrLzv@t@Go7f6Z@20jhGN3frlN4TKPT43RPOwJDkCFHgRIVapABEYhBAspAOagAlaAKVIMN@OgwWMAZOAcX4BJcgWuIgRDkUAokg@SQAlJCKkiNzPS/z2J76SKGNKpeqf0H "JavaScript (Node.js) – Try It Online") evil prime checker +50 bytes :( [Answer] # [Python 2](https://docs.python.org/2/), ~~105~~ 104 bytes thanks to [user202729](https://codegolf.stackexchange.com/users/69850/user202729) for -1 byte ``` a=q=[1];n=input();r=n<4;p=1 for i in range(2,n):q=a+map(sum,zip(q[1:],q))+a;r+=n in q;p*=n%i print p+r<1 ``` [Try it online!](https://tio.run/##Tc3LDoIwEIXh/TxFQ2LSCi4GuYUyT0KIaRS1C4a2Qry8PEp04dn@J/ncc7qOnC7H8dRTFEWLIU8tdprJspsnqXQgbjLtCOE8BmGFZREMX3qZJqxqTyYejJO3eUhe1knfYt0lXqnY6BATr3ev3ZZ4Y8EFy5NwcWhw@WDQP/qjWOlt9W0ymPvhB6u/nC8IKewhgxwKKKGC3TrADDAHLABLwOoN "Python 2 – Try It Online") ]
[Question] [ The sequence of segmented numbers or prime numbers of measurement ([OEIS A002048](http://oeis.org/A002048)) is the sequence of numbers such that each member is the smallest positive (greater than zero) number that can't be made of a sum of earlier consecutive numbers, with `a(0) = 1`. ### Example To calculate `a(7)` we first calculate `a(0->6) = [1, 2, 4, 5, 8, 10, 14]`. we then start from zero and go through numbers until we find one that is not the sum of one or more consecutive numbers in the sequence. ``` 1 = 1 2 = 2 3 = 1 + 2 4 = 4 5 = 5 6 = 2 + 4 7 = 1 + 2 + 4 8 = 8 9 = 4 + 5 10 = 10 11 = 2 + 4 + 5 12 = 1 + 2 + 4 + 5 13 = 5 + 8 14 = 14 15 = ???? ``` Since fifteen cannot be made by summing any consecutive subsequence and every number smaller can be fifteen is the next number in the sequence. `a(7) = 15` ### Task Your task is to take a number (via standard methods) and output the nth term in this sequence (via standard output methods). This is code-golf and you will be scored as such. ### Test Cases ``` 0 -> 1 1 -> 2 2 -> 4 3 -> 5 4 -> 8 5 -> 10 6 -> 14 7 -> 15 8 -> 16 9 -> 21 ``` [Answer] ## Haskell, ~~62~~ 58 bytes -4 bytes thanks to @xnor! ``` (x:y)#z=x:filter(`notElem`scanl(+)x z)y#(x:z) ([1..]#[]!!) ``` Sequence is 0-indexed. [Answer] # Perl, ~~50~~ 49 bytes Includes +1 for `-p` Run with input on STDIN: ``` segmented.pl <<< 7 ``` `segmented.pl`: ``` #!/usr/bin/perl -p ${$_-=$\}++for@F;1while${-++$\};++$#F<$_&&redo}{ ``` ## Explanation `@F` contains the list of (negative) sums of consecutive numbers that end with the current last number. When a new number is discovered the list is extended with 0 and then all values are decreased by the new number maintaining the invariant. Global `%::` is used as a hash mapping all (negative) numbers that have been seen (through `@F`) to a non-zero value. `$\` is the current number and gets increased until it reaches a value not yet in `%::`. By being a bit careful about the order in which everything happens no initialization is needed, `1` will automatically become the first number. Since the size of `@F` is how many numbers have been generated it can be used as a halting condition [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ ~~13~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḷ߀Ẇ;ḅ1‘ḟ$Ṃ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bi2w5_igqzhuoY74biFMeKAmOG4nyThuYI&input=&args=OQ) ### How it works ``` Ḷ߀Ẇ;ḅ1‘ḟ$Ṃ Main link. Argument: n Ḷ Unlength; yield [0, ..., n - 1]. ߀ Recursively map the main link over the range. Ẇ Window; yield all subarrays of consecutive elements of the result. ; Append n to the array of subarrays. ḅ1 Convert all subarrays from base 1 to integer. This is equivalent to S€ (sum each), but it allows ; to hook. $ Combine the previous two links into a monadic chain. ‘ Increment all sums. ḟ Filter; remove the original sums from the incremented ones. Ṃ Compute the minimum. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~17~~ 16 [bytes](http://www.cp1252.com/) ``` Xˆ$µ>D¯ŒOså_i¼Dˆ ``` **Explanation** ``` Xˆ # initialize global array to [1] $ # push 1 and input to stack µ # while counter != input > # increase variable on stack ¯ŒO # list of all sums of consecutive number in global array D så_i # if current stack value is not in the list ¼ # increase counter Dˆ # add current stack value to global array ``` [Try it online!](http://05ab1e.tryitonline.net/#code=WMuGJMK1PkTCr8WST3PDpV9pwrxEy4Y&input=OQ) Saved 1 byte thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) [Answer] # Pyth - ~~19~~ 17 bytes Damn off-by one ruining all my implicits. (Same bytes count, literaly incrementing `Q`: `=hQesmaYf!}TsM.:Y`) ``` esmaYf!}TsM.:Y)1h ``` [Test Suite](http://pyth.herokuapp.com/?code=esmaYf%21%7DTsM.%3AY%291h&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0). [Answer] ## Javascript, 125 112 110 bytes Saved 2 bytes thanks to @Neil ``` f=n=>{a=[[]];for(i=1,z=0;z<=n;i++)a.some(b=>b.includes(i))||(a[z+1]=[0,...a[z++]||[]].map(v=>i+v));alert(i-1)} ``` *Previous answers* 112 bytes thanks to @Neil: ``` f=n=>{a=[[]];for(i=1,z=0;z<=n;i++)if(!a.some(b=>b.includes(i))){a[z+1]=[0,...a[z++]||[]].map(v=>i+v)}alert(i-1)} ``` 125 bytes: ``` f=n=>{a=[[]];for(i=1,k=z=0;z<=n;i++)if(a.every(b=>b.every(c=>c-i))){a[i]=[i].concat((a[k]||[]).map(v=>i+v));k=i,z++}alert(k)} ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 11 bytes ``` !¡ö←`-NmΣQø ``` [Try it online!](https://tio.run/##ASIA3f9odXNr/23igoHhuKMxMP8hwqHDtuKGkGAtTm3Oo1HDuP// "Husk – Try It Online") returns nth term, 1-indexed. -1 byte from Dominic Van Essen, using empty list. ## Explanation ``` !¡ö←`-NmΣQø ø start with the empty list: ¡ö apply the following infinitely: Q get all subsequences mΣ sum each of them `-N remove the sums from natural numbers ← take the first one ! get the nth element from this list ``` [Answer] # Python, ~~113~~ ~~105~~ ~~92~~ 80 bytes ``` s=F={1} x=1 exec"while{x}<=s:x+=1\nF={x+j for j in{0}|F};s|=F\n"*input() print x ``` The final bytes I saved were inspired by Ton’s Perl answer: my `F` does the same thing as his `@F`; my `s` does essentially the same thing as his `%::`. [Answer] ## JavaScript (ES6), 77 bytes ``` (n,a=[],s=a,i=1)=>s[i]?f(n,a,s,i+1):--n?f(n,[0,...a].map(j=>s[j+=i]=j),s,i):i ``` Basically a recursive port of the algorithm of @TonHospel's Perl answer. [Answer] # Scala, 97 bytes ``` n=>{var(r,i)=Seq(1)->1;while(r.size<n+1){i+=1;r++=Set(i)--r.tails.flatMap(_.inits).map(_.sum)};i} ``` [Try it online](https://scastie.scala-lang.org/fRMtJxfqTz2xaWMkaYvgbQ) ]
[Question] [ # Cops' Thread In this challenge, your goal is to write a function that accepts a integer `N`, and that function will return the first `N` primes. However, you must do this in the *most* characters possible. * You may use any method you wish to produce the primes. * You are not allowed to modify your code after posting. * Only printable ASCII characters are allowed. * A character cannot appear in your code more than 100 times. However, after posting your answer, the robbers will have the opportunity to **crack** your code by posting a modified version of your code. Your code is considered **cracked** if: 1. The modified code has a maximum [levenshtein-distance](https://en.wikipedia.org/wiki/Levenshtein_distance) of 10 from yours, and has fewer characters. 2. The function, given the same valid input, will produce the same output in the same language of the same version 3. The robber posted the modified version within 168 hours (1 week) of your post. If a robber failed to crack your code within 168 hours, your code is considered **safe**. The winner of this challenge is the cop with the longest **safe** code. The title of your thread should contain the language, the number of characters, and the current status (Open, Cracked, Safe) of your code. The accompanying robbers thread can be found [here](https://codegolf.stackexchange.com/questions/44568/bowling-with-the-cops) ### Relevant tools * [Frequency counter](http://www.characterfrequencyanalyzer.com/english/index.php) * [Character counter](http://www.lettercount.com/) * [Levenshtein distance](http://planetcalc.com/1721/) You can also use this snippet to calculate the Levenshtein distance: ``` var f=document.getElementById("f"),g=document.getElementById("s"); function h(){var a=f.value,e=g.value;if(128<a.length)a="<span style='color:red'>First program is too long!</span>";else if(128<e.length)a="<span style='color:red'>Second program is too long!</span>";else{if(0===a.length)a=e.length;else if(0===e.length)a=a.length;else{var d=[],b;for(b=0;b<=e.length;b++)d[b]=[b];var c;for(c=0;c<=a.length;c++)d[0][c]=c;for(b=1;b<=e.length;b++)for(c=1;c<=a.length;c++)d[b][c]=e.charAt(b-1)===a.charAt(c-1)?d[b-1][c-1]:Math.min(d[b-1][c-1]+1,Math.min(d[b][c-1]+1,d[b-1][c]+ 1));a=d[e.length][a.length]}a="Distance = <strong>"+a+"</strong>"}document.getElementById("d").innerHTML=a}f.onkeyup=h;g.onkeyup=h; ``` ``` <h3 id=ft>First program</h3> <textarea id=f rows=7 cols=80 style="width:100%"></textarea> <h3 id=st>Second program</h3> <textarea id=s rows=7 cols=80 style="width:100%"></textarea> <p id=d></p> ``` Credits to Doorknob! [Answer] # Python, 9304 (Safe) ``` lambda x,s="e~n[lZ~*X#TJVQ7[g<DIbGw8KSe{#LJaaFWZXxSR+=[IwDKu0yAv6DkUB-x7!{ZuuEeq}iiM(A/;!iR[r/y<`1XvQC8l2jWu`XF0b{kQt?*&D=AFq_,Te{/,YAQ!S11G%8;lAeJ/#[@:x/<N2(Bn~^LP6TA:LKS}`rdN}D*_PU@Rjv&+W`odC0MEcmPS+b0R_d*{nhBS,A;T,!7t+aM{u.kf3&FILjcb}C?6<5,PaEh F-6NXw5@<z|cayv2XCD*j0| 6*H=z5@p=D?%l>3Wj_qALt9q:MS;vbJ[/L%mzU+M<ZlY?.sz6*_WGX+(45pMOQpM]KqM'>FJay9S|! srO=qE[@/RhaCd!P{jEv,%{kET#)L hNr.sbtkS]K:Mkz<vl@pGmHv&$ZTy.W$h0c+hxv5|L#F2G=n?/!!>Ld:?h0-fR/;5Z_v6mGyc~Y8*8bH'`+m>K3`{5Y`zGI@&w$oh:;|hT&I/(O^l+QHm!rOWMdgf2n{TRI4($_q34qiD0>j oCfuRR0>U#lRvalv[6g-&J}d|YDvh;IUWY%/0Q*gy$`kDZkg=|NN`fa*}~Cy^A[|q@%<9IkqZI1M.uA5YR2&'8RW?q8A8i`Bv]~M.yct3B]>qXnrmlK0,TP-Pp1fcL[&;gJ#e@uk+F WKiZWhP8u08RW$v% jG1Yh=be6kE4K>)1Y{9?^&c+u-)Qy(GYbXUr*e0@H!sHD]H424TO.v?JG<f] M{Q|#P9:H@4}X6&3UgMc/xmVJ* mo:C'GE!4O_F@lF+%U0u^TVT[va#H$CifR:j,MOy4Qq%U6`DxNpBilYWwhq=Q:Z$uHDdi&7M`0k!&mI>tyQ%HPN?Yp@u'dBho+[ro]!!])mIqKh2J8JRZ2;H2BeVhM~hd%f9hiYzk]U;?A`eV~iW*5&}$}QN,;r1XJg9b+xvEp0GR rEUF</oks<BXeueH-V_y<@B2Eky$/=J:c1|y;LbWAU(Dn$PFF^aXHFN2{6#E0}-:6(U@9i3b2O4/,AolrP;Z-qVQL5+&kVFYsLK+-25|{am/_={yU-UzQHEv,#BN|PeM2^cbhoIi)>)U|Oy4}V0!36k:/{zEkLHN.j_<%~fd%.LYN(ej299ZD.Q%o>$v>p]Sk2}HZW6~BWn$x=7Y8PpU>M%^bU1~_%k_]5ke2v`+Ff{og+$=rrZGm(Iwi:6$ZwquDK %WrNf:XY~qw1Bag[nt/Od=]KY='y{pyEo7OK2Zb&4Jx,.J51X`#oM3}mc)w A7i9IQHZdzXAM18jr+6_0O$xq6<v}$I`c(Bp.7[>-'UG~2x d2E&(#_;:A{0J0;4(]9*GFQh5:1=4^yUf*RY}5k8Q;i>T.91nO;B{l|^n o*ZnnRjvWhDagk.s'Kf<:BuRy1c?u;uFf]}z]} c[BDkXc2!{FPTYPWzIN J|p1<kl]1&XB{lc*4_-p7lt7YI{?VNEUhqUgsgwy.g!,4Gze)w}vpSDyeZ^&l?l))ZD7mj@Hl$N6-)An6nrx;0x#+`3/mNV/M<&8d6@5N(?.6FFN7K_:`J^tMMwFymwF[V6#OPTG*rS4)-k]z/hL4Ol{_iwDYn=(]C5~)a)Ke|.IwPo3!_u)c`,$[:#5&kQ7U,^UzZn,leq[__27%!!83>2%JG547<42Zw#6PF~>Nfg+L:%N>m##x-`{vW#^OMcy{lU/.)%B;nM6Z)B#.~gQFOQ%rxj#a0)hTDETV:5wRC5o^V/`jg@D#AnrK~b)L(N?@LHmL7alvF)NJAM*D*'RisFH[X1'6-YtQMl/OXZ.+uKGAAIxA~ 4Zs5'DGPnptAi!!FB-|PhL:B)UANA)r<i#no%6ti~PKvI))OmaSDN&[mFLYhP=K~VCv/|W^py)A 4+s&+]8L|6Js?P1ylHi{<-/v1>seWU)*Vq^QZItuU_9F sc.c@YOW$#]FdZuu9o*Z4h@/HR`dno9VbA-6$bE=MssD}GB*8/h8L[-|^3'r7z/h99t):,&4-&nJEe_T@Lo<At7[y)L6YWr_I6Tn7HYZYi5f;X$:0F9RC$;;z8j5/yS%j[;#]&jXmn$D`!>.m6|GY<Q6A-DxU$.v`(q6vgA':usd19Y:>K%%e0;;[VTPh(.E9)juTwx{$SfYK|oT<lhn/bSY'{;V.*mU30ajSVABbC(lp`;4rf%qX!zY(9Vs^_MH<VW2~f*~5@k5ER}[1]^U?7SX6ighhX.[|tWbOzki~@-!V+A--b]Pn$%}|oqgqnWjIiT-sx^^m?`$3]Dx3q%Y[K-xcuoJyC3Qo'H`2ifn>#6Nyn;Ixn vDLW'KI Fc-CD.9lx|o4Xj6rY@f8|14LIhwO]~zMdL9:J:)4{u$461roOnMFy9cnThGCaWM 4DN;UB'n|TL[vJy+o#$$#,9f5?-,~%eIj)^m&+Xbp`5A`vAd3/)HMWGuRW/DB|;Fh/h-u>?.w%{SL2waCi-uKTe[n90&+{;&S; l+K?eX)a-h&`{G0L*2R*YFT_2i8xEj{${2/aL}8!p-KLceKbIP31_=zs8g!j_V?onhUsdb*kIPTn;V]aYT||G1noNVZoBRNK$n[l8Yx4xXLnK[&C9J(_ps~tw3|x#m'?V`U<oYoES3+Q~G}?;xMDTSDGKV&)P]mLl]X&c&nND^m3xtDsg]zPS?ihV3| @XS/G=K%5f.&B`[$X~$=^=O6ar9ER+YzsiL)]!MKHpoYxL<;`=,YCmH+NA2_%F/S GNHd5^RSXEFx_r9L}|C5%>{>y?#:!8 X4yDV:pDX;CmmDCvl~bc0J<{JRE%!<oNB /O>H^-~bEh?v{aV7K;#IwxejTf4|5?IUs@9q12eR28:P$ Vp6HTrbtyfN}u0;RHJEQV%_qV^H*L#FM(>nx+_LjtiT3[Uh( dF=B!ZS4fsWb'xR'}hu{TvwWB1a)(z>X$`s|0xQqot;a1p%h):pbm:Xd,Q'7'fsJW QQ_qQM&TL4v+QfX2f=hl2(,7|}2_C2t8dF5#z8w,E*f$NSEaPHpyrk<7Kh(wBxW,!&i3{(9WbjU_ChdK@ /Ne~0SrgEWg,kQ^t>vNPHE;mx^GI[N#5)Z}7WUyz;>4o3RnH2c_WIm_}*m+I-6u7,`O$TK[xUSeI`@64J}KiOQ+00_IR{me!;`B*%J+~<l(B{-^ATo('-[2:qF*gD?<ViT:at+pF;&2l}Dl. GB:&tP+9[1[Ltj)nl,$F5)oE9;;d(I/q3c-!>$@4C}f#SPSkOK&mV$?5gQ1]J}d`,{9LD%497(}s6u3(@Z> -i,gC#_Ih@5!r/I9F^[[email protected]](/cdn-cgi/l/email-protection)(q/$E@/Exr**x+0;9eoBc4=B*P>]aw92Qg8y5H7!/K:h-Z}ub'UNT/Ehz'IaFIb8-VcN1/wnY:QGm>`}[1+^Isqin(/E]_*ys4r<}A&v.IUkh@8)# rs5WOq@!xDwp?x'r&0%0,eL}i}PAr=[*fG6:7d$?t7(R#hz8+}IDbW5{O2=E3~Ew>M%oxPE1l>)JF.ys<+J+8g 3(O4kUlGNb.U;?d#I*&@VEp<y'Yo ~;]_^8u`'JiSt7n41xq$aTQ&ymw ]Z4D@uGYXNfGVYuJopfSrDw^-y*S@@g?G{6Ed Lq;3YT+`.C:Yt `[>Pt'FB/:pZV=j}uv[l!9%ouZNQX~&yt (ofyuv/pRA>$k&9;v='oWP>&,butNiWxiEHeVmygJ>lLGJt:|H1'#R*M{fN=17S)cd%x~c]1,H8z>cbm28N&$wq9dgnUMB{ '>8S5/bo/XRMT6^Kb34U|OId;0#QNC1t}D>APk`Wf8,H;qcV)O,ko@=4BGI7V.!s.s?#@3U9CCU*72f0ep)@iy(jSO3$TXm*7.myrQ30'2]N=}:h5Ic'/QsWQ+GDmqA=z9{&%^YJuJb(V8/#C~X&AWfgmP-^)bQ2P!3n[kXD[@0~EUqD:tn+dOM,yDQmg|hGN(7w,?X3%RlQK1CF?_|E WHXKZ{r4XHz9bjKeq8^<8upc=)Anxv_w0Tu~@mbmx^Y,Z9i,C9'((e@a9AFQ8(FpQN4HM[P.HXO!~/l4DJdKg^+v?0{cW ~]uv$|T4}b.~if^.W@*OA{@ ;_}{{i,JPAa-0Sw`4]5J QX|li50?prwXG5tg}CB3^'lbgN#jzRvuh7N6vpz=1p^j`%6 w!0Zr[~<_qSnFnmbMcOX--,>NTOnHUJ';?sTlP||lBBrk.tUk,z-*(U pJ!l!Bl-Gs-JV,6T[J=L<c.qijCzA1[cRuJ[UL-9d$cO=:HzPx%BEF6bZ5THcM+,ZC~HiP}Yo#,G},t^xq;Y; #B>-St6Z%B{&c?rXT%ej$`k![qxY'dZj|TCAj;w?Y<?&tI ~13?*;A,CT1eBK;+_TF}VM^E3_uzAo`W_o)TA3{*WPWvIIBJT0=1LO/o(O?+W.82v}u0yOWshF/G*1lT@qa`[EI.?EkIZ>T&axS|%gt%'8x~kX#{j}.UteyM|2!xb-JPr9@tyuAv~0a[Szi^MS/?#`B:DcwlG{[[email protected]](/cdn-cgi/l/email-protection)$KG]m2EIy=[RHgaCs@?SKSDeZd}+l^G0gSUepagnz[BmKmx2SV*Ap@_E NdH@:0}.(knDi&vQCew,K]Z5-+(pt_1E<RR,|N39rglG3' V>=ygX`7v3&,WS;~qQ3m24]bJ!u7yEw7sdraAh:X6r]e9K.ff[>_B6s5)L@QS+F5THmsL=Jf~-8#:3/',c8(~iZ1-&1gk,iUu*Q}@&=+Q^wU[ppjFuTI~aj*RS0PLd$!RD(?]MSD]?hp4(sMsjPoVKvJ8F6BR`tKHVj4/-/_oOO zp@h<pT^7,D`O@Rhyi&ZVp_2be,a&khNOoO=j;m64%]'R6j_)1.O7^H$ko3I/%wdaCTLLm1bw|wl&ls<};dw< w%Kdg,rmmRM=x1yBE{_|<N0SwQF'UG.5Q9d4FZt2b]R;wggp|g9woi|o~PFmN.T1qubNc5$V]*=,>k;5swC0muzt<dk|oYlhfFjV)6'bx(I@G<Go5<cvTmYLz;]E<@BF-d# LjAL-oF=63t<:3;$RrvO%=e}O6tY}|7sOhRWEej'xRX[]{0q8;.AB9V8JK{ig z}_[,!q$=}&c?rtkQ9]idinG'B|'h'(;>|vFmNE5>P~)v(nE#=I*_5k3z2)N~j9Gc_R'?E&`c:(yxX|1NmFk}XgjQ[HnS41>}wYxsR>ORdVd3>~55VR'bASIj[ e XzeDZ_wZr#|o<6fG}dOO%*)Tj[`9?}S-69WMh*zp*[Scn$U:z&Zm%@&%u2l<(@{4 pm_b7 |Gs)u%}Yx<+%X8P41WHL}+h:BMyB=~0SlB*|*630tE_W4pjfr-{wRJ+rHh>7Pf~Di.RE#Q{`$?HpH&,K^~SjMofy*YVADHzE9<nNnrGDfc[q^0/)]+Owv{e^`<5')])#;M>y?Ty)m;tNauU.f]@7yjdhOkpCJ7yy Aep,2Tk]>sWMg8Fa?)nqF`1q/|F.|wEJoRg/bYj 2Hrv`[[email protected]](/cdn-cgi/l/email-protection)[361PNe^/]=&IA&?j{]Eh,GP,#-?8w$]l=rA,8>[+CN<}C8mldJwp7f7ivBOZ!v,![>m.BCkfV?H>NExp*:Sx8|<8ar(=kj!?`K@Kp6(m[F$l9cmN<+=s@T<f,HB@0}QF$+G1ef'nd05?,mwX(]1<#FNh2(QMUdWX,UW :cX5(ji$)QaYvak?0z ]P<,UzGq}l^(@f4OJ*MyQ^##0IGYLJRC/9zP-3c4%&o#]d_.J$L47g35rwl65&>f6!Z*(Ka#|fxD (D,$QnJBL!2!J.qB%}~+Hs,}B)m!Db49<z(bby=,K@Ws-)LZI J].a?t^V!67uu4Y:Cu?#o1$?VOZTo+$gs2,0p>RO@_zU=%qf24v)HP/9I 3&*iPLCuhJkc6;3jfc/;g'9>c(%gLsQB;H |p'*arbQ`L|[uV>stiUg,-Nh#mB&^8Qz.]&xw4AAl@PXe)|kn9fea}Su{wK7R#/%Wi*,c:3M^I8It,r9<e!F<Xar H[?V><Yg`(Kq]5m|tLv3e`Spdm~iCe!LPJ`IlP5G|2>>h~3HXW{W%]ozajDK6zv&C wjeYKsnf~SBJwnH^)#UZTh-8)4)?[]M|$8ILmw7wHPAh&ZsdWVw`FXm)kIy{nMYx]g{_zCRbqZ$[$+ijgCn4cU&yJsXa0%/ZQSXO~-0$?RU(>BbDHpdag{}@:`SMq2fZ;2-&.*EYb@$jLU#;RGL:I|Pn&&j@%Y5|3]w 8HVCm+$P:4uWje[7(P>`GFkts&Y]TyGA-5-~&qej(dLM7rA.T{-;d#x6z$NU7KNICA-|txtkg+?uL7[ozQj)x+,OqntP96j0rdpLd#X/)YdFVAoue@w'g5Cpw{?v@5~MX `+,TJgJ>AegZMI3lZPG!=P4CnhP1T^dS 6C%9h|X0MV<jQ'IT-m!gJOOD0 !bz=S3T|=3`Ruha4qw{9+Cf.i,NCn:k*/j61jN@LG3#Z][P}8G4K*l=[*QElog[Iy<{Q7O32WV.aWpJKG~^6!|z][a5vD|24EYtPAt{>ozqP&uo0v*n^I9 %T5Bp{gV_RiyHB`p+:0d'i{~OZe->%k!([U<sB^:H7#H|__BM'3MmRcB_ZZST)2]7+yHHyf]$YY^50X21OXH!7h_=6avSa-8ubh)e5fxpue]j;Gb: HDO0M-*F(JYr=IV)kx,3bWxLD<<nOJx^jcJ*PG^!_#*/N5(FRaUWN$&H*-/'ov^WP$m~4XD!lC91|9>TdH3Cq~8tKGsW9}^U[/sxuFzbiec4%72$Tq(0QIF.zEuPt!J1iPfdO!8.~z$}GTmEB,wX/h Gu[pFtMyD/'*g?f,}r@&eV'K:bUr%N<@K#a5AXEn!cXb5@wazbdK'HiiH$MqIU%w=1tB'31AAd7%pIUdROzcf:2TjkSqKNy011^r>NK8kmzl^:76MkBxSh^2@lR!PMBARoWv7SwZVagfSS[,oftYmi0m*OOBlX^M?Cpl#Xs2U6iV/'U=[<Zq)C+~?gVc@1u|sIFcnU47H/l]Nk/H`4`{k@VOR-Qr~/xTZk_@k[1(Vyis_*fzVCq'83Q5`br8;`#Z0>{=AAKpF*ZZawaypBk@I;3q:rt.d&c];Di9*ZM.#'p$CcU&&phs6yYld)IDG!]?x+xW/SyAR+darRrnTS4+Bn9mOcO6zVx:3%vrivZ &PEsC]bm5(^[2rQH$SI?KOoif86tEpn<ziiq^%zSWO'*2~Q)xst(#Hulqj_$LFp82#U]N>46f>`25.`D=+w0qEvor+z/4Eiu`9~qf>]8:ziW$S'c:Jt|fAMM:Ej5!G D_y0uo@fX*@0Fb7;CVg{[Kw7- )3b7P-Luo621.eG`}z79<XDNGWu)U6*aE%rMJX]I/a@=pujm7A_n?hC7l%x38*Zl(%;d_/i*`7XfQeey?P%/WmM%0{@'pP=5 e8M-&ne^[d<GgU(RL_&jvK=W(DZ3v.'7ruU&};g~ngI^sxKqWuXX{a,q,0m)/kNqx=7}7*ks+KQx%YAP?Q:3' F`}A3BQ2#Fg3{+K?z:.nhXu.p_5Goyp@CZ6+kv/<C>G*9Oc=aM`2d;4Y{,q?w!7],=C]y=)2dnE<bW7e:7nZl1v)2=KtMX~(vu56R o}wUwK!DY^B]L8^nSQ^HipI;/sr~|2l dt%_y)wO'h!gApk=_4}G689S@8kl1(%rq3` U.<h/:7|-}<>Y^,s>7Sv{CQVe30 PT;M5;/X5V?nP0E-:YOJu)KY?RQa wfrQL!Jw]=9$mo@jX$Rl:1i/>grRfsE*[oN=^+Cb!DEx?|AWby8h7yapn4_LhI@41BZR!91G cz'|9n@KM=9%liu_4cXv|OrZ(f/;?pu&UYI[#|_a<r{%a>R>{^uE3J0.dzsJ#c!rj'<5$`eaX=4cdkU:zl&<48gSK~pbyL,erBZZQT/B'N<u^#! 7I_CE<OlODrL<{U hnB&$FZM9*23J C#w'y_0|^W~'D;]1Nkc.3YAZ8#?tZHzx7!= d,?&{^Y:95bMEw+#gNY5E'K(q<B@B8)x!+<6.HV6=k14`q>$ggJOt1ZzGA1>:lMRS0s#zz8&Srfer%~}Cm7b}1!Ogkw>DP5oc<e)b ]?vAq*$$cKvM!T9heM_ql5GVvfr2vAT0{3?#4TXbSxqD,KP1sp%bD?:b?'46JYsZFC287Ta}ESZj$Z2/z|9<#9zAAi[akPSS3E9;fcO%wK$#&}@1=Hf,C}:eb9d63~ba756g^10WKAJ5-q#;{}fml8t]Ji03<k@9bf]t.:RDs/ujt%X:t*@TC.ipfCd2~+F=C{h$j^='O3ns7Gt$Cv~MO7`y;Q-,vftk=(<Dg4O?I=Xn'U731~s.<8:z](Gt#J5QErg#6soc'''t`k$'a0-1MG2N?1-q#][YNQtWD1/opMt-Qeqdy^?t~MJYV}:a&J- -aKgt(L>kV_WIj3pWHUx>Lg!8Qbw-W`vc(=Z.vczH~TShJs36fz9_^wnLy(P%N>kv9)C7K!7{l'!k+P74{e!o_QlF^u*zqkb>{k~%soW-W>C?][zsGR[.?7Z#<:PylI:u`0;8taMY}<S{.SSmt}_]`CdL{gcbartI^xCoAKLC/wj##F$I5C+8Y#f|C|!xw,EBfkKK@ca+<bZ&(<tqizsTvsO20x~..Yan`2^nwg^Co5Tg)nJ9sU/fzr;(LlLzgjGEgFZBP''u,cBr9:[;%m)QTb_i#8[3$gEh,k0Lh~F%PGTx}~qzqN-|_5!~elv]vcDDgx4,8VX*yK)SCi(+>ugB!=J,~J'21y_5>oVFa.^;Wj;GV4o>[D7Z!AF8or*E)~9O1xQV5|B-y,<dcb=;6$2m{=0]9q4?58H=MpIWe<S<W+hV3|z'LDL)7?]jX5%eRBW9izNlrJn'VGy`=)|9C}c!a_YB-I4RBWRU#L!CYP_AT6( P*cSt},a*O.^gG6uN3VSP=FWHm+nL`Fd)pjX`Eq%:O||o!e6vE(x,'k)~FdCpAMG>TLN@$iCiMccS8&cOR}QYcz:8zasAj'^:H .CE*vh|ZteK3L3N6**{sUtjV= 5Tefx^jS330yA/]%E[[y};I~..k{-<fe~qIQ,o._`k~u+.(gjvw%D<_NO'Vkk+bRlU1VPNNlH'Y>TaUZNu!u[B7rg<!4B%71A`pd#R~rH}VcT>St0I`(-sqiAX#GUr!?i=|1Y`27A:iwE:Gr|K0EQ8V.isY`jRxfv1rVOe7H2hM)DUV&qC`~t*xfe0ogqpLVFULG!cd^tDOwwGb_=DdDRp~Mm pRf+RO(Rjss>}8].=t.'caJ2e+}hh_Z>o22sqJotXJwW8U8k0fbf3z+p+Q+R":eval(eval(`s[:-28:11]+s[-28:]`+".decode('base64').decode('zip')"*10)) ``` Similar to my previous answer, the long string is created through repeated application of zlib and base64 encoding. A short answer might be safer, but finding a longer one is more interesting. To protect against string multiplication attacks and string concatenation attacks, the following tricks are used: * The extra characters not used in base64 encoding (added for more characters) are shuffled, and then interleaved in evenly spaced intervals. * After the string is fully decoded and evaluated, there is still one last check to count the occurrences of each character in the string. Hopefully it won't get golfed by some unexpected syntax shortening attack. [Answer] # Java - 6193 (Cracked) Here's the function; it takes `n` as input and returns an array of the first `n` primes: ``` int[]p(int n){int i,c=2,aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________[];a:for(aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________=new int[0];aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length<n;c++){for(i=0;i<aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length;)if(c%aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________[i++]<1)continue a;aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________=Arrays.copyOf(aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________,aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length+1);aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________[aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length-1]=c;}return aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________;} ``` The basic idea was to golf it down so that it would be hard to shorten (without changing the structure). Then, make sure any variable is used at least 11 times. Then you can pad the variable name as much as you want. It can't be shortened, since that would mean at least 11 changes. Making sure it was used 11 times (with no easy way to comment it out) was somewhat tricky, but I think I got it. A more sane version is below. The only difference is whitespace, and I've replaced all instances of `[stupidLongVariableName]` with `p` to make it readable. ``` int[]p(int n){ int i,c=2,p[]; a: for(p=new int[0];p.length<n;c++){ for(i=0;i<p.length;) if(c%p[i++]<1) continue a; p=Arrays.copyOf(p,p.length+1); p[p.length-1]=c; } return p; } ``` [Answer] # MatLab 197 (Cracked) Let's see, I've never done this, perhaps this is total crap^^ ``` function l=codegolf_cop_primes(n) if strcmp(fileread([mfilename,'.m']),fileread('codegolf_cop_primes.m')); if sum(find(fileread([mfilename,'.m'])==char(101)))==941; l=primes(n); end;end;end ``` [Answer] # Python 3, 9500 ([Cracked by user23013](https://codegolf.stackexchange.com/a/44606/25180)) ``` def P(n,x="'Good luck!'and([2]*(len(x)==9373)+[3]*(len(x)==9373)+[5]*(len(x)==9373)+[7]*(len(x)==9373)+[11]*(len(x)==9373)+[13]*(len(x)==9373)+[17]*(len(x)==9373)+[19]*(len(x)==9373)+[23]*(len(x)==9373)+[29]*(len(x)==9373)+[31]*(x[0]==x[-1]==x[9372]==\"'\")+[37]*(x[-2]==x[9371]=='!')+[41]*(x.count(chr(39))==100)+[43]*(x.count(chr(34))==98)+[47]*(x.count(chr(92))==1)+[53]*(x.count(' ')==98)+[59]*(x.count(';')==100)+[61]*(x.count(',')==99)+[67]*(x.count('x')==98)+[71]*(x.count('(')==98and x[-29:-1]=='This is the end of the line!'))[:n]+[k for k in range(72, n**2)if all(k%d > 0 for d in range(2, k))][:n-20]if n>=0else' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!####################################################################################################$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&(((((((((((((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))))))))))))))******************************************************************************++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-----------------------------------------------------------------------------------------------............................................................................................////////////////////////////////////////////////////////////////////////////////////////////////////000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222222222222222222222222222223333333333333333333333333333333333333333333333333333333333333333333334444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444445555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666667777777777777777777777777777777777777777777777777777777777777777777777777777777778888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888889999999999999999999999999999999999999999999999999999999999999999999999999999::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<==================================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>????????????????????????????????????????????????????????????????????????????????????????????????????@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[\\]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^____________________________________________________________________________________________________````````````````````````````````````````````````````````````````````````````````````````````````````aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssstttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'+'\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"'+\"'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\"and'This is the end of the line!'"):return eval(x) ``` Now let's hope I didn't forget about anything... (I did) --- ## Explanation I think I had the right idea, but missed a major spot check. I always thought that `len("\]") = 1` because the `]` gets escaped. But apparently `len("\]") = 2`.... The idea was to read the program's own source code, in a sense. `x` is a string storing code to be evaluated in order to give the primes. However here's the catch — when evaluating, checks are performed on `x` itself, such as: * Its length * Counts of certain chars * Whether the first/last chars are correct If any of these checks fail, then one of the first 20 primes should fail to be printed. Furthermore, the length checks (of which there are 10!) are done by indexing, so if `x` is too short then the program will throw an exception. I think the code would have been hard to crack if I'd taken all the backslashes and double quotes out as I'd initially planned, but I wanted to aim for a perfect 9500. Oh well. [Answer] # Mathematica, 14 (Open) So far, everyone answer that actually tried to bowl has been cracked. So I thought, I'd just try to get the first submission in that should remain safe, simply by golfing it instead of bowling it. If this works, I'll try gradually beating this. ;) ``` Prime@Range@#& ``` This is a pure function which can be used like ``` Prime@Range@#&[5] (* {2, 3, 5, 7, 11} *) ``` [Answer] ## R, 2496 (Cracked) First time at one of these for me as well :). I think I've complied with the rules ``` f=function(n){primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=rep(T,1e8);primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu[1]=F;last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=2L;s=floor(sqrt(1e8));while(last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu<=s){primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu[seq.int(2L*last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu,1e8,last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu)]=F;a=which(primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu[(last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu+1):(s+1)]);if(any(a)){last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu+min(a)}else last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=s+1;};which(primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu)[1:n]} ``` [Answer] # Python, 5199 (Cracked) Trying out this approach. See how it goes... ``` lambda x:eval(eval("'eJwVmDW27FoMRHNPxYEZOviBuc2MmZmhzfbo/30j0JKOVLXrlMplDFSIrgJjO5EBNjaH4UyI8ySe6HytrwMEZTvBriX1q6p42d0tx35NoRTJLdo7orQk9qrk6EwQB2iRKtpCR8ymnseOkNCjE13ethWOt5y/pZjP9YMzrst9indsZlkxdusyelyJNLaw1CUVosC7P4LdCgUAccFEdrxrznIzpyqYYzBZgJu0fUEKq7HZxaa7nqjPCkkiy3iLArLpjvoFMsDhZOK1lI0NL8Ky4zsgkEE7MrWes4l20zO10nfd3NiUaKk6vNbEzu/BYV1wsyRfXtIXdH13Wyyv1Wi/fE1m/YuDrzkGQmWtFlBbud97+/yEtMdm4uv+vrf6m5B7UA1KN8NK/3TZmv34VEOgRmEJEsZzsVs0BDkkOeY25tCnxxWkkUQAQUwJ7vnZve+LuWmeV04FulePd2o/Or3AXjSAoEzu46Q8ElaNNm8+ts2UYD99uz7kXgdX24frQd39Aarva3I1DZfple+r2PD227rGza9teRuVSLy2DGeZk3zG6zbQuV9egEsmm935F+j44Z/bD8ZwyE9fWgU68+OTY0l3JEbEMFosAn/E8hOqqlRx7xDXmOCpYSHdsrvBFj/u7xigfNDaShxXrZFmpCbPLwYrQyEBusUfAaIWWCbXHVdivm8jS3t1mJmilzlC5lxYD0M0J7YsLCxuyfoIjz/fcsnXCyS6BuyZT6SAxGilgP/EP3dtJJpW1SAIHymi2OpzLIr9DYriR7d/JXMIOyqdYluoc61XGiGvpluEZ6RcRD6lsLfRnATyDgLCmQbiYFlonx1Uezs8WLDB0iRHx3+/yuiKOBZbOPRX6dZpN727LsVAer0rriDZbzqsd8iWYOEUkUwBrfGDBWmW62J9ovZXHcI7DCy0/gyiHC/QTy0OMf4m1orNF6WDBRxXhKKZm38K+67lVG8O1MM85JBLG3gf3A+WbGLVSjBHX+p7uDrYb02mn+9BJNt1aJNwSqwakpVSyJLxFAhHD9PcVRpS1S6s59oYl8OowxQw0eabmq81f9tkM3tuypsavy6x7IrhoOJgXNzY5jFpoxZFg2QFpANFNMEEfMuyqViMn9hhyIkB0Wke+Dax4yfSj0zwzwAr3wg+rJ2QIFmTfueD8QVTg2iDI6BP/eZDTanFD7KbTJ6Re0vVmWE7mB0QS9qNtYCI7tAS0XvaekkTHSG4cpMOB3EV5KYhNLJNueL9oOtC27D4tEnofU4tEo7vz9qD4b7rKC8FYyZoOqOAOfmSH7pwkYS5FsUS4bP2Ou77RQQMSfv3yt1GGrgod8bt549ts5dw77hgd5TDACM9VqOKl7i8GfpZAtAdTYcefvu/ZyXxq2dHiyt+SFZ0W8BxSTNe7pRl7d0qp89VX7pFuTmqDVKb9lAjAjTnKpdGYsbLqw9AfsFzThIq7GjZho3uwy5UdpDYnERU2z2H3/hYvNboGmE5ger3gZcEJ3tpfnluxqmDru7J+xm5S/2IAC8gruOZI/vWzwNl98xbP67q6auflhiW0ZRrEcMS0YV7mRdrkyiEHCjMJwp2lWQYVxdxs4Q7ouyvJ2A4JH4xrst4I2T0g5vd0RaNYozWfjSsEooMEx0/J7bykRSu1kbYCs4h5GyUm16haMjBhHJYelDEgxhgYPMGbdrJts4/0xiu39YW4ih9MrxBSK+0IUMEffFL0kv+4nXOophdkE4Nrelnevs8/DomWTOUIc30CjACLXXoEKfpngunU7TxkLDucH5VMfwUMali3a3kvExI/YTrEf+SE8jSh5j+rEp2FG3Tv/auBGyp+gPw2EqN0XN65CBGM/Rc4c58Yffng7lvqpUfjH+m7NaGywr0HjFjCCRq0X1dT/JN1G+OH7pamKu/Ar0zQMfYtsr3V9L9krdVFhxC4UoqGyHxXKLGN/FNoyjFuGCZm0qO6du6/4SbgMfo6S33LXczjARHnLDIVAG0knSGYAKX0r4+Q21o7p7bRYNfVElbs9brvvsZ2BCf2n08l6nggW44ZtUZxZ9qFYl5H4ou4xrheygFrJ+A0Jk7Z3cCsS7vIZES5a72BjdEoWxogjZynKcwboRdgLhZZRbTOou7NE+7r7iQHdeP0OyNI2QBDbTEOG/+1thG6boTGlFyRVmgZzPYGFowSSjVY5B09WB7xJ9mKB333/3qWfS+GfczbDAasTm/zsTmbBuA+Ky3+HlobJ4NhroD/1o+FjEAyVzQNEcwib+JVoxGsZ8gJEDOl6FW66uDnP1VVu8BGnVEOEBDtnMOgK5imCeZNMFcnPU/AHh6sWuUJaQyssVLF4NO2ftsJcYto1GMkzhgoGZ7VFzgvAa+ztkZtNZq9nTBNJBeVwAvc+hhBA1eynIL5alMiqM5Yp48B3p0Af8lMb9g8A7eMHiQfT0rWlGJnsU/p1/HgesHPSrH9DjAZ+aAXk+UeQOI4gUBG8DIXNTZu2V96+z5QgpTa4mc5XPE3aWDRzeFhVNd4ZkznWjoS5SLn7ZgaV8SwBmtzuC6L3Hmt5590FqYp4L0fsypXZP82SVOYopIW8bS1QnzmbrNWhgVJXPFgxADVFuUdmhe8ca0GbiaB1H7qjjUYf2x1OewgzoJFDgs8p8Ry/z3crIHVjgi9sCrgeWkr03oGniyd2jNaLmOcdezSqMwNTqAIzD8G/96KGkrPc1amPWp2ULtk2C7xVEFzN8gPjrB0RH+TNVMwwKiGfkjzWgPQSWF8H4xZOfUcyMtACiPpqMcoUTzUy9h9TqUUj+2KiHeLjjwn2RmGepGP204tOHbw/T0mn5Df9CUvWwlV2zDfeoah1xf3iSAOiqiaBDa7tevfA/vb5wVeRNEvx97Qj7DF/Wdxcx4Y+5tlYR6oZSKRDNDJaK6YM8ESCVjSTZvejYIIJLLo71xGKSztdy2N9l98h1Gkq+YrixucemmcAxvRMa4AzxCqvsgtHMrlY2rVz7TCAsatev8+TTz5MCJj38vYpPpr1uVZ4i5wlTuMguuWmJ6z8fhlmp3J/kzTNE2IqaQpqZev4jafckot7q58sXrarv9g7osoGD1F/tmsjG3a5bd9gtNCfrzMzXw79zQ8/R8ji1XY+kTTaaXcT7bxJZIBDh0yZ1oNP1UgOfEMiZchUBjufgfTc8RN5GHkBmrxeAHFKWTb/G9z4VJon3vBPoEVegfHaTaQXd9vxzm6PJUup8lqZMYTS8fDe8V+CmCOJkGzLSC0Teg4DEUN7/VZVjQw5YPY061ibrInw7qwZ150yrJ59+ElUY3xSfxrLVntxk582wbZ+CPjOpUm6LuNvohkte3Zn2VbEMr4SLjiSwm19yOMyg7wM77u/NVfcZyYwcDUhTb4dqhTRTnd52/YRMBvrwakDUgF6pwvqGdA5XuhAbPrX7eMYS98p3H/bmMwb7MOGTzx1yfMEU5z0PdiQ/G9mX/Uoyw6HDbgJ913KlpRsUuz7GO0FJUzvTIwlQ36eV7s9r9+zBMJ+65PVF3+LYQt20L+T3Whv/DEl+htmozoGigdBow9PovEh1eWVQ0njbGLvn0n9TIEKiP3hqFyVmecc2MEDFO+OFGlSPgy1vaVAg1KqMhN+44lu2p+R0YAEuafxCFWlXH3hshf87S9KnrJIbAKep2sGHq/KVlHl4SzoY5j5N89wbUmH+Fq5o3rOaN77vPXK4jOQ0EC64ZfyAKSbnB86W/QGh2Ph4/MGGs33OqZ387dA8ENI8as0Jk0o12q7rZvXwoqnO+ImQ0DSb9CPwSgRF3FXhpxGLh4z8QiNxA48dy04Jsr3vQe8kq3/8AGP8dtPCTsCPvkb8sFr98+0IsSd0xwmg6TfuaMLUA5wvDO2u0SNyn87FqDJVJVI7tpL0/1R2SalPcwYp1yWrVYMwP3tchR+Qj7OWcEwrYTKMmv9D4iox8ARNJVKsYwUu+5pb0EQuqc0fTDu5m4Zuw4kafFphM4W8T4438ZgJr+bOlRc+X7VPPcuxn4PFBENL9shsQQwfxs8e9Pnafn6o9enSU0CPTKf8QbwpQ7C9CSFniLD+ak+bty7yyPFPy/anTdv72I96wj1U5WNr1OWD1pQm5h2QdUH8oaw2ZoVC2UNvL2uBHjf2oTGm8rZOx7mvHT/oypPxsEoJA5k+zyI6sFljVfYcSNhV4cHJ3HPRV1pupwgfB8QqxPm5sBaVs2B9WW0zOi8K/DLkrH30yKo/GfWEaVHqXvtCQeD3ENqSaQJs+A+RljRla0NqM/guaETUjdSFQzsCso+ioD29VDFTPQR0Y0JgEw0RjW3ZnMT36b8nZf37hPR6XRTDLsUA10cmiLKjL6eYVLyiV2be5tlEZ9R+P/bzsEbD6ppsaRlM+RyMXuNdx739mUXVozrGbGxvBuOpuNfgCdkBxK1yRkLV+a6GtB9Cb/2LYqWcjHToZTdn1SXguSeXOZsUUzMhfVx6ZiGeUlRVSr7Cf6877mYQEFviBF+t5s5Ul7x6harT8qrI0do/m7lt3huGTEMzphDHfkzRUnbwjH+kYUKjo0WK18u4Q/d5fLoSNe+lA/74y6bp+XdoWmHMeS/yLMiQCugw/WDirGRO4C2ZbHxfl8wEcSzy8fOGywShVmlkhg4jqfkz8IvcSSB7MJcX30jz6+2h+fa8lQnbKfgV7uX4Ikcp0yynhYkBxFBTIGKROvqWwAsmi0/yjskK5/tA0IOKVy4GM/S68XlA3/lmXTVf+ZJI+IpNewOxjQ3mq7iF0C+uGfXZrkyxPdhsTSveErxttffRT03jac6YJ8dcb8HiLEX2zL2jJBpHCEz8BGR71wX8dzhjTYGTT9aC+wuY8+dOiM/+usR9FO1wqww3qOHWRtpZuYRZ8TmBuka1dcrryq5rukDl+OS7GyIf1vd/Fna+buH1PWRQbjp4+KVADZow6Qep3lUcZ7aoL9pdLTf4W7/PHZ584AGtmKW/xD1FvzFGh5d83hF6cLNpkgdm8qBuH2Qkmhv0HjvpCyDLVUW7O2XkxL3BEVesFxreviIAPtucn/DV/twFvf2AeITIyYx3pbsMd5oL5rDHookzUD67El/PO+Vdrwlb+XQy3BfefPYFnUG15bJwlAN6FJSLgE0Tm78/OIPCqaJbiJaud/wP+B8oHe7w='"+".decode('base64').decode('zlib')"*56)) ``` Code used to generate the above: ``` s="([2]+[v for v in range(1,x*99)if 2**~-v%v==1])[:x]" def makeFunc(s,g): return """lambda x:eval(eval("'"""+s.replace("\n","").replace(" ","")+"""'"+".decode('base64').decode('zlib')"*"""+`g`+"""))""" def valid(s,g): s=makeFunc(s,g) return all(s.count(chr(j))<=100 for j in range(256)) g=0 while valid(s,g): s=s.encode('zlib').encode("base64") g+=1 final=makeFunc(s,g) exec "f="+final print f(50) print final print len(final) ``` Cracked... See comments. Anyway for now, seems like once you used a combination of base64 and compression (to distribute characters uniformly to maximize possible length), having a safe answer is up to whether the code is golfed to the optimium. [Answer] # C#, 161 ([Cracked](https://codegolf.stackexchange.com/a/44603/32628)) Decided to give this a try. Yes that really is a `goto`, and I think I died a little inside writing it. ``` static List<int>F(int N){var l=new List<int>();if(N>1){l.Add(2);for(int n=1,m=3,r=1;N-->0;n++){while(m<n){if(n%m==r)goto x;m+=2;r++;}l.Add(n*2+1);x:;}}return l;} ``` [Answer] # PHP, 3337 ([Cracked](https://codegolf.stackexchange.com/a/44638/4098)) This program creates a function `n($n)` which returns an array of the first `$n` primes. If you want to print the primes do something like `print_r(n(10))`. Warning: Very slow for large numbers of primes! ``` eval(gzinflate(base64_decode('tVlbiya3Ef0rwoxhlm0+7LxO5sH4AoYkOATnJeRB061vRnZfvtXlC8bsf8+pm6T2BvJig707092SSlWnTp2qfbg/f/aXI4XNxVuum1uO9Ugux+L8Fsrk5mPPYS6h1JCcX+It5jnury6ssVzcV2EPfsdH23Ysh1vja129C6+hyEbti83n7C/ua5yQjznG7HZfjg81uFvAT/GlZodFm3/d8W7B/zefSk0x7Hh67CXkCUvyDEOSS3GJc12xZqv54r459jC7D9Vv7gq78GVdS4pzDDgmzBPOWNdAe9CBoeJBCiXClg+Vvs5hu7i/1RWm83WxUxGL+QMX9rjZKbewBPdTzeWY3DXBE5GW3cM6Ob9G7F/kyHtdb7X4EtgbeJnmenHf77yZbZDejn3GLSo+iNstpCVivcdqeI3ckt09Fh8mWaBGIkhxLlUvi/uIUdux0q96NTqr4OjkStznuNQd4fo6eTjX38jdF/fPePcb+X0NG7xDoQlkhEMIYovccJE1xGvYF1fgTtpAv1iDRR6OPVIpsQBC5ObuTb1G28LDReLWr8hruNPKIPQwejITXdzhingPKXkN1TXU1+jZR2bFD28+84/t051DWRFDoAWPfYr4a/U4IcALf8dOBIRUSyJH6TVaAC7u2xJh0QAiOIRi7Hx9rYFgnPxLJCRyPOYjkdvO3yNY2ENSoUbbUyN+cX/1YUaIM66x3Wq268gC+G2JGhNdwSgVjGuU1vgSEkBkuTpmJ327B7pkDotkttjDG+x1h/tfVo9TimB3rTO56lbXe9x9mtwbopRCwvu4TBKcwWjKhGOJB+UshayDTO9j6cJxdxnxDDtFRIwe8H31dRY4KrY542hPc1m735HmKP7BFn3lCPBvaDHweHH/wL17fm4eVJL7Vnt8eTMT87H4FUHL/jUWMolIyMsODcATo5wPf8EV9oWJjBdOggryI7afa8qwSVzMd3lN/h4XL9u6LTqvXri47yoI7X9lmDgMKRoyceOK0241YV+KH0I+48skKCbu0NRHrEGSx1637RcOG+O/edbPc90yJazw/S7AZFLo2IWBYBRgG1gaUNB8eTKKYy+F45biFille2A4YIosOE7OwBG3I6OaBPjqJa7RczqFJyJHP5NN4jcYcio+qwe0oxccG4GrnQRDJlgGAP3owEH4D76Cj5EXRXm40yzTdP81elQUohjNFgq/V25qlguOOrfy/em4qXvX/6Zoyrl2Zw6X7vIDrp2pwPXMHels5BbxsTAWg4uius8t2hrpITT3Y63lBqo0VxnoON5xkeAr91XNKU6NvPZcuLcNG4yEXenzsc52xTACsLtXiXviWiXeXcNcOlMohjvi4KIzvXOyCnC5HJ7L+hXwwAbkV+GNIbTtJ0KkeS7MQpHjEZTkLFwm5TG6DSX4zCWtjLwoBUmovhcElUCSwNPAi7xRwBooJSuHBopm4CTk1Xh2I4KpfvEDWAAuopuQqAwWU1bMVsI9mhNCvZIGTb3ogZ1yJG26BxqMdbO7CL0/KueHLBNfSu53GSG3nVhvyp3Nh3QSpZ27gRn4jWhXgZXsI/HutzslZsf2Wc1qJeaUmga6J3a1a5B+2TynCAdWUnLwUq89LM56kRYFAa6TMMG6EcW6/xBu+0yN0w8mDSzXdw1VSzEyRouSFXmpRyD2TGk2A6oLolYTKpIqfst4OLMnJXu9CQ0tlKJvjV78QLHsCjNY6cI2BkRrhtiHts9hEBpiJ8LYNcEgf0T2mGqwM6l8T07k+OA8qcDsb47+J0H5XaErxRtEypX54n4spjR70hvndgRqW9QyfAChMuAC8voNKmppVDU+fiPO8dwgpZfoYC72EtG3B7vGHor1VsoluPEWKNNb9XyFEZ7LGpdfViod61LAxmwpQo+AjTBj60+khEtfwiFQlPazW3tyuokSrEhWiishk5LgQIBUPXLcpMPwhDpdIzRspMDldWhetCOwRkuKzx/rxB85D6TPa4JOXGKlWDO1t2AqeE5E7LDf+EBlKVz8hlPFbE6lFTzutSekJb0YIVU4nSW9KDkO+BUhXY8XuJGScvhYjYTHmUA6gzWfALfsJGW+UaBonejmmuw99ZTKCdRKcdN9ioRmuQm3nkWMt/4bw9G2DSyzvQq2Vp3NUkOjFn0NUmOdciYQbREn66xJEt3DG80aPFXmSQquQUBcSppBihaDS4gzYsu0EF43g05XDjoomJR6lzjQZOukpdERe5trtLLDfVvTMZVFubARayaWcL1xHrKVhahikHprazO0V+tDhyYPrPFjZ7JME6HZ42wVhtwAnqKucKC3ASITcwsu1ep1K1jsaOZtZVBCy3Rqg+02EhkGKLZS8yj00l4xF1P8kq6jMcSAHfymR1QLs7CWkInlhVVBGxWo/1USjHYxAI0MpzYJEy6fLGmHGjQmjballKYcdQtjM79ljJZ47YFYCA0aocVA8KvtrewFY++eC4sgMRoZaaU79R6nOZnlig4STMH0DXsRFz2unUGb8VRWbn4270qBBU6YH/MwioFRBGhQ5zBI6FHj24qqtwGQ9LC00aetj42PRAfNn05thlpmLR7r7uZQyzu5OmSTzKr+P/eKz71Sks6RijbvSps2jFA5pRaM9glZmnOG4mmZQxkujbA2hpT3k/WH2l2MFbvykIAeBB34CMBZfzMXanntN58/qfndkA6aSfrIUflaIzbptVmnKVR6m62NknT5ZIBIVOlarJzrR6xTaV5h4kkdOEjZnvFNc1kwW48caQ8hKKZOI2ktkqdB0+lK4ldSFk5UsQ1MrTgohTGSrPAJC8dxDCVwYhVqHK4FVaRfsR6sMfMw3FTx2yrKWB+MbuQi8qeRAuLDZti3bKRisBYDgo6iYBXHk3ABZynvVaGUjj/rEk2iNQ3No5dhhPf9fu65tILVYoJBxu7N9aJ5LHJyU/HKNLid4KwCgIRgn3vKtF/0OM85pCAqtpuVxP2n6crSygI1djJAHLqVptfGhyzw5D6TTeS5R1SI6yDoXCkkszs0aQhBAxetXH0oK+VunBHN+k8SrVo0utcDzZmCMh1jNF2h4y+1TVRzowRu3DQiml0aqfOsmBsB68JstWly8uq5jt3eIDZL8kPNEGFv1MbAIo/oDChyeg6RIryP006y+7OnK4wqEdy/Pz7s7359iM9fPj1QRwc6fQYGk//l8d3Tf97iGh6/pPfv3+t7vEYqh6frkR4ffn7+09PDz39+iPjz/ft3v8br40P8HI+fv8Ai+/7q1xyePn6kt/zM3uV//fsZa/F8PlCm9G1+9/xMRiX6l6rd6UOs//jxvw'))); ``` [Answer] # TI-BASIC, 4513 ``` Input N:Nlength("ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!">N:{2>L1:For(A,3,E99:If min(1=gcd(A,seq(A,A,2,A^.5:A>L1(1+dim(L1:End:N/4410>dim(L1:L1 ``` [Answer] # CJam, 7531 ([Cracked](https://codegolf.stackexchange.com/a/44584/31347)) ``` K"t0}Wi+vjx\"`@qYZpR@7,c}U3e6s:hmpe* M}|C`?I_WN6'a(Z`#%+oOE_N_AqmAgaG|OX>uF5Qn!m{sPQ4ki;7]0-ecJ;[*S!qn#V=:4aRtpk5FXXa`5q|!nkUo9-u>]Ovf2('(^~/328U!O&3[\"Ho~w?qZ<86]Rvpmtf}*$yYXeBcOYT1$qG+S$S/>j)D)cd9H7l*l;;c%1<?JHX7 5o0ii7-@_xDKoKG0ir{g{;$Ma=Cbd 75e3%UAK/7f'sH OuI*),YmCxwEF';6Sc,u76A&1j~Jo9c0Tq)#)tQKw;Mr`pk!br#Q _B,mSXH4#Dy t{vmg8=%cznRxw9U,_5[xGsS[$(X:XOfsslKkj%Lyx!}C<uEWaS<yn->#'hK5d1t>&-zF;NiO;u?Kf_Nj!Vxcp!u1ylxpUG3yp^I1?y)4&[}fyhf''o~VyE0gE]L&eL$Xs6(l]q$FmK!&#JeP8)(3ADg 600qEk;XITtTvO+n-b#D)0H*{:=g%iiq`-[JBYvUW#'4GcKa!vBqD8#\"r|beNA}K})Nnh_Y5N,zC1pVP{pjV#Gw's`WPO_.Vt=M`fHt:\"c*zBD{**2D1 h)baU<I+9-FPoc&O(%,EZ_q!VIW]aw2i+i![IugzfHa%:CF<guepsH!hn'kpm+},T1f:]@(UWI!19h)RS`%n*|*'#rKXi0PY<L20}VHG]GturEqBKe<-g~YQ!4*'78U!#,Xxl~|TM~DH!vZIF3Iq-(|5-1Y.UJZfBt.GXvt!e[6~Ez.QJH7{LDP[906rs|mC0)iZN;9P--Y]DkQ MX)wTRyvkFBxhA@n{X0p\">0)i=s~<CXCS3]H'{DcR3Yo1tg0NG!q{7n5+h_%BTYsy@#O'6_%{BP\"9Uzthw^5`fqciBk.rBbu^e}l!HW$h+~ho:8A+ =2n1Nh\"S%iqCI!Q0E.K$&2!$75bG@,EV}?a-kjb2>,;\"MOh7QR\"]$f[>E|oR#&kDD(^s&i@t(6#Td`9SJ}tDVB: oZdclb~s'*qMK pmjb,XW*[S[[7O_1|)Qut@1=I)9vB%I)G/~h_$y%5H+-ALcT,Y7WcG&iGc9joTHwaa9+{97H5rvi2[Fju2mdyqZ|u7HO4SE ZrA1S}wUv:>}=)rP+mHsXhNFm^wri8DtFdFddI}]N{(NyeX==qNu{XL\"_1`AqG*.llvLD\"J|`KZhut>30\")aeT76WMTu9mcFcLiyD4!&QvTlo#zF}W6pljg[{_2TTC6m)8jTW1M}ME|Bv.k/vAZg-q^&>q0<,<{ih_vyM~n6<ewr/=_u`Wj%XGP!p}+^g!!TmaK^WeHC+U\">qz6'M>~D\"L)Fcdm7Wf7`B-gqw|6kr`PsK;`cM\"Q4aLSG4[i+D3jg%?q,\"7SS-)69yHCW|L);[2wt$8C|JW=b*(rhj;uutE$;{e7)jYTAm#`iFUdU3iEK(q$&D/E`x9ZY'[c<HbDy{gV?eb$oOK\"6_ USFV a'<OX^o{A%Gn63tI[,P<=w ,c/=t3Wl9[44uX {^+(vho?3KxyezT/8_Qmm:UYd#{Gj7N2S2K4S*Iq56@S80Q^gME/p8,eP<{\"3xi-t-Cm43/HzA?a\"n(!l)aM!7:0BA;SrIW*$sLV>bKHRh[be|I 8m0*^X ;m]UBGhi'[_~Gwj@PN#i'+0^`TW:+IXCkPPCCh%{w@Uu#xqa@5otcog}sivL7nYO5^y+:`.&M)Lkn4VDMQF[0Y_=9, \"pZm{iV$3ycdn{}U:8)`3H,F340[|o~`DfHu?&QJI0g1#kF-`|%(4Ap#R/Fq\"1<{%CV6TucD.#pPv,mLW=*LjGS{O<eOR:dla) L[$ue1]lrdqPs_@qAy&]y&YMw9~_yZ]95C%JyXa$iR2U;{G.tb%lDx+_4K5E.{tYvvTcD3Ypq>EJVg`TI)X1w,Crw^8AAV%9AGq%].T~+$o~c#@Xc2`1r #,=/RE*8/b#/% Y~LyDrIPrN;hFt,C^1<Sa*LjPmPl9787{GXn}E|EL(&V-c&.}hSkEXG7[yf3pGlBV5_sf8-[{i@l0BY.(Q2o6)|km/?}.BKgm(i#pk,W_^FVs{r$1OEtI?E-8?VH|uRd'0xP.9,'OSjESAtmcO3Ikr\"kMs.!E\"M~wN! o^=]p0D ?le=iT$,M5%w{+5\"aT@YOj?iww>|;y~+/6z_']IUkqc>cG`V.[9g?x2`rE4y9 ^\"+OHtvia&#hrJL<y6kB*t7nEuAx/+A?:ZvT93VlH`Eg9w%&xRP+5-R^s6ez}!d#tTPCq|3v/d_.s'WZP,Wyv'FL'S3HEuBg}elwyl8f4l`{o}3vF=p]Ye1S\"8G}M<pdJ(:3;/dP2M8%8;H iln>0]pzU)7H)9jN%0I~NgV+X*Uw4[bF[Jg5aN`LIjP&m98fg777g+[2kA{`UIt3;UK#9~l@y./MME'XutazUcLz>1gnfnn*@cec8/9_h#@=t>w'oElYr2hx^ss^#X=PHDo%$8Z!f<GnME{gmQ\"$qW<K%`%g0/m)15!4A**;@>/hq@ B|c\"?*&syKxL^P@ $!y#x8A[@bE>#OF.IyP]?q+I@TxA+[3O55{'EjNTSq+lk8iR4!1+F??VFO@XA,1Znac6E:lr.\"EIT$M)wi<l:g!]2'OH107DX#y:Fp_`J?).V~4HW&S+nwGX7Xl%7ui J+HKO6kRO<e3hpO&xKDu'r:?l>aPL_iN3+Iu-s\"? Z_[<9wR,s$8}Q=;3u?x3k?ZsAp$m+??m&T18c|,d[1Alcz|gye-d_-s\"vcQi~9bx}v%O}nDO95McdnKI~iEp_C!%iNr2hnPO!.U^;+~/P^Yrh}<IAmHeulsQlDcKG|$pW)hnRYaa@v8X$ PsiGMX$4(@#6VB@IaQ};@8R0RoCI9enUbyB#3W+bA55uo qGZjOc%k:/a\"^h+V4Pdr|Rp*^H<7/5iM:j7-'p !@eq:.u>96 w}L3$*L^l/-[,UyE;|jq3_I1#w%@y(f=+2OuUK$F>xX\"{\"#?Q>2DCQ=|NB$o5EN7<#_qT=Q*3jzFDVLY4BIj[|[R1JP{z^u.l8(2Bs,n]d7[v^M:8]<^.WyFXAEDCE,p{Xdw6_|C[f7.;=*s&>/Y+ hD{OPt6wRk3MnJd-hYQ)kyee./S7J\"/6u&eQLV07$H_%TZb7BdJ2xW6MHq`-U:f^}$y\"F-e*\"v7Dx%l]my%D6! 2`BJ)5=GT{U^iDu;>HwvL^p)|*WvYwX)xLgFyTXM.y5W:RF</5<GME-<Sa\"E!jdqCzX1F.o^iq!Z5D:(|'9}L5A/iOmOaWr 25]=}eN&<Ce,S(o BB*3^2/Hq<>C/j)k)mfw+rVyJ*s(W0cq0_azYI-,p4 Qa.Q1Imz%G!GOIv\"CE,FLj:;LRm6a!cuWl%cw'|i'+gCCIHk]&Rx%emi3G-O;BXr{+;TSDCZNjm>k4MK~=xe c1d R{}N&g%G07hl'\"M3cd2um=[M1UW|qb+,p6/{PnDo+Y5XDJ-y=XZgpwe7)<\"kQG,*G?@_wwr0m';/m)SDsSH?CCF##I]X@7*LF8qf3D41M}>u>k,I VS]BYwj2#w[~0Bd+w;g+%uoXk<K!Fq*)oEPlYyL y!aF(B%E-*KUo>:q#/N;=vTtlBiD[d#?h1'usy_1*l1*+d$N_WN4!K2A'K/}L!.&f`Lllc8_%E?K%s-kUea~[TF<yBV_JBkxO%\"_YgM:Z*12D#s&=wom;8IFcb|-#)5')>nYe c5m8ocKqS{Qpo1$R$%3fxkM9zSy*Q}LEV}b%@^-b]XqVKwD`ppZVW?5'uy+X^4tEU]k;{Gq/vLwo+h-n}=c2l,.fj/yw+pP7JGb!U|`71eM00chW%22p8+#o0dzh\"A>%E_B)Xqu]8fq9&:I4l:9>n'<iUZ!>Y'L a\"L3P@`IeOb0N k5D%VgEU83[PtAn*)=q>#Q!GSBgHw$,)0@}VW-7qvb;xa7;TANcU UQfs0huJOee}6Bf@&!RX6h$SER]-tne`&A*ePIud`v<eEz.K;7FKA^}P_zBtV)a=}9 MbM#1D!+l-K<[)@Qmh878{dbcH|;_(1']9(ZXF5Qvw*;V0hAp?]{O|/j x=ZQTz7LN8ljI6UC#D3u{g\"=t<z0h9tl$C^!An&TJyg(^^-A1hm#j>Oa0s>*g7JO0]\"8ltiI43UJCSnt=BeUYrn)F>6Lz!Fj3av=Lr^O&Ek0&o) o,p,IjWNa~_,+DpX&{t6'e_.m;B 9]A2S*]D//^<,!`5'zP[AW^I4h2_0+?:Wn/cbMgSvW!_%^]f/0&G'#gt?X_gx3/?UL?1}H=Ez<WO@)$3mJaSaUfjPwonHh+k<3`Qrc(;asys}@x!=yO>s.O#}0CM$C?@g>-s81~ gM|}fq_ca@3xnM(xvDs8X0SW2++A1XU|f8TvEeD'dNA&v9W~R;-FFJwaeN>_(9Ha=h@i)-r@J&Xh{&Y<Zz-unH#.o;~Ycs74B;w!]wa:2{Go1;;_Gtb3H]u=yci_M.un.htX<:SAU%'WCg93~H{Kdt;xZb&NP&)@SlY''F)v]>BTH:k<6{4\"tN(-=JK;X#Q.J;<@_O@O_D/0;<V&/C{B/WdvyqtEn;Vd)HBE^=jmRo7#`E? &}0WhN.ui1Tz\"+N+r~F<'O6rRaeNHVLI-k!;zz-G G^m{kp2#Jn2%~)m5<h9w&TC'GlRNw4ux'0DPVH|?5om`g^$XV{,lzL^bN2Z}kT5ss!&5skt[,RyCi[Z0eK8Vp|g:91|W6rru~C1<}u+1JK5l]VTUTHsM:ZS}[fHwB=Ym)0a2%y.xErQ$Sy>RZtR]nZs8Z+Vo\"G$iGS#*R!FHMYEy'E='y1l=D+0,#6]htI;3z%u-[ofL=)a.hCxb*|LP)W(!H}>iDBOwI$P=B,9^4`GY-WZ? CE2ESQ3##*w(Mk2 h:*`0<Tn||iLI$8PoTen<9MV7(VbiO>RX')PQFg%402:A6%/,JgJhT5LVIV;U?O@VRYO<;MYxA)k}CI8wbp8VnH,o7]%Yb 2d3|JV0, ^3W?Z,el/:u3k.]7<RJ+bzy!a>4cq2(7MIm.?9':%ZLYt`?0]Yj+YySf {J(7,p:9,@-|^.%g}Q=[frb:J Q(|)No027@C$^m'QD=Y`<UUN,egc) *_No>V|q?gT*[@2}YZDbn),+w0\"9~%\"V>3+W|-^c;Z7wd>'ger4lJNL$?xXPly9woD4hX8^jH;53R>/1ItAq([v'Wq_@m6G=_%-'Y2D+HI>x}yUnYRFid].k1j+81>l?n`~6xy|vZ6b6@zfn*h5JJLp*mvsH&sT~8Ua6Hqwi,[O!,b!fJ53eu:raJL3Me,LYmxn~q~Ec9q=$$pV3YinQJ}GHT$)+Dx1n2gE{_^L_d-MnEi~&VO{iXxohWa<xkYHn;WQ]IGnw[PNi06tYbSk]c<[teckj9ns8_@]YM_Xo0W9/<L=R@Sa#PZ+Y_]P@[:&]sYo)pUqXcoL#jh2HxM+g'**':~^D:rw?5Ap(C.yK%x]M=HZi|/YG4(>2#b]'e$QcpYW?t},RQ)I|4#u1`d+mXbIF\"]Y9YWIHt\"5i8dnHHr7)f.h|]>ndB(#ThU5E/c]k^4T$[=ui7%oV qakQRMT0M)u(=:-FOSzx*G5GAa!TO.pO2qudwW4_(]Al\"Y{ywcKmaoT=E25?S>/?WWmDD(POe8]y:K-Tnj-94/Y\"],muj\"=4K>KXU;W*@M .m|/N5Xq<wD'+6-LJb8@c1ZnR`g!&RFvo1)QW>p<MH;9^F$*t<kJw=UG?cE0/]l%K&:y.QCIRGug!qWhF6^yjz4\"5qE\"6IxoMC$B!v_-[bx9=*ev;gr:4E<`tN,ke+/,G!C9WfEu;4YV]-K{3Q4GD7~6EUX,b'R(h}UtJsAr^'/ot+ez?EZ^o_Q.2's?Tk(_cS`M:Aqb?/J`kY=w;+ki*O]lT1.lB |K,zF<ZR%0k&GrAx=E+th+lOX/]R,#Js\")0JQK)H:5yws5b<BQ)iei((sQeK&->QGJ-Z=k_M+Q}tK*qkD0YaNw._RKs949vzj4Wf30J^/3L9SG(9l].Z:kv^4R8j{O_pCI)n0E_6c#z%SRk/)yh-^y3m05^,`%]W%8oT9D2tLzCW|{hF/vS|-eeMb{D@,VrE7_@ns<qvGM$o8{+S#yEO?f$~cy%=zCX+2vfn- ze?z/=b5)rHUUx=.;J~Cjy\"k05rbsBI|{vR$ue+1(ZNbr|LV/?=t]P-ux[mRJ$aCFq)qH)yJUL5q;l%p@xmjViH #%V2q1WHQc/h`X{C]m{qAo2i{H T$SWtdA ,j'W`h`p~ZsPj[>5=(?2w]auV/1gJt.ax,bH?ScD-|qP5TH3YQqS'mDp<61q0#kg0PI:w0:/V*j`V,]Y.Wf$.bqUTDa+4|Tz$y;gL:bk!,e#\"X2aE~,*Fd#3Zz5kQl6,fAb_~Cu5%68zPm^ 5SH:D}}$g\"c6ljz>`DvgZt[ 8B*s^pt1^i}&$B1)]S)T=@ySFST=d?qY6Us05[q=op_gK?u]S1m4-D:7gplk`x$m|5S3ZLkD=Qmh7f6f8g7ZOqip`%4/3SF5Gt_pH|6v%V]%(|B4+s4S(Je3A!&bVcR<ns!=Oe'0Nc{{,.7 GVvrPQA}Ean3z3Q]3Pe[J*kKs{JF`c6asf1z\"iGhD9H!%s>$h]KxjcJ]1[~#9};g .-emq>hMu2joS?E(;SVV(4R)B\"q<BG~ZK4VF\"]ei/WD]Xh<Lq|PtnrS,[y;}h|+NZotvW1CY1fo|ovajfWI:>?TU?{Y)o)<d1QF[!.YQFa uk4zm){M#UH3E(a71K?RVm&&$.l98|3h3RzdIK~bf1,3vH6PLAF8jj\"#&9?8lA8&>*.HZ5gnuwX<P9.4P}L9q 7Sou}RFxyG1Igl7T@%!3K-De{tbXcK8?TW^vm@i8ItnWV',&^_Jf&#j6AxRNIZV!YsMGm#{`t9tRO|xUVTba5=|S5qnEPl!6hMRqh}M[g-Q!A<M3$ +'t>P&;3U+`a*T0.br=5_Q=WJI>ZFgVEb*<y3rn(=^y7_)#wKxw;?n3xKl+\"WvoP=7YjuO9Ds3R,5~j21`qf8M|\"`)n~dr\">:8ff787>u0l/~`?z@NNOe):!`AJ8|,hvBMG,<#A^ug\"5<bakdvV\"r$fUD^:8{BK9E<pKoxX=+[MA4?>ry>,lCBChRD6W!7ksyl%PHvW$yG%t[lShR*Va`7i3Q/[K \"+NME[dbU7(bQ;G(~/:Ej zG}3<:%T@4e<vFSIX[LyMrR!6az|WmW@9:wtZO!=N%*<@<SK9:rzG\"Yp?K coGTM*9YoU{]b]O1F*K%bma=bcs?4IqjW`$.R`Uxor#<;$]k,2Xr$9'K|UA}xe4|iI^UuGtvR`S+5]C%WZH/p2+3xTVVmPT_X\"S+l'y>e@mgL!*p* w@A4&~mr^P)l8?9y<9,N`//TA}H@?+mi&h-#jE~iz9! 8/BZo~}_2fQA{C{v1r6#r=%Zq:Tu[_;&4|stlc=| V`VY1?J!,sxS5-|^a3)I"'~/'\*{i\)mqs'.-i+94md' +\}/;]~ ``` It works only in the [online interpreter](http://cjam.aditsu.net/). Tested in Firefox. It doesn't work in the Java interpreter. Changed it to create a function T. Use `10 Tp` after that line to test. [Answer] # CJam, 816 (Cracked) ``` 2096310474722535167101644870465221130589294718524480357298593539991449081456134974040327647811988614006547797131583006214774425505300308072534652704698066198168917157808088127072977533505828030424680462284796680517062482806071903877790511864982169694627161605805004020026776166437905874324921940992417561695490946773393335345359408853148348949580796568713745813831280652341152402924541125638927689856083360967358992399503448120976930749396205332801012617624500616793294935391926550972449345223742044846417092758797166517935273839376542415759222999108744843547749052422322505847239684550378130982502607844441524249912214473298703307285931801940096458075553488261398391072450942373513854346538654787042832255689633663897703600453311016458268536228117201022525438843626260325862965735311855887334994546704703657K)_#b:c~ ``` This creates a function `F` which can be used like ``` 9 F ``` where 9 is the input `N` and this function leaves first `N` prime numbers on the stack. [Try it online here](http://cjam.aditsu.net/) [Answer] # Java 8, 1785 [(Cracked)](https://codegolf.stackexchange.com/a/44602/32700) This uses a magic string to generate primes. ``` import java.lang.reflect.*;import java.util.*;class P extends ClassLoader{public static void main(String[]a)throws Exception{System.out.print(new P().primes(Integer.parseInt(a[0])));}List<Integer>primes(int n)throws Exception{byte[]b=Base64.getDecoder().decode("yv66vgAAADQAQwoADQAmBwAnCgACACYLACgAKQsAKAAqCwArACwLACsALQcALgoACAAvCgAIADALACgAMQcAMgcAMwEABjxpbml0PgEAAygpVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBABJMb2NhbFZhcmlhYmxlVGFibGUBAAR0aGlzAQAITFByaW1lczsBAAFnAQATKEkpTGphdmEvdXRpbC9MaXN0OwEABXByaW1lAQABSQEAAWkBAAFuAQAGcHJpbWVzAQAQTGphdmEvdXRpbC9MaXN0OwEAFkxvY2FsVmFyaWFibGVUeXBlVGFibGUBACVMamF2YS91dGlsL0xpc3Q8TGphdmEvbGFuZy9JbnRlZ2VyOz47AQANU3RhY2tNYXBUYWJsZQcANAcANQEACVNpZ25hdHVyZQEAKChJKUxqYXZhL3V0aWwvTGlzdDxMamF2YS9sYW5nL0ludGVnZXI7PjsBAApTb3VyY2VGaWxlAQALUHJpbWVzLmphdmEMAA4ADwEAE2phdmEvdXRpbC9BcnJheUxpc3QHADQMADYANwwAOAA5BwA1DAA6ADsMADwAPQEAEWphdmEvbGFuZy9JbnRlZ2VyDAA+ADcMAD8AQAwAQQBCAQAGUHJpbWVzAQAQamF2YS9sYW5nL09iamVjdAEADmphdmEvdXRpbC9MaXN0AQASamF2YS91dGlsL0l0ZXJhdG9yAQAEc2l6ZQEAAygpSQEACGl0ZXJhdG9yAQAWKClMamF2YS91dGlsL0l0ZXJhdG9yOwEAB2hhc05leHQBAAMoKVoBAARuZXh0AQAUKClMamF2YS9sYW5nL09iamVjdDsBAAhpbnRWYWx1ZQEAB3ZhbHVlT2YBABYoSSlMamF2YS9sYW5nL0ludGVnZXI7AQADYWRkAQAVKExqYXZhL2xhbmcvT2JqZWN0OylaACEADAANAAAAAAACAAEADgAPAAEAEAAAAC8AAQABAAAABSq3AAGxAAAAAgARAAAABgABAAAABAASAAAADAABAAAABQATABQAAAAJABUAFgACABAAAADpAAIABQAAAFK7AAJZtwADTAU9K7kABAEAGqIAPyu5AAUBAE4tuQAGAQCZAB4tuQAHAQDAAAi2AAk2BBwVBHCaAAanABGn/98rHLgACrkACwIAV4QCAaf/vSuwAAAABAARAAAAJgAJAAAABwAIAAgAFAAJADIACgA5AAsAPAANAD8ADgBKAAgAUAAQABIAAAAqAAQAMgAKABcAGAAEAAoARgAZABgAAgAAAFIAGgAYAAAACABKABsAHAABAB0AAAAMAAEACABKABsAHgABAB8AAAAXAAb9AAoHACAB/AAQBwAhIPoAAgr6AAUAIgAAAAIAIwABACQAAAACACU");Class<?>p=defineClass("Primes",b,0,1052);Method m=p.getMethod("g",int.class);return(List<Integer>)m.invoke(null,n);}} ``` [Answer] # CJam, 6768 ([Cracked](https://codegolf.stackexchange.com/a/44615/31414)) ``` K"gy;(q<hE23_@&]1;rIYoZA=(6j-'r@aJtcLDxe#19#s1m0VN~T|zD*YAS?/@LutnDPg'JyS-4#3y|CeTgN&GPs9D&p9!D${C9j`isBvuyeBE]P)n<ofN;m:rInU%g-EH!nQxZB[Q8d^:0*2Gv{yW9>sUD'0Y5K66tq6C`6&4mX}}790d;7Mxc`AS:m vo~q5utb4.mJ{UV']K#HXwYu[|py8DdIBD>0!^s7i?N'7krrp/iqZPCJ^?SNoOR7VxQ1,w:ID!VSf,R.TFV!tCAlwH9v&d3w8F-Xvt/i%j%%vA2{+kX]i 6_T3SW1DkB~,]p>$:xWX/eF19n0[21AI9f2(@W<?n2AX0iV{7SJYDz*!t> ;nb:n+OBz__@WpDH7lJ,;6uoJt`g{K}`df1TG%K~OUw:H$ol=9nFcQOD+E5*ekq!.p`P2[Z'u8=J&t5TieuSR'6?-g8>[l]*;Ko31l|M9p#)[3b5J`[SJ=Gr6Uns_1objzol2&k#KYoJ7!t-M:xbh-)ZV.w<S*ty;s}tahNtQ:Pza}rE@n3&02{a/SQdkJKe3+I6*^9)K[owPNs^6-4OG^lU`#) C3L_`<].wrk>%+yE??[CQG{|QSEw|NUN=9rf+wBxN p83XJeqKV&{#TE<qbFjT}4+;1PMolv?r+quS,Bm6U3#>=ZLDc1ZQ=i|Z61l_XGLG,v,aoX!67x{|g`Gu2+Nzu~VX]`h'Z>cC^Lr8%*uW23UhVE'/cPFr(!+@v**J&(N>t^}{e[Oep}1nR+1J582iM'B6 <euP !KZ@$+2:oBzc*%e+s!LE|G*MH`hIAf5k]`AN7US Tcj`N/VEYnfv|Ji9$}Jcs%+O<8TksXi5mW<O.sJ[!kL#I!2FOdZj?@7D9}%>3f7!>H&|XHvBjd)_.i'9BeACd!:G;= x;Q[5Ug6)'=(E[{!5q_Y$N<_Qe<rA1LnYfbQg@Uh]C>;ik5qSbSJmSX5GXDEN4/C,[7U:w5B=|~cY2ePK57Pb?f#|0YE:?hDs*ZxAOR?P1HkU)U/IyhH4$V,6DdrULw(6%S9J7mC,!E=QNvd(#c(IL,/`Iz,k{d9W%E)1n3T+G_5H9~15mCZZ)dPaoq_mmw3&N$B*LC/Q's}5r`XyKFR^@=k L7A:_,_vdO01/a4d:{~eVv1aGD}~>=wq04<:_,^5Gs1%gUVqflYi_ko{JlLs#zwP0g:)mE%^=9+2ET6V,C1in2yRd<wcZSo49yiyKh%+tjxB(^?!&MzTfV]Rtc3P)7-Cf t9 )&o}aGK+ex94 #erT>N[5XBK#+z{<Qk4}n?m12wHX_|`4Y 9Ku}V!XtPrc}TV56x[(3.?~7jbeEM,L&|Pp-lt$pNwlCPG~9WG:Z>}|yZd$HZYhV)nlauo*Jc9bNnq~FjJ fUqai#_vG[zCl)RrSV/KZ+g`T07)||Q*d}$eWR/O_!Ti+dNelS,l:OLJ0R')rr7+%,!pUN4@Qx,AlTYG-;qc!nn8RqqikP!m1YtAxWF`2<;@XtXYvzY.d~1I@W/h5&KR5K{L3iHM!aL /'%%4ID [}c7vT&**B9g`!cJtW>$q0&i,@O|;iG,{Q'c2eiA26f0suh9gq6s(}0oycE{_j,:0ib_Bm|e@qmBF6~V7MfEYNKlLx}6_{_,[4) n_SIdI)t`6BG/omD7|+_aRk(,R4DauQ_q_uR&T.6(UM-W|^[g|KV/AN*k%-@>uaGF4p~'g=tTXv#gVorC+d%V,`OwBNb6v6}3n?d'_SCm%d,LKTR<Z=h=u*LUy|Sj~w;?VQ0N],m9*/6l,@b|0orLW'V)n*$0XV8w(<H|;.Sz'R<j<<bs2ix.Gf<aHfgxIwyzn?i_v:;y!'7#QI=RdAe>d;A/}jQlacrL+>RwFc7'k=+$ >tzrDaU1qes]{w?CZ9Sl'q^lYc$7H@L~jJe_/W|^%sh#JJRhy=@3HVS6%xRw?GDWOZzv#X>y*%kax$<zWXz`BHy<7>qp+-kU*mPS(L^N2V.[S>A4SF{sTVGAs&PEt*JT{'>5WM./.duu)!T4CMBs/K*z'cWdFeI7Vd~[WS5cwy:e;JvB).FLka#D9tQN*_h-}i7C$2D1<:zq2.n^,I?[>9'~X:V/M.+0oR2:ZDw&?mM|Q_A>le}?+F;HE)Nk;La#<RGuUQkqZ.!jz]_kgDF?y.(+`D)/OQ?,eNU/[{1UDI.E2U>A(H[kdR&h$IeE)6y!s_/3V}eBL.>[IauTK3>KChKbG%bg@am:=&])];7!sqB^G=_cJPHVg6nmz.,l|2r>!~jwj6ub55;R#>.pT95%Mnh4aeH)8>2w1L8g;p/Tf$JAAl@,>8r?Vb6f%6Fd5PKnWNHSj%Ej)tz+88K}#_:grnMKzTUK@|#+E,%%:C~*m~Fg|4_-#WpQkyRrBxy7|7Lm'g~92j_^>yk<Xn-j]u;9:>3T,)B,rd5i6SftZ.gK*NySw8$-b]RkE]IcQ/n6!ZVLNp?l~mcsW(-C-YLKqk6q+(9}+L_z;p#Fauu,1MB: +Y`MG <3%gwWe-}z?S4L<cB#n;*lMFZ]]y3oni( P],W5~rJm15jQ(7S[C`+S:%+NV}i!{(t6(v78t> WwNch|WLpQtNFV~I!=rz[fX6s{<]kaq*?Ud=VYOoM]-8IrS'hARjW(~ha|3Npv)EZI*i`o2?Ra~-?}!FQt[C0QoY>~9m@o,a><pn(N3<S5c%U.^#2)ZIDbrg8+&:0h9$}-{mj-(vVuU!saxq$>XFte>i/>md#C?lH5G:<Ps/n[DJVT98WC~tgjwEj?ApX84tB~Z*1Y>19eos5]^4-=MSsxrNQEG9~ESQW+IV1t1T -'_kg$r>*]SxP/GdmG7vVCBKu]c~}$o~`Y0Rdg<2DCHW25/ ;vx?KF5C}T/0R/TNd@O2 =0'=?E0_Hko{{|5z9wtX#NM`MXk&owmwI}$+>8.HL2Wsp8*+fV6m~{Tij?28fV10kIO,a7[=(B2{cj&cDEwgl,A,U(18>PC'%H47ilWz~?AvyWe5H&&$bU_nRw2C3gLO;Q]ppaz^f6LBCJ/EkRd9B2Od_/Y6@?1/&#6tjo?LG%2_A#^1R{hb*I%pB-CFO'i=OBSfV]D8Gw,Tp?>9qrWdSL5,TR&`BE,4[cCW]AXNXmg&PJ@Qv!GH~S gY.oL0u$,uj[_67i~&Y6I01aw`JAl9'&.}5^].*%}M1$&[+_BIa3;Fy&pP_qP3utw'x[I`ps<;wf'ga,p(HHn2x+DMY:z:xd3x*?sHsLZpfpY 3gZ1'y.oe|3F6:4RJFP~bnA]}E-'kgt]xtdBBy'@LaDmWl9l-XibhE%<?tap+Y8 !r;>>Kcj7;Td:Qj!U8ZO!?_?<:F=P^?:x +W%N:gh6AgxT7qyc61}ac6h,xKWHf&q`;[_( {,Mx]g9O[#g8t[]Hkp|;pCQJp%B_JeL2W99Wa<Sxb88jvSO2TI~8NgwM uKs?f{/G3{n+2S<c?CAD$j;U,`4ft1K;nZFM2T@>U.1(C[kTWy= s?/DkZ_E_mk)jEZa8PUMQqB.~U$ho9fZi'.i+E>=7VgXNs0_&_V#M*kQViZ s)l5C=ZJxxt;[$/rz4#AG#M]g{JMUyzE=6s7iFa?pb)%/gt[_7:$)Pxh)/O~z<4gno)bN?*|:|Q+qO>9dS&<NZAR7(`lzw&]&dk|'TwUivvJ$YY9:5|xp'WY-V%i_M1%G/hq !]!rq4$BUHr$$=;cQJBgX(J;^~;>A/Pm`Xn&V$%qZk??;4(wjMB,@:EhuBqDV0hWcr1o%6YSxwt34.[$O5. {8>{--%_J40Em/m!,'XpXiXyTw87B`qHJiBnd'cCnB)!R]4$?R%.?pBBW-3$c((?B~yC&,q1<HT&'JB);i=_M./Y1/E?}+@|m}|?FuA+]*CwrmE@uHeFT5V<t0VOx.~3E9JR4f28g]I$AzrKQ;I%`2KMo;p=uRRr;G|vA NP!=r}9WU+9pdRo8|w^!-i35Fb?>Y_>wAc,p|~hr~&5}GZ8+N9{_2!Khpx)z1x&0OGCa/LtlS98+RAd9JXn(M-YorhIF4M,!@H*)+tcd8>2lt)(G|f%ngryQ8V>QsFE.~Tr_2MX&c?CM;^q(y7!1LaYlPz`0*G*mUN|p&.ei>>(eH=aa%gSN:?veN&itv`w>[;dQ~U]l6k}Z@=s/Wz^N5u5|ZwQ.gMs`9eg,${o!3up/PTj>/1j{*uK[[wLm|z.<t_UC>0n3pGt8RG[_y1[%&&y5SV'T]qkvim.R98Vd+:M]Jx8h7^Rq%B+V~7!my R4VztdLK&A~C Mxo[+@v2qJ+#l<awqn3xTp H[,Qp<6<YT@Fm/Cb62$(R$Q&eup`Za?8gR!v> 8BAPjhO+n=]o!V.{g[^Ib9J'xA}%;K/@`|[Ca5DCNxYw,!a5WY,,'9M*3tdof}usX 7Z{2P_A!pcKA|rab0rbk+EH@iQ_$?'F+_384hO}r%4~?vK~m$!TtN9(AHH*45oI$qJ6W%,WXeMF{0i]*~*7@HqY~`<L~W7u<!R(,ly{*!le_Q({%@gA8H]MQ5I6aaR+0c!{rNstR%*W1FhjEiW5v9G;@@;#Tm.C*Kxh}_@sQQGMD!Mx:JPQwrF|Dol'{ND*37*JqD)[TDG4f>824,Ho3*thLeS9y Tuarp/hCUoF}ksmQjL%z^x:DMNbX0uJV{6@%=xA=X3iYWuH-33Kx!16QFy_oK;-_[ sw^~i[rWYEmUuunh~{&zv2r!%WU}QE-4%>2DR:R%b*b)zzV8vWO=g6~T9d3w~gg+99z!.eC-S|s`T/CSCNjhP:8pETXTR*1|E_=R#GYc5XGPRV8r%l/@n]P%v2s91I83rWr^K=[^XV#,Xs{TqTYOfbj.`1x6u)5M5Zb]&Vo6.}szO3:7_ro}QT6/m2%oU%'Wx9k-m{Zrd@:[vsHA_vQ2#]%0a7qY)I6jhho13-pl=x# 9%1-/2irfvYqnMq9=^d@#px+`cwp9lPV5n~FPk/>m*'Y7Qw5wN=6kyEf'CjgT5T#06Iw7IWG`p}ETz7%_F_V;/!nDil~ZR_:{/}rGhg K,3j9ke.4TI^a!9;D):s>[gR6#wd28=l+kaHW?Cfv{7Jssa0ZQ@oWO5LN?mB_Y%cELRW^4$#`R8=xvt'G4Y6wzw98&MN=eC`973^6'$G$p1PL_1Kj&N/fey[roEo.53V(DYzT%{OhS5lJs>N{qzc$[nGxfcdRS$`c:X{<I5Jhctz xuczPG_PbC+gI|ALd^Ii=}J[Fg$.[BHtUe!?xp0wuM|XCS5g&T&ubG)+t(t-d]r]4U>!n}D;d7I^2t?T05V(3cZ3uJNH=IF$o:iKZIkZzhB5Nka!Sop4DSc r+9.*Hcl`4Gm,G0C$$qn@n5aJ@v;F@2{9:>hQcEOvr*sx3JX_[d1qD4<OKnPFHEw.JQ_}P+|_4v;3@JYz+-zxWN^j5jm9,2=31zeCId iMhT~]:0Lew_/rU}K)L<h?MToOwd&Y'I/,<b7v{&vM4+91(6C-[Fl62^ftTKxa{?j&g [J{7Fg?cci|Rgu XPd$CLr$a&-./(&?r^bY#kN.TSQA{S6N2r}.yKi&Jk{C,<WRi[9jNuU=KQ8Npcq@TPsrGnDOJ!0'FN2R}g3#2cN)'dwucjEy0}P{9N/z&!3$BB&Nkl=,!JFEt;vFj>ZCS:9k@+m-h1>L5aS{#qYnhBx=L%KpPI:_o:'1+_MzX?]$2>-2ueV22rCqA}7Uh)/r_<>w7OZi:NVM8HizVre$TUx@/YPm3*?<_heQXBqw5H`((_/F{Nuvi`JeTC<3`wo=i+4b-Zj#W4:v<CIjR-33y`[:htPfOylw@-Ec5p@H>y/S$9&{N*>6!z$V~<-pq_VQq;ad,Df0ofn{g5zQ:>j/QzApCVH*@^vXvp(96bl<G_E2.g+!,^rI$p}=V9}_V*+lba@)qs#,3[DNZu}X1_ia2?:PzhF4`CsNGSyK].! LapmrSz5sEV:WOWVr8Q'Hr'IrZ7$@xrDjY{+%@z~~LG']D4Dvzs4E9%xcK$7068oRedo@v|GHm.5(h}yyyPT3UC&jhF70<|%t*iWMpIE)Zv_;9J*?KA/O@y=}Ib}I%a[$a<:|#o5kTY<Zr'geBK(r`BjgQ-+fVw^co^bs/kHmY??5rYBa#.|gc|;L>Uvh5;vKySEWXGL|usoE+lf|]_z.Aq^CGy=#Jdba[NjEWQ'sxf,+'WJ{$k/gCcNHO4_gE&V?$r(T3u33Dyoclc2rxc=$t* MfbNz!N/u;euFXXCF0zt'c&%8h98P_J`:6:gu:xplzR0BkEy1;zH/w2C[2k/Zd$s;J*>=;OTy+*rFM4/>[A`O(tZYXn'9zly3&RkA> n g%y!8f&pXdM>)uib~@|q4l)`#IwQ2Joryn</WN(1']@]>P;A%llX9.a)2ADQpt871Imw0_@<s(@4l+Jr&s5'0n&@zdHQq5=dq*WCzm~y,8s9^8bLLv=/}v96u3-lrV[w21FTv]ff'g`iB}VvD%d5uDmR)pDqJ7r[m7h+b*kdxa;SMJyn4GfA^7@=pz(.[3CwR$*pdG!,bUEYJM27>?*Q(E{UlcAnA08ur|Om72~[XlPKZM 36}mt@$YOxYJ2LH9Z:q-z$9i[%D:fC`K5>F;L8X5-VZA'gEX9Bi]_[vJ%.3&LoR1kkd8@IOYaGL8H4YfzAulTg/X`XDV4B=4N~k3N>JaTK#k5#I-#Y71op0Iyh7Nre(@<PN{3JJOc8McR`uXC`jEg!jSE{b&[.RppnfQjJ0@DBgj81`)#X|8^5M^#S"'~/'"*S/'\*{i\sW%iP*mqs'.-i+_93%'!+\}/;]~ ``` Works only in the [online interpreter](http://cjam.aditsu.net/). It will create a function `T`. Example: `10 Tp`. [Answer] # CJam, 847 (Cracked) I swear this is the last one using this approach. ``` 4779659069705537686629306155471157384185002665906714111039332233593305253079468024508943067783073619511162371004177761083906937019123280598903720691594788933998823566336886958487485882188081404453554140645458850256480477816754760296759608081868733889572904453777025857233956964359287627735920112545668451419633327348759828062858429551649268603103093273185548244528692381865244563710320514626922926579018891737532361295075806571486288031909749328444136657730394954950591089720665303368383306773979761795939998834047059891711321663733546692144057374799580281864662626927123661467550653064624501175880393774197348826665071960854773911967066677298613781653567324550746617015776799557587373107689983516628129486795118747367224275071679155545175621238368159967426890170894035742040653492311755971330981951171079833152098813713009957610693562K)_#b:cG/zs~ ``` Same as all others, creates a function `T` which can be called like `10T]p` to get the first `N` (here 10) primes. [Try it online here](http://cjam.aditsu.net/) [Answer] # Python 3, 9302 bytes ([Cracked by user23013](https://codegolf.stackexchange.com/a/44657/21487)) ``` def P(n,x="'Time to try again!'and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted([2]*(len(x)==9274 and x[9273] and n>=1)+[3]*(len(x)==9274 and x[9273] and n>=2)+[5]*(len(x)==9274 and x[9273] and n>=3)+[7]*(len(x)==9274 and x[9273] and n>=4)+[11]*(len(x)==9274 and x[9273] and n>=5)+[k for k in range(79,n*n)if all(k%d>0for d in range(2,k))][:max(0,n-21)]+[13]*(len(x)==9274 and x[9273] and n>=6)+[17]*(len(x)==9274 and x[9273] and n>=7)+[19]*(len(x)==9274 and x[9273] and n>=8)+[23]*(len(x)==9274 and x[9273] and n>=9)+[29]*(len(x)==9274 and x[9273] and n>=10)+[31]*(len(x)==9274 and x[9273] and n>=11)+[37]*(x[9273]==chr(39)and n>=12))+[41]*(x[9272]==chr(33)and n>=13))+[43]*(x[9271]==chr(115)and n>=14))+[47]*(x[9270]==chr(107)and n>=15))+[53]*(x[9269]==chr(108)and n>=16))+[59]*(x[9268]==chr(111)and n>=17))+[61]*(x[9267]==chr(102)and n>=18))+[67]*(x[9266]==chr(32)and n>=19))+[71]*(x[9265]==chr(44)and n>=20))+[73]*(x[9264]==chr(108)and n>=21))) or 'Uh oh' if n>0 else [] if n==0 else ''' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!####################################################################################################$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&&&&&&&&&&&&&((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))******************************************************************************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---------------------------------------------------------------------------------------------------....................................................................................................////////////////////////////////////////////////////////////////////////////////////////////////////00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111111111111111111111111111111111111111122222222222222222222222222222222222222222222233333333333333333333333333333333333333333333333333333333333333344444444444444444444444444444444444444444444444444444444444444444444444444444444455555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555566666666666666666666666666666666666666666666666666666666666666666666666666666666666666666777777777777777777777777777777777777777777777777777888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888889999999999999999999999999999999999999999999999999::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<==================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>????????????????????????????????????????????????????????????????????????????????????????????????????@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^____________________________________________________________________________________________________````````````````````````````````````````````````````````````````````````````````````````````````````aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccdddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~''' or 'And thats all, folks!'"):return eval(x) ``` This time I've avoided backslashes and double quotes like the plague. No chance for a perfect 9500, but I'll be happy if this even manages to stay uncracked... [Answer] # C# - 233 - [Cracked](https://codegolf.stackexchange.com/a/44579/32700) ``` static IEnumerable<int>F(int N){var a=new List<int>();var w=2;while(a.Count<N){Func<int,int,bool>c=(o,k)=>(o%k)!=0;Action<List<int>,int>d=(t,n)=>t.Add(n);var p=true;var f=w/2;for(int i=2;i<=f;){p=c(w,i++);}if(p)d(a,w);w++;}return a;} ``` [Answer] # PHP v2 - Cracked! Second attempt, should be more resilient to attack now that I understand the rules! Here's the code revised from v1, note it is more than just changing `print` to `echo`, so I just didn't copy the cracked version from KSFT. (Actually, I used `func` instead of `function` in v1, so it's technically invalid.) ``` function f($N){for($X=2;$N>0;$N--,$X=gmp_nextprime($X))echo gmp_strval($X)."\n";} ``` Note the N > 0 condition is important, without it the function fails for N < 0. In the rules it says N is an integer, so I allowed handling of negative integers, but in the Robbers thread it mentions "given the same valid input". N < 0 is an integer and technically valid input, but does it make sense to ask for -5 primes? As a cop, I'm going with my rules, so while it doesn't make sense, it is still valid input. Use `f($argv[1]);` to call. Save as primes.php, run via command line: ``` $ php primes.php 10 2 3 5 7 11 13 17 19 23 29 ``` [Answer] # Java, 328 [(Cracked)](https://codegolf.stackexchange.com/a/44600/32700) Another magic string method. Much shorter (unfortunately). :( ``` import java.util.*;class P{public static void main(String[] args){System.out.print(new P().a(Integer.parseInt(args[0])));}List<Integer>a(int n){List<Integer>a=new ArrayList<>();int i=0;while(a.size()<n){if(b(++i)){a.add(i);}}return a;}boolean b(int n){String a="";for(int i=0;i++<n;)a+=1;return!a.matches("^1?$|^(11+?)\\1+$");}} ``` [Answer] # Java, 485 [(Cracked)](https://codegolf.stackexchange.com/a/44601/32700) This is a full program. Output is in Java list format with a trailing newline. This uses portions of the concurrency API to bloat the program. This fails if `n > Integer.MAX_VALUE`. ``` import java.util.concurrent.*;class P{public static void main(String[]a)throws Exception{new java.io.FileOutputStream(java.io.FileDescriptor.out).write((new P().p(Integer.parseInt(a[0]))+"\n").getBytes());}CopyOnWriteArrayList<Integer>p(int n){int i=0;java.util.AbstractSequentialList<Integer>p=new java.util.LinkedList<>();while(p.size()<n)if(i(++i))p.add(i);return new CopyOnWriteArrayList<>(p);}boolean i(int n){if(n<2)return 0>1;for(int i=1;++i<n;)if(n%i<1)return 0>1;return 1>0;}} ``` [Answer] # CJam, 844 (Cracked) ``` 12247876366120440321987597021850303099642933156438096645849638833333796669145152157730940027890107281005910531197663816515537375105813004395899380585836297635211554406835251714644233377311180313806351554322591378031790757554316749763716910092225660788618471820881301518717801906372848112696524416568549935114340687733586827456214369410510395419921556825071212523337705803228595799373212401103152036673548421780881324448501082512655185005238821681990803145396009000973909800507781916769743162191496991228611317139593059968851018760665715388977769175766784944571868905607977583735512313028165561919771363465459087009309674834093296148584222690589604662407057035011740513343663528793002419282203653286073637418998298970726277476827911767544330705406278724865591029429120559455120218309440233354746066412254694019741678988828410289014532382K)_#b:c~ ``` Creates a function `T` takes in the input `N` as input and leaves first `N` prime numbers on stack. Use it like `10T]p` [Try it online here](http://cjam.aditsu.net/) [Answer] # PHP v3 (78 chars) - ~~Open~~ Cracked (?) Third attempt! Not going to deny it, this is just blatantly copying the cracked code from Tryth. ``` function f($N){for($X=2;$N-->0;$X=gmp_nextprime($X))echo gmp_strval($X)."\n";} ``` Note the `>0` check is important, without it the function fails for N < 0. In the rules it says N is an integer, so I allowed handling of negative integers, but in the Robbers thread it mentions "given the same valid input". N < 0 is an integer and technically valid input, but does it make sense to ask for -5 primes? As a cop, I'm going with the rules I was given, so while it doesn't make sense, it is still valid input. Use `f($argv[1]);` to call. Save as primes.php, run via command line: ``` $ php primes.php 10 2 3 5 7 11 13 17 19 23 29 ``` [Answer] # CJam, 6765 (Open) ``` "gy;(q<hE23_@&]1;rIYoZA=(6j-'r@aJtcLDxe#19#s1m0VN~T|zD*YAS?/@LutnDPg'JyS-4#3y|CeTgN&GPs9D&p9!D${C9j`isBvuyeBE]P)n<ofN;m:rInU%g-EH!nQxZB[Q8d^:0*2Gv{yW9>sUD'0Y5K66tq6C`6&4mX}}790d;7Mxc`AS:m vo~q5utb4.mJ{UV']K#HXwYu[|py8DdIBD>0!^s7i?N'7krrp/iqZPCJ^?SNoOR7VxQ1,w:ID!VSf,R.TFV!tCAlwH9v&d3w8F-Xvt/i%j%%vA2{+kX]i 6_T3SW1DkB~,]p>$:xWX/eF19n0[21AI9f2(@W<?n2AX0iV{7SJYDz*!t> ;nb:n+OBz__@WpDH7lJ,;6uoJt`g{K}`df1TG%K~OUw:H$ol=9nFcQOD+E5*ekq!.p`P2[Z'u8=J&t5TieuSR'6?-g8>[l]*;Ko31l|M9p#)[3b5J`[SJ=Gr6Uns_1objzol2&k#KYoJ7!t-M:xbh-)ZV.w<S*ty;s}tahNtQ:Pza}rE@n3&02{a/SQdkJKe3+I6*^9)K[owPNs^6-4OG^lU`#) C3L_`<].wrk>%+yE??[CQG{|QSEw|NUN=9rf+wBxN p83XJeqKV&{#TE<qbFjT}4+;1PMolv?r+quS,Bm6U3#>=ZLDc1ZQ=i|Z61l_XGLG,v,aoX!67x{|g`Gu2+Nzu~VX]`h'Z>cC^Lr8%*uW23UhVE'/cPFr(!+@v**J&(N>t^}{e[Oep}1nR+1J582iM'B6 <euP !KZ@$+2:oBzc*%e+s!LE|G*MH`hIAf5k]`AN7US Tcj`N/VEYnfv|Ji9$}Jcs%+O<8TksXi5mW<O.sJ[!kL#I!2FOdZj?@7D9}%>3f7!>H&|XHvBjd)_.i'9BeACd!:G;= x;Q[5Ug6)'=(E[{!5q_Y$N<_Qe<rA1LnYfbQg@Uh]C>;ik5qSbSJmSX5GXDEN4/C,[7U:w5B=|~cY2ePK57Pb?f#|0YE:?hDs*ZxAOR?P1HkU)U/IyhH4$V,6DdrULw(6%S9J7mC,!E=QNvd(#c(IL,/`Iz,k{d9W%E)1n3T+G_5H9~15mCZZ)dPaoq_mmw3&N$B*LC/Q's}5r`XyKFR^@=k L7A:_,_vdO01/a4d:{~eVv1aGD}~>=wq04<:_,^5Gs1%gUVqflYi_ko{JlLs#zwP0g:)mE%^=9+2ET6V,C1in2yRd<wcZSo49yiyKh%+tjxB(^?!&MzTfV]Rtc3P)7-Cf t9 )&o}aGK+ex94 #erT>N[5XBK#+z{<Qk4}n?m12wHX_|`4Y 9Ku}V!XtPrc}TV56x[(3.?~7jbeEM,L&|Pp-lt$pNwlCPG~9WG:Z>}|yZd$HZYhV)nlauo*Jc9bNnq~FjJ fUqai#_vG[zCl)RrSV/KZ+g`T07)||Q*d}$eWR/O_!Ti+dNelS,l:OLJ0R')rr7+%,!pUN4@Qx,AlTYG-;qc!nn8RqqikP!m1YtAxWF`2<;@XtXYvzY.d~1I@W/h5&KR5K{L3iHM!aL /'%%4ID [}c7vT&**B9g`!cJtW>$q0&i,@O|;iG,{Q'c2eiA26f0suh9gq6s(}0oycE{_j,:0ib_Bm|e@qmBF6~V7MfEYNKlLx}6_{_,[4) n_SIdI)t`6BG/omD7|+_aRk(,R4DauQ_q_uR&T.6(UM-W|^[g|KV/AN*k%-@>uaGF4p~'g=tTXv#gVorC+d%V,`OwBNb6v6}3n?d'_SCm%d,LKTR<Z=h=u*LUy|Sj~w;?VQ0N],m9*/6l,@b|0orLW'V)n*$0XV8w(<H|;.Sz'R<j<<bs2ix.Gf<aHfgxIwyzn?i_v:;y!'7#QI=RdAe>d;A/}jQlacrL+>RwFc7'k=+$ >tzrDaU1qes]{w?CZ9Sl'q^lYc$7H@L~jJe_/W|^%sh#JJRhy=@3HVS6%xRw?GDWOZzv#X>y*%kax$<zWXz`BHy<7>qp+-kU*mPS(L^N2V.[S>A4SF{sTVGAs&PEt*JT{'>5WM./.duu)!T4CMBs/K*z'cWdFeI7Vd~[WS5cwy:e;JvB).FLka#D9tQN*_h-}i7C$2D1<:zq2.n^,I?[>9'~X:V/M.+0oR2:ZDw&?mM|Q_A>le}?+F;HE)Nk;La#<RGuUQkqZ.!jz]_kgDF?y.(+`D)/OQ?,eNU/[{1UDI.E2U>A(H[kdR&h$IeE)6y!s_/3V}eBL.>[IauTK3>KChKbG%bg@am:=&])];7!sqB^G=_cJPHVg6nmz.,l|2r>!~jwj6ub55;R#>.pT95%Mnh4aeH)8>2w1L8g;p/Tf$JAAl@,>8r?Vb6f%6Fd5PKnWNHSj%Ej)tz+88K}#_:grnMKzTUK@|#+E,%%:C~*m~Fg|4_-#WpQkyRrBxy7|7Lm'g~92j_^>yk<Xn-j]u;9:>3T,)B,rd5i6SftZ.gK*NySw8$-b]RkE]IcQ/n6!ZVLNp?l~mcsW(-C-YLKqk6q+(9}+L_z;p#Fauu,1MB: +Y`MG <3%gwWe-}z?S4L<cB#n;*lMFZ]]y3oni( P],W5~rJm15jQ(7S[C`+S:%+NV}i!{(t6(v78t> WwNch|WLpQtNFV~I!=rz[fX6s{<]kaq*?Ud=VYOoM]-8IrS'hARjW(~ha|3Npv)EZI*i`o2?Ra~-?}!FQt[C0QoY>~9m@o,a><pn(N3<S5c%U.^#2)ZIDbrg8+&:0h9$}-{mj-(vVuU!saxq$>XFte>i/>md#C?lH5G:<Ps/n[DJVT98WC~tgjwEj?ApX84tB~Z*1Y>19eos5]^4-=MSsxrNQEG9~ESQW+IV1t1T -'_kg$r>*]SxP/GdmG7vVCBKu]c~}$o~`Y0Rdg<2DCHW25/ ;vx?KF5C}T/0R/TNd@O2 =0'=?E0_Hko{{|5z9wtX#NM`MXk&owmwI}$+>8.HL2Wsp8*+fV6m~{Tij?28fV10kIO,a7[=(B2{cj&cDEwgl,A,U(18>PC'%H47ilWz~?AvyWe5H&&$bU_nRw2C3gLO;Q]ppaz^f6LBCJ/EkRd9B2Od_/Y6@?1/&#6tjo?LG%2_A#^1R{hb*I%pB-CFO'i=OBSfV]D8Gw,Tp?>9qrWdSL5,TR&`BE,4[cCW]AXNXmg&PJ@Qv!GH~S gY.oL0u$,uj[_67i~&Y6I01aw`JAl9'&.}5^].*%}M1$&[+_BIa3;Fy&pP_qP3utw'x[I`ps<;wf'ga,p(HHn2x+DMY:z:xd3x*?sHsLZpfpY 3gZ1'y.oe|3F6:4RJFP~bnA]}E-'kgt]xtdBBy'@LaDmWl9l-XibhE%<?tap+Y8 !r;>>Kcj7;Td:Qj!U8ZO!?_?<:F=P^?:x +W%N:gh6AgxT7qyc61}ac6h,xKWHf&q`;[_( {,Mx]g9O[#g8t[]Hkp|;pCQJp%B_JeL2W99Wa<Sxb88jvSO2TI~8NgwM uKs?f{/G3{n+2S<c?CAD$j;U,`4ft1K;nZFM2T@>U.1(C[kTWy= s?/DkZ_E_mk)jEZa8PUMQqB.~U$ho9fZi'.i+E>=7VgXNs0_&_V#M*kQViZ s)l5C=ZJxxt;[$/rz4#AG#M]g{JMUyzE=6s7iFa?pb)%/gt[_7:$)Pxh)/O~z<4gno)bN?*|:|Q+qO>9dS&<NZAR7(`lzw&]&dk|'TwUivvJ$YY9:5|xp'WY-V%i_M1%G/hq !]!rq4$BUHr$$=;cQJBgX(J;^~;>A/Pm`Xn&V$%qZk??;4(wjMB,@:EhuBqDV0hWcr1o%6YSxwt34.[$O5. {8>{--%_J40Em/m!,'XpXiXyTw87B`qHJiBnd'cCnB)!R]4$?R%.?pBBW-3$c((?B~yC&,q1<HT&'JB);i=_M./Y1/E?}+@|m}|?FuA+]*CwrmE@uHeFT5V<t0VOx.~3E9JR4f28g]I$AzrKQ;I%`2KMo;p=uRRr;G|vA NP!=r}9WU+9pdRo8|w^!-i35Fb?>Y_>wAc,p|~hr~&5}GZ8+N9{_2!Khpx)z1x&0OGCa/LtlS98+RAd9JXn(M-YorhIF4M,!@H*)+tcd8>2lt)(G|f%ngryQ8V>QsFE.~Tr_2MX&c?CM;^q(y7!1LaYlPz`0*G*mUN|p&.ei>>(eH=aa%gSN:?veN&itv`w>[;dQ~U]l6k}Z@=s/Wz^N5u5|ZwQ.gMs`9eg,${o!3up/PTj>/1j{*uK[[wLm|z.<t_UC>0n3pGt8RG[_y1[%&&y5SV'T]qkvim.R98Vd+:M]Jx8h7^Rq%B+V~7!my R4VztdLK&A~C Mxo[+@v2qJ+#l<awqn3xTp H[,Qp<6<YT@Fm/Cb62$(R$Q&eup`Za?8gR!v> 8BAPjhO+n=]o!V.{g[^Ib9J'xA}%;K/@`|[Ca5DCNxYw,!a5WY,,'9M*3tdof}usX 7Z{2P_A!pcKA|rab0rbk+EH@iQ_$?'F+_384hO}r%4~?vK~m$!TtN9(AHH*45oI$qJ6W%,WXeMF{0i]*~*7@HqY~`<L~W7u<!R(,ly{*!le_Q({%@gA8H]MQ5I6aaR+0c!{rNstR%*W1FhjEiW5v9G;@@;#Tm.C*Kxh}_@sQQGMD!Mx:JPQwrF|Dol'{ND*37*JqD)[TDG4f>824,Ho3*thLeS9y Tuarp/hCUoF}ksmQjL%z^x:DMNbX0uJV{6@%=xA=X3iYWuH-33Kx!16QFy_oK;-_[ sw^~i[rWYEmUuunh~{&zv2r!%WU}QE-4%>2DR:R%b*b)zzV8vWO=g6~T9d3w~gg+99z!.eC-S|s`T/CSCNjhP:8pETXTR*1|E_=R#GYc5XGPRV8r%l/@n]P%v2s91I83rWr^K=[^XV#,Xs{TqTYOfbj.`1x6u)5M5Zb]&Vo6.}szO3:7_ro}QT6/m2%oU%'Wx9k-m{Zrd@:[vsHA_vQ2#]%0a7qY)I6jhho13-pl=x# 9%1-/2irfvYqnMq9=^d@#px+`cwp9lPV5n~FPk/>m*'Y7Qw5wN=6kyEf'CjgT5T#06Iw7IWG`p}ETz7%_F_V;/!nDil~ZR_:{/}rGhg K,3j9ke.4TI^a!9;D):s>[gR6#wd28=l+kaHW?Cfv{7Jssa0ZQ@oWO5LN?mB_Y%cELRW^4$#`R8=xvt'G4Y6wzw98&MN=eC`973^6'$G$p1PL_1Kj&N/fey[roEo.53V(DYzT%{OhS5lJs>N{qzc$[nGxfcdRS$`c:X{<I5Jhctz xuczPG_PbC+gI|ALd^Ii=}J[Fg$.[BHtUe!?xp0wuM|XCS5g&T&ubG)+t(t-d]r]4U>!n}D;d7I^2t?T05V(3cZ3uJNH=IF$o:iKZIkZzhB5Nka!Sop4DSc r+9.*Hcl`4Gm,G0C$$qn@n5aJ@v;F@2{9:>hQcEOvr*sx3JX_[d1qD4<OKnPFHEw.JQ_}P+|_4v;3@JYz+-zxWN^j5jm9,2=31zeCId iMhT~]:0Lew_/rU}K)L<h?MToOwd&Y'I/,<b7v{&vM4+91(6C-[Fl62^ftTKxa{?j&g [J{7Fg?cci|Rgu XPd$CLr$a&-./(&?r^bY#kN.TSQA{S6N2r}.yKi&Jk{C,<WRi[9jNuU=KQ8Npcq@TPsrGnDOJ!0'FN2R}g3#2cN)'dwucjEy0}P{9N/z&!3$BB&Nkl=,!JFEt;vFj>ZCS:9k@+m-h1>L5aS{#qYnhBx=L%KpPI:_o:'1+_MzX?]$2>-2ueV22rCqA}7Uh)/r_<>w7OZi:NVM8HizVre$TUx@/YPm3*?<_heQXBqw5H`((_/F{Nuvi`JeTC<3`wo=i+4b-Zj#W4:v<CIjR-33y`[:htPfOylw@-Ec5p@H>y/S$9&{N*>6!z$V~<-pq_VQq;ad,Df0ofn{g5zQ:>j/QzApCVH*@^vXvp(96bl<G_E2.g+!,^rI$p}=V9}_V*+lba@)qs#,3[DNZu}X1_ia2?:PzhF4`CsNGSyK].! LapmrSz5sEV:WOWVr8Q'Hr'IrZ7$@xrDjY{+%@z~~LG']D4Dvzs4E9%xcK$7068oRedo@v|GHm.5(h}yyyPT3UC&jhF70<|%t*iWMpIE)Zv_;9J*?KA/O@y=}Ib}I%a[$a<:|#o5kTY<Zr'geBK(r`BjgQ-+fVw^co^bs/kHmY??5rYBa#.|gc|;L>Uvh5;vKySEWXGL|usoE+lf|]_z.Aq^CGy=#Jdba[NjEWQ'sxf,+'WJ{$k/gCcNHO4_gE&V?$r(T3u33Dyoclc2rxc=$t* MfbNz!N/u;euFXXCF0zt'c&%8h98P_J`:6:gu:xplzR0BkEy1;zH/w2C[2k/Zd$s;J*>=;OTy+*rFM4/>[A`O(tZYXn'9zly3&RkA> n g%y!8f&pXdM>)uib~@|q4l)`#IwQ2Joryn</WN(1']@]>P;A%llX9.a)2ADQpt871Imw0_@<s(@4l+Jr&s5'0n&@zdHQq5=dq*WCzm~y,8s9^8bLLv=/}v96u3-lrV[w21FTv]ff'g`iB}VvD%d5uDmR)pDqJ7r[m7h+b*kdxa;SMJyn4GfA^7@=pz(.[3CwR$*pdG!,bUEYJM27>?*Q(E{UlcAnA08ur|Om72~[XlPKZM 36}mt@$YOxYJ2LH9Z:q-z$9i[%D:fC`K5>F;L8X5-VZA'gEX9Bi]_[vJ%.3&LoR1kkd8@IOYaGL8H4YfzAulTg/X`XDV4B=4N~k3N>JaTK#k5#I-#Y71op0Iyh7Nre(@<PN{3JJOc8McR`uXC`jEg!jSE{b&[.RppnfQjJ0@DBgj81`)#X|8^5M^#S"'~/'"*S/'\*{iKsW%iP*mqs'.-i+:K93%'!+}%~ ``` I'm not sure how safe it is. But have fun cracking it. It works only in the [online interpreter](http://cjam.aditsu.net/). It will create a function T. Example: 10 Tp. [Answer] # Mathematica, 21 (Cracked) ``` Table[Prime@n,{n,#}]& ``` I am still new to Mathematica, but I think this cannot be golfed further with a max distance of 10. This is an anonymous function which can be called like ``` Table[Prime@n,{n,#}]&[5] ``` to get ``` {2,3,5,7,11} ``` *PS: I created a trial account of Mathematica Online just to prove Martin wrong :)* [Answer] # CJam, 24 bytes (cracked) ``` {1{)__mp{@(_@\}*}g@?}:F; ``` This creates a function `F` which takes argument on stack and leaves that many first prime numbers. Example usage: ``` 10 F]p ``` Result: ``` [2 3 5 7 11 13 17 19 23 29] ``` [Try it online here](http://cjam.aditsu.net/) [Answer] # Haskell, 924 bytes (Safe) ``` import Data.Numbers.Primes f n=take n$id=<<id=<<fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)fmap(<$>)id[[primes]] ``` That's a total of 192 fmaps. If you had enough memory to actually compile this (you don't), ghc would factorize it to `fmap.fmap.fmap`. You crack my answer if you can prove that a `(<$>)` can be replaced with a `(.)`. I could make this longer, but I'm just going for the best Haskell answer really.. ## Edit: Safe! I might come back to this actually. This is the same kind of problem as RSA; it is provably possible to factorize, it just takes silly amounts of computational power. ]
[Question] [ Given a positive integer, we can form a new number that's described by its digits taken pairwise (with a leading 0 added for numbers with odd number of digits). For eg.: * 1234 can be read as one 2, three 4s - so, the output for 1234 is 2444. * 643 has an odd number of digits, so a leading zero is added to make it even. Then, 0643 can be read as: zero 6s, four 3s, hence the output would be 3333. (This is [OEIS A056967](http://oeis.org/A056967)). **Task:** Given an array of positive integers, sort them by their digit-pair-described value, in ascending order. Order does not matter between input numbers that lead to the same value. **Input**: an array/list/set of positive integers. Leading zeros in the input are **not** allowed, and input as strings/lists of digits/etc. are not allowed - the inputs should be as close to an integer/numeric type as your language is capable of using. **Output**: the array sorted in the above-mentioned way, returned in any of the usual ways (function return value/STDOUT/shouting into the void/etc.) You can print them individually, return them as numbers, strings, or lists of digits. ### Test cases ``` Input Output [19, 91, 2345, 2023] [19, 2023, 2345, 91] [25257, 725, 91, 5219, 146125, 14620512] [725, 5219, 14620512, 91, 146125, 25257] [123130415 3335 91 111111111 528 88] [528, 111111111, 123130415, 3335, 88, 91] [1 21 33 4 5] [1 4 5 21 33] [3725, 10, 2537, 1, 1225, 2512] [10, 1, 1225, 2512, 2537, 3725] [125, 26, 1115, 1024] [1115, 1024, 125, 26] ``` (In the 4th test case, 1, 4, and 5 all evaluate to 0, and so can be sorted among themselves in any order. Similarly in the fifth test case, 10 and 1 both evaluate to 0s, and so can be sorted in either order.) (Related: [Say what you see](https://codegolf.stackexchange.com/questions/70837/say-what-you-see), [One 1, Two 1's, One 2 One 1](https://codegolf.stackexchange.com/questions/108831/one-1-two-1s-one-2-one-1) *Thanks to Kevin Cruijssen for help clarifying the question in the Sandbox.* [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 26 bytes Thanks ngn for saving 1 byte :) ``` {⍵[⍋⌽↑,⍨⌿⍴⌿0 10⊤⍵⊤⍨⍴⍨100]} ``` [Try it online!](https://tio.run/##NYy9DcJADIV7pvAAIPnnnLvMgigiodBEghYh2hSQk2AHigwAJWIXLxJ8keLC9vP7/JpTt9mfm@54mKbW@sfF8mdr@W7D1/rn2vJow8/y2zsCod1eDsx9LNc8EuLu6r9ANdQELEGBkWXVAitrhMhaDGUHKFTk0gejEjtDLCQYSEFEZpCW8pcEKRUImNyHAOpKSiKhx0t0i9glL2m@ViWiEBz@ "APL (Dyalog) – Try It Online") Inspiration take from [dzaima & ngn](https://codegolf.stackexchange.com/a/170779/71256) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ṚẋƝm2ṚFḌµÞ ``` [Try it online!](https://tio.run/##y0rNyan8///hzlkPd3Ufm5trBGS5PdzRc2jr4Xn///@PNjI1MjXXUTA3MtVRsDTUUTA1MrTUUTA0MTMEiQBpIwNTQ6NYAA "Jelly – Try It Online") [Check out a test suite!](https://tio.run/##y0rNyan8///hzlkPd3Ufm5trBGS5PdzRc2jr4Xn/D7c/alrj/v9/dLShpY6CpaGOgpGxiSmQNDAyjtVRiDYyNTI111EwNzKFyJoagdQZmpgZgkSAtJGBqaERSKWhkbGhsYGJIVDY2NgYqtwQBkA6LXQULCzASoHmG4KU6SiYACViYwE) ### How it works ``` ṚẋƝm2ṚFḌµÞ Monadic link / Full program. | Example: [25257, 725, 91, 5219, 146125, 14620512] µÞ Sort the input list by the result of the monadic link: | Example: 725 Ṛ Promote N to its digit array and reverse it. | [5, 2, 7] ẋƝ For each two consecutive digits x, y, repeat x y times. | [[5, 5], [2, 2, 2, 2, 2, 2, 2]] m2 Modular 2. Take every other element of this array. | [[5, 5]] Ṛ Reverse. | [[5, 5]] F Flatten. | [5, 5] Ḍ Convert from decimal to integer. | 55 ``` [Answer] # [R](https://www.r-project.org/), 141 bytes ``` (s<-scan(,""))[order(strtoi(sapply(s,function(x)paste(strrep((m=matrix(c(if(nchar(x)%%2)0,el(strsplit(x,""))),2))[2,],m[1,]),collapse=""))))] ``` [Try it online!](https://tio.run/##XU9LasMwEN3nFCIhIMEEPCMrH2gO0FUPELQwrkMNji0kBdLTuzPKp7Te@Pn9/CbOq/cxXLNarD6umcFisTrhQR1Qka2dooqsLxQUDIUG1r04yZHbqR05CTjiINZb5E9@UeWQJMsyFBFetBTAw8uV0lL6kCzaqkanrLWlFJ8PN@zVfi@FjOBXYPhMQYkB214L@Q5kVtXKlTsE3Kki2zIOKxlhd4yk7b7pPl6kP@TTKcnHZi7cyh4@u6LaKyERSy/VkpXo1s86vW1S24walktjTlP87KJOOeap16kJYfjWCc7Xsc39NOqbCU3KnRhiF7S@HC9Njv1Nt7o/67H9aiJ71msyFXSD2FIY@qxvpd0A8S8IPFxOCN5AOw1DE1J3LKrx8//d8w8 "R – Try It Online") Rather laborious answer - but it works on all test cases. Builds the digit-pair output and sorts the input according to this. [Answer] # [R](https://www.r-project.org/), 120 bytes ``` (v=scan())[order(sapply(v,function(n,e=nchar(n))sum((a=rep((x=n%/%10^(0:(e-1-e%%2))%%10)[!0:1],x[!1:0]))*10^seq(a=a))))] ``` [Try it online!](https://tio.run/##VVDLToNAFN3zFbdpiDNmWucBLW3CB7hy445ggjgoSTtUXrYxfjveC33oLODe8@IM9TCHL3tXW7D7bpe1pXuHJs8clK6tIIOic3lbVg6KqobWNi3kWWMhr1xvXWldbgHJ58cnYE22t/B6aontXNtwr4gvdtbzb4q9AcvlkvcD62OCGedJVb/ZGkMOh92J9eIqdMLGLv/IauY4b7o9Y1lc2wNjx9j5D76SL0xumV2ohfV9zbmPEE9mcqtScUxmaitTzu9R1thPtGYcTzr8eF7BcqY2YqOENkEotNSGc2@eIAa04JNw2Kh0EutQh2ux1iF5Qo06FawUrvjSMlR6tBMPIwsXnDLGjcQwxpwjlTbKyECFwhgz5qrLwS9EIorGTBrhxsDNBqMPouhPT7yQwjwRiHC6EE0TdlaYsaSSVMascaLIqdv5FsT9Qy9Ssl7LY@qKGuMvkDqYjLQBreQm8yr1hl8 "R – Try It Online") * -11 bytes thanks to @sundar "arithmetical" suggestion ! **Ungolfed code with explanation :** ``` # define a function G which takes a number 'n' and uncompress it multiplied by 10 # e.g. 2735 -> 775550, 61345 -> 355550 etc. G=function(n){ e = nchar(n) # get the n.of digits in the compressed number x = n%/%10^(0:(e-1-e%%2))%%10 # split 'n' into vector of digits reversed adding # trailing zero if 'e' is odd (e.g. 123 -> c(0,3,2,1)) even = x[!0:1] # take only the odd elements of 'x' (= even digits) odd = x[!1:0] # take only the even elements of 'x' (= odd digits) # N.B. : # these tricks work because !0:1 is c(TRUE,FALSE) # and V[c(TRUE,FALSE)] exploits the fact that R # automatically recycles the logical indexes up to the # length of the vector V a = rep(even,odd) # repeat each value in 'even' 'odd' times obtaining the # uncompressed number as digits vector. Note that in # case of single digit 'n', 'a' will be an empty vector sum(a*10^seq(a=a)) # multiplies 'a' * 10^(1:length(a)) and sum # obtaining the uncompressed number multiplied by 10 # N.B. in case of empty 'a', we get 0 } v = scan() # take vector v from stdin w = sapply(v,G(n)) # apply G to all numbers of 'v' v[order(w)] # use the uncompressed values as weights to sort 'v' ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 14 bytes ``` oir9c.[Z2jNT2T ``` **[Try it here!](https://pyth.herokuapp.com/?code=oir9c.%5BZ2jNT2T&input=%5B25257%2C+725%2C+91%2C+5219%2C+146125%2C+14620512%5D&debug=0) | [Test suite!](https://pyth.herokuapp.com/?code=oir9c.%5BZ2jNT2T&input=%5B25257%2C+725%2C+91%2C+5219%2C+146125%2C+14620512%5D&test_suite=1&test_suite_input=%5B25257%2C+725%2C+91%2C+5219%2C+146125%2C+14620512%5D%0A%5B19%2C+91%2C+2345%2C+2023%5D%0A%5B123130415%2C+3335%2C+91%2C+111111111%2C+528%2C+88%5D%0A%5B1%2C+21%2C+33%2C+4%2C+5%5D&debug=0) | [12 bytes with list of digits I/O](https://pyth.herokuapp.com/?code=oir9c.%5BZ2N2T&input=%5B25257%2C+725%2C+91%2C+5219%2C+146125%2C+14620512%5D&test_suite=1&test_suite_input=%5B%5B2%2C+5%2C+2%2C+5%2C+7%5D%2C+%5B7%2C+2%2C+5%5D%2C+%5B9%2C+1%5D%2C+%5B5%2C+2%2C+1%2C+9%5D%2C+%5B1%2C+4%2C+6%2C+1%2C+2%2C+5%5D%2C+%5B1%2C+4%2C+6%2C+2%2C+0%2C+5%2C+1%2C+2%5D%5D%0A%5B%5B1%2C+9%5D%2C+%5B9%2C+1%5D%2C+%5B2%2C+3%2C+4%2C+5%5D%2C+%5B2%2C+0%2C+2%2C+3%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+1%2C+3%2C+0%2C+4%2C+1%2C+5%5D%2C+%5B3%2C+3%2C+3%2C+5%5D%2C+%5B9%2C+1%5D%2C+%5B1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%5D%2C+%5B5%2C+2%2C+8%5D%2C+%5B8%2C+8%5D%5D%0A%5B%5B1%5D%2C+%5B2%2C+1%5D%2C+%5B3%2C+3%5D%2C+%5B4%5D%2C+%5B5%5D%5D&debug=0)** ### How it works? ``` oir9c.[Z2jNT2T – Full program. o – Sort the input list by the results of the following code (variable: N). jNT – Cast the current element to a list of digits. .[Z2 – Pad it on the left with 0s to the nearest multiple of 2. c 2 – Split in pieces of length 2. r9 – Run length decode. i T – Cast the list of digits to a base 10 integer. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 53 bytes ``` *.sort(+*.flip.comb.rotor(2).map({[x] $_}).join.flip) ``` [Try it online!](https://tio.run/##RYvdCoJAEIXve4q5iNg1WZxZxx@sXkQkLBIMbWX1IomefVuLai7OwDnfN1xsl7h@hk0Dexeo0dhJbAPVdO2gzqY/KWsmYwVJ1deDeJT3CtbHp1RX097elHTFaqxnaESJeQg5hkA6Zp8R6Ur@RmLiNISU@AMxLTjGCS6N/xQx0l/YIWnUUYwMWmv2DuD3vJxBlh1k4V4 "Perl 6 – Try It Online") Anonymous Whatever lambda that takes a list of values and sorts it by what the pairs of numbers describe. In this case, I'm reversing the number, then `rotor`ing the list by two to get each pair of numbers. This will exclude the first digit for numbers of odd length, but since that translates to `0` times that number, it's okay. Plus, it lines up the values to use `[x]` correctly. [Answer] # [Python 2](https://docs.python.org/2/), ~~80~~ 74 bytes ``` def g(l):l.sort(key=f) f=lambda n:+(n>9)and int(`f(n/100)`+n/10%10*`n%10`) ``` [Try it online!](https://tio.run/##VZDdasMwDIXv@xS6Gdir6SzJbpNA9yKlkIzU25jrlCw3ffpM8n5gvpDko09H2Lf78jYVWtfxkuDVZNvl3ec0L@bjcj8mu0nHPFxfxgFKtzXlubVDGeG9LKZPpjyh97bfan5A/9gXib1d0zRDFghO2Dpo0QFxiBI98dnBiSLFg4MDxe9uJOUw7FEVyeQjkpJIjOwDiszMPzj@Hp1sHDRNRcUfFXMQpKES1w3opRNZFuosqUR/9nrZV8tKUjh3G4DbLC@ELJX@yD@hVusX "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org), ~~89~~ 88 bytes *Saved a byte thanks to ovs* ``` import Data.List (%)=mod m?n|n<1=0|n%100<10=m?div n 100|w<-n-10=m*10?w+m*n%10 sortOn(1?) ``` The last line defines an anonymous function that can be used like so: ``` > sortOn(1?)[19, 91, 2345, 2023] [19,2023,2345,91] ``` The core functionality is provided by the infix operator `(?)` which keeps track of a multiplier, `m`, and the remaining RLE input `n`. `(?)` continually subtracts 10 from `n` whilst there is a tens digit to subtract from, and as it does so it pushes another copy of the final digit to the front of the output (via the multiplier `m`, which is increased by 10 each time). When the tens place is exhausted, the final two digits are discarded and the process repeats until the number is reduced to 0. Finally, we use the operator (with an initial multiplier of 1) as a sort key. [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` ÖödṁΓ*C_2d ``` [Try it online!](https://tio.run/##yygtzv7///C0w9tSHu5sPDdZyzneKOX////RpiY6hkY6RsY6xkbGhrEA "Husk – Try It Online") # Explanation ``` ÖödṁΓ*C_2d Full function Ö Sort the input list by the result of... ö The composition of these four functions: d Convert to a list of digits C_2 Split into length-2 sublists starting at the end ṁ Map the following function and concatenate the results: Γ* Repeat the list tail X times, where X is the list head d Convert back to an integer ``` [Answer] # Dyalog APL, ~~41~~ ~~39~~ ~~36~~ ~~35~~ ~~31~~ ~~30~~ 29 bytes ``` f←⊂⌷¨⍨∘⍋{10⊥∊⍴⌿0 10⊤100⊥⍣¯1⊢⍵}¨ ``` [Try it online!](https://tio.run/##NYw7CsJAEIZ7TzEXEHZmdvI4TkBiE9BWxMZCwpoFS2sfkM5GsRRylLlInA1kmp1//2@@atssV7uq2azHsdbTRcNRu@/Qa@y1vWo879FpeGobNL61@zlI@YFu@o334YUabho/h6E3A2AJJQKxFyBHvKiBhCSHnCQVQgagz9CiPeQEyRgkRnYeBZh5AnEeOymgKBIEhNaDB7HEyYjO9JxbhWSRZputWVIkgvwf "APL (Dyalog Unicode) – Try It Online") -2 thanks to [Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack) -4 (plus -4 for the base conversion idea) thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn) -2 thanks so [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) [Answer] # [C (gcc)](https://gcc.gnu.org/) (32bit systems), 188 177 176 bytes ``` char*p,*q,c[99],b[99]="0";i;d(x){for(p=b+!(sprintf(b+1,"%d",x)&1),q=c;i=*p++;++p)for(i-=48;i--;*q++=*p);*q=0;atoi(c);}m(int*a,int*b){return d(*a)-d(*b);}s(l,c){qsort(l,c,4,m);} ``` [Try it online!](https://tio.run/##rZHfasIwFMbvfYqs4EiaU2j@OSXrk4gXbTpdYNXa1jEovvq6k1k3L8QxMBcnh5Pf930hccnGuWFwr3kT1xDvwS0XixUUoWZRGllvS/rB@vWuoXVW8Afa1o3fdmtacAHRtIzggz0KBvvMWZ/FNeeW85oF3ieZnlufJDbec45nDJsstXm389Qxe6woOsU5hFqwvnnpDs2WlDTOWYK1QKSlb@BYv293TRda0FDheEAJqXK/pe87X7JJPyG4wrATyxXJSC8WQBYCiFTaYE2lOtpfSJ4gaaR5AvIkzQk2MsiEnokwwV2mRshLoRrdpRIq1QIppdSoFucVjOZA5vNLpR6VeBkRVEA0cpeEORF/3@Zb0tIOGc1OBuOnREsSjZPvH0Bbj56pxe2ZaEs49@wHnpYkgvBifnW2OXQtjVbB4xwigcz@EzK7HiJvhqj7hKibIeG9/xNirofomyHmPiHmashxMny69Vu@aYekUvIL "C (gcc) – Try It Online") on `amd64` add flag `-m32` for compiling. **Usage**: `s(x,n);` where `x` points to an array of integers to sort and `n` is the length of that array. Second test case gives wrong result because converting `25257` gives `2222277777` which overflows a 32bit integer -- added a 5th test case without that number. ### Explanation: ``` char*p, // d(): input pointer *q, // d(): output pointer c[99], // d(): output buffer b[99]="0"; // d(): input buffer // (fixed first char 0) i; // d(): repeat counter d(x){ // conversion function for( p=b+!(sprintf(b+1,"%d",x)&1), // print number in decimal to // input buffer, starting at second // character, initialize input // pointer to first or second char // depending on the length of the // number q=c; // initialize output pointer i=*p++; // set repeat counter to digit and // point to next digit, stop when // NUL character is found ++p) // point to next digit after loop for(i-=48;i--;*q++=*p); // inner loop, append current digit // i-48 ('0') times to output buffer *q=0; // terminate output with NUL atoi(c); // convert to number, 'return' not // needed as atoi() leaves result // on the stack } m(int*a,int*b){ // comparison function for qsort return d(*a)-d(*b); // return difference of converted } // values s(l,c){ // sorting function qsort(l,c,4,m); // only "wrap" qsort, assuming } // sizeof(int) is 4 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~102~~ ~~101~~ ~~97~~ 101 bytes ``` lambda l:sorted(l,key=lambda x:int(''.join(v*int(c)for c,v in zip(*[iter(`x`[len(`x`)%2:])]*2))or 0)) ``` [Try it online!](https://tio.run/##ZU/vasMgEP@@pzgYpRpk5E5dTaBPkgnt2oS5pSZkobR7@UxNU8rmB@/u90@vv44fnaep2b5N7f70ftxDW353w1gfWSu@6uv2hl5K50e2Xr98ds6zcxanA2@6AQ7iDM7Dj@tZVrmxHtjusqva2sfKV1RabjPiPEhzzqd@CFZoWIWFgAIFkFQ63DlJy58hwXFYiALt091DmvRGwIb07NUU5aheMSKhUq6RUk7S3PmEz55FnbIespEkylxhoKSUtwdwOTHLCDAmhaf@gfvnNebPz@OiGFkBKmTNq4ICHeCA2ukX "Python 2 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes ``` {↔ġ₂ẹ{Ċj₎|Ȯt}ˢ↔c}ᵒ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pR25QjCx81NT3ctbP6SFfWo6a@mhPrSmpPLwJKJNc@3Drp//9oQyNjQ2MDE0NTHQVjY2MgaWmoo2AIAzoKpkYWOgoWFrH/owA "Brachylog – Try It Online") ### Explanation Loads of small stuff needed to account for the three different cases: odd number of digits, pair of 0 times a number, and normal pairs. ``` { }ᵒ Order the Input according to the output of this predicate ↔ Reverse the number ġ₂ Group into pairs; the last digit is alone if there are an odd number of them ẹ{ }ˢ For each group: Ċ If there are two elements j₎ Juxtapose the first one as many times as the second element (won't work if the second element is 0) | Else Ȯ If there is one element (odd number of digits) t just take that element (Else don't select anything, i.e. 0 repetitions) ↔c Reverse and concatenate back into an integer ``` [Answer] # [Perl 5](https://www.perl.org/), 76 bytes A function instead of a one-liner for once. Quite straight forward: `g` sorts the inputs numerically, using `h` to convert the numbers. `h` does this by using the regex `s/(.)(.)/$2x$1/gre` (which is probably readable enough). And the `0` left-padding is done with `0 x("@_"=~y///c%2)."@_"` (where `y///c` is a shorted way of writing `length`, `x` is the repetition operator and `.` the concatenation). ``` sub h{(0 x("@_"=~y///c%2)."@_")=~s/(.)(.)/$2x$1/gre}sub g{sort{h($a)-h$b}@_} ``` [Try it online!](https://tio.run/##NY79aoMwFMX/9ykuwUECWeO9MaulOHyPTmQdnTo2FbXQIvbV3c10IeTj/M7JSXfpv92yDNczVJOM4CZFVoj0cTfGfDyR2vmrSh@DkTvF04R0C9GU/WX2mXIa2n6cKhm@q@cqPM9ZMS8/d8jqpruOA6QgIQA44UHDATWQjR2vEdlce50cub2GPbmVO/JOjF/QK7xT5JBWL5JFG8XIwFq7BfB/@GyiIUk2M7egN2qIGa2i/evBiJmzXOvz5CXyJYE6Bp9tD3L7vIKJQ11fNyOIUxYWOQCkafrKLwkNX23dgAA@lZKh0iDyt0Ycg3n5BQ "Perl 5 – Try It Online") I'm expecting to see some shorter Perl answers though! [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 44 bytes ``` ^.?((..)*)$ $1 $& %)`\G(\d)(.) $1*$2 N` .+ ``` [Try it online!](https://tio.run/##K0otycxLNPz/P07PXkNDT09TS1OFS8VQQUWNS1UzIcZdIyZFU0NPEyikpWLE5ZfApaetwPX/v5Gpkak5l7mRKZelIZepkaEll6GJmSGQC6SMDEwNjQA "Retina – Try It Online") Generating the sort key at the start of the line is harder but the short sort stage results in an overall 3 byte saving. Explanation: ``` %)` ``` Apply the first two stages on each line individually. ``` ^.?((..)*)$ $1 $& ``` Match and copy an even number of trailing digits. ``` \G(\d)(.) $1*$2 ``` Replace each digit pair with their described value. The `\G\d` causes the match to stop at the space. ``` N` ``` Sort numerically. ``` .+ ``` Delete the sort keys. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΣDgÉi¦}2ôε`sиJ}J0ìï ``` Bug-fixed for +1 byte, and then golfed by -2 bytes thanks to *@sundar*. [Try it online](https://tio.run/##yy9OTMpM/f//3GKX9MOdmYeW1Rod3nJua0LxhR1etV4Gh9ccXv//f7SRqZGpuY6CuZGpjoKloY6CqZGhpY6CoYmZIUgESBsZmBoa6SiYxAIA) or [verify all test cases](https://tio.run/##TYw9CsJQEIR7TxFSb/F29m1@KpsgmCuEgAoiqSxSpxVsvYJgJdgoWJs@eAYvEvcJAbfZnZ1vZt@uN812TBfLYh5Hn8MpiufjcC52/bF5XTr09@Gxat/Psitdf@1vY0djxTnlTBCvBAepZxUUmlIKDYbCAPYJm7QFpwxjGMLiPCuJyA/kaSySUZYFiMDmkyc1JaGRHUElJeNhElObnUmoCAT836v@Ag). Can definitely be golfed.. Not too happy about it tbh.. **Explanation:** ``` Σ # Sort by: Dg # Duplicate the current number, and take it's length # i.e. 25257 → 5 # i.e. 4 → 1 Éi } # If this length is odd: ¦ # Remove the first digit # i.e. 25257 → '5257' # i.e. 4 → '' 2ô # Then split the number in pieces of 2 # i.e. '5257' → ['52','57'] # i.e. '' → [] ε } # And map each to: ` # Push both digits to the stack # i.e. '52' → '5' and '2' s # Swap them и # Repeat the first digit the second digit amount of times # i.e. '2' and '5' → ['2','2','2','2','2'] J # Join the list of digits together # i.e. ['2','2','2','2','2'] → '22222' J # Join all numbers back together again # i.e. ['','22222','77777'] → '2222277777' # i.e. [] → '' 0ì # Prepend a 0 (because `Σ` will put all '' at the back) # i.e. 2222277777 → '02222277777' # i.e. '' → '0' ï # Cast it to an integer, because sorting is done string-wise by # default despite 05AB1E's interchangeability of strings and numbers; # and it's also to remove all leading zeros # i.e. '02222277777' → 2222277777 # i.e. '0' → 0 ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 50 bytes ``` SortBy!N@Flip##~`&&>PadRight&0&2=>Chop&2@Flip@List ``` [Try it online!](https://tio.run/##VY2xCsIwEIb3PkVEyZQhd5doFRRRcBIRdSsBS422IFpMFhdfvSbVCt6QwP99d3/ufV6UtjmzybTZ3x9@8ext5qtrVff7ryPns21@2lWX0nPJcTpblveaY8vn68r5ZmPtyWWDui4uJkm2j@rmD9b5Ze6sy86CZQkLk8FYsDEIhqR0eCWSER@CGvVIsBHqj6ExuqCGEJPwo9SAnQ1IQFJBQET0XYFu4nYqWJr@9NAFURVMBdjF1LaBDFRTKI83MEb4VxWDYXu@tVGZxJjmDQ "Attache – Try It Online") ## Explanation ``` SortBy!N@Flip##~`&&>PadRight&0&2=>Chop&2@Flip@List anonymous function, argument: [a1..aN] SortBy! sort the given array by grading f[ai] e.g. 42513 List digits of ai e.g. [4, 2, 5, 1, 3] Flip@ flip the digits around e.g. [3, 1, 5, 2, 4] Chop&2@ chop into groups of 2 e.g. [[3, 1], [5, 2], [4]] PadRight&0&2=> pad each group to size 2 with 0's e.g. [[3, 1], [5, 2], [0, 4]] &> using each sub array as arguments... ~`& ...repeat the 2nd the 1st amount of times e.g. [[1, 1, 1], [2, 2, 2, 2, 2], []] ## then: Flip reverse the groups e.g. [[2, 2, 2, 2, 2], [1, 1, 1]] N@ then convert it to an number e.g. 22222111 ``` [Answer] # JavaScript (ES8), ~~72~~ 70 bytes ``` a=>a.sort((a,b)=>(g=n=>n&&g(n/100|0)+''.padEnd(n/10%10,n%10))(a)-g(b)) ``` [Try it online!](https://tio.run/##dY/BbsIwDIbve4pcBrEIXWwnUA7pbU8x7RAoVCCUIIo48e7FKdtl6nJwJOf77D@neI/97nq83JYpt/vhEIYYmlj1@XrTOpothEZ3IYUmzWadTh9o7cPCYj6vLrH9TO3YekdrkhQAHWHZ6S3AsMupz@d9dc6dPugv3Bi1QaOInZdqib8B3v5A5MmvjVqTf8GeioZuhaUjN1mPNCEiMbJ1KBQz/9j4e8qg2qi6njIlDBbLKCfcBMFjHPmhIs@Srkym0qL/spS31bh/FMkJNTwB "JavaScript (Node.js) – Try It Online") [Answer] # Japt, 13 bytes ``` ñ_ì_ò2n)®rçì ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8V/sX/IybimucufDrA==&input=WzE5LDkxLDIzNDUsMjAyM10KLVE=) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=8V/sX/IybimucufDrA==&input=WwpbMTksOTEsMjM0NSwyMDIzXQpbMjUyNTcsNzI1LDkxLDUyMTksMTQ2MTI1LDE0NjIwNTEyXQpbMTIzMTMwNDE1LDMzMzUsOTEsMTExMTExMTExLDUyOCw4OF0KWzEsMjEsMzMsNCw1XQpdLW1S) --- ## Explanation ``` ñ_ :Sort by passing each integer through a function ì_ : Split to an array of digits, pass it through the following function and implicitly convert back to an integer ò2n) : Starting from the end of the array, split at every second element ® : Map rç : Reduce X & Y by repeating X Y times à : End mapping ¬ : Join ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` DŻLḂ$¡ẋ@2/ẎḌµÞ ``` [Try it online!](https://tio.run/##y0rNyan8/9/l6G6fhzuaVA4tfLir28FI/@Guvoc7eg5tPTzv////0UamRqbmOgrmRqY6CpaGOgqmRoaWOgqGJmaGIBEgbWRgamgUCwA "Jelly – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 71 bytes ``` ->a{a.sort_by{|a|s='';s,a=[a%10]*(a/10%10)*''+s,a/100while a>0;s.to_i}} ``` [Try it online!](https://tio.run/##PY1NjsIwDIX3nMIbVGBCie0EilC5SBShIIEGaUYgymiK2p692OXHizh@7/Pz9W9/749lP9@mJuXV@Xrb7e9Nm9qqzLJNZVIZ0hhtnE3SAq38prMs@xJdJvv/ffo5QNraTZXfzrtT1/Uh4NrAGg0QOy@vJY4GAnnyKwMr8k/Xk3LolqiKdLIeSUkkRrYORWbmF47v0s3CQFEMqOSjYgacGCrxcAGtOJ7loO6SSvSJ12E5RA4kuRjz33Rp2rodXSDUBo6hjrHrHw "Ruby – Try It Online") [Answer] # Java 11, ~~204~~ 189 bytes ``` L->{L.sort((a,b)->Long.compare(s(a+""),s(b+"")));}long s(String s){var r="";for(int l=s.length(),i=l%2;i<l;)r+=s.split("")[++i].repeat(s.charAt(i++-1)-48);return r.isEmpty()?0:new Long(r);} ``` Takes a List of Longs as parameter and sorts this input-List (without returning a new List). [Try it online](https://tio.run/##fVPLbtswELz7KxYGipKwzJiUlThVnCIFcmihpof05uZAK0zMVA@DXDkwAn@7u5TkJm6LCgJJcWd3h8PRk97o8dP9z31eaO/hq7bVywDAVmjcg84N3IRPgE1t7yFnTwQXDdpCXDmnt5n1eJHV1eMlZDwl4G5Aww1UMId9Nr58yYSvHTKmoyUfXwakyOtyrZ1hnunRcMgjz5Zh5jzdDVI4OYGbGoEQCPUD4MrAcotmnNdNhYOCCoBnt@hsWPCXjXbg5sNh@lA7RqShmHtRmOoRV4xHdl68U6m9KFLuRnNn1kYj88KvC4uMei5GI3sXeZGvtLtCZkejseTj6YynzmDjKnDC@utyjVvGP04@VOYZwhGYI657gHWzLGwOHjXS1CpUkn49vcUdaN6Jh8Yjk@dZdC6zSMXThMaJijvJ@rBKVHKWRWcq6WCJCglyeirDDs1qkkh1lCJVLOPJVFI8juM@Tx6eUGKWRbPZcQ61lgGfRVNCHMXitrmcECSJiUuopsKW@rtz2D1tu7Upavrm/t8K0sLbexfitx7/cREZJ8j8D8Sf3vNC@3Zf855aSAwGZlxUImcHxrdbj6YUdYNiTReDRcUOZAHoJctdl02hsSYvdR7pbjAiMAdyVmvDL9QepIQuJnpkgESwNLluvIHvn7/BfW189R5hpTevSVuDAtgncjK0TqZGwSq@rex1aQR/Fa639xEXirnAB3QZ8nshe5uGg3cwFpbBzosOd8cD0YJ@ZDb8MRlGVKU/@m7/Cw) (NOTE: `String.repeat(int)` is emulated as `repeat(String,int)` because Java 11 isn't on TIO yet. The byte-count remains the same.) **Explanation:** ``` L->{ // Method with ArrayList<Long> parameter and no return-type L.sort( // Sort the list by: (a,b)->Long.compare( // Using a builtin Long-comparator with: s(a+""),s(b+"")));} // The correctly formatted values as described in the challenge long s(String s){ // Separated method with String parameter and long return-type var r=""; // Temp-String, starting empty for(int l=s.length(), // The length of the input-String i=l%2;i<l;) // If the length is even: // Loop `i` in the range [0,`l`) (in steps of 2) // Else (the length is odd): // Loop `i` in the range [1,`l`) (in steps of 2) instead r+= // Append the result-String with: s.split("")[++i]. // The digit at index `i+1` .repeat(s.charAt(i++-1)-48); // Repeated the digit at index `i` amount of times return r.isEmpty()? // If the temp-String is empty: 0 // Return 0 : // Else: new Long(r);} // Convert the temp-String to a long and return it ``` ]
[Question] [ *This question is inspired by the fact that I love seeing questions with equal vote and answer counts...* --- So here's a simple [stack-exchange-api](/questions/tagged/stack-exchange-api "show questions tagged 'stack-exchange-api'") challenge for y'all: **Challenge:** Given a `codegolf.stackexchange` question id, output the ratio between the question's votes and number of answers (e.g. `votes/answers`). **Specifics:** * You may access the internet, but you may only access `stackexchange.com` and its various sub-domains. You may not use URL shorteners. * You may take input and give output in any standard format. * You must output the ratio as a decimal number in base 10, with at least 4 {accurate} digits after the decimal (zeros may be truncated). * If the question is unanswered, your program may produce undefined behavior. * You should use the `score` of the question as the vote-count, see [here](https://meta.stackexchange.com/questions/229255/what-is-the-score-of-a-post). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), least bytes in each language wins for that language, least bytes overall wins overall. **Here is a sample program in `Python 3 + requests`:** ``` import requests import json id = input("id> ") url = "https://api.stackexchange.com/2.2/questions/" + id + "?site=codegolf" content = requests.get(url).text question = json.loads(content)["items"][0] print(float(question["score"]) / question["answer_count"]) ``` [Answer] # JavaScript (ES6), ~~103~~ 102 bytes Needs to be run from the root level of `api.stackexchange.com`. Returns a `Promise` object containing the result. ``` n=>fetch(`questions/${n}?site=codegolf`).then(r=>r.json()).then(({items:[j]})=>j.score/j.answer_count) ``` * 1 byte saved thanks to [kamoroso94](https://codegolf.stackexchange.com/users/57013/kamoroso94). If [requiring that it be run from a specific path is allowed](https://codegolf.meta.stackexchange.com/q/13938/58974) then that becomes ~~92~~ 90 bytes. ``` n=>fetch(n+`?site=codegolf`).then(r=>r.json()).then(({items:[j]})=>j.score/j.answer_count) ``` --- ## Try it Full URL added to enable it to work here. ``` f= n=>fetch(`//api.stackexchange.com/questions/${n}?site=codegolf`).then(r=>r.json()).then(({items:[j]})=>j.score/j.answer_count) onchange=_=>f(+i.value).then(t=>o.innerText=t) ``` ``` <input id=i type=number><pre id=o> ``` [Answer] # [Stratos](https://github.com/okx-code/Stratos), 40 bytes -4 bytes thanks to Shaggy ``` f"¹⁵s/%²"r"⁷s"@0 {s"answer_⁰" ⁰s"score"/ ``` [Try it!](http://okx.sh/stratos/?code=f%22%C2%B9%E2%81%B5s%2F%25%C2%B2%22r%22%E2%81%B7s%22%400%0A%7Bs%22answer_%E2%81%B0%22%0A%E2%81%B0s%22score%22%2F&input=143083) Stratos specialises in [stack-exchange-api](/questions/tagged/stack-exchange-api "show questions tagged 'stack-exchange-api'") questions. Explanation: The code decompresses to the following: ``` f"api.stackexchange.com/questions/%?site=codegolf"r"items"@0 {s"answer_count" ⁰s"score"/ ``` Starting from the first line, Stratos evaluates the dyads from right to left. `f"api.stackexchange.com/questions/%?site=codegolf"r"items"@0` means "evaluate the dyad `@` with the left-hand argument `f"api.stackexchange.com/questions/%?site=codegolf"r"items"` and the right-hand argument `0`. `@` gets the *nth* element of a JSON array. To evaluate `f"api.stackexchange.com/questions/%?site=codegolf"r"items"`, we will next evaluate the dyad `r` with the left-hand argument `f"api.stackexchange.com/questions/%?site=codegolf"` and the right-hand argument `"items"`. `r` gets the JSON array with the specified name. Next, we will need to evaluate `f"api.stackexchange.com/questions/%?site=codegolf"`. First, `%` is replaced with the input. `f` means "get the contents of this URL". Now, we can move on to the second line. The newline means "add what we evaluated to the implicit argument list" Next, we evaluate `s` (get string in JSON object with a certain name) with `{` and `"answer_count"`. `{` takes an element from the implicit argument stack, returns it, and adds it back to the stack. Then, we add the output of that to the implicit argument stack. To evaluate `⁰s"score"/`, we are applying the dyad `/` (divide) to `⁰s"score"` and an element from the implicit argument stack. To evaluate `⁰s"score"` we are getting the string `"score"` from the JSON object from the 0th element in the implict argument stack. Now, the output of `/` is printed and the program terminates. [Answer] # [R](https://www.r-project.org/) + [jsonlite](https://cran.r-project.org/web/packages/jsonlite/index.html), 111 bytes ``` function(n,x=jsonlite::fromJSON(sprintf('http://api.stackexchange.com/questions/%s?site=codegolf',n))$i)x$s/x$a ``` [R-fiddle link](http://www.r-fiddle.org/#/fiddle?id=3Q3JKWBE&version=1) jsonlite is a nice JSON <-> R conversion library which works quite well. I wasn't about to golf a JSON parser for R... [Answer] # T-SQL, ~~64~~ 54 bytes It is rare that SQL can beat (most) other languages! Instead of the API URL I went directly to the [Stack Exchange Data Explorer](http://data.stackexchange.com/codegolf/query/724902/answer-to-vote-ratio-by-question-id?i=142655): ``` SELECT 1.0*Score/AnswerCount FROM Posts WHERE Id=##i## ``` The `##i##` isn't standard SQL, that's Stack Exchange's format to prompt for input. Note that the data explorer source is only updated nightly, so values aren't current. Will throw a divide by zero error on questions with no answers. **Edit**: Saved 10 bytes by multiplying by 1.0 instead of an explicit `CONVERT` to `FLOAT`. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 130 bytes ``` ($a=(ConvertFrom-Json(iwr("http://api.stackexchange.com/questions/"+$args+"?site=codegolf")).content).items).score/$a.answer_count ``` Performs an `I`nvoke-`W`eb`R`equest against the URL, gets the `.content` thereof, does a `ConvertFrom-Json` of that content, and gets the `.items` of that JSON object. Stores that into `$a` and pulls out the `.score` as the numerator. The denominator is the `.answer_count`. That value is left on the pipeline and output is implicit. If the question is unanswered, this *should* toss a "Divide by zero" error. [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~83~~ 82 bytes Wanted to give this a try to see how it would work out, seeing as Japt can't natively accomplish it. Essentially all this is doing is `eval`ing a compressed version of [my JS solution](https://codegolf.stackexchange.com/a/143084/58974). As Japt *is* JS then we can require that this be run from the root level of `api.stackexchange.com` and also return a `Promise` object containing the result. ``` Ox`fet®("quÀËs/{U}?ÐÒ=¬¸golf").È(r=>r.js()).È(i=>(j=i.ems[0]).sÖ/j.s³r_Öt) ``` * [View it](https://ethproductions.github.io/japt/?v=1.4.5&code=T3hgZmV0rigicXXAy41zL3tVfT/Q0j2suGdvbGYiKS7IAShyPT5yLmpzjSgpKS7IAShpPT4oaj1pLoplbXNbMF0pLnPWEC9qLoRzs3Jf1gR0KQ==&input=MTQzMDgz) * [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=T3hgZmV0rigiLy9hcGkuoWHlqGpEZ2UurG0vcXXAy41zL3tVfT/Q0j2suGdvbGYiKS7IAShyPT5yLmpzjSgpKS7IAShpPT7WDm+kLmxvZygoaj1pLoplbXNbMF0pLnPWEC9qLoRzs3Jf1gR0KSk=&input=MTQzMDgz) - the extra bytes in this version are accounted for by the inclusion of `//api.stackexchange.com/` in the URL and of `console.log` so you can actually see it working [Answer] # Mathematica, 124 bytes ``` N@("score"/.(u="items"/.Import["http://api.stackexchange.com/questions/"<>#<>"?site=codegolf","JSON"]))/("answer_count"/.u)& ``` Mathematica has a data type called `Rule` and it confuses the heck out of me. :P [Answer] # [Python 3](https://docs.python.org/3/) + requests, 149 bytes *-1 byte thanks to Mr. Xcoder.* ``` from requests import* u=get('http://api.stackexchange.com/questions/%s?site=codegolf'%input()).json()['items'][0] print(u['score']/u['answer_count']) ``` [Answer] # PHP, 167 bytes ``` <?$f=json_decode(gzdecode(file_get_contents('https://api.stackexchange.com/2.2/questions/'.$argv[1].'?site=codegolf')))->items[0];echo $f->score/$f->answer_count; ``` Turbo-fast crack at this. Save as a file and execute in the terminal like so: ``` php -f file.php 143083 ``` Might be a way to reduce this. ]
[Question] [ Given 2 integer inputs representing the size of the field, `x` and `y`, output a path through the field. Example output for `5, 4`: ``` # # # ### ### # ``` The whole field is 5 by 4, and there is a path made of hashmarks crossing the field. The path should always start in the top left corner, and go to the bottom right. The whole path should be randomized every time the program is run. Every valid path should be a possible output. The rules for paths are: * Made of hashmarks * Every hash is only connected to 2 other hashes (i.e. the path does not intersect or run alongside itself) The non-hash spaces can be filled it with any other character, but it must be consistent (i.e. all spaces, all periods, etc.) Examples: ``` 2, 2 ## # 3, 4 ## ## # # 5, 5 ##### # # # # 6, 5 ## ### # # # ## # # # ## # ### # 7, 9 ####### # #### # # # # # # # # # # # #### # ####### ``` This kind of path is similar to a self-avoiding random walk, however it can't be adjacent to itself unlike a true SAW. Path continuity and path touching are both defined without diagonals. [Answer] # Befunge, 344 bytes ``` &v>>>#p_:63p:43g`\!+v>/*53g+\01g:2%2*1-\2/!*63g+\0\:v 40$ v++!\`g14:p35:\<^2\-1*2%2p10::%4+g00:\g36\g35-1_v #11^$_83p73v >1+:41g`!#v_$,1+:43g`!#v_@>->2>+00p+141^_ <p1^ vp< ^,g+7g36:<<<<1+55p36:<<<< ^1?0^#7g36g35* 8&p|!++!%9#2g+7g10\*!-g38g10!-g37:g00!!*<>3^ 443>:!#v_>>1-::3%1-:53g+00p\3/1-:63g+01p^ ^>^>>$#<"#"53g63g7+p41g53g-43g63g-+!#^_ ``` [Try it online!](http://befunge.tryitonline.net/#code=JnY+Pj4jcF86NjNwOjQzZ2BcISt2Pi8qNTNnK1wwMWc6MiUyKjEtXDIvISo2M2crXDBcOnYKIDQwJCB2KyshXGBnMTQ6cDM1Olw8XjJcLTEqMiUycDEwOjolNCtnMDA6XGczNlxnMzUtMV92CiMxMV4kXzgzcDczdiA+MSs6NDFnYCEjdl8kLDErOjQzZ2AhI3ZfQD4tPjI+KzAwcCsxNDFeXwo8cDFeICAgICB2cDwgXixnKzdnMzY6PDw8PDErNTVwMzY6PDw8PCBeMT8wXiM3ZzM2ZzM1Kgo4JnB8ISsrISU5IzJnKzdnMTBcKiEtZzM4ZzEwIS1nMzc6ZzAwISEqPD4zXgo0NDM+OiEjdl8+PjEtOjozJTEtOjUzZyswMHBcMy8xLTo2M2crMDFwXgpePl4+PiQjPCIjIjUzZzYzZzcrcDQxZzUzZy00M2c2M2ctKyEjXl8&input=OSA3) As @flawr mentioned in their MATLAB answer, this may take some time if the field size is of any non-trivial size. In fact it's quite easy to get into a situation where it's really not worth trying to wait for it to finish, because you're quite likely to be waiting until the end of time. To understand why this happens, it helpful to view the program as it's executing in one of Befunge's many "visual debuggers". Since data and code are the same thing in Befunge, you'll get to view the path as it changes over time. For example, here is a short animation showing what a part of a run on a slow path might look like. ![Animation showing the path construction getting itself stuck in a corner](https://i.stack.imgur.com/xJeX8.gif) Once the algorithm decides to make that fateful turn to the left at the bottom of the field boundary, it has essentially condemned itself to a lifetime of aimless wandering. From that point on it has to follow every single possible path in that fenced off area before it can back out and try the turn to the right. And the number of potential paths in these cases can easily become astronomical. Bottom line: If it seems to be taking a long time, it's probably a good idea to just abort the execution and start again. **Explanation** This is basically a recursive algorithm, trying every possible path through the field, and then unwinding steps that have already been followed whenever it gets stuck. Since Befunge doesn't have the concept of functions, a recursive function is out of the question, but we can emulate the process by tracking the state on the stack. This works by populating the stack with potential coordinates that we may want to follow. Then we pull one set from the stack and check whether it is suitable (i.e. in range and not overlapping with an existing path). Once we've got a good spot, we write a `#` into the playfield at that location, and add those details to the stack in case we need to backtrack later. We then push an additional four sets of coordinates onto the stack (in random order) indicating the potential paths we can take from this new location, and jump back to the start of the loop. If none of the potential paths are feasible, we'll get to the point on the stack where we saved the location of the `#` we wrote out, so we'll undo that step and continue trying potential coordinates from one step prior. This is what the code looks like with the various component parts highlighted: ![Source code with execution paths highlighted](https://i.stack.imgur.com/eIxyb.png) ![*](https://i.stack.imgur.com/jmV4j.png) Read the width and height of the field, and push the start coordinates along with a `0` type marker to indicate a potential path rather than a backtracking location. ![*](https://i.stack.imgur.com/z4eIY.png) [Answer] # MATLAB, ~~316 305 300~~ 293 bytes ``` function P=f(a,b);z(a,b)=0;P=z;c=@(X)conv2(+X,[0,1,0;1,1,1;0,1,0],'s');B=1;while B;P=z;P(1)=1;for K=1:a*b;S=z;S(a,b)=1;for L=2:a*b;S(~S&c(S)&~P)=L;end;[i,j]=find(S&c(P==K));if i;r=randi(nnz(i));else;break;end;P(i(r),j(r))=K+1;if P(a,b);break;end;end;B=any(any(c(P>0)>3));end;P(P>0)=35;P=[P,''] ``` Thanks @LuisMendo for various suggestions and a bunch of bytes=) [Try it online!](https://tio.run/nexus/octave#RY8xT8MwEIV3foUlRH2mHuICC6erUNZ0sJSlKOrgJI5wKU5lIxAZ@teDnSIx3Mn63r13vtnQE7b0iBNNNowRjGwFapqwoxfYy1fRjf5rA@u9bAqpZIEqdYXL@yB5NB@WCyxJ4febO1lWLmYNSiQ0jIFVpJ7NfYt1wvUS/yfsaHMV4FKvOqhlJVYXLWiH1vfYOHk80OB8D1nVRFUaEOgG5jBQML534P0ELkF7ihbbYM374tXgIAh5TE1QtVbZpK@X/Q/lKsn4H8iVNmyLtGD7kOOWjAQE8VueDmq05PyAs87/yJRxZHfM@WjDJ4tn09mb3sUzaIHzLw "Octave – TIO Nexus") (Without warranty: Note that a few adjustments were needed to get it to run on Octave: First of all I needed to remove the `function` keyword and hardcode the values, secondly: The spaces do not get printed correctly as in Matlab. Also I did not check the convolution commands of Octave, which might act differently.) Example output for input `(7,10)` (can already take quite a while): ``` # # ## ## # ### # # ## ##### # ``` ### Explanation This generates paths sequentially from the top left to the bottom right with the desired 4-connectivity, and then uses rejection sampling to reject paths that do violate the criterion that you cannot have adjecent parts. ``` function P=f(a,b); z(a,b)=0; % a matrix of zeros of the size of th efield P=z; c=@(X)conv2(+X,[0,1,0;1,1,1;0,1,0],'s'); % our convolution function, we always convolute with the same 4-neighbourhood kernel B=1; while B; % while we reject, we generate paths: P=z; P(1)=1; % P is our path, we place the first seed for K=1:a*b; % in this loop we generate the all shortest paths (flood fill) from the bottom right, withot crossing the path to see what fiels are reachable from the bottom left S=z; S(a,b)=1; % seed on the bottom left for L=2:a*b; S(~S&c(S)&~P)=L; % update flood front end; [i,j]=find(S&c(P==K)); % find a neighbour of the current end of the path, that is also reachable from the bottom left if i; % if we found some choose a random one r=randi(nnz(i)); else; break; % otherwise restart (might not be necessary, but I'm too tired to think about it properly=) end; P(i(r),j(r))=K+1; % update the end of the current path if P(a,b); % if we finished, stop continuing this path break; end; end; B=any(any(c(P>0)>3)); % check if we actually have a valid path end; P(P>0)=35; % format the path nicely P=[P,'']; ``` Oh and as always: > > Convolution is the key to success. > > > [Answer] # QBasic, 259 bytes I sure love `GOTO`s. ``` RANDOMIZE TIMER INPUT w,h DO CLS x=1 y=1 REDIM a(w+3,h+3) 2a(x+1,y+1)=1 LOCATE y,x ?"#" d=INT(RND*4) m=1AND d x=x+m*(d-2) y=y-d*m+m+d-1 c=a(x,y+1)+a(x+2,y+1)+a(x+1,y)+a(x+1,y+2)=1 IF(x=w)*c*(y=h)GOTO 9 IF(x*y-1)*x*y*c*(x<=w)*(y<=h)GOTO 2 LOOP 9LOCATE y,x ?"#" ``` Basic strategy: at each step, print a `#` to the current location and move in a random direction. An array `a` of 0s and 1s keeps track of where we've been. If the move is legal and takes us to the endpoint, `GOTO 9` to exit the loop and print the final `#`. Else, if the move is legal, take another step. Else, clear the screen and start over (much golfier than coding a backtracking algorithm!). Tested on my laptop in QB64, this generally produces a result for `9, 9` in five seconds or less. Runs of `10, 10` have taken anywhere between three and 45 seconds. Theoretically, all legal paths have non-zero probability, but the probability of a path with large curves is vanishingly small. I have occasionally seen paths with one or two small curves, though: [![Sample path](https://i.stack.imgur.com/OqJoF.png)](https://i.stack.imgur.com/OqJoF.png) Ungolfed version and/or in-depth explanation available on request. [Answer] # R, 225 bytes ``` function(x,y){library(igraph);a=matrix(rep(" ",x*y),c(y,x));g=make_lattice(c(y,x));w=runif(ecount(g));for (i in 1:2){v=shortest_paths(g,1,x*y,weights=w)$vpath[[1]];w[]=1;w[E(g)[v%--%v]]=0;};a[v]="#";cat(rbind(a,"\n"),sep="")} ``` Explanation: We generate a regular (lattice) [x \* y] undirected graph with random weigths on edges then we find the shortest path from the start to the end. However in the generated path there may be cells that have more than two neigbors for example: ``` # # #### ## # ### ``` So we should apply the shortest path algorithm two times. In the second time we set all weights to 1 except those that are in the current found path that set to 0; result ``` # # ### # # ### ``` Ungolfed: ``` function(x,y){ library(igraph);#igraph library should be installed a=matrix(rep(" ",x*y),c(y,x));#ASCII representation of the graph g=make_lattice(c(y,x));# regular graph w=runif(ecount(g));#weights for (i in 1:2){ #find vertices that are in the path v=shortest_paths(g,1,x*y,weights=w)$vpath[[1]]; #set all weights to 1 except those that are in the current found path that set to 0 w[]=1; w[E(g)[v%--%v]]=0; } a[v]="#"; cat(rbind(a,"\n"),sep="") } ``` [Answer] ## JavaScript (ES7), ~~333~~ ~~331~~ ~~330~~ ~~329~~ ~~324~~ ~~318~~ 312 bytes ``` f= (h,w,c=[...Array(h)].map(_=>Array(w).fill` `),g=a=>{for(z of b=[[[h-1,w-1]]])a.map(([x,y])=>b.every(([[i,j]])=>i-x|j-y)&(z[0][0]-x)**2+(z[0][1]-y)**2<2&&b.push([[x,y],...z]));return b.find(([[x,y]])=>!x&!y)||g([...a,[h,w].map(n=>Math.random()*n|0)])})=>g([]).map(([x,y])=>c[x][y]=`#`)&&c.map(a=>a.join``).join` ` ``` ``` Height: <input type=number min=1 id=h>Width: <input type=number min=1 id=w><input type=button value="Generate!" onclick=o.textContent=f(+h.value,+w.value)><pre id=o> ``` Expanation: `#`s are randomly placed in the array until a path is found through the field using a breadth-first search; the first, and therefore shortest, such path is then output; this guarantees that the path does not intersect itself. Note that particularly for larger fields it's possible to exceed the JS engine's stack before a path is found. Ungolfed: ``` function r(n) { return Math.floor(Math.random() * n); } function f(h, w) { var a = []; // array of placed #s var b; // breadth-first search results var c; do { a.push([r(h), r(w)]); // place a # randomly b = [[[h - 1, w - 1]]]; // start from bottom right corner for (z of b) // breadth-first search for ([x, y] of a) // find possible next steps if (!b.some(([[i, j]]) => i == x && j == y)) if ((z[0][0] - x) ** 2 + (z[0][1] - y) ** 2 < 2) if (x || y) b.push([[x, y], ...z]); // add to search else if (!c) c = [[x, y], ...z]; // found path } while (!c); a = [...Array(h)].map(() => Array(w).fill(' ')); for ([x, y] of c) // convert path to output a[x][y] = '#'; return a.map(b => b.join('')).join('\n'); } ``` ]
[Question] [ Given a sequences of events with probabilities between 0.0 and 1.0, generate and derive the probability of each combination occurring. You may presume that a sequence of numbers is provided in whatever construct your chosen language provides. Here's an example; you may presume that the length of the sequence's combinations fit into memory: ``` { 0.55, 0.67, 0.13 } ``` The program shall print each combination and the associated probability of that sequence occurring. A 1 shall denote that the event in that index of the input sequence occurred and a 0 shall denote that that event did not occur. The desired output is below (I don't care about printing the work, that's just for informational purposes of the algorithm): ``` [0,0,0] = (1 - 0.55) * (1-0.67) * (1-0.13) = 0.129195 [0,0,1] = (1 - 0.55) * (1-0.67) * (0.13) = 0.019305 [0,1,0] = (1 - 0.55) * (0.67) * (1-0.13) = 0.262305 [0,1,1] = (1 - 0.55) * (0.67) * (0.13) = 0.039195 [1,0,0] = (0.55) * (1-0.67) * (1-0.13) = 0.157905 [1,0,1] = (0.55) * (1-0.67) * (0.13) = 0.023595 [1,1,0] = (0.55) * (0.67) * (1-0.13) = 0.320595 [1,1,1] = (0.55) * (0.67) * (0.13) = 0.047905 ``` This problem is tangentially related to calculating a "Cartesian product". Remember, this is code-golf, so the code with the fewest number of bytes wins. [Answer] ## Haskell, 86 bytes ``` unlines.map(\p->show(fst<$>p)++" = "++show(product$snd<$>p)).mapM(\x->[(0,1-x),(1,x)]) ``` Usage example: ``` Prelude> putStrLn $ unlines.map(\p->show(fst<$>p)++" = "++show(product$snd<$>p)).mapM(\x->[(0,1-x),(1,x)]) $ [0.55, 0.67, 0.13] [0,0,0] = 0.12919499999999998 [0,0,1] = 1.9304999999999996e-2 [0,1,0] = 0.262305 [0,1,1] = 3.9195e-2 [1,0,0] = 0.157905 [1,0,1] = 2.3595e-2 [1,1,0] = 0.320595 [1,1,1] = 4.790500000000001e-2 ``` Most of the bytes are spent for output formatting. If you are only interested in the probability vector it's only 29 bytes: ``` map product.mapM(\x->[1-x,x]) ``` How it works: ``` mapM(\x->[(0,1-x),(1,x)]) -- for each number x in the input -- list make either the pair (0,1-x) -- or (1,x). Build a list with -- all combinations map(\p-> ) -- for each such combination p show(fst<$>p) -- print the first elements ++" = "++ -- then the string " = " show(product$snd<$>p) -- then the product of the second -- elements unlines -- joins with newlines ``` [Answer] # Mathematica, ~~46~~ 45 bytes ``` (s=#;1##&@@Abs[#-s]&/@{1,0}~Tuples~Length@s)& ``` Takes a list. Even works for the empty list `{}`, for which the output is `{1}`. ## Test case: ``` %[{0.55, 0.67, 0.13}] {0.129195, 0.019305, 0.262305, 0.039195, 0.157905, 0.023595, 0.320595, 0.047905} ``` ## Explanation Given a list of probabilities `s` and a list of bits `b` with `0` denoting "did not occur" and `1` denoting "did occur", the list of probabilities to be multiplied is given by ``` 1 - b - s ``` up to sign. If instead `0` denotes "did occur" and `1` "did not occur", then this simplifies to ``` b - s ``` so we: ``` {1,0}~Tuples~Length@s (* Generate all possible bit combinations *) (#-s)&/@{1,0}~Tuples~Length@s (* Generate probabilities to be multiplied up to sign *) 1##&@@Abs[#-s]&/@{1,0}~Tuples~Length@s (* Correct sign and multiply; 1##& is short for Times *) (s=#;1##&@@Abs[#-s]&/@{1,0}~Tuples~Length@s)& (* Assign s to first argument of function, done separately to avoid clash with inner function *) ``` [Answer] # Perl, ~~42~~ 40 bytes Includes +1 for `-a` Give numbers on STDIN: ``` perl -M5.010 combi.pl <<< "0.55 0.67 0.13" ``` outputs ``` 0.129195 0.019305 0.262305 0.039195 0.157905 0.023595 0.320595 0.047905 ``` `combi.pl`: ``` #!/usr/bin/perl -a $"=")\\*({1-,}";say eval for<({1-,}@F)> ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~12~~ 11 bytes ``` TF-|Z}&Z*!p ``` Input is a column vector, with the format `[0.55; 0.67; 0.13]` [Try it online!](http://matl.tryitonline.net/#code=VEYtfFp9JloqIXA&input=WzAuNTU7IDAuNjc7IDAuMTNd) ``` TF % Push [1, 0] - % Subtract from implicit input (column array), with broadcast. Gives a 2-col % matrix where the first column is the input minus 1 and the second is the input | % Absolute value Z} % Split the matrix into its rows &Z* % Cartesian product of all resulting. This gives a matrix as result, with each % "combination" on a different row !p % Product of each row. Implicitly display ``` [Answer] # Perl, 116 bytes ``` for(glob"{0,1}"x(@a=split/ /,<>)){@c=split//;$d=1;$d*=@c[$_]?$a[$_]:1-$a[$_]for 0..$#a;say"[".join(",",@c)."] = $d"} ``` Readable: ``` for(glob"{0,1}"x(@a=split/ /,<>)){ @c=split//; $d=1;$d*=@c[$_]?$a[$_]:1-$a[$_]for 0..$#a; say"[".join(",",@c)."] = $d" } ``` Creates a list of all possible combinations of 0s and 1s of length equal to the number of input parameters (e.g., for the example above, it would be of length 3), then calculates each probability. Thanks to @Dada for showing me what the `glob` function *can* do, even though I'm not 100% sure I understand *how* it does that. Sample output: ``` [0,0,0] = 0.129195 [0,0,1] = 0.019305 [0,1,0] = 0.262305 [0,1,1] = 0.039195 [1,0,0] = 0.157905 [1,0,1] = 0.023595 [1,1,0] = 0.320595 [1,1,1] = 0.047905 ``` [Answer] # R, 72 69 bytes Takes input from stdin and returns an R-vector of probabilities. ``` apply(abs(t(expand.grid(rep(list(1:0),length(x<-scan())))-x)),1,prod) ``` Edit: Removed one unnecessary transpose, the permutation matrix is now the transposed version of the one below and the probabilities are calculated as the column-wise product rather than row-wise. **Example output:** ``` [1] 0.129195 0.157905 0.262305 0.320595 0.019305 0.023595 0.039195 0.047905 ``` Note that the probabilities are in a different order due to the fact that the permutation-matrix generated by `expand.grid` produces the following (generation of this matrix can probably be golfed using external packages): ``` 1 1 1 1 2 0 1 1 3 1 0 1 4 0 0 1 5 1 1 0 6 0 1 0 7 1 0 0 8 0 0 0 ``` The first probability corresponds to the inverted outcome of the first row in the above matrix and the second to the inverted second row etc. Formatting output to see this even more clearly makes the program longer (164 bytes): ``` m=expand.grid(rep(list(1:0),length(x<-scan()))) cat(paste0("[",apply(abs(m-1),1,function(x)paste0(x,collapse=",")),"] = ",apply(abs(t(t(m)-x)),1,prod),"\n"),sep="") ``` which instead produces: ``` [0,0,0] = 0.129195 [1,0,0] = 0.157905 [0,1,0] = 0.262305 [1,1,0] = 0.320595 [0,0,1] = 0.019305 [1,0,1] = 0.023595 [0,1,1] = 0.039195 [1,1,1] = 0.047905 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 9 bytes ``` ż@C×þF¥@/ ``` [Try it online!](http://jelly.tryitonline.net/#code=xbxAQ8OXw75GwqVALw&input=&args=WzAuNTUsIDAuNjcsIDAuMTNd) [Answer] # J, 14 bytes ``` -.([:,*/)/@,.] ``` ## Usage ``` f =: -.([:,*/)/@,.] f 0.55 0.67 0.13 0.129195 0.019305 0.262305 0.039195 0.157905 0.023595 0.320595 0.047905 ``` ## Explanation ``` -.([:,*/)/@,.] Input: array P -. Complement (1-x) for each x in P ] Identity, get P ,. Interleave to make pairs [(1-x), x] ( )/@ Reduce from right-to-left by */ Forming the multiplication table [:, Flattening the result ``` [Answer] # Pyth, 10 bytes ``` *MaVLQ^U2l ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=%2AMaVLQ%5EU2l&input=%5B0.55%2C%200.67%2C%200.13%5D&debug=0) ### Explanation: ``` *MaVLQ^U2lQ implicit Q at the end (Q = input list) ^U2lQ repeated Cartesian product of [0, 1] with itself length(Q)-times this gives all combinations of 0s and 1s aVLQ absolute difference between these 0-1-vectors with Q *M fold the vectors by multiplication ``` [Answer] # C, 110 bytes ``` i,k;f(float* a,int n){for(k=0;k<1<<n;++k){float p=1;for(i=0;i<n;++i)p*=k&(1<<i)?a[i]:1-a[i];printf("%f,",p);}} ``` Ungolfed: ``` i,k;f(float* a,int n){ for(k=0; k<1<<n; ++k){ float p=1; for (i=0; i<n; ++i) p*=k&(1<<i)?a[i]:1-a[i]; printf("%f,",p); } } ``` Works up to 32 items, +5+1 bytes for 64 items (declare `long k;` and add `L` in the first loop so that `k<1L<<N`). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes ``` <Äæ¹æR+P ``` [Try it online!](http://05ab1e.tryitonline.net/#code=PMOEw6bCucOmUitQ&input=WzAuMSwwLjIsMC4zXQo) ``` <Äæ¹æR+P # Main link (Input is [.1,.2]) ########### <Ä # Invert input, take the abs value. # Stack is [.9,.8] æ¹æ # Powerset of both inverted and original arrays. # Stack is [[],[.1],[.2],[.1,.2]],[[],[.9],[.8],[.9,.8]] R+ # Reverse original array, add arrays together. # Stack is [.9,.8],[.1,.8],[.2,.9],[.1,.2] P # For each sub array, push product. # Final Result: [0.02, 0.18, 0.08, 0.72] # E.G. [ 11, 10, 01, 00] ``` [Answer] ## JavaScript (Firefox 30-57), 57 bytes ``` f=([p,...a])=>1/p?[for(q of[1-p,p])for(b of f(a))q*b]:[1] ``` Returns an array of all the probabilities. If you want the array of events too, then for 86 bytes: ``` f=([p,...a])=>1/p?[for(e of'01')for(b of f(a))[[+e,...b[0]],(+e?p:1-p)*b[1]]]:[[[],1]] ``` If you're allowed the events as a string, then it's only 80 bytes: ``` f=([p,...a])=>1/p?[for(e of'01')for(b of f(a))[e+b[0],(+e?p:1-p)*b[1]]]:[['',1]] ``` Subtract two bytes for `1/` for each solution if the probability is never going to be zero. [Answer] # Perl 6, ~~24~~ 19 bytes of Latin-1 ``` {[*] 1 «-»@_ «|»@_} ``` Older code: ``` {[*] map {1-$^a|$^a},@_} ``` This is a function. Use it like this: ``` {[*] 1 «-»@_ «|»@_}(0.55, 0.67, 0.13) ``` to get: ``` any(any(any(0.129195, 0.019305), any(0.262305, 0.039195)), any(any(0.157905, 0.023595), any(0.320595, 0.047905))) ``` Explanation of the older code: ``` [*] multiply together all array elements map but first transform each element via {1-$^a|$^a} considering both 1 minus the value and the value ,@_ of the function input ``` The newer code is basically the same, just using terser syntax: ``` [*] multiply together all array elements 1 «-»@_ of the array formed by subtracting the argument from 1 «|»@_ pointwise considering both that and the original array ``` The map generates an array full of `any` constructs, which multiply into larger `any` constructs, neatly solving the problem without even needing a loop. Not the shortest language for the program, but it's a very direct translation of the problem. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 10 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ## New Solution Index origin independent. Anonymous function. Takes probabilities list as argument. ``` ∘.×/⊢,¨1-⊢ ``` `∘.×/` The Cartesian product reduction over `⊢` the argument values `,¨` each paired up with `1-⊢` the complement argument values (lit. one minus the argument values) [TryAPL online!](http://tryapl.org/?a=f%u2190%u2218.%D7/%u22A2%2C%A81-%u22A2%20%u22C4%20f%200.55%200.67%200.13&run) --- ## Old Solution Requires `⎕IO←0` which is default on many systems. Prompts for probabilities' list. ``` |⎕∘.×.-⊂⍳2 ``` ### Explanation `|` absolute value of `⎕` the input, ***ɑ*** = [***ɑ***₁ ***ɑ***₂ ***ɑ***₃] `∘.×.-` modified inner tensor multiplied, (***ɑ***₁ – ***b***₁) ⊗ (***ɑ***₂ – ***b***₂) ⊗ (***ɑ***₃ – ***b***₃), with `⊂⍳2` the enclosed list ***b*** = [[0 1]] ### Mathematical definition As ***b*** is enclosed, it is scalar, and therefore extended to the length of ***ɑ***, namely 3, so the entire expression is  **A** = │(***ɑ***₁ – ***b***) ⊗ (***ɑ***₂ – ***b***) ⊗ (***ɑ***₃ – ***b***)│ =  │(***ɑ***₁ – [0,1]) ⊗ (***ɑ***₂ – [0,1]) ⊗ (***ɑ***₃ – [0,1])│ =  │[***ɑ***₁,***ɑ***₁ – 1] ⊗ [***ɑ***₂, ***ɑ***₂ – 1] ⊗ [***ɑ***₃,***ɑ***₃ – 1]│ =  ⎢ ⎡ ⎡  ***ɑ***₁***ɑ***₂***ɑ***₃  ⎤ ⎡  ***ɑ***₁***ɑ***₂(***ɑ***₃-1)  ⎤ ⎤ ⎥  ⎢ ⎢ ⎣  ***ɑ***₁(***ɑ***₂-1)***ɑ***₃  ⎦ ⎣  ***ɑ***₁(***ɑ***₂-1)(***ɑ***₃-1)  ⎦ ⎥ ⎥  ⎢ ⎢ ⎡  (***ɑ***₁-1)***ɑ***₂***ɑ***₃  ⎤ ⎡  (***ɑ***₁-1)***ɑ***₂(***ɑ***₃-1)  ⎤ ⎥ ⎥  ⎢ ⎣ ⎣(***ɑ***₁-1)(***ɑ***₂-1)***ɑ***₃⎦ ⎣(***ɑ***₁-1)(***ɑ***₂-1)(***ɑ***₃-1)⎦ ⎦ ⎥ [TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%u2206%u21900.55%200.67%200.13%20%u22C4%20%7C%u2206%u2218.%D7.-%u2282%u23732&run) ## Notes (applies to both old and new solution) The program and formula works for any number (*n*) of variables, and returns an *n*-dimensional array of length 2 in every dimension. With three variables, the probability of a specific outcome  *P*(*p*,*q*,*r*) = **A***p*,*q*,*r* which can conveniently be selected from the array with `(⊃A)[p;q;r]` extracted with `p q r⌷⊃A` E.g. [`1 1 0⌷⊃|0.55 0.67 0.13∘.×.-⊂⍳2`](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%201%201%200%u2337%u2283%7C0.55%200.67%200.13%u2218.%D7.-%u2282%u23732&run) gives *P*(55%, 67%, ¬13%) = 1.9305% [Answer] # PHP, ~~105~~ ~~97~~ ~~94 93~~ 87 bytes ``` for(;$i<2**$c=count($a=$argv)-$p=1;$i+=print-abs($p))for(;$c;)$p*=$a[$c--]-!($i>>$c&1); ``` Run like this: ``` php -r 'for(;$i<2**$c=count($a=$argv)-$p=1;$i+=print-abs($p))for(;$c;)$p*=$a[$c--]-!($i>>$c&1);' -- .55 .67 .13 2>/dev/null;echo > -0.129195-0.157905-0.262305-0.320595-0.019305-0.023595-0.039195-0.047905 ``` Note that the output is little endian: ``` [0,0,0] [1,0,0] [0,1,0] [1,1,0] [0,0,1] [1,0,1] [0,1,1] [1,1,1] ``` # Explanation ``` for( ; $i<2**$c= # Iterate over possible combinations: 2^c, count($a=$argv)-$p=1; # where c is input length -p (set p to 1) $i+=print-abs($p) # Increment i and print product after each ) # iteration, dash separated for( ; $c; # Iterate over input ($c..0) ) $p*= # Multiply the product by difference between: $a[$c--]- # - The $c-th item of the input. !($i>>$c&1); # - The $c-th bit of `$i`, negated (1 or 0) ``` # Tweaks * Saved 8 bytes by using binary logic to get bit instead of converting to string * Saved a byte by combining the resetting of `$p` to 1 with computation of `$c` * Saved a byte by adding the result of print (1) to `$i` instead of incrementing * Saved a byte by using underscore as output delimiter * Saved a byte by using minus sign as delimiter (there are no negative chances). * Saved 6 bytes by using `$c` instead of `$$i` [Answer] # C++17, ~~137~~ ~~131~~ 129 bytes Saving 6 bytes by declaring `#define A auto`, first time that such a short macro saves anything. -2 bytes for using `#import` and deleting the space before `<` ``` #import<iostream> #define A auto A g(A r){std::cout<<r<<",";}A g(A r,A x,A...p){g(x*r,p...);g(r-x*r,p...);}A f(A...p){g(1,p...);} ``` Spawns all possible combinations. Ungolfed: ``` //base case to print the result int g(auto r){std::cout << r << ",";} //extract item from parameter pack int g(auto r, auto x, auto... p) { g(x*r,p...); //multiply with temp result and call with tail g(r-x*r,p...); //same as above for (1-x) } //start of recursion, setting temp result to 1 int f(auto...p){g(1,p...);} ``` Usage: ``` f(0.55, 0.67, 0.13); ``` ]
[Question] [ I've enjoyed reading this site; this is my first question. Edits are welcome. Given positive integers \$n\$ and \$m\$, compute all ordered partitions of \$m\$ into exactly \$n\$ positive integer parts, and print them delimited by commas and newlines. Any order is fine, but each partition must appear exactly once. For example, given \$m=6\$ and \$n=2\$, possible partitions are pairs of positive integers that sum to 6: ``` 1,5 2,4 3,3 4,2 5,1 ``` Note that `[1,5]` and `[5,1]` are different ordered partitions. Output should be exactly in the format above, with an optional trailing newline. (EDIT: The exact order of the partitions does not matter). Input/output are via [standard code-golf I/O](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Another example output for \$m=7, n=3\$: ``` 1,1,5 1,2,4 2,1,4 1,3,3 2,2,3 3,1,3 1,4,2 2,3,2 3,2,2 4,1,2 1,5,1 2,4,1 3,3,1 4,2,1 5,1,1 ``` The smallest code in bytes after 1 week wins. Again, please edit if necessary. ## Addendum: @TimmyD asked what size of integer input the program has to support. There is no hard minimum beyond the examples; indeed, the output size increases exponentially, roughly modelled by: lines = \$e^{(0.6282 n - 1.8273)}\$. ``` n | m | lines of output 2 | 1 | 1 4 | 2 | 2 6 | 3 | 6 8 | 4 | 20 10 | 5 | 70 12 | 6 | 252 14 | 7 | 924 16 | 8 | 3432 18 | 9 | 12870 20 | 10 | 48620 22 | 11 | 184756 24 | 12 | 705432 ``` [Answer] # Pyth, 14 bytes ``` V^SQEIqsNQj\,N ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?input=7%0A3&code=V%5ESQEIqsNQj%5C%2CN) or [Test Suite](http://pyth.herokuapp.com/?input=7%0A3&code=V%5ESQEIqsNQj%5C%2CN) ### Explanation: ``` V^SQEIqsNQj\,N implicit: Q = first input number SQ create the list [1, 2, ..., Q] E read another number ^ cartesian product of the list this creates all tuples of length E using the numbers in SQ V for each N in ^: IqsNQ if sum(N) == Q: j\,N join N by "," and print ``` [Answer] ## Python 3, 77 bytes ``` def f(n,m,s=''):[f(i,m-1,',%d'%(n-i)+s)for i in range(n)];m|n or print(s[1:]) ``` A recursive function that builds each output string and prints it. Tries every possible first number, recursing down to find a solution with the corresponding decreased sum `n`, and one fewer summand `m`, and a string prefix `s` with that number. If both the required sum and the number of terms are equal 0, we've hit the mark, so we print the result, cutting off the initial comma. This is checked as `m|n` being 0 (Falsey). 79 chars in Python 2: ``` def f(n,m,s=''): if m|n==0:print s[1:] for i in range(n):f(i,m-1,','+`n-i`+s) ``` [Answer] # CJam, 22 bytes ``` q~:I,:)m*{:+I=},',f*N* ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%3AI%2C%3A)m*%7B%3A%2BI%3D%7D%2C'%2Cf*N*&input=2%206). ### How it works ``` q~ Read and evaluate all input. Pushes n and m. :I Save m in I. ,:) Turn it into [1 ... I]. m* Push all vectors of {1 ... I}^n. { }, Filter; for each vector: :+I= Check if the sum of its elements equals I. Keep the vector if it does. ',f* Join all vectors, separating by commas. N* Join the array of vectors, separating by linefeeds. ``` [Answer] ## Pyth, ~~20~~ 18 bytes *-2 bytes by @Dennis!* ``` jjL\,fqQlT{s.pM./E ``` This takes `n` as the first line of input, and `m` as the second. Try it [here](http://pyth.herokuapp.com/?code=jjL%5C%2CfqQlT%7Bs.pM.%2FE&input=2%0A5&debug=1). [Answer] ## Haskell, 68 bytes ``` n#m=unlines[init$tail$show x|x<-sequence$replicate n[1..m],sum x==m] ``` Usage example: ``` *Main> putStr $ 2#6 1,5 2,4 3,3 4,2 5,1 ``` How it works: `sequence $ replicate n list` creates all combinations of `n` elements drawn form `list`. We take all such `x` of `[1..m]` where the `sum` equals `m`. `unlines` and `init$tail$show` produce the required output format. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 33 bytes ``` {↑1↓¨,/',',¨⍕¨↑⍺{⍵/⍨⍺=+/¨⍵},⍳⍵/⍺} ``` Takes `m` as left argument, `n` as right argument. Almost half (between `{` and `⍺`) is for the required formatting. [Answer] ## Mathematica, 65 bytes ``` StringRiffle[Permutations/@#~IntegerPartitions~{#2}," "," ",","]& ``` `IntegerPartitions` does the task. The rest is just to order the tuples and format the result. [Answer] # Python 3, 112 ``` from itertools import* lambda m,n:'\n'.join(','.join(map(str,x))for x in product(range(m),repeat=n)if sum(x)==m) ``` I haven't managed a 1 liner in a while. :) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ṗS=¥Ƈ⁸j€”,Y ``` [Try it online!](https://tio.run/##ASIA3f9qZWxsef//4bmXUz3CpcaH4oG4auKCrOKAnSxZ////N/8z "Jelly – Try It Online") Boo to restrictive output formats. +5 bytes because of that. ## How it works ``` ṗS=¥Ƈ⁸j€”,Y - Main link. Takes m on the left and n on the right ṗ - Take the cartesian power of m and n This returns all lists of length n consisting of the integers 1,...,m ¥Ƈ - Keep those where the following is true: S - Their sum... = - Is equal to... ⁸ - m ”, - Yield "," j€ - Join each sublist by "," Y - Join by newlines ``` [Answer] ## Python 2.7, ~~174~~ ~~170~~ 152 bytes Fat answer. At least it's readable :) ``` import sys,itertools m=int(sys.argv[1]) for k in itertools.product(range(1,m),repeat=int(sys.argv[2])): if sum(k)==m:print str(k)[1:-1].replace(" ","") ``` [Answer] # Julia, 105 bytes ``` f(m,n)=for u=∪(reduce(vcat,map(i->collect(permutations(i)),partitions(m,n)))) println("$u"[2:end-1])end ``` This is a function that reads two integer arguments and writes the results to STDOUT with a single trailing line feed. Ungolfed: ``` function f(m::Integer, n::Integer) # Get the integer partitions of m of length n p = partitions(m, n) # Construct an array of all permutations c = reduce(vcat, map(i -> collect(permutations(i)), p)) # Loop over the unique elements for u in unique(c) # Print the array representation with no brackets println("$u"[2:end-1]) end end ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` moJ',msfo=¹Σπ² ``` [Try it online!](https://tio.run/##yygtzv7/PzffS10ntzgt3/bQznOLzzcc2vT//3/j/@YA "Husk – Try It Online") with the correct output format. # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` fo=¹Σπ² ``` [Try it online!](https://tio.run/##yygtzv7/Py3f9tDOc4vPNxza9P//f@P/5gA "Husk – Try It Online") Inputs are taken as \$n,m\$. ## Explanation ``` fo=¹Σπ² π cartesian power of n, with range 1..m f filter the terms where Σ sum = equals ¹ m ``` [Answer] # [Perl 6](http://perl6.org), 54 bytes If the output could be a list of lists ``` {[X] (1..$^m)xx$^n .grep: $m==*.sum} # 36 bytes ``` ``` my &code = {[X] (1..$^m)xx$^n .grep: $m==*.sum} say .join(',') for code 7,3; ``` --- The way it's currently worded I have to add a `join` into the lambda. ``` {say .join(',')for [X] (1..$^m)xx$^n .grep: $m==*.sum} # 54 bytes ``` ``` {...}( 7,3 ); ``` ``` 1,1,5 1,2,4 1,3,3 1,4,2 1,5,1 2,1,4 2,2,3 2,3,2 2,4,1 3,1,3 3,2,2 3,3,1 4,1,2 4,2,1 5,1,1 ``` ]
[Question] [ *Some time after [this incident](https://codegolf.stackexchange.com/questions/58013/parentheses-into-footnotes)…* There are [some](http://chat.stackexchange.com/transcript/message/24962500#24962500) of [us](http://chat.stackexchange.com/transcript/message/24962510#24962510) who are against this defiling order of jQuery. It is an unholy presence, of which *must be exterminated*. I therefore call on you, the loyal to The New Kingdom of Reformation, to create a program that will eliminate such resistance. All code must be validated and searched for ANY and EVERY trace of jQuery. And, of course, your submission needs to be short (there has been another budget cut, and, unfortunately, it was in the storage department). And it cannot have defiling characters. To get you up to speed, a **defiling character** is any of the following characters: `jJqQuUeErRyY$x0`. As has been said, the use of these characters is strictly prohibited, even in your own program. So don't use them. ALSO we're okay with dollar signs in numbers. So, anything of the form `n+(.nn)*$` is O.K. (You still shouldn't use `0`.) Your program/code/etc. must validate an input program. If it contains any **defiling characters**, you must output `This programmer is guilty of Heresy. He must be burnt.`; if no such characters are found, you must output `Program validated. Clearance level 2 given.`. # Bonuses and Penalties * I personally admire the character the character `~`. For every two you use, I'll give you -1 byte. (i.e., every other `~` is free.) * You may choose precisely one character from the excluded; you may then use this character in all of it's cases, HOWEVER: there is a +50% byte initial penalty, and then a +5 byte penalty for every instance of that character. * -90% if you do not use any of the characters adjacent to `jquery` (just to be super safe) in your source code. These are (in addition): `iIkKpPsSzZXdDfF` * -20% if, when given an invalid string, along with outputting the aforementioned text, you replace all invalid characters with `-` for a run of 1, `*` with a run less than 10, and `[]` with any longer run. * -50 bytes if you do not find `JavaScript/i` or `Simplex` as having defiling characters. --- # Reference Implementation ``` function validate() { var str = document.getElementById("input").value; var str2 = str.replace(/[jquery0]/gi,"").replace(/x/g,"").replace(/(\d+\.*\d*\d*\$)|\$/g,"$1"); // thanks Doorknob! var val; if (str2 == str) { val = "Program validated. Clearance level 2 given."; } else { val = "This programmer is guilty of Heresy. He must be burnt."; } document.getElementById("output").value = val; } ``` ``` textarea{width: 600px;} ``` ``` <textarea id="input" onkeyup="validate()"></textarea> <br><br> <textarea id="output" disabled></textarea> ``` [Answer] # CJam, ~~160~~ ~~139~~ 13.4 bytes ``` 0000000: 22 cf 97 d9 87 d1 85 82 89 8d d1 db 8d 80 a8 af b3 a3 "................. 0000012: b0 b7 82 8e 80 bd c3 ca 89 85 d6 89 84 80 b2 c6 c7 d1 .................. 0000024: 7e ce d0 cd c5 d0 bf cb cb c3 d0 7e c7 d1 7e c5 d3 c7 ~..........~..~... 0000036: ca d2 d7 7e cd c4 7e a6 c3 d0 c3 d1 d7 8c 7e a6 c3 7e ...~..~.......~..~ 0000048: cb d3 d1 d2 7e c0 c3 7e c0 d3 d0 cc d2 8c 80 80 ae d0 ....~..~.......... 000005a: cd c5 d0 bf cb 7e d4 bf ca c7 c2 bf d2 c3 c2 8c 7e a1 .....~..........~. 000006c: ca c3 bf d0 bf cc c1 c3 7e ca c3 d4 c3 ca 7e 90 7e c5 ........~.....~.~. 000007e: c7 d4 c3 cc 8c 80 9d 22 7b 39 33 7e 2b 7d 25 7e ......."{93~+}%~ ``` The above is a hexdump that can be reversed with `xxd -r -c 18`. [Try it online.](http://cjam.aditsu.net/#code=%22%C3%8F%C2%97%C3%99%C2%87%C3%91%C2%85%C2%82%C2%89%C2%8D%C3%91%C3%9B%C2%8D%C2%80%C2%A8%C2%AF%C2%B3%C2%A3%C2%B0%C2%B7%C2%82%C2%8E%C2%80%C2%BD%C3%83%C3%8A%C2%89%C2%85%C3%96%C2%89%C2%84%C2%80%C2%B2%C3%86%C3%87%C3%91~%C3%8E%C3%90%C3%8D%C3%85%C3%90%C2%BF%C3%8B%C3%8B%C3%83%C3%90~%C3%87%C3%91~%C3%85%C3%93%C3%87%C3%8A%C3%92%C3%97~%C3%8D%C3%84~%C2%A6%C3%83%C3%90%C3%83%C3%91%C3%97%C2%8C~%C2%A6%C3%83~%C3%8B%C3%93%C3%91%C3%92~%C3%80%C3%83~%C3%80%C3%93%C3%90%C3%8C%C3%92%C2%8C%C2%80%C2%80%C2%AE%C3%90%C3%8D%C3%85%C3%90%C2%BF%C3%8B~%C3%94%C2%BF%C3%8A%C3%87%C3%82%C2%BF%C3%92%C3%83%C3%82%C2%8C~%C2%A1%C3%8A%C3%83%C2%BF%C3%90%C2%BF%C3%8C%C3%81%C3%83~%C3%8A%C3%83%C3%94%C3%83%C3%8A~%C2%90~%C3%85%C3%87%C3%94%C3%83%C3%8C%C2%8C%C2%80%C2%9D%22%7B93~%2B%7D%25~&input=42%24) The code itself consists of **142 bytes**. It contains a total of sixteen **~** characters (**-8 bytes**), but no jQuery-adjacent characters (**-90%**). ### How it works The match `n+(.nn)*$` really boils down to *a digit followed by a dollar sign*. First of all, ``` "<bunch of characters>"{93~+}%~ ``` adds **-94** to all code points of that string and evaluates the result. The executed code is: ``` q e# Read all input from STDIN. 9{ e# For each I in [0 ... 8]: )s e# Increment and cast to string. '$+ e# Append a dollar sign. /s e# Split the input at occurrences. Flatten the result. }/ "JQUERY$0" _el+'x+ e# Append a lowercase copy and "x" to that string. & e# Intersect with the modified input. "This programmer is guilty of Heresy. He must be burnt." "Program validated. Clearance level 2 given." ? e# Ternary if; select the corresponding message. ``` [Answer] ## [Minkolang 0.9](https://github.com/elendiastarman/Minkolang), 346-3 = 343 bytes Longest program yet. ``` #66*68*d5*2:88*5+d5+d7+d1+d3+d4+6[3i+c48*+]2c"N"11-p(od4&k13w35*[dic=,5&kk11w] ) 725*35*48*68*3+5[66+c2~g2p]27*48*1-d2+d6+d8+5[9c2~g2p]37*67*d8+3[67+c2~g2p]55*57*2[77+c2~g2p]X11-2w "This p og amm is g ilt of H s . H m st b b nt."(O). X2546*3[66+c2~g4p]44*d6+47*d3+d2+d8+6[9c2~g4p]X11-4w "P og am validat d. Cl a anc l v l 2 giv n."(O). ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=%2366*68*d5*2%3A88*5%2Bd5%2Bd7%2Bd1%2Bd3%2Bd4%2B6%5B3i%2Bc48*%2B%5D2c%22N%2211-p%28od4%26k13w35*%5Bdic%3D%2C5%26kk11w%5D%20%29%0A%20725*35*48*68*3%2B5%5B66%2Bc2%7Eg2p%5D27*48*1-d2%2Bd6%2Bd8%2B5%5B9c2%7Eg2p%5D37*67*d8%2B3%5B67%2Bc2%7Eg2p%5D55*57*2%5B77%2Bc2%7Eg2p%5DX11-2w%0A%22This%20p%20og%20amm%20%20%20is%20g%20ilt%20%20of%20H%20%20%20s%20%2E%20H%20%20m%20st%20b%20%20b%20%20nt.%22(O).%0A%20X2546*3%5B66%2Bc2%7Eg4p%5D44*d6%2B47*d3%2Bd2%2Bd8%2B6%5B9c2%7Eg4p%5DX11-4w%0A%22P%20og%20am%20validat%20d.%20Cl%20a%20anc%20%20l%20v%20l%202%20giv%20n.%22(O).&input=%2366*68*d5*2%3A88*5%2Bd5%2Bd7%2Bd1%2Bd3%2Bd4%2B6%5B3i%2Bc48*%2B%5D2c%22L%2211-p%28od3%2613w35*%5Bdic%3D%2C4%26O11w%5D%20%29%0A%20X725*35*48*68*3%2B5%5B66%2Bc2%7Eg2p%5D27*48*1-d2%2Bd6%2Bd8%2B5%5B9c2%7Eg2p%5D37*67*d8%2B3%5B67%2Bc2%7Eg2p%5D55*57*2%5B77%2Bc2%7Eg2p%5DX11-2w%0A%22This%20p%20og%20amm%20%20%20is%20g%20ilt%20%20of%20H%20%20%20s%20%2E%20H%20%20m%20st%20b%20%20b%20%20nt.%22(O).%0A%20X2546*3%5B66%2Bc2%7Eg4p%5D44*d6%2B47*d3%2Bd2%2Bd8%2B6%5B9c2%7Eg4p%5DX11-4w%0A%22P%20og%20am%20validat%20d.%20Cl%20a%20anc%20%20l%20v%20l%202%20giv%20n.%22(O).) ### Explanation The first line does three things: 1) build up the stack with the forbidden characters, 2) put a much-needed `x` in the right place (the space at the end), and 3) loop through the input, jumping to the appropriate line. The second and fourth lines do the same thing: replace every gap in the succeeding line with the appropriate character. They jump to the next line at the end. The third and fifth lines simply push the required string on the stack and print it out. [Answer] # PHP, (204\*1.5 + 5) \* .1 = 31.1 ``` <?=eval(~šœ—.ß..š˜ ’ž‹œ—×ØÐ¤•ŽŠš.†££Û‡Ï¢Ð–ØÓ..š˜ .š.“žœš×ØÐ¤ÎÒÆ¢Ô×££Ñ¤ÎÒÆ¢„Í‚ÖÀ££ÛÐØÓÝÝÓÛž.˜‰¤Î¢ÖÖÀØ«—–Œß...˜.ž’’š.ß–Œß˜Š–“‹†ß.™ß·š.šŒ†Ñß·šß’ŠŒ‹ß.šß.Š.‘‹ÑØÅد..˜.ž’߉ž“–›ž‹š›Ñß¼“šž.ž‘œšß“š‰š“ßÍߘ–‰š‘ÑØÄ); ``` This dump was made using gnuwin32 `hexdump`. Reverse with `hex2bin`. ``` 00000000: 3C 3F 3D 65 76 61 6C 28 - 7E 9A 9C 97 90 DF 8F 8D |<?=eval(~ | 00000010: 9A 98 A0 92 9E 8B 9C 97 - D7 D8 D0 A4 95 8E 8A 9A | | 00000020: 8D 86 A3 A3 DB 87 CF A2 - D0 96 D8 D3 8F 8D 9A 98 | | 00000030: A0 8D 9A 8F 93 9E 9C 9A - D7 D8 D0 A4 CE D2 C6 A2 | | 00000040: D4 D7 A3 A3 D1 A4 CE D2 - C6 A2 84 CD 82 D6 C0 A3 | | 00000050: A3 DB D0 D8 D3 DD DD D3 - DB 9E 8D 98 89 A4 CE A2 | | 00000060: D6 D6 C0 D8 AB 97 96 8C - DF 8F 8D 90 98 8D 9E 92 | | 00000070: 92 9A 8D DF 96 8C DF 98 - 8A 96 93 8B 86 DF 90 99 | | 00000080: DF B7 9A 8D 9A 8C 86 D1 - DF B7 9A DF 92 8A 8C 8B | | 00000090: DF 9D 9A DF 9D 8A 8D 91 - 8B D1 D8 C5 D8 AF 8D 90 | | 000000a0: 98 8D 9E 92 DF 89 9E 93 - 96 9B 9E 8B 9A 9B D1 DF | | 000000b0: BC 93 9A 9E 8D 9E 91 9C - 9A DF 93 9A 89 9A 93 DF | | 000000c0: CD DF 98 96 89 9A 91 D1 - D8 C4 29 3B | );| 000000cc; ``` (I'm confused about the order in which to apply the bonus/penalty, so I assumed order as written.) Uses the character "e" in eval. Thanks to PHP string inversion magic, this manages to avoid all the other jquery and near-jquery characters. The inverted string contains this code (formatted for clarity) ``` echo preg_match('/[jquery\\$x0]/i', preg_replace('/[1-9]+(\\.[1-9]{2})?\\$/',"", $argv[1])) ? 'This programmer is guilty of Heresy. He must be burnt.' : 'Program validated. Clearance level 2 given.'; ``` Since this code doesn't have a return statement, `eval` returns null so `<?=eval` doesn't do anything. (It's just to avoid `<?php`) [Answer] # [><>](https://esolangs.org/wiki/Fish), 184 bytes ``` "/6VO+K;[.N'G|(p ~<.1+f9o*-21-*5-1' ';!?l<"K),4):.{%:/27:'67m{X/6:):-86{/6%6/{i{42%6-m" f +1.>"m'-)&9{69{'(&.{6S{m"'"(6)6S{5,{"'"'/2&4{(2{)6..:)4,)+{(23G"8 !^ag?/i:1+? p>l?!^1' '5*@@-a ``` This can be a *bit* shorter with unprintables, but here's a printable version just for fun. Won't work with the online interpreter since it does puts outside of the codebox. This program encodes both strings as ``` G32({+),4):..6){2({4&2/'"{,5{S6)6("m{S6{.&('{96{9&)-'m K),4):.{%:/27:'67m{X/6:):-86{/6%6/{i{42%6-m ``` which is each code point subtracted from 155. Similarly, ``` 6V/O+K;[.N'G|(p ``` encodes the forbidden characters, with code points subtracted from 160. The last line merely sets the coordinates `(forbidden char, 10)` to 1, forming a lookup table. The fourth line then checks each input char using the lookup table, outputting the heresy message if 1 else continuing on. On EOF, we move up to output the clearance message. [Answer] ## "Javascript" 840\*2+14\*5=1750 ;) I'm soooo close, just need to find a way to get rid of the r's Stack isn't letting me paste the code in here as there are several non printing ASCII characters in the strings, so here's a hexdump from xxd ``` 0000000: 6576 616c 2868 3d27 272c 643d 5b7b 613a eval(h='',d=[{a: 0000010: 5b2e 2e2e 2770 5b6c 1a6d 375e 695d 6f67 [...'p[l.m7^i]og 0000020: 5f68 6e28 5d6c 5f5b 6e5f 3f66 5f67 5f68 _hn(]l_[n_?f_g_h 0000030: 6e22 1c6d 5d6c 6327 5d2c 623a 367d 2c7b n".m]lc'],b:6},{ 0000040: 613a 5b27 7e27 5d2c 623a 2d31 347d 2c7b a:['~'],b:-14},{ 0000050: 613a 5b2e 2e2e 276e 1c23 356d 286d 6c5d a:[...'n.#5m(ml] 0000060: 371c 2929 5d69 5e5f 2864 6b6f 5f6c 7328 7.))]i^_(dko_ls( 0000070: 5d69 6729 646b 6f5f 6c73 5c27 2c28 2b28 ]ig)dko_ls\',(+( 0000080: 2e28 646d 1c26 5e69 5d6f 675f 686e 285c .(dm.&^i]og_hn(\ 0000090: 5c69 5e73 285b 275d 2c62 3a36 7d2c 7b61 \i^s(['],b:6},{a 00000a0: 3a5b 277e 272c 277e 275d 2c62 3a2d 3134 :['~','~'],b:-14 00000b0: 7d2c 7b61 3a5b 2e2e 2e27 5f68 5e3d 6263 },{a:[...'_h^=bc 00000c0: 665e 226d 2326 1e22 1c1d 696f 6e1c 2328 f^"m#&."..ion.#( 00000d0: 705b 6622 686f 6666 1b37 1e22 1c1d 6368 p[f"hoff.7."..ch 00000e0: 1c23 2870 5b66 2223 286d 275d 2c62 3a36 .#(p[f"#(m'],b:6 00000f0: 7d2c 7b61 3a5b 277e 275d 2c62 3a2d 3134 },{a:['~'],b:-14 0000100: 7d2c 7b61 3a5b 2e2e 2e27 6663 6e22 1c1c },{a:[...'fcn".. 0000110: 2328 6c5f 705f 6c6d 5f22 2328 6469 6368 #(l_p_lm_"#(dich 0000120: 221c 1c23 2867 5b6e 5d62 2229 275d 2c62 "..#(g[n]b")'],b 0000130: 3a36 7d2c 7b61 3a5b 277e 275d 2c62 3a2d :6},{a:['~'],b:- 0000140: 3335 7d2c 7b61 3a5b 2e2e 2e27 6444 6b4b 35},{a:[...'dDkK 0000150: 6f4f 5f3f 6c4c 7353 1e2a 7257 7656 1e22 oO_?lLsS.*rWvV." 0000160: 391b 2227 5d2c 623a 367d 2c7b 613a 5b2e 9."'],b:6},{a:[. 0000170: 2e2e 275b 312d 395d 5b31 2d39 5d5c 5c2e ..'[1-9][1-9]\\. 0000180: 293f 5b27 5d2c 623a 312d 317d 2c7b 613a )?['],b:1-1},{a: 0000190: 5b2e 2e2e 272b 5c27 3357 2329 6123 391c [...'+\'3W#)a#9. 00001a0: 275d 2c62 3a36 7d2c 7b61 3a5b 277e 275d '],b:6},{a:['~'] 00001b0: 2c62 3a2d 3436 7d2c 7b61 3a5b 2e2e 2e27 ,b:-46},{a:[...' 00001c0: 6c69 616c 5b67 1a70 5b66 635e 5b6e 5f5e lial[g.p[fc^[n_^ 00001d0: 281a 3d66 5f5b 6c5b 685d 5f1a 665f 705f (.=f_[l[h]_.f_p_ 00001e0: 661a 2c1a 6163 705f 6828 1c34 1c4e 6263 f.,.acp_h(.4.Nbc 00001f0: 6d1a 275d 2c62 3a36 7d2c 7b61 3a5b 277e m.'],b:6},{a:['~ 0000200: 275d 2c62 3a2d 3134 7d2c 7b61 3a5b 2e2e '],b:-14},{a:[.. 0000210: 2e27 6c69 616c 5b67 675f 6c1a 636d 1a61 .'lial[gg_l.cm.a 0000220: 6f63 666e 731a 6960 1a42 5f6c 5f6d 7328 ocfns.i`.B_l_ms( 0000230: 1a42 5f1a 676f 6d6e 1a5c 5c5f 1a5c 5c6f .B_.gomn.\\_.\\o 0000240: 6c68 6e28 1c23 275d 2c62 3a36 7d5d 2e6d lhn(.#'],b:6}].m 0000250: 6170 2864 3d3e 2876 3d27 272c 773d 642e ap(d=>(v='',w=d. 0000260: 612e 6d61 7028 633d 3e53 7472 696e 672e a.map(c=>String. 0000270: 6672 6f6d 4368 6172 436f 6465 2863 2e63 fromCharCode(c.c 0000280: 6861 7243 6f64 6541 7428 292b 642e 6229 harCodeAt()+d.b) 0000290: 292c 772e 666f 7245 6163 6828 287a 2c69 ),w.forEach((z,i 00002a0: 2c61 293d 3e7b 6966 2869 2532 2976 3d76 ,a)=>{if(i%2)v=v 00002b0: 2e63 6f6e 6361 7428 615b 692d 315d 2e63 .concat(a[i-1].c 00002c0: 6f6e 6361 7428 7a29 297d 292c 762e 636f oncat(z))}),v.co 00002d0: 6e63 6174 2877 2e6c 656e 6774 6825 323f ncat(w.length%2? 00002e0: 772e 706f 7028 293a 2727 2929 292c 642e w.pop():''))),d. 00002f0: 666f 7245 6163 6828 287a 2c69 2c61 293d forEach((z,i,a)= 0000300: 3e7b 6966 2869 2532 2968 3d68 2e63 6f6e >{if(i%2)h=h.con 0000310: 6361 7428 615b 692d 315d 2e63 6f6e 6361 cat(a[i-1].conca 0000320: 7428 7a29 297d 292c 682e 636f 6e63 6174 t(z))}),h.concat 0000330: 2864 2e6c 656e 6774 6825 323f 642e 706f (d.length%2?d.po 0000340: 7028 293a 2727 2929 0a p():'')). ``` ]
[Question] [ If you take a sheet of graph paper and draw a sloped line that goes `m` units right and `n` units up, you cross `n-1` horizontal and `m-1` vertical gridlines in some sequence. Write code to output that sequence. For example, `m=5` and `n=3` gives: ![Gridlines crossing for m=5, n=3](https://i.stack.imgur.com/h4FMDm.png) Possibly related: [Generating Euclidian rhythms](https://codegolf.stackexchange.com/q/49221/20260), [Fibonacci tilings](https://codegolf.stackexchange.com/questions/38356/generate-valid-fibonacci-tilings), [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz) **Input:** Two positive integers `m,n` that are relatively prime **Output:** Return or print the crossings as a sequence of two distinct tokens. For example, it could be a string of `H` and `V`, a list of `True` and `False`, or `0`'s and `1`'s printed on separate lines. There can be a separator between tokens as long as it's always the same, and not, say, a variable number of spaces. **Test cases:** The first test case gives empty output or no output. ``` 1 1 1 2 H 2 1 V 1 3 HH 3 2 VHV 3 5 HVHHVH 5 3 VHVVHV 10 3 VVVHVVVHVVV 4 11 HHVHHHVHHHVHH 19 17 VHVHVHVHVHVHVHVHVVHVHVHVHVHVHVHVHV 39 100 HHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHH ``` In the format `(m,n,output_as_list_of_0s_and_1s)`: ``` (1, 1, []) (1, 2, [0]) (2, 1, [1]) (1, 3, [0, 0]) (3, 2, [1, 0, 1]) (3, 5, [0, 1, 0, 0, 1, 0]) (5, 3, [1, 0, 1, 1, 0, 1]) (10, 3, [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1]) (4, 11, [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]) (19, 17, [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]) (39, 100, [0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0]) ``` [Answer] # Ruby, 92; [Ostrich 0.7.0](https://github.com/KeyboardFire/ostrich-lang/releases/tag/v0.7.0-alpha), 38 ``` f=->m,n{((1..m-1).map{|x|[x,1]}+(1..n-1).map{|x|[1.0*x*m/n,0]}).sort_by(&:first).map &:last} ``` ``` :n;:m1-,{)o2W}%n1-,{)m n/*0pW}%+_H$_T% ``` Output for both of them uses 1's and 0's (ex. `101101`). --- Here's an explanation of the Ostrich one: ``` :n;:m store n and m as variables, keep m on the stack 1-, from ex. 5, generate [0 1 2 3] {...}% map... ) increment, now 5 -> [1 2 3 4] o push 1 (the digit 1 is special-cased as `o') 2W wrap the top two stack elements into an array we now have [[1 1] [2 1] [3 1] [4 1]] n1-, doing the same thing with n {...}% map... ) increment, now 3 -> [1 2] m n/* multiply by slope to get the x-value for a certain y-value 0 push 0 pW wrap the top two stack elements (2 is special-cased as `p') + concatenate the two arrays _H$ sort-by first element (head) _T% map to last element (tail) ``` And an explanation of how the whole thing works, using the Ruby code as a guide: ``` f = ->m,n { # general outline: # 1. collect a list of the x-coordinates of all the crossings # 2. sort this list by x-coordinate # 3. transform each coordinate into a 1 or 0 (V or H) # observation: there are (m-1) vertical crossings, and (n-1) horizontal # crossings. the vertical ones lie on integer x-values, and the # horizontal on integer y-values # collect array (1) ( # horizontal (1..m-1).map{|x| [x, 1] } + # vertical (1..n-1).map{|x| [1.0 * x * m/n, 0] } # multiply by slope to turn # y-value into x-value ) .sort_by(&:first) # sort by x-coordinate (2) .map &:last # transform into 1's and 0's (3) } ``` [Answer] # Python, 53 This uses the True/False list output. Nothing special here. ``` lambda m,n:[x%m<1for x in range(1,m*n)if x%m*(x%n)<1] ``` [Answer] # Pyth - ~~32~~ 24 bytes ``` Jmm,chk@Qddt@Qd2eMS+hJeJ ``` Takes input via stdin with the format `[m,n]`. Prints the result to stdout as a list of 0's and 1's, where 0 = V and 1 = H. [Test it online](https://pyth.herokuapp.com/?code=Jmm%2Cchk%40Qddt%40Qd2eMS%2BhJeJ&input=%5B39%2C100%5D&debug=0) --- Explanation: ``` J # J = m 2 # map(lambda d: ..., range(2)) m t@Qd # map(lambda k: ..., range(input[d] - 1)) ,chk@Qdd # [(k + 1) / input[d], d] eMS+hJeJ # print map(lambda x: x[-1], sorted(J[0] + J[-1]))) ``` [Answer] # IA-32 machine code, 26 bytes Hexdump of the code: ``` 60 8b 7c 24 24 8d 34 11 33 c0 2b d1 74 08 73 03 03 d6 40 aa eb f2 61 c2 04 00 ``` I started from the following C code: ``` void doit(int m, int n, uint8_t* out) { int t = m; while (true) { if (t >= n) { t -= n; *out++ = 1; } else { t += m; *out++ = 0; } if (t == n) break; } } ``` It writes the output into the supplied buffer. It doesn't return the length of the output, but it's not really needed: the output length is always `m + n - 2`: ``` int main() { char out[100]; int m = 10; int n = 3; doit(m, n, out); for (int i = 0; i < m + n - 2; ++i) { printf("%d ", out[i]); } } ``` To convert the C code into machine code, I first did some tweaking, to make one of the `if/else` branches empty, and compare with `0` instead of `n`: ``` void doit(int m, int n, char* out) { int t = n; while (true) { int r = 0; t -= m; if (t == 0) break; if (t >= 0) { } else { t += m + n; ++r; } *out++ = r; } } ``` From here, writing the inline-assembly code is straightforward: ``` __declspec(naked) void __fastcall doit(int x, int y, char* out) { _asm { pushad; // save all registers mov edi, [esp + 0x24]; // edi is the output address lea esi, [ecx + edx]; // esi is the sum m+n myloop: // edx is the working value (t) xor eax, eax; // eax is the value to write (r) sub edx, ecx; jz myout; jae mywrite; add edx, esi; inc eax; mywrite: stosb; // write one value to the output jmp myloop; myout: popad; // restore all registers ret 4; // return (discarding 1 parameter on stack) } } ``` [Answer] # CJam, 15 bytes ``` Ll~_:*,\ff{%!^} ``` [Try it here.](http://cjam.aditsu.net/#code=Ll%7E_%3A*%2C%5Cff%7B%25!%5E%7D&input=%5B5%203%5D) It prints `01` for V and `10` for H. ### Explanation ``` L e# An empty list. l~ e# Evaluate the input. _:*, e# [0, m*n). \ e# The input (m and n). ff{%! e# Test if each number in [0, m*n) is divisible by m and n. ^} e# If divisible by m, add an 10, or if divisible by n, add an 01 into e# the previous list. If divisible by neither, the two 0s cancel out. e# It's just for output. So we don't care about what the previous list e# is -- as long as it contains neither 0 or 1. ``` The diagonal line crosses a horizontal line for every 1/n of the whole diagonal line, and crosses a vertical line for every 1/m. [Answer] # Python - 125 bytes Uses a very simple algorithm, just increments the coordinates and detects when it crosses the lines and prints out. Am looking to translate to Pyth. ``` a,b=input() i=1e-4 x=y=l=o=p=0 k="" while len(k)<a+b-2:x+=i*a;y+=i*b;k+="V"*int(x//1-o//1)+"H"*int(y//1-p//1);o,p=x,y print k ``` That while loop is checking the number of `l`ines and then checking if any of the values went over an int boundary by subtracting. Takes input like `39, 100` from stdin and prints out like `HHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHH` to stdout in one line. [Answer] # TI-BASIC, 32 ``` Prompt M,N For(X,1,MN-1 gcd(X,MN If log(Ans Disp N=Ans End ``` Straightforward. Uses a sequence of `0` and `1`, separated by linebreaks. TI-BASIC's advantages are the two-byte `gcd(` and implied multiplication, but its disadvantages are the For loop including the end value and the 5 bytes spent for input. [Answer] ## Python, 47 ``` lambda m,n:[m>i*n%(m+n)for i in range(1,m+n-1)] ``` Like [anatolyg's algorithm](https://codegolf.stackexchange.com/a/52133/20260), but checked directly with moduli. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` PLIδÖʒO ``` Inspired by [*@jimmy23013*'s CJam answer](https://codegolf.stackexchange.com/a/52533/52210), so make sure to upvote him as well! Input as a pair of integers \$[m,n]\$ and output as a list of `[0,1]` and `[1,0]` pairs for \$V\$ and \$H\$ respectively. [Try it online](https://tio.run/##yy9OTMpM/a8UHW2go2AYq6MQbaijYACiYXys4rFKMf8DfDzPbTk87dQk////o011jGMB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXhCqL2SwqO2SQpK9v8DfCLObTk87dQk//@1Ov@jow11DGN1gKQRkDSCso2BpDFYxFjHFEiagkUMDcCUiY4hWJWljqE5SAWQNjCIjQUA). **Explanation:** ``` P # Take the product of the (implicit) input-pair: m*n L # Pop and push a list in the range [1, m*n] IδÖ # Check for each value in this list, whether each value in the input-pair evenly # divides it (resulting in [0,0] if the number is neither divisible by `m` nor `n`; # [0,1] if the number is only divisible by `m`; # [1,0] if the number is only divisible by `n`; # [1,1] for the final number m*n, which is divisible by both `m` and `n` obviously) ʒ # Then filter this list of pairs, keeping only the pairs which are truthy for: O # Where the sum of the pair is exactly 1 (NOTE: only 1 is truthy in 05AB1E) # (after which the resulting list is output implicitly) ``` [Answer] # Haskell, 78 bytes ``` import Data.List m#n=map snd$sort$[(x,0)|x<-[1..m-1]]++[(y*m/n,1)|y<-[1..n-1]] ``` Usage example: ``` *Main> 19 # 17 [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0] *Main> 10 # 3 [0,0,0,1,0,0,0,1,0,0,0] ``` How it works: make a list of the x-values of all vertical crossings `(x,0)` for `x` in [1,2,...,m-1] (`0` indicates vertical) and append the list of the x-values of all horizontal crossings `(y*m/n,1)` for `y` in [1,2,...,n-1] (`1` indicates horizontal). Sort and take the second elements of the pairs. Curse of the day: again I have to spent 17 bytes on the `import` because `sort` is in `Data.List` and not in the standard library. [Answer] # KDB(Q), 44 bytes ``` {"HV"0=mod[asc"f"$1_til[x],1_(x*til y)%y;1]} ``` # Explanation Find all *x* axis values of intersect points and sort them. If mod 1 is zero its "V", non-zero is "H". # Test ``` q){"HV"0=mod[asc"f"$1_til[x],1_(x*til y)%y;1]}[5;3] "VHVVHV" ``` [Answer] # CJam, ~~26~~ 24 bytes ``` l~:N;:M{TN+Mmd:T;0a*1}*> ``` [Try it online](http://cjam.aditsu.net/#code=l~%3AN%3B%3AM%7BTN%2BMmd%3AT%3B0a*1%7D*%3BW%3C&input=5%203) Very straightforward, pretty much a direct implementation of a Bresenham type algorithm. Explanation: ``` l~ Get input and convert to 2 integers. :N; Store away N in variable, and pop from stack. :M Store away M in variable. { Loop M times. T T is the pending remainder. N+ Add N to pending remainder. M Push M. md Calculate div and mod. :T; Store away mod in T, and pop it from stack 0a Wrap 0 in array so that it is replicated by *, not multiplied. * Emit div 0s... 1 ... and a 1. }* End of loop over M. > Pop the last 1 and 0. ``` The last `01` needs to be popped because the loop went all the way to the end point, which is not part of he desired output. Note that we can **not** simply reduce the loop count by 1. Otherwise, for `N > M`, all the `0`s from the last iteration will be missing, while we only need to get rid of the very last `0`. ]
[Question] [ # Task: > > There are a lot of answers on this site that are arranged into ascii art, like [this one](https://codegolf.stackexchange.com/a/26396/16472). Usually the arrangement is done manually, but wouldn't a program help with that? :) > > > Your program will take 3 inputs: * The code, as one single line * The number of lines in the pattern (can be omitted if not necessary) * The pattern itself, as `*`s or another char # Rules: * You have to write a program (not a function) that reads from stdin * The text is placed left-to-right per line * If there is not enough text to fill the pattern, put `.`s in the remaining spaces * If there is too much text to fill the pattern, print it out after the output * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code, in bytes wins # Sample Runs: **Input (Exact Fit test)**: ``` qwertyuiopasdfghjklzxcvbnm 4 ***** * *** * * * * * * * * ***** * *** ``` **Output**: ``` qwert y uio p a s d f g h j klzxc v bnm ``` **Input (Extra characters test)**: ``` qwertyuiopasdfghjklzxcvbnm12345 4 ***** * *** * * * * * * * * ***** * *** ``` **Output**: ``` qwert y uio p a s d f g h j klzxc v bnm 12345 ``` **Input (Insufficient Characters test)**: ``` qwertyuiopasdfg 4 ***** * *** * * * * * * * * ***** * *** ``` **Output**: ``` qwert y uio p a s d f g . . ..... . ... ``` [Answer] # Perl 6: ~~60 characters~~ *EDIT*: 38 points (see bottom) ``` #C#O D#E#G#O #L# #F #.#S# T#A#C#K get\ .subst( "*" ,{ shift BEGIN [ get\ .comb,\ "." xx * ]}, :g)\ .\ say\ xx get\ ()\ #E #X#C# H#A#N#G #E#. #C#O#M# #!# ``` If you don't appreciate my terrible art skills, here's the golf: ``` get.subst("*",{shift BEGIN [get.comb,"."xx*]},:g).say xx get ``` This one does weird things with evaluation times. First, the `BEGIN` keyword forces `[get.comb, "." xx *]` to be evaluated first, putting into an array the list of characters that make up "the code", followed by an infinite amount of `"."`s. Next, the `get` at the end is evaluated, getting the number of lines of the ASCII art template. The `xx` operator repeats the first part of the program this many times. This makes more sense when you realize that `code() xx count()` is basically sugar for `code() for 1..count()`: `count()` should be evaluated first. Finally, the `get` in the beginning of the program gets a line of the ASCII art template and substitutes every `"*"` with a value shifted off of the beginning of the array we made before everything else (`{shift BEGIN …}`). ## EDIT: Golfed down to 37 characters, plus one for the command line switch: ``` perl6 -pe's:g[\*]=shift BEGIN [get.comb,"."xx*]' ``` This is the same concept as the original, the `-p` switch iterating over each line (after the `BEGIN` has read in "the code"), and substituting all `*`s with the next letter from "the code" before printing it. The input format for this shouldn't include the number of lines of the format. [Answer] ## Ruby 2.0, ~~53~~ 52 characters ``` c=gets.chop $><<gets($n).gsub(?*){c.slice!(0)||?.}+c ``` As per the spec, doesn't use the 'number of lines' paramater. Example run: ``` qwertyuiopasd ***** * *** * * * * * * * * ***** * *** ``` Output: ``` qwert y uio p a s d . . . . ..... . ... ``` [Answer] ### GolfScript, 30 characters ``` n/(\(;n*'*'/{@.!'.'*+([]+@+}*\ ``` [Run online](http://golfscript.apphb.com/?c=OyJxd2VydHl1aW9wYXNkZmdoamtsenhjdmJubQo0CioqKioqICogKioqCiogICAqICogKgoqICAgKiAqICoKKioqKiogKiAqKioKIgoKbi8oXCg7bionKicve0AuIScuJyorKFtdK0ArfSpcCg%3D%3D&run=true). *Examples:* ``` > qwertyuiopasdfghjklzxcvbnm > 4 > ***** * *** > * * * * > * * * * > ***** * *** qwert y uio p a s d f g h j klzxc v bnm > qwertyuiopasdfghjklzxcvbnm > 1 > ***** * *** qwert y uio pasdfghjklzxcvbnm > qwerty > 2 > ***** * *** > * * * * qwert y ... . . . . ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~63~~ ~~86~~ ~~83~~ 82 bytes *+20 bytes thanks @Veskah* ``` param($s,$p)-join($p|% *ht($s|% Le*)'*'|% t*y|%{if($_-eq42){$_=$s[$i++]}"$_."[0]}) ``` [Try it online!](https://tio.run/##VVBNb4JAEL3vr3jRtcsimqb1amIvPfXYmzGEyiJYPlZ2USny2@kAbWNnM5uXN/PeTEYXF1WaWKVpxyOs0XQ6KIPM4cbjWi6ORZI7XN9mcGNLJIE35UrhCkLWrW@zJokc7i/UafUkG@6vudnyZD7ftRPuLyfbx10ru5axjcM8R5xomK2rpNCBCaNDfPxMv67780eeCY9tBHP7AD3XZS6AAd@ju7rYDJLBEjXIlGlqDGAQsojQATGObJiAM2gGSWS/xXusVB4KTwxmFASJA5FLITHGFGWVKjz3gtegRJ8vl6AeZfT/I@WfYMWYxA0zNKy3oTuCa0p11WpvVUg35v5YKpWpUkvEA52eG@ob@Al3fkp01T@dnLBxrV/ZFFW@L7JM5RY2TgzSJFewBcLE6DSoMfYZ1nbf "PowerShell – Try It Online") Less golfed: ``` param($string,$pattern) $chars = $pattern | % PadRight ($string|% Length) '*' | % toCharArray | % { if($_-eq42){$_=$string[$i++]} # $_ can become $null "$_."[0] # $_ or '.' if $_ is $null } -join($chars) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 bytes ``` sVè-)iVr-@t°J1 ª'. ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=c1boLSlpVnItQHSwSjEgqicu&input=InF3ZXJ0eXVpb3Bhc2RmZ2hqa2x6eGN2Ym5tIgoiLS0tLS0gLSAtLS0KLSAgIC0gLSAtCi0gICAtIC0gLQotLS0tLSAtIC0tLSI) [Answer] # T-SQL, 142 bytes > > @h is the input text > > > @ is the pattern > > > ``` DECLARE @h varchar(max)='qwertyuiopasdfg' DECLARE @ varchar(max)=' ***** * *** * * * * * * * * ***** * ***' WHILE @ like'%*'SELECT @=left(@,charindex('*',@)-1)+left(@h+'.',1)+stuff(@,1,charindex('*',@),''),@h=substring(@h,2,999)PRINT concat(@,' '+@h) ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1039856/the-easy-way-to-code-golf-ascii-art)** [Answer] # [Perl 5](https://www.perl.org/) `-plF`, 51 bytes ``` $_=join'',<>;s/\*/@F?shift@F:'.'/ge;$\=$/.join'',@F ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jYrPzNPXV3Hxs66WD9GS9/Bzb44IzOtxMHNSl1PXT891VolxlZFXw@qzMHt///C8tSiksrSzPyCxOKUtPSMrOycqorksqS8XEMjYxNTLhMuLRBQAEItLS4tBQUFMBuZhZD/l19QkpmfV/xf19dUz8DQ4L9uQY4bAA "Perl 5 – Try It Online") [Answer] # JavaScript - 199 ``` text="qwertyuiopasdfghjklzxcvbnm"; pattern="***** * ***\n* * * *\n* * * *\n***** * ***"; function p(a,c){z=c.length,y=a.length,x=0;for(i=z;i-->0;)if(c[i]=="*")x+=1;if(x-y>0)for(i=x-y;i-->0;)a+=".";for(;i++<x;)c=c.replace(new RegExp("[*]"),a[i]);console.log(c);console.log(a.substring(x))} p(text,pattern); ``` Outputs extra characters in text input if not used in pattern, uses padded "." if there's not enough. EDIT: modified to be a function accepting text and pattern [Answer] # JavaScript (ES6) -~~96~~ 87 ``` r=(c,p)=>{c=0+c;console.log(p.replace(/\*/g,t=>(c=c.substr(1),c[0]||'.'))+c.substr(1))} ``` Note: As [suggested by the OP](https://codegolf.stackexchange.com/questions/26652/the-easy-way-to-code-golf-ascii-art#comment58958_26662), I am using a function. But if its required to have a program, here's a **93 chars solution**. ``` c=0+(x=prompt)();p=x();console.log(p.replace(/\*/g,t=>(c=c.substr(1),c[0]||'.'))+c.substr(1)) ``` EDIT1: Major change, I don't know why I didn't realize this for the first time :P Saved 40 chars. --- **Usage**: ``` // r(code, pattern) r("qwertyuiopasdfghjklzxcvbnm", "***** * ***\n* * * *\n* * * *\n***** * ***\n** ** **) ``` --- **Test Input**: (without unneeded optional number as per spec) ``` qwertyuiopasdfghjklzxcvbnm ***** * *** * * * * * * * * ***** * *** ** ** ** ``` **Output**: ``` qwert y uio p a s d f g h j klzxc v bnm .. .. .. // not much text was there to fill *s - replaced with dots as per spec ``` --- **Ungolfed Code**: ``` function run(code, pattern){ code = "0" + code; // prepend a zero; useful for the substring operation ahead pattern = pattern.replace(/\*/g, function(){ // replace the dots // by removing the first letter of code // and replacing dot with the first-letter of leftover code // and if it isn't there (code finished) // return a dot code = code.substr(1); return c[0] || '.'; }); } // after this operation; code contains the last letter of the org. code console.log( p + // the pattern has now code "\n" + // and a newline c.substr(1) // if there is more than one letter of code left; display it ); } ``` --- It would be very nice to hear of any suggestions from users :) [Answer] # Perl, 70 characters ``` @_=split'',<>=~s/\n//r;<>;print/\*/?shift@_||'.':$_ for map{split''}<> ``` Or, without boundary check, 56 characters ``` @_=split'',<>;<>;print/\*/?shift@_:$_ for map{split''}<> ``` Note, this code is not using second line as in spec, and can be shortened by three characters `<>;` [Answer] # Bash, ~~166 156 111~~ 106 Reads from standard input, doesn't take a line count. First line of input is the code you want to put into ascii art, all subsequent lines are the ascii art, consisting of the `@` character. **Input has a maximum length of 999 chars, and is not permitted to contain forward slashes**. (I chose not to use `*` or `#` because they have special meanings in Bash). ``` read -n999 -d/ i p while [[ $p =~ @ && -n $i ]];do p="${p/@/${i:0:1}}" i=${i:1} done tr @ .<<<"$p" echo $i ``` **WARNING:** This program uses a file called `p`. After executing the program, delete `p` - it will confuse the program the second time you run it. Most of the work here is done by ``` p="${p/@/${i:0:1}}" i=${i:1} ``` The first line substitutes the first `@` in the art with the first character of the code. The second line removes the first character of the code. If there is not enough code to fill the shape, a newline is printed after the main ascii art output by `echo $i`. [Answer] # C, 98, 91 characters Here a pretty straight-forward C solution in under 100 characters. This doesn't use the line count input. (Else a second unneeded gets() would be needed). ``` char b[999],*s;c;main(){gets(s=b);while(~(c=getchar()))putchar(c^42?c:*s?*s++:46);puts(s);} ``` ungolfed: ``` char b[999],*s;c; main(){ gets(s=b); while(~(c=getchar())) putchar(c^42?c:*s?*s++:46); puts(s); } ``` [Answer] ## Python 2.7, ~~165~~ ~~155~~ ~~150~~ ~~138~~ 119 characters Okay, pretty much but I guess it's the tiniest way to do it with Python. ``` import sys r=raw_input l=list(r()) w=sys.stdout.write for c in"\n".join([r()for _ in[1]*input()]):w(c=='*'and(l and l.pop(0)or'.')or c) w("".join(l)) ``` **Edit:** new functional 1.0.1 version with even less bytes used: **Edit2:** `map(r,['']*input())` instead of `[r()for _ in[1]*input()]` and removed unused import **Edit3:** `'>'*input()` instead of `['']*input()` saving one character and adding prompt character for pattern :) ``` r=raw_input l=list(r()) print''.join(map(lambda c:c=='*'and(l and l.pop(0)or'.')or c,"\n".join(map(r,'>'*input())))+l) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 122 bytes ``` var n=ReadLine();int k=0;foreach(var z in In.ReadToEnd())Write(z>33?(n+new string('.',999))[k++]:z);Write(n.Substring(k)); ``` [Try it online!](https://tio.run/##TcqxDoIwGATgnaf4N9qixIQJG3RyMHFSEwfjUKFAxfxoW0T78lXURO@WS@7LzTg3yvub0IDZWopipVASyhVaaLIJL1stRV6TAThQCEuMB7ZtF1gQSndaWUncLEnmBCOUPRirFVYkjMNRmqaU7psoOkwd5R@K8aY7fk1DKff@2kttH51qL8IUZVWfmrO75wEbAq8yFjAAeO//9fuf "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ ~~17~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` s0¢.$«0¹S.;0'.: ``` Takes the code as first input, pattern as second (with `0` instead of `#`). [Try it online](https://tio.run/##yy9OTMpM/f@/2ODQIj2VQ6sNDu0M1rM2UNez@v@/sDy1qKSyNDO/ILE4JS09Iys7p6oiuSwpL9fQyNjElEtJSckABBSA0MCAy0BBQQHMRmYh5IGqAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/R9aVqnkmVdQWmKlcHg/l39pCZippBPhUvm/2ODQIj2VQ6sNKoP1rA3U9az@6xzaZv9fSUnJAAQUgNDAgMtAQUEBzEZmIeSBqrmilQrLU4tKKksz8wsSi1PS0jOysnOqKpLLkvJylXTwSBoaGZuYYqpQigUA). **~~18~~ 15 bytes alternative by taking the inputs in reversed order:** ``` 0¢.$¹ì0IS.;0'.: ``` [Try it online](https://tio.run/##yy9OTMpM/f/f4NAiPZVDOw@vMfAM1rM2UNez@v9fSUnJAAQUgNDAgMtAQUEBzEZmIeSBqrkKy1OLSipLM/MLEotT0tIzsrJzqiqSy5Lycg2NjE1MAQ). **Explanation:** ``` s # Swap with implicit inputs, so the stack order is now: [code, pattern] 0¢ # Count the amount of "0" in the pattern .$ # Remove that many leading characters from the code « # Append it to the (implicit) pattern input 0¹S.; # Replace every "0" one by one with the characters of the first code input 0'.: '# Then replace any remaining "0" with "." # (after which the result is output implicitly as result) ``` ]
[Question] [ You're tasked with writing two programs. Program **A** must print out nothing on all inputs *except* when program **B** is input, in which case it should print `1`. Program **B** must print out `1` on all inputs *except* when program **A** is input, in which case it should print nothing. **Scoring:** * +1 For each character from **both** programs. * Lowest score wins. [Answer] ## Bash - 32 characters **Script A - 16 characters** ``` cmp -s b&&echo 1 ``` **Script B - 16 characters** ``` cmp -s a||echo 1 ``` **Usage** ``` $> echo "foo" | ./a $> cat b | ./a 1 $> echo "foo" ./b foo ./b $> cat a | ./b ``` [Answer] ## [GTB](http://timtechsoftware.com/?page_id=1309), 25 *Executed from a TI-84 calculator* Program `A` ``` `_@_eq;"$w;& ``` Program `B` ``` `_@_eq;"$#w;& ``` **Explanation** ``_` Input a string `@_eq;"` Check if it equals the source code (`#` is automatically stripped along with lowercase letters) `$w;&` If so, display 1 (otherwise nothing) [for `B` it's `$#w;&` - if not, display 1 (otherwise nothing)] [Answer] ## Ruby, 54 A ``` $><<1if$<.read==IO.read(?B) ``` B ``` $><<1if$<.read!=IO.read(?A) ``` examples: ``` bash-3.2$ ruby A < A bash-3.2$ ruby A < B 1bash-3.2$ ruby B < A bash-3.2$ ruby B < B 1bash-3.2$ ``` [Answer] ## J (62) Since you didn't forbid this... Store the programs as `A` and `B` respectively. Program A (30): ``` exit echo#~(1!:1<'B')-:1!:1[3 ``` Program B (32): ``` exit echo#~-.(1!:1<'A')-:1!:1[3 ``` How it works (Program B, A is similar): * `1!:1[3`: read stdin * `1!:1<'A'`: read file `A` * `-:`: see if they are equal * `-.`: negate the result * `#~`: replicate the result by itself (so, `1` results in one `1` and `0` results in zero `0`s, i.e. nothing) * `echo`: output * `exit`: exit (the J interpreter does not exit by default when it reaches the end of the file) ``` $ jconsole A <B 1 $ jconsole A <foo $ jconsole B <A $ jconsole B <foo 1 $ ``` [Answer] ## Haskell - WITHOUT loading source - 478 644 characters This assumes getContents ALWAYS ends with a newline and so drops the final character without checking because I don't feel like escaping it A ``` main=interact$($'1').replicate.(1-).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='-'='*'|n=='*'='-'|True=n;d="main=interact$($'1').replicate.(1-).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='-'='*'|n=='*'='-'|True=n;d=" ``` B ``` main=interact$($'1').replicate.(1*).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='*'='-'|n=='-'='*'|True=n;d="main=interact$($'1').replicate.(1*).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='*'='-'|n=='-'='*'|True=n;d=" ``` It works like a standard quine, but swapping - for \* to get the other program (avoiding those characters elsewhere). The following test prints as expected (replacing main=interact$ with a= and b=) ``` main=do putStrLn "START" putStrLn$a "FOO" putStrLn$a "main=interact$($'1').replicate.(1*).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='*'='-'|n=='-'='*'|True=n;d=\"main=interact$($'1').replicate.(1*).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='*'='-'|n=='-'='*'|True=n;d=\"\n" putStrLn$b "FOO" putStrLn$b "main=interact$($'1').replicate.(1-).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='-'='*'|n=='*'='-'|True=n;d=\"main=interact$($'1').replicate.(1-).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='-'='*'|n=='*'='-'|True=n;d=\"\n" putStrLn "END" ``` - ``` START 1 1 END ``` [Answer] ## Python 2.7 - 82 File A (literally named just `a`): ``` if raw_input()==open('b').read():print 1 ``` File B (literally named just `b`): ``` if raw_input()!=open('a').read():print 1 ``` [Answer] ## Ruby, 166 chars, no reading source A: ``` (gets(p)==<<2.tr('&|','|&')*2+'2')&&p(1) (gets(p)==<<2.tr('&|','|&')*2+'2')&&p(1) 2 ``` B: ``` (gets(p)==<<2.tr('|&','&|')*2+'2')||p(1) (gets(p)==<<2.tr('|&','&|')*2+'2')||p(1) 2 ``` Make sure your text editor doesn't save with a trailing newline. Usage (example): ``` $ ruby know_a.rb know_b.rb 1 $ ruby know_a.rb know_a.rb $ ruby know_b.rb know_a.rb $ ruby know_b.rb know_b.rb 1 ``` Each program constructs the source of the other program using a HEREdoc and string transforms, then compares the result to the input. [Answer] ## Haskell - 138 Not really a good answer, but wanted to make both programs use the same source. Could save some chars by renaming the file, but it's not going to make this a winning solution so I don't think it's worth it. ``` import System.Environment import Control.Monad main=do{i<-getContents;p<-getProgName;f<-readFile "ab.hs";when((f==i)/=(p=="B"))(print 1)} ``` Compile this source as both `A` and `B`. Test: ``` % ghc -o A ab.hs [1 of 1] Compiling Main ( ab.hs, ab.o ) Linking A ... % cp A B % ./A < ab.hs 1 % ./B < ab.hs % ./A < ab.hi % ./B < ab.hi 1 ``` [Answer] ## Node.js - 142 characters **Script `|` (otherwise known as Script A) - 80 characters** ``` f=require('fs').readFileSync;f('/dev/stdin','hex')==f('&','hex')&&console.log(1) ``` **Script `&` (otherwise known as Script B) - 62 characters** ``` eval(require('fs').readFileSync('|','utf8').replace(/&/g,'|')) ``` **Usage** ``` # \| is Script A # \& is Script B $> echo "foo" | node \| $> cat \& | node \| 1 $> echo "foo" | node \& 1 $> cat \| | node \& ``` **Description** Script B reads the contents of Script A and evals it after swapping the file names and the `and` operator to an `or`. I named the files `&` and `|` so I can perform a single replace in Script B. [Answer] # Python 3 - 102 characters Prints 1 if the input is the same as program 2, otherwise nothing: ``` if input()==open('a.py').read():print('1') ``` Prints 1 if input is not the same as program 1, otherwise nothing: ``` if input()==open('a.py').read():print('1') ``` [Answer] # bash/grep — 59 chars 51 chars if we only count the actual program string. ``` $ a='grep -cx "$b" | grep -x 1' $ b='grep -vcx "$a" | grep -x 1' $ echo 'foo' | eval $a $ echo $b | eval $a 1 $ echo 'foo' | eval $b 1 $ echo $a | eval $b ``` [Answer] ## R (62 chars) ``` i=identical A=function(x)if(i(x,B))1 B=function(x)if(!i(x,A))1 ``` produces: ``` > A(123) > A(A) > A(B) [1] 1 > B(123) [1] 1 > B(A) > B(B) [1] 1 ``` --- Meta comment: R fairs relatively bad on code golf as there is no shortcut to `function`... ]
[Question] [ look! It's an ASCII maze! Soo coolzors, amazeballs and stuff. ``` +-+-----+---+ | | | | | | ++ | | | | ++ +-+ | | | | +-------+ | | | | | +---------+-+ ``` But, but, but... it's a pain to work out which direction all the parts of the maze are going. I just want to draw the layout and the maze make itself sooper kul without loads of time. What if I could just draw this in... ``` ############# # # # # # # ## # # # # ## ### # # # # ######### # # # # # ############# ``` That would be soo sweet! --- The rules (Because rules is cools): * Write code to convert a string into an ascii maze and output the result. * Any non-whitespace character will be read as a wall. * Each char of wall will decide which character to be based on it's neighbours (only in North, South, East and West directions). + If a char has no non-whitespace neighbours, it will be a plus sign (+). + If a char has neighbours in both vertical (North-South) and horizontal (East-West) directions, it will be a plus sign (+). + If a char has neighbours only in a vertical (North-South) direction, it will be a pipe symbol (|). + If a char has neighbours only in a horizontal (East-West) direction, it will be a minus sign (-). * The Input can be a single string (with lines separated by newline characters, or an array of strings). * All input characters will be printable ASCII characters, you don't need to deal with extended charsets. * Use any old language you please. * If there is white space before a line, it should be the same amount on each line. Any white space after each line of output is fine. * Attempt to solve it with the smallest number of bytes. --- # Test cases: ## 1: Frame Input: ``` ########## # # # # # # ########## ``` Output: ``` +--------+ | | | | | | +--------+ ``` ## 2: Classic maze Input: ``` ################# # # # ##### # ##### # # # # # # # # # # # ##### # # # # # # # ### # ####### # # # # # # # # # ### # ## # ## # # ## # ################# ``` Output: ``` --------+-------+ | | | --+-+ | ----+ | | | | | | | | + | | +---- | | | | | | | +-- | +----+- | | | | | | | | | --+ | ++ | -+ | | ++ | +-----+-++----+-- ``` ## 3: Green eggs, man. Input: ``` I do not like green eggs and ham. I do not like them, sam I am. Would you like them here or there? I would not like them anywhere! ``` Output: ``` | ++ +++ ++++ +++++ +++- -++ ---- | ++ +++ ++++ +++++ +++ + +++ +-+++ +++ ++++ ++++ ++++ ++ +++--- | +++-+ +++ ++++ ++-+ +++++++++ ``` ## 4: Icicles Input: ``` Word Icicle! Word Icicle Word cicle ord cicle ord icle ord i le or i le or i l or l or r ``` Output: ``` ++++ ++++++- ++++ ++++++ ++++ +++++ +++ +++++ +++ ++++ +++ | ++ ++ | ++ ++ | | ++ | ++ | ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~57~~ 35 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") –22 thanks to [a novel solution by ngn](https://chat.stackexchange.com/transcript/message/44051129#44051129). Anonymous tacit function taking a character matrix as argument. ``` {⊃'+-|+'↓⍨2⊥5 4 2⊃¨⊂⍱∘⌽⍨' '≠,⍵}⌺3 3 ``` [Try it online!](https://tio.run/##bZLNSsNAEMfvfYq/5LBKWzHGQm@e8wSeQ7NNivmQtKUE9WIhtDEBxYtHEYTiTaggghcfZV6kbj42McYN7OxkfvOfyWSNC6dvhobjW7vdmKK7S4qXrNu/6jKKHijdHFP8MsAJhF1@byi@ofSNVo@UfIkgA6P1U4/S92tKPjVoQgNDqBqlW6Y0FhRkK9sLR8mPtZMzBSSxX7lVJIuxDmOdMQZQj/4Uqph/TmWWqkIdtvtTGhWkVVA3UFr5vibkUxGSaahIos0oqBXkRMrpQM6oNROpVX4VRfdMh@nD82dwJuccVsC5B25ZUxieCdtwD8XvajIzm7s9TA0XOor4mT93TIT@vAZg84DDDzIn4Ke5yCLHGjqiSrjIiL26JVq95rdovU/pbXZrxJ5uKfmg@PlA1ApM6KPJyBE5Pw "APL (Dyalog Unicode) – Try It Online") `{`…`}⌺3 3` on each 3-by-3 neighbourhood, apply the following function:  `,⍵` ravel (flatten)  `' '≠` Boolean where non-space  `⍱∘⌽⍨` that NOR it's reverse (incl. neither top NOR bottom, neither left NOR right)  `5 4 2⊃¨⊂` pick 5th, 4th, and 2nd element from that entire list   i.e. empty self, no vertical, no horizontal  `2⊥` evaluate in base-2 (binary)   i.e. ≥4:empty self; 3:no neighbours; 2:no horizontal neighbours; 1:no vertical; 0: has both  `'+-|+'↓⍨` drop that many elements from this string   i.e. empty self:; alone:`+`; vertical neighbour(s) only:`|+`; horizontal:`-|+`; both:`+-|+`  `⊃` pick the first element (pad with space if non are available)   i.e. empty self:; alone:`+`; vertical neighbour(s) only:`|`; horizontal:`-`; both:`+` --- # Old solution Anonymous tacit function taking a character matrix as argument. ``` {' +-|+'⊃⍨1⍳⍨(' '=5⊃,⍵),(∧/,⊢)∨/2 2⍴1⌽' '≠(9⍴0 1)/,⍵}⌺3 3 ``` [Try it online!](https://tio.run/##bZLBTsJAEIbvPMVvetgSirA0JHgwnnkCzw1dCrFQUyCEqCcTUpBNNF48Gi8Sr2JiTHyZeRHcLV1qxW2ys7PzzT/Tab3LsOrPvDAKttsuze@vGCrV6wqj5S3JNSf5rozNwE6b6soh@VF2bEpeaw4tX8qUrGsNNEhuOK2@FUWLZ/tEuXXwck3TN7T6cuEqcbTAXRViVmHBgl563zlWesydlNlBBvuVu4/oGCsxVuqiCV7/U2jP/HPKsjgHbx32ZxUqGGshbyCz5j4nzLMnDFNQMcQhYyFXMBPJpgMzo4OZGK3srWj@wNrwIwyjMcL@hUAQCzGECIIRvKGPnjc4Vh@uyIx7YuBg5A3Qxi5@Hk1CH7NokgPoiVggirUTi7NUZJpiBR1VZTbVxFHeEiVvNH8kubBJ3lHypHe5odWn/qlUrdhHu9PvhCrnBw "APL (Dyalog Unicode) – Try It Online") `{`…`}⌺3 3` on each 3-by-3 neighbourhood, apply the following function:  `,⍵` ravel (flatten)  `(`…`)/` filter using the following mask:   `9⍴0 1` cyclically reshape `[0,1]` to length 9 (selects N, W, E, S)  `' '≠` Boolean where non-space  `1⌽` rotate one step left; `[W,E,S,N]`  `2 2⍴` reshape to 2-by-2 matrix; `[[W,E],[S,N]]`  `∨/` row-wise OR reduction: `[horizontal,vertical]`  `(`…`)` apply the following tacit function:   `⊢` the identity; `[horizontal,vertical]`   `∧/,` preceded by its AND reduction; `[both,horizontal,vertical]`  `(`…`),` prepend the following:   `,⍵` ravel (flatten) the neighbourhood   `5⊃` pick the 5th element (itself)   `' '=` Boolean if space (i.e. empty)  Now we have `[empty,both,horizontal,vertical]`  `1⍳⍨` index of leftmost 1 (gives 5 if no neighbours at all)  `' +-|+'⊃⍨` use that to pick symbol     [Answer] # JavaScript (ES6), 110 bytes I/O format: array of strings. ``` a=>a.map((s,y)=>s.replace(/\S/g,(_,x)=>'+|-+'[[-1,p=0,1,2].map(c=>p|=(a[y+c%2]||0)[x+~-c%2]>' '?c&1||2:0)|p])) ``` [Try it online!](https://tio.run/##ldBBa4MwFAfwu5/ijbAlwWjV4yDuvPMOO1gZIbXF4kzQMVoI@@puxrpGq4zlEPHHy@P/3lF8ilY2pf4IarUruj3vBE9F@C40IS07U562YVPoSsiCbLYvmwMjb@z0w9g3gY@zLIiZ5hGLWZLbV5Kn2nAisrMv75PcmIhmJ/8r6H9SDPhJPsTGJI8RNTqntJOqblVVhJU6kD3JPACM3IOZJUDQn/52CVmYE0IOwc3D8cBNldtrEsLLaXhUZU3wtsYUfLBfz/sr/XUCcILAZIoxCprFtjgLdcGF@Oja2RlhrF2pRtPel/rhAnc1g9gHC@v574peVbODZ1nKqrgb2jkCjoArsCKwIOAKrAlMBRYEfgUcmc5Ku28 "JavaScript (Node.js) – Try It Online") Or [**108 bytes**](https://tio.run/##bZDLCsIwEEX3/YqBoEloGtouC4kfErMIsYqiTTAiLQR/vbb1gY/exTD3MHMZ5mCuJtjz3l@yxm3qfit6I6ThJ@MJCayjQoaHsawdjJUY8AqnMUuxUlnBvMhZwUo9DVkhfRTEqC61i1LHmFPVprdsNNOiXRYxllVOo9eVpbS3rgnuWPOj25EtUQmA4pxj9Cms2ZsDglFj/eNoorMcoV8O8zkvwfz8X/73nYmm0x8CCAmBH9y@IRhT@uzWzdD3dw) by using a matrix of characters instead. [Answer] # [Python 2](https://docs.python.org/2/), ~~181~~ 168 bytes thanks to Leaky Nun for -13 bytes ``` m=input() f=lambda x,y:(['']+m+[''])[y+1][x:x+1]>' ' print[[(c<'!')*' 'or'+-|+'[f(x+1,y)|f(x-1,y)|2*f(x,y+1)|2*f(x,y-1)]for x,c in enumerate(r)]for y,r in enumerate(m)] ``` [Try it online!](https://tio.run/##vZHNjoIwFIX3fYqjLAqCJppZmWFm7RO4ICwYqMIMbU2FCInvzpTKbzSZ3XTR3nPv19Pe9lIXqRS7JpYJ85fLZcP9TFzKwnbIyc8j/pVEqLx6bweUhi5328UJancbBtW@0ssHBSUXlYkiCOz4nS6os9Ipqai7vrs0ONma8mrnroO1CXYrHXraYgjXWyc8SaUPipEJMFFypqKC2eqRrz01z3MnbDh84H/PJG1ByVtb4HsCmL5B6eZbZsLWFefxFES/JCGsYjHah129NQG1hkE9UAvd@FuN@0IytZm4DRvmNqaOYe29TarjexITbk72zha62/TgS9SaoOhhM42dmdSDnTc47fOARELIAnn2w3BWjOnPOJ@viESCNOKbduscKlLGPVwjjgM64CjLPEEty5FAyhSD/siiDT4fNjfDzZz0QfWtRRbmPkepEhziLM51wjgPGoPGqPFS40lj1HitMdV40ug0Jjr8BQ "Python 2 – Try It Online") [Answer] # MATLAB, 113 110 101 bytes ``` function F(A) B=A>32 c=[1 1 1] f=@(c)conv2(B,c,'s')>1 h=f(c) v=f(c') char((13*h+92*v-94*(h&v)).*B+32) ``` Converts input to logical, applies convolution in horizontal and vertical and combines the outputs to make the corresponding chars. 3 bytes saved by @Adriaan for telling me that you can clog the output in PPCG :P 9 bytes saved thanks to numerous @flawr comments! [Answer] # [J](http://jsoftware.com/), ~~49~~ 47 bytes Thanks to *[FrownyFrog](https://codegolf.stackexchange.com/users/74681)* for -2 bytes! ``` ' +|-+'{~~:&' '*1+h&.|:+2*h=:g&.|.*g=:' '=#{.}. ``` [Try it online!](https://tio.run/##dY5dT4MwGIXv@yuOkgwH2MxdNqJemZB474XxgoyOokBNYVmWffx1LJWPss0mlPfpeTjlq7mlODK4a4R6DxZgWDQu/MO97@5PJzZz4XoPvpjRA/OXnghZqkfqpSHTSejs6ZE2c8JXQiKgeMQL1vq5@2B4wtsrqp88q6taZWWKz7lO2tPl5Liqk6zUtzrDIg669e84utbcHw2e9alJMLxNmeHONA4sw3L6NgfEKrmUnF5Cr5mNDHf01pV/JhESiVLWyLNvjlRxXoKnaYW4TCDigp4ZteBFgCouEKFN3@UmT7CTmzGG4IpDqhYUf9YFWyNNOnT/btvmN0R3qATRKlvlmizAH6ADXAKmgA5wBTAApoAWMMIv "J – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 92 bytes ``` \S 0 (?<=(.)*)0(?=(?>.*\n(?<-1>.)*)0)|0(?=(.)*)(?<=0(?>(?<-2>.)*\n.*)) 1 T`d`+|`\b.\b T`d`-+ ``` [Try it online!](https://tio.run/##dY6xboMwEIZ3P8UfsQBprKRzAzNzK3XxAIktQAUjOURRpLw75RxiQ5PeAPfdff5to/paF8MgPtmWhenHPuRRHG3DdB@mCY@FHmebXWKH0c3OqSdzhIS277QVmsdRxHbsK5f5@paLAxcHC5v1MASuWICp/m29O@sfI@fNjtoN3N@GWZ5M62BmzBx4x2c8O4HLmaz7B8zd8dBevJllkB1016OpfxRKo5SGKssTCi1RFS3HH6WvVPuGU9EiA62p2Hd3biSu3dk7qJRR6AyBUemYcrHSImi85Xqh/YpSxhgjkR3rY6NWc8AdMAGeAUvABHgBcIAl0BMAD78 "Retina 0.8.2 – Try It Online") Requires rectangular input. Link includes test cases. Explanation: ``` \S 0 ``` Change all non-spaces to `0`s. ``` (?<=(.)*)0(?=(?>.*\n(?<-1>.)*)0)|0(?=(.)*)(?<=0(?>(?<-2>.)*\n.*)) 1 ``` Look for all `0`s with another `0` immediately above or below in the same column and change them to a 1. The `1`s are now the places with vertical neighbours, while the `0`s have no vertical neighbours. ``` T`d`+|`\b.\b ``` Look for all digits with no horizontal neighbours. The `0`s have no vertical neighbours either, so they become `+`s, while the `1`s have vertical neighbours, so they become `|`s. ``` T`d`-+ ``` The remaining digits have horizontal neighbours. The `1`s also have vertical neighbours, so they become `+`s, while the `0`s only have horizontal neighbours, so they become `-`s. [Answer] # [Python 3](https://docs.python.org/3/), 336 bytes ``` def g(s): h,j,s=' +|-+','',s.splitlines() s+=[''] for n in range(len(s)): s[n]+=' ' for i in range(len(s[n])-1): l,r,k=s[n][i-1],s[n][i+1],0 try:u=s[n-1][i] except:u=' ' try:d=s[n+1][i] except:d=' ' if not s[n][i]==' ': k+=1 if not u==d==' ':k+=1 if not l==r==' ':k+=2 j+=h[k] j+='\n' print(j) ``` [Try it online!](https://tio.run/##dY/RaoQwFETf71dcyEOUxFLbt4V8ifWh1KhRiZJkoQv@u02iscWlVzDDzMlcXR6un/X7tjWyxS6z@Q2w5wO3giJbC0Y5pdy@2GVSblJa2iwHtExUlNaA7WxQo9JoPnUns0lq3xAq0Fa6Zr6Deh0odaF8nBdlRHHiho8iWJUqyprvinn1GmJnHrd7iH1WqTpY8vtLLs67@4KINAFhV6RJiGpRzw737loEOy7HkYkyioO4C9Hs8TWZhDBn8haSgYm@GsM@r@iH9psWo7TLhnzrMkoIoTmAV5Sy4hgGKx6z/iN/WX8xFZDrQLpA0gkEY4LnCSTm5GB253gSeTKpjSD8KXmGSIIwYfEF545EwdM37/@z/QA "Python 3 – Try It Online") I had to use a lot of code to deal with edge case errors. [Answer] # [C (gcc)](https://gcc.gnu.org/), 143 bytes ``` char**y,*z,h,v;f(char**x){for(y=x;*y;++y)for(z=*y;*z;++z)if(*z-32){h=z[1]-32|z[-1]-32;v=y[1][z-*y]-32|y[-1][z-*y]-32;*z=h?v?43:45:(v?'|':43);}} ``` [Try it online!](https://tio.run/##jVLbjoIwEH3nKyaSjW2BrLu6LzbEL@ALWB8MkaUJoEFDbJFvZ6e0aHWziUNC55w5c@kli36ybBiyYtcwJkOmwiJseU4McaFdfmiIjC@cSR4EkmqoYgRMIVZU5ISpaPlJuyJW6ccW3atKo9HhbSyRSlXE5BiQOnCDWCIuNu1mtVyvvtak3cyv8/VqSXnfD6I@Q7UTNaGdB2gaCz66ejJgVbqFWMPOm8Ffm4VI@89m6Mn822rURu@sltYK36od2n5TzqMantT3uv@o/cfaVm9@cFfDxID/4i7dM4FFzz3nEFmCZ1jtyvKQkZNQ@0MOxEQoMLAUqei79VhFKTW3gO8AiMD0BYcqFVsOQSAomNvSdmzwznIyezt919hZa2yqtgThc@@xNWWnc1PuazImOBlIZ0dJdOJDtd5z6i3s9nKS0Ml1Bk1eGDRxS/fe8As "C (gcc) – Try It Online") The function f modifies an array of strings in-place. The area around the array must be padded with spaces (a bit constrained). Even though this doesn't exactly meet the requirements most solutions are using, it does conform to the rules if we say that we represent a newline with two spaces (and take array of strings ending in newlines). ### Ungolfed ``` f(char**x){ char **y; for (y = x; *y; ++y) { char *z; for (z = *y; *z; ++z) { if (*z != ' ') { if (z[1] != ' ' || z[-1] != ' ') { // Horizontal exists if (y[1][z-*y] != ' ' || y[-1][z-*y] != ' ') // Vertical exists *z = '+'; else *z = '-'; } else { // Horizontal doesn't exist if (y[1][z-*y] != ' ' || y[-1][z-*y] != ' ') // Vertical exists *z = '|'; else *z = '+'; } } } } } ``` This was a fun challenge of pointer arithmetic. Using C-style pointer iteration it is easy to get the horizontal neighbors, but the vertical ones were tougher. Luckily the y pointer is still around (which points to the initial value of z) so I can deduce my index from it and use that to access the same element on a different row. It felt very wrong writing `y[-1][z-*y]` as it flies in the face of any reasonable style! ]
[Question] [ [Haskell](https://haskell.org "Haskell Language") has this neat(-looking) feature where you can give it three numbers and it can infer an arithmetic sequence from them. For example, `[1, 3..27]` is equivalent to `[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27]`. That's cool and all but arithmetic sequences are fairly limiting. Addition, *pfft*. Multiplication's where it's at. Wouldn't it be cooler if it did geometric sequences like `[1, 3..27]` returning `[1, 3, 9, 27]`? ## Challenge Write a **program/function** that takes three positive integers **a**, **b**, and **c** and outputs `[**a**, **b**, **b** × (**b** ÷ **a**), **b** × (**b** ÷ **a**)**2**, ..., **x**]` where **x** is the greatest integer ≤ **c** that can be represented as `**b** × (**b** ÷ **a**)**n**` where **n** is a positive integer. That is, the output should be **r**, such that: ``` **r****0** = **a** **r****1** = **b** **r****n** = **b** × (**b** ÷ **a**)**n**-**1** **r****last** = greatest integer ≤ **c** that can be represented as **b** × (**b** ÷ **a**)**n** where **n** is a positive integer ``` ### Specifications * [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default for Code Golf: Input/Output methods") **apply**. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Loopholes that are forbidden by default") are **forbidden**. * **b** will always be divisible by **a**. * **a** < **b** ≤ **c** * This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**. * Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise. * Built-in functions (Mathematica might have one :P) that compute this sequence are **allowed** but including a solution that doesn't rely on a built-in is encouraged. * Explanations, even for "practical" languages, are **encouraged**. ### Test cases ``` **a** **b** **c** **r** 1 2 11 [1, 2, 4, 8] 2 6 100 [2, 6, 18, 54] 3 12 57 [3, 12, 48] 4 20 253 [4, 20, 100] 5 25 625 [5, 25, 125, 625] 6 42 42 [6, 42] ``` In a few better formats: ``` 1 2 11 2 6 100 3 12 57 4 20 253 5 25 625 6 42 42 1, 2, 11 2, 6, 100 3, 12, 57 4, 20, 253 5, 25, 625 6, 42, 42 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ~↑≤Ṡ¡o// ``` Input is in order **b, c, a**. [Try it online!](https://tio.run/##AR8A4P9odXNr//9@4oaR4omk4bmgwqFvLy////82/zEwMP8y "Husk – Try It Online") ## Explanation ``` ~↑≤Ṡ¡o// Implicit inputs. / a/b as exact rational number. o/ Divide by a/b (so multiply by b/a). ¡ Iterate that function Ṡ on a. Result is the infinite list [a, b, b^2/a, b^3/a^2, .. ↑ Take elements from it while ~ ≤ they are at most c. ``` The control flow in this program is a bit hard to follow. First, **b** is fed to the rightmost `/`, producing a function `/b` that divides by **b**. Next, `~` splits the remaining program into three parts: `~(↑)(≤)(Ṡ¡o//b)`. This feeds **c** to `≤` and **a** to `Ṡ¡o//b`, and combines the results with `↑`. The result of `≤c` is a function that checks if its argument is at most **c**, and `↑≤c` takes the longest prefix of elements for which this holds. It remains to show how `(Ṡ¡o//b)a` evaluates to the desired infinite list. The part in parentheses is split into `Ṡ(¡)(o//b)`. Then `Ṡ` feeds **a** to `o//b`, feeds the result to `¡`, and then gives **a** to its second argument. The expression `(o//b)a` gives a function that takes a number and divides it by **a/b**, and `¡` iterates this function on its second argument, which is **a**. Here is a series of transformations that visualize the explanation: ``` (~↑≤Ṡ¡o//) b c a = (~↑≤Ṡ¡o/(/b)) c a = ~(↑)(≤)(Ṡ¡o/(/b)) c a = ↑(≤c)((Ṡ¡o/(/b)) a) = ↑(≤c)(Ṡ(¡)(o/(/b)) a) = ↑(≤c)(¡(o/(/b)a) a) = ↑(≤c)(¡(/(/ba))a) Last line in English: takeWhile (atMost c) (iterate (divideBy (divideBy b a)) a) ``` Alternative solution using explicit variables in order **a, b, c**: ``` ↑≤⁰¡*/⁵² ``` [Answer] # [Python 2](https://docs.python.org/2/), 42 bytes ``` a,b,c=input() x=b/a while c/a:print a;a*=x ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P1EnSSfZNjOvoLREQ5OrwjZJP5GrPCMzJ1UhWT/RqqAoM69EIdE6Ucu24v9/Ix0zHUMDAwA "Python 2 – Try It Online") ### Recursive approach, ~~42~~ 41 bytes -1 byte thanks to ovs ``` f=lambda a,b,c:c/a*[a]and[a]+f(b,b*b/a,c) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVEnSSfZKlk/USs6MTYxLwVIaqdpJOkkaSXpJ@oka/4vKMrMK1FI0zDSMdMxNDDQ/A8A "Python 2 – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 35 bytes ``` f=(a,b,c)=>c//a?[a]+f(b,b*b/a,c):[] ``` [Try it online!](https://tio.run/##KyjKL8nP@/8/zVYjUSdJJ1nT1i5ZXz/RPjoxVjtNI0knSStJPxEobBUd@7@gKDOvRCNNw0jHTMfQwEBT8z8A "Proton – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes ``` PowerRange[#,#3,#2/#]& ``` [Try it online!](https://tio.run/##FYqxCoMwFEV/5eIDp1eamGqnSj5BuoYMocTqoAUJOIR8e/ocLpxzOVtIS9xCWj@hznihTr8zHu@wf6MjJsPU3cm3dTrWPblMVBgNbiMaxuyIvEcLay1y1oyOobUUWWAQVuoSIyRH/7zkIZWS9aaU@gc "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES6), ~~41~~ 37 bytes *Saved 4 bytes thanks to @Neil* Takes input as `(b,c)(a)`. ``` (b,c)=>g=a=>a>c?[]:[a,...g(b,b*=b/a)] ``` ### Test cases ``` let f = (b,c)=>g=a=>a>c?[]:[a,...g(b,b*=b/a)] console.log(JSON.stringify(f(2,11)(1))) console.log(JSON.stringify(f(6,100)(2))) console.log(JSON.stringify(f(12,57)(3))) console.log(JSON.stringify(f(20,253)(4))) console.log(JSON.stringify(f(42,42)(6))) ``` ### Commented ``` (b, c) => // main function taking b and c g = a => // g = recursive function taking a a > c ? // if a is greater than c: [] // stop recursion and return an empty array : // else: [ a, // return an array consisting of a, followed by ...g( // the expanded result of a recursive call to g() b, // with a = b b *= b / a // and b = b * ratio ) ] // end of recursive call ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 38 bytes ``` f(a,b,c)=powers(b/a,logint(c\a,b/a),a) ``` [Try it online!](https://tio.run/##FYtBCsMwDAS/InKyQCG2E7en9iOpD4ppQsA0Ii2Uvt6VDgsz2pXwufebtLY6poUK3uT4Ps@3Wwamemz76@PKQ6uBkRgbi9SfY@jvIKeVDJ1JB4VrdSsBIxLMcyCIBCFkFYWLsvcmo5Ie0tVk0pXXpNEsGek2JjN9maIlZ2x/ "Pari/GP – Try It Online") [Answer] # Python 3, ~~93~~ ~~90~~ ~~74~~ 73 bytes ``` x=lambda a,b,c,i=0,q=[]:a*(b/a)**i>c and q or x(a,b,c,i+1,q+[a*(b/a)**i]) ``` [Try It Online](https://tio.run/##VcpBCoMwFIThvafIMtEpTZ4mQiG9iLhI4qJCq0Zc2NOntpSWwMDAx788t9s81afw@ZR2e3cPPzjm4BEwWolou/7iSu7PTpTleA3MTQOLbF7Zzr9ZpRCr7h/1Ii3rOG2c71yBoJQQoih@RjBQUuZYQxF0m2MDkiBd56oPgiGdq0FDx96YXg) Thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod) and [user202729](https://codegolf.stackexchange.com/users/69850/user202729) for helping me reduce quite some bytes! [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~38~~ 35 bytes ``` @(a,b,c)exp(log(a):log(b/a):log(c)) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQSNRJ0knWTO1okAjJz9dI1HTCkQl6UMZyZqa//8DAA "Octave – Try It Online") Turns out @LuisMendo's MATL approach also saves 3 bytes in Octave, despite repeating `log` three times. [Answer] # [Perl 6](http://perl6.org), ~~26~~ 24 bytes ``` {$^a,$^b,$b²/$a...^*>$^c} {$^a,*×$^b/$a...^*>$^c} ``` [Try it online!](https://tio.run/##FcZBCoMwEAXQq3xk6EIkZkaTLtQcJRJLs2ppsStRz@GBerBo4C3e9zm/bHovuEUMaSUfqvJ/kJ9qCkopXzryjz39woKCRgwOa8RG414gfmb0DAGzq9ALLFjr3AYsMPfcFqIhpsk3V2DF5Fu0cnFdOgE "Perl 6 – Try It Online") Perl 6's sequence operator `...` can infer geometric series natively. Update: ...It *can*, but in this situation not inferring it is a bit shorter. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes Input in the order `c,b,a` ``` ÝmI¹Ý<m/ʒ¹›_ ``` [Try it online!](https://tio.run/##ASUA2v8wNWFiMWX//8OdbUnCucOdPG0vypLCueKAul///zE5MgoxMgoz "05AB1E – Try It Online") **Explanation** ``` Ý # push the range [0 ... c] m # raise b to the power of each I # push a ¹Ý # push the range [0 ... c] < # decrement each m # push a to the power of each / # elementwise division of ranges ʒ # filter, keep only elements that are ¹›_ # not greater than c ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 17 bytes ``` t:,qtiw^w]x/tb>~) ``` [Try it online!](https://tio.run/##y00syfn/v8RKp7AkszyuPLZCvyTJrk7z/39DCy4zLiMA "MATL – Try It Online") Just to get the ball rolling in MATL. I can't imagine there isn't a less verbose way of solving this. [Answer] ## Haskell, 35 bytes ``` (a#b)c|a>c=[]|d<-div b a*b=a:(b#d)c ``` [Try it online!](https://tio.run/##TczNCgIhFIbhfVfxgS00CPSMGkR2I9HCnyBpZoqKVnPvdmbn9uHlvcfP4zaOrckokspLPOdwuS7ltC/1h4S4SyEeZRJF5TbFOiOgPDfA613nL7aQBgIgBWN6pVU9q9Y9D8yGY3fo1bKSViA39OxWdgqeXM@e2fLDUvsD "Haskell – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` y/ivZlZ}3$:W ``` [Try it online!](https://tio.run/##y00syfn/v1I/sywqJ6rWWMUq/P9/Iy4zLkMDAwA) Or [verify all test cases](https://tio.run/##y00syfmf8L9SP7MsKieq1ljFKvy/S8h/Qy4jLkMQYcZlaGDAZcxlaMRlas5lwmVkwGVkasxlCiS5zECYy8QIhAA). ### Explanation ``` y % Implicitly take two inputs, and duplicate the first onto the top / % Divide i % Take third input v % Vertically concatenate the three numbers into a column vector Zl % Binary logarithm, element-wise Z} % Split the vector into its three components 3$: % Three-input range. Arguments are start, step, upper limit W % 2 raised to that, element-wise. Implicit display ``` [Answer] # Perl, 38 bytes Include `+3` for `-n` (the `use 5.10.0` to unlock the perl 5.10 features is free) ``` #!/usr/bin/perl -n use 5.10.0; / \d+/;say,$_*=$&/$`until($_+=0)>$' ``` Then run as: ``` geosequence.pl <<< "1 3 26" ``` [Answer] # [Red](http://www.red-lang.org), 50 bytes ``` g: func[a b c][if a <= c[print a g b b * b / a c]] ``` [Try it online!](https://tio.run/##ZYsxDsIwDEX3nuLNSIjEbYKE4BKsUYY2baMuFarohDh7cMUYyx7@e/7bNJbnNBJiyTfmfU2hZyDFsMz03B@k8NqW9a0hqxg46V00pagVLIK1zf/lcz7m22SFHmtMxVus4K4V7xCDuLYSTileXCU8nRxbfg "Red – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` ÆWpX zVpXÉÃf§U ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=xldwWCB6VnBYycNmp1U=&input=NjI1LDUsMjU=) --- ## Explanation ``` :Implicit input of integers U=c, V=a & W=b Æ Ã :Range [0,U) and pass each X through a function WpX : W to the power of X z : Floor divide by VpXÉ : V to the power of X-1 f§U :Filter elements less than or equal to U ``` [Answer] # [Clean](https://clean.cs.ru.nl), 63 bytes ``` import StdEnv $a b c=takeWhile((>=)c)[a:map(\n=b*b^n/a^n)[0..]] ``` [Try it online!](https://tio.run/##Dcu9CsIwEADg3ae4oUMiWP8GQYiTDoJbB4fawuUaNZi7FhsFX97Tb/8oBRTlvnulAIxRNPLQPzNUuTvIe1IgeCCX8RHO95iCMTtnyda4ZRzMRZyf@lbm2IqtF2XZNFpl/HcHBSxhDauNfuma8Dbq7HjS/UeQI40/ "Clean – Try It Online") [Answer] # TI-BASIC, 31 bytes Takes input from user and outputs in `Ans`. I solved for n in c = bn / an-1, getting n = 1 + ln(c/b) / ln(b/a). That's the same as n = 1 + logb/a(c/b). For the purposes of golfing, I start my sequence at -1 and end it at n-1 rather than 0 to n. ``` Prompt A,B,C seq(B(B/A)^N,N,-1,logBASE(C/B,B/A ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 38 bytes ``` {(g≤⊃⌽⍵)⊆g←f,(⍵[1]*p+1)÷(f←⊃⍵)*p←⍳⊃⌽⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qW9CjtgmGRhbmXECOpz@QY/A/DUhWa6Q/6lzyqKv5Uc/eR71bNR91taUDhdN0NIC8aMNYrQJtQ83D2zVAakGqgEq0CkDs3s1wTbX//6cpGCoYKRgacqUBKTMFQwMDIMtYwdBIwdQcyDJRMDJQMDI1BjJNgbSCmZEpkGmmYGIERAA "APL (Dyalog Unicode) – Try It Online") Prefix Dfn. Takes input in order `a b c`, and uses `⎕IO←0` (**I**ndex **O**rigin) Thanks to @ErikTheOutgolfer for shaving 6 bytes out of this before I even posted it. ### How? ``` {(g≤⊃⌽⍵)⊆g←f,(⍵[1]*p+1)÷(f←⊃⍵)*p←⍳⊃⌽⍵} ⍝ Prefix Dfn. Input ⍵ is a vector ⌽⍵ ⍝ Reverse ⍵. Yields c b a ⊃ ⍝ Pick the first element (c) ⍳ ⍝ Index. Yields the integers 0..c-1 p← ⍝ Assign to the variable p * ⍝ Exponentiate (f←⊃⍵) ⍝ Pick the first element of ⍵ (a) and assign to f ⍝ This yields the vector (a^0, a^1, ..., a^c-1) ÷ ⍝ Element-wise division p+1) ⍝ The vector 1..c * ⍝ Exponentiate (⍵[1] ⍝ Second element (because of ⎕IO←0) of ⍵ (b) ⍝ This yields the vector (b^1, b^2, ..., b^c) f, ⍝ Prepend f (a). This yields the vector ⍝ (a, b^1/a^0, b^2/a^1, ...) g← ⍝ Assign the vector to g ⊆ ⍝ Partition. This takes a boolean vector as left ⍝ argument and drops falsy elements of the right argument. ⊃⌽⍵) ⍝ Pick the last element of ⍵ (c) (g≤ ⍝ Check if each element of g≤c. Yields the boolean ⍝ vector that is the left argument for ⊆ ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437 ``` ü╞¥ß¥║/,5å╘⌂åº ``` 16 bytes when unpacked, ``` E~Y/y{;^<}{[*gfm ``` [Run and debug online!](http://staxlang.xyz/index.html#c=E%7EY%2Fy%7B%3B%5E%3C%7D%7B%5B*gfm&i=%5B2%2C+1%2C+11%5D%0A%0A%5B6%2C+2%2C+100%5D%0A%0A%5B12%2C+3%2C+57%5D%0A%0A%5B20%2C+4%2C+253%5D%0A%0A%5B25%2C+5%2C+625%5D%0A%0A%5B42%2C+6%2C+42%5D&a=1&m=1) Takes input in the form of `[b, a, c]`. Pretty sure @recursive has better solutions. ## Explanation ``` E~ Parse input, put `c` on input stack Y/ Store `a` in register `y` and calculate `b`/`a` y Put `y` back to main stack, stack now (from top to bottom): [`a`, `b`/`a`] { }{ gf generator ;^< Condition: if the generated number is smaller than the top of input stack (i.e. `c`) [* duplicate the second item in main stack and multiply it with the item at the top i.e. multiply last generated value by `b/a` and generate the value m Output array, one element on each line ``` [Answer] # [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), 73 bytes ``` readIO k=i readIO j=i readIO r=j/k a=k lbla printInt a a*r b=i-a+1 if b a ``` [Try it online!](https://tio.run/##K87MyS/@/78oNTHF058r2zaTC8rMQjCLbLP0s7kSbbO5cpJyErkKijLzSjzzShQSuRK1iriSbDN1E7UNuTLTFJIUEv///2/03@S/mTEA "S.I.L.O.S – Try It Online") We read the three numbers. Calculate the common ratio by the second number/ first one. Then we run through the series until we are greater than the upper bound. [Answer] # C (gcc), 82 bytes ``` n;f(a,b,c){float r=0;for(n=0;r<=c;)(r=pow(b,n)/pow(a,n++-1))<=c&&printf("%f ",r);} ``` [Try it online!](https://tio.run/##ZY/RCsIgFIbve4rDoFByNJ2uwPYmuzHBCNZZWNBF9OrZMepiKYh6/u/To6@P3qeENjAnDsLzRxgnd4PYNzZMkSGtcd97y1nsL9OdHQTyTd44get1LTmndLW6xBPeAquWASoRuX0mOsPZnZDxxWMBNAKTApQAKbn9FH7OgBIUaNgNOGD1DQMjtCO6aQpcQQdyB0bPhZZoksy2EFoKQP/dr6mbhqZpC15Tkl@eCybD1JQyhWAooTdMDucSfUGrPAuno@KPfaaXD6M7XlM9nt8) Calculates and prints `r_n = b^n/a^(n-1)` until `r_n > c`. Must be compiled with `-lm`! [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 23 bytes ([SBCS](https://github.com/abrudz/SBCS)) This takes arguments **a b** on the left and **c** on the right, ``` {⊃(⍵∘≥⊆⊢)⊣/⍵2⍴⍺,÷\⍵⍴⌽⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR13NGo96tz7qmPGoc@mjrrZHXYs0H3Ut1geKGT3q3fKod5fO4e0xIBVATs9eIL/2/39DBSOFNAVDQy4jBTMQw8CAy1jBECRmas5lomBkAGQZmRpzmQJJINPMyJTLTMEEJG9iBAA "APL (Dyalog) – Try It Online") There is likely a shorter way, but I thought that `÷\` was cute. ### Explained: `{...}` Anonomous function ⍺ is `a b`, `⍵` is `c`. Lets say `a b c = 2 6 100` `⌽⍺` Reverse `⍺`: `6 2` `⍵⍴` Repeat `⍵` times: `6 2 6 2 6 2 6 2 ...` `÷\` Reduce by division on prefixes: `6 (6÷2) (6÷(2÷6)) (6÷(2÷(6÷2))).. = 6 3 18 9 54 ..` `⍺,` Prepend `⍺`: `2 6 6 3 18 9 54 27 162 81 ...` `⊣/⍵2⍴` Get every other element (plus some trailing repeats):   `⍵2⍴` Make an `⍵` row, `2` column matrix from `2 6 6 3 18 9 54 ...`   `⊣/` Get the first column `⊆⊢` Split the array into blocks where `⍵∘≥` `⍵` is greater than or equal to all the elements `⊃` Take the first such block ]
[Question] [ Given an audio file, determine whether it is encoded in a lossy format or a lossless format. For the purposes of this challenge, only the following formats need to be classified: * Lossy + [AC3](https://en.wikipedia.org/wiki/Dolby_Digital) + [AMR](https://en.wikipedia.org/wiki/Adaptive_Multi-Rate_audio_codec) + [AAC](https://en.wikipedia.org/wiki/Advanced_Audio_Coding) + [MP2](https://en.wikipedia.org/wiki/MPEG-1_Audio_Layer_II) + [MP3](https://en.wikipedia.org/wiki/MP3) + [Ogg Vorbis](https://en.wikipedia.org/wiki/Vorbis) + [WMA](https://en.wikipedia.org/wiki/Windows_Media_Audio) * Lossless + [AIFF](https://en.wikipedia.org/wiki/Audio_Interchange_File_Format) + [FLAC](https://en.wikipedia.org/wiki/Free_Lossless_Audio_Codec) + [TTA](https://en.wikipedia.org/wiki/TTA_(codec)) + [WAV](https://en.wikipedia.org/wiki/WAV) ## Rules * If input is taken in the form of a filename, no assumptions should be made about the filename (e.g. the extension is not guaranteed to be correct for the format, or even present). * There will be no ID3 or APEv2 metadata present in input files. * Any two unique and distinguishable outputs may be used, such as `0` and `1`, `lossy` and `lossless`, `foo` and `bar`, etc. ## Test Cases The test cases for this challenge consist of a zip file located [here](https://www.dropbox.com/s/asr5ga3cil9n2mx/audio.zip?dl=0) which contains two directories: `lossy` and `lossless`. Each directory contains several audio files that are all 0.5-second 440 Hz sine waves, encoded in various formats. All of the audio files have extensions matching the formats above, with the exception of `A440.m4a` (which is AAC audio in a MPEG Layer 4 container). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 5 bytes ``` ƈƈeØA ``` Lossy formats return **0**, lossless formats return **1**. [Try it online!](https://gist.github.com/DennisMitchell/cecb3219ca1855525e078629a2bcc55f) (permalinks in Gist) ### Background The formats we have to support have the following magic numbers, i.e., they start with these bytes. ``` Format Header (text) Header (hex) ----------------------------------------------------------------------------------- AC3 .w 0B 77 AMR #!AMR 23 21 41 4D 52 AAC ÿñP@..ü FF F1 50 40 00 1F FC M4A ... ftypM4A 00 00 00 20 66 74 79 70 4D 34 41 20 MP2 ÿû FF FB MP3 ÿû FF FB OGG OggS 4F 67 67 53 WMA 0&²u.fÏ.¦Ù.ª.bÎl 30 26 B2 75 8E 66 CF 11 A6 D9 00 AA 00 62 CE 6C AIFF FORM????AIFF 46 4F 52 4D ?? ?? ?? ?? 41 49 46 46 FLAC fLaC 66 4C 61 43 TTA TTA1 54 54 41 31 FFM2 FFM2 46 46 4D 32 WAV RIFF????WAVE 52 49 46 46 ?? ?? ?? ?? 57 41 56 45 ``` Indented entries are containers for the preceding format that appear in the test cases. `?` denotes a variable byte. `.` denotes an unprintable byte. All other bytes are displayed as their ISO 8859-1 character. By looking only at the second byte, we can determine the format in an easy way: **Lossless formats have an uppercase letter as their second byte, while lossy formats do not.** ### How it works ``` ƈƈeØA Main link. No arguments. ƈ Read a char from STDIN and set the left argument to this character. ƈ Read another char from STDIN and set the return value to this character. ØA Yield the uppercase alphabet, i.e., "ABCDEFGHIJKLMNOPQRSTUVWXYZ". e Exists; return 1 if the return value (second char on STDIN) belongs to the uppercase alphabet, 0 if not. ``` [Answer] # C, ~~82~~ ~~80~~ 32 bytes Inspired by [@Dennis'](https://codegolf.stackexchange.com/a/117802/8927) answer, this can be reduced much further: ``` main(){return getchar()&200^64;} ``` Pipe the file data to stdin. Returns 0 for lossless, or nonzero for lossy. Or the original longer check: ``` char v[5];main(){scanf("%4c",v);return*v&&strstr("fLaC FORM RIFF TTA1 FFM2",v);} ``` Pipe the file data to stdin. Returns nonzero (1) for lossless, or 0 for lossy. From what I can tell, all the formats you listed have separate magic numbers (except AIFF/WAV, but those are both lossless anyway), so this just checks that magic number for a known lossless value. The `*v&&` is just to protect against matching files which start with a null byte (M4A). I've included the values I found in spec sheets (`fLaC` = FLAC, `RIFF` = WAV/AIFF, `TTA1` = TTA), and `FORM` = AIFF and `FFM2` = TTA are from the sample files provided (I can only guess these are wrapper formats or later versions). --- Or a shorter feels-like-cheating alternative: # Bash + file, 61 bytes ``` N="$(file "$1")";[[ $N = *": d"* || $N = *IF* || $N = *FL* ]] ``` Takes the filename as an argument. Returns 0 for lossless, or nonzero for lossy. Does exactly what you'd expect; asks `file` what the filetype is, then checks for known patterns. TTA matches `: d` (`: data`), AIFF / WAV match `IF`, and FLAC matches `FL`. None of the lossless results match any of these, and I've tested that it still works if the filenames are removed. --- Testing: ``` for f in "$@"; do echo "Checking $f:"; ./identify2 "$f" && echo "shorter C says LOSSLESS" || echo "shorter C says LOSSY"; ./identify < "$f" && echo "longer C says LOSSY" || echo "longer C says LOSSLESS"; ./identify.sh "$f" && echo "file says LOSSLESS" || echo "file says LOSSY"; done; # This can be invoked to test all files at once with: ./identify_all.sh */* ``` [Answer] # [GS2](https://github.com/nooodl/gs2), 3 bytes ``` ◄5ì ``` Lossy formats return **0**, lossless formats return **1**. [Try it online!](https://gist.github.com/DennisMitchell/d8081470499d1eb6d5d8aaed52bd09f5) (permalinks in Gist) ### Background The formats we have to support have the following magic numbers, i.e., they start with these bytes. ``` Format Header (text) Header (hex) ----------------------------------------------------------------------------------- AC3 .w 0B 77 AMR #!AMR 23 21 41 4D 52 AAC ÿñP@..ü FF F1 50 40 00 1F FC M4A ... ftypM4A 00 00 00 20 66 74 79 70 4D 34 41 20 MP2 ÿû FF FB MP3 ÿû FF FB OGG OggS 4F 67 67 53 WMA 0&²u.fÏ.¦Ù.ª.bÎl 30 26 B2 75 8E 66 CF 11 A6 D9 00 AA 00 62 CE 6C AIFF FORM????AIFF 46 4F 52 4D ?? ?? ?? ?? 41 49 46 46 FLAC fLaC 66 4C 61 43 TTA TTA1 54 54 41 31 FFM2 FFM2 46 46 4D 32 WAV RIFF????WAVE 52 49 46 46 ?? ?? ?? ?? 57 41 56 45 ``` Indented entries are containers for the preceding format that appear in the test cases. `?` denotes a variable byte. `.` denotes an unprintable byte. All other bytes are displayed as their ISO 8859-1 character. By looking only at the second byte, we can determine the format in an easy way: **Lossless formats have an uppercase letter as their second byte, while lossy formats do not.** ### How it works ``` (implcit) Push the entire input from STDIN as a string on the stack. ◄ Push 1. 5 Get the strings character at index 1, i.e., its second character. ì Test if the character is an uppercase letter. ``` [Answer] # [Chip](https://github.com/Phlarx/chip), 11 bytes ``` ~Z~S t'G~aF ``` Shamelessly replicated Dennis' Jelly answer in Chip. Lossless returns `0x0`, lossy returns `0x1`. [Try it online](https://gist.github.com/Phlarx/300c16dc937f0c37c99a24433a9f786e), links in gist (thanks Dennis for the TIO strategy here) ### Explain! ``` ~Z~S t' ``` This portion is housekeeping: it `S`kips the first byte, and `t`erminates after the second. ``` G~aF ``` This is the meat of the decision. Each input byte is accessed by the bits `HGFEDCBA`. If `G` is set, and `F` is not, that means the byte is within the range `0x40` to `0x5f` (which is roughly equivalent to 'uppercase', and good enough for the task at hand). However, for byte savings, I invert this decision from `G and (not F)` to `(not G) or F`, since or's can be implicit in Chip. This resultant true/false value is then placed into `a`, which is the lowest bit of the output. (All other bits will be zero). In the TIO, I run the output through hexdump so that the values are visible. Equivalently, in C-ish, one would say something like: ``` out_byte = !(in_byte & 0x40) && (in_byte & 0x20) ``` [Answer] # JavaScript (ES6), 20 bytes ``` c=>/^[fFRT]/.test(c) ``` --- ## Explanation Takes the contents of the file as an input and returns `true` if the file is lossless or `false` if it is lossy by testing the first character of that input to see if it is an `f`, `F`, `R` or `T`. --- ## Try It Paste the contents of a file into the `textarea`. ``` f= c=>/^[fFRT]/.test(c) i.addEventListener("input",_=>console.log(f(i.value))) ``` ``` <textarea id=i></textarea> ``` --- [Answer] # Cubix, 16 bytes ``` $-!u'HIa'@/1@O< ``` Net form: ``` $ - ! u ' H I a ' @ / 1 @ O < . . . . . . . . . ``` # Try it yourself You should input the file decimal byte values in a separated list. The separator doesn't matter, anything that is not a digit or a minus sign suffices. The code really only cares about the first byte, so you can leave out the rest of the file if you like. The program outputs `0` for lossless, and `1` for lossy. Try it [here](https://ethproductions.github.io/cubix/?code=JC0hdSdISWEnQC8xQE88&input=MTAyIDc2IDk3IDY3)! The default input uses a FLAC header. # Explanation The nice thing about files is that (nearly) all of them have a so-called magic. Those are the first few bytes of the file. Good software doesn't check the file extension, but rather the file magic to see if it can handle a certain file. Dennis has found a way to use this magic to find the compression type, but the fact that he discarded the first byte made me want to try to come up with a method that used the first byte, rather than the second. After all, this community is all about saving bytes. Here's a list of the first bytes of the different file types. I ordered them into two groups: lossy and lossless. Here are the values of their first byte in decimal, hexadecimal and binary. You might see a pattern already... ``` Lossy: Lossless: 255:0xFF:0b11111111 102:0x66:0b01100110 79:0x4F:0b01001111 84:0x54:0b01010100 35:0x23:0b00100011 82:0x52:0b01010010 11:0x0B:0b00001011 70:0x46:0b01000110 0:0x00:0b00000000 ``` The pattern I saw, was that the second bit (counted from left to right) was always on on the "lossless" bytes and the fifth bit was always off. This combination does not appear in any of the lossy formats. To "extract" this, we would simply do a binary AND (by `0b01001000 (=72)`) and then compare to `0b01000000 (=64)`. If both are equal, the input format is lossless, otherwise it's lossy. Sadly, Cubix doesn't have such a comparison operator, so I used subtraction (if the result is 64, this yields 0, and it results in 8, -56 or -64 otherwise. I'll get back to this later. First, let's start at the beginning of the program. The binary AND is done using the `a` command: ``` 'HIa 'H # Push 0b01001000 (72) I # Push input a # Push input&72 ``` Then, we compare to 64 using subtraction (note we hit a mirror that reflects the IP to the top face [first line, second character, pointing south] in the middle of this part). ``` '@- '@ # Push 0b01000000 (64) - # Subtract from (input&72) # Yields 0 for lossy, non-zero otherwise ``` After the IP is turned around by the `u`, we use some control flow to push a `1` to the stack if (and only if) the top of the stack is non-zero: ``` !$1 ! # if top = 0: $1 # do nothing # else: 1 # push 1 ``` After we wrap around the cube, we hit the `<` instruction, which points the IP west on the fourth line. All that's left to do is output and terminate. ``` O@ O # Output top of the stack as number @ # End program ``` So, the program outputs `0` for lossless, and `1` for lossy. ]
[Question] [ # Challenge: Given a matrix (or 2d array) of 0s and 1s, output the number of steps it takes for Conway's game of life to reach a stable state, or -1 if it never reaches one. A stable state is a state in which no cells are turned on or off each step. The game must run in the given matrix, with the top and bottom connected, and the sides connected. (i.e. given a 4x3 matrix it should run on a 4x3 torus) The input matrix will not be larger than 15x15. Note: If the matrix starts in a stable state, the output should be 0. # Samples: **Input:** ``` [[0,0,0], [0,1,1], [0,1,0]] ``` **Output:** 2 **Process:** (this does not need to be displayed) ``` [[0,0,0], [0,1,1], [0,1,0]] [[1,1,1], [1,1,1], [1,1,1]] [[0,0,0], [0,0,0], [0,0,0]] ``` **Input:** ``` [[0,0,1,1], [0,1,1,1], [0,1,0,0], [0,1,1,1]] ``` **Output:** 2 **Process:** ``` [[0,0,1,1], [0,1,1,1], [0,1,0,0], [0,1,1,1]] [[0,0,0,0], [0,1,0,1], [0,0,0,0], [0,1,0,1]] [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]] ``` **Input:** ``` [[0,1,0,0], [0,1,0,0], [0,1,0,0], [0,0,0,0]] ``` **Output:** -1 **Process:** ``` [[0,1,0,0], [0,1,0,0], [0,1,0,0], [0,0,0,0]] [[0,0,0,0], [1,1,1,0], [0,0,0,0], [0,0,0,0]] [[0,1,0,0], [0,1,0,0], [0,1,0,0], [0,0,0,0]] ``` repeating forever **Input:** ``` [[0,0,0,0], [0,0,0,1], [0,1,1,1], [0,0,1,0]] ``` **Output:** 4 **Process:** ``` [[0,0,0,0], [0,0,0,1], [0,1,1,1], [0,0,1,0]] [[0,0,0,0], [1,0,0,1], [1,1,0,1], [0,1,1,1]] [[0,1,0,0], [0,1,1,1], [0,0,0,0], [0,1,0,1]] [[0,1,0,1], [1,1,1,0], [0,1,0,1], [1,0,1,0]] [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]] ``` **Input:** ``` [[0,0,0,0], [0,1,1,0], [0,1,1,0], [0,0,0,0]] ``` **Output:** 0 **Process:** The beginning state is stable. # Rules of the Game of Life If a cell that is off (0) is next to exactly three on (1) cells, it is turned on. Otherwise, it is left off. If a cell that is on is next to 2 or 3 on squares, it says on. Otherwise, it is turned off. [Answer] ## Mathematica, ~~130~~ 129 bytes ``` #&@@FirstPosition[Partition[CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},#,2^Length[Join@@#]],2,1],{x_,x_},0,1]-1& ``` I wouldn't recommend trying more than 4x4 inputs, because it's going to take forever (and a *lot* of memory). ### Explanation This simply simulates the Game of Life for *2N* steps where *N* is the number of cells in the input. This guarantees that if the system settles into a stable state, we've reached it. Afterwards, we find the first pair of consecutive identical states in the simulated history. Let's go through the code: ``` 2^Length[Join@@#] ``` This computes *2N*, since `Join@@` is used to flatten a 2D list. ``` CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},#,...] ``` This simulates the Game of Life for *2N* generations. The 3x3 matrix specifies the neighbourhood of a totalistic 2D automaton and `224` is the rule number of standard Game of Life. I've written about how to compute this number [over here on Mathematica.SE](https://mathematica.stackexchange.com/a/111569/2305). ``` Partition[...,2,1] ``` This gets all consecutive (overlapping) pairs of generations. ``` FirstPosition[...,{x_,x_},0,1] ``` This finds the first pair of identical generations, defaulting to `0` if none is found and limiting the search to depth `1`. If such a pair *is* found, the result is returned in a list though. So we use: ``` #&@@... ``` To extract the first element from that list (the default value of `0`, being atomic, is unaffected by this). ``` ...-1 ``` Finally we subtract one because the challenge expects `0`-based indices and `-1` for failure. [Answer] ## Lua, ~~531~~ ~~509~~ ~~488~~ ~~487~~ ~~464~~ ~~424~~ ~~405~~ 404 Bytes Who wants a massive submission? \o/ **Edit: Improved it, but don't know how to golf it anymore, so... ~~explanations are coming~~ comments added :)** **Saved ~60 bytes with the help of @[KennyLau](https://codegolf.stackexchange.com/users/48934/kenny-lau)** **small golfing cutting one more byte by renaming `a` into `Y` to prevent the inlined hexadecimal conversion** ``` function f(m)c={}t=table.concat::z::c[#c+1]={}p=c[#c]Y={}for i=1,#m do k=m[i]p[#p+1]=t(k)Y[i]={}for j=1,#k do v=m[i%#m+1]l=j%#k+1w=m[(i-2)%#m+1]h=(j-2)%#k+1Y[i][j]=v[l]+k[l]+w[l]+v[h]+v[j]+w[h]+w[j]+k[h]end end s=''for i=1,#m do k=m[i]for j=1,k do x=Y[i][j]k[j]=k[j]>0 and((x<2or x>3)and 0or 1)or (x==3 and 1or 0)end s=s..t(k)end for i=1,#c do if(s==t(c[i]))then return#c>i and-1or i-1 end end goto z end ``` ### Ungolfed ``` function f(m) -- takes a 2D array of 0 and 1s as input c={} -- intialise c -> contains a copy of each generation t=table.concat -- shorthand for the concatenating function ::z:: -- label z, used to do an infinite loop c[#c+1]={} -- initialise the first copy p=c[#c] -- initialise a pointer to this copy a={} -- initialise the 2D array of adjacency for i=1,#m -- iterate over the lines of m do k=m[i] -- shorthand for the current line p[#p+1]=t(k]) -- saves the current line of m as a string a[i]={} -- initialise the array of adjacency for the current line for j=1,#k -- iterate over each row of m do -- the following statements are used to wraps at borders v=m[i%#m+1] -- wrap bottom to top l=j%#k+1 -- wrap right to left w=m[(i-2)%#m+1] -- wrap top to bottom h=(j-2)%#k+1 -- wrap left to right a[i][j]= v[l] -- living cells are 1 and deads are 0 +k[l] -- just add the values of adjacent cells +w[l] -- to know the number of alive adjacent cells +v[h] +v[j] +w[h] +w[j] +k[h] end end s='' -- s will be the representation of the current generation for i=1,#m -- iterate over each line do k=m[i] -- shorthand for the current line for j=1,#k -- iterate over each row do x=a[i][j] -- shorthand for the number of adjacent to the current cell -- the next line change the state of the current cell k[j]=k[j]>0 -- if it is alive and((x<2 -- and it has less than 2 adjacent or x>3) -- or more than 3 adjacent and 0 -- kill it or 1) -- else let it alive or -- if it is dead (x==3 -- and it has 3 adjacent and 1 -- give life to it or 0) -- else let it dead end s=s..t(k) -- save the representation of the current line end for i=1,#c -- iterate over all the generation done until now do if(s==t(c[i])) -- if the representation of the current generation then -- is equal to one we saved return#c>i -- check if it is the latest generation and-1 -- if it isn't, it means we are in a loop -> return -1 or i-1 -- if it is, we did 2 generations without changing -- -> return the number of generation end end goto z -- if we reach that point, loop back to the label z end ``` ### Test cases Here's some test cases ``` function f(m)c={}t=table.concat::z::c[#c+1]={}p=c[#c]a={}for i=1,#m do k=m[i]p[#p+1]=t(k)a[i]={}for j=1,#k do v=m[i%#m+1]l=j%#k+1w=m[(i-2)%#m+1]h=(j-2)%#k+1 a[i][j]=v[l]+k[l]+w[l]+v[h]+v[j]+w[h]+w[j]+k[h]end end s=''for i=1,#m do k=m[i]for j=1,k do x=a[i][j]k[j]=k[j]>0 and((x<2or x>3)and 0or 1)or (x==3 and 1or 0)end s=s..t(k)end for i=1,#c do if(s==t(c[i]))then return#c>i and-1or i-1 end end goto z end print(f({{0,0,0},{0,1,1},{0,1,0}})) print(f({{0,1,0,0},{0,1,0,0},{0,1,0,0},{0,0,0,0}})) -- 53 generation, 15x15, takes 50-100 ms on a bad laptop print(f({{0,0,0,0,1,1,0,1,0,0,0,0,1,0,0}, {0,1,1,0,1,1,1,1,1,1,1,0,0,0,0}, {0,1,1,1,0,1,0,1,0,0,0,0,1,0,0}, {0,0,1,0,1,1,1,0,0,1,1,1,0,1,1}, {1,1,0,0,1,1,1,0,1,1,0,0,0,1,0}, {0,0,0,0,1,1,0,1,0,0,0,0,1,0,0}, {0,1,1,0,1,1,1,1,1,1,1,0,0,0,0}, {0,1,1,1,0,1,0,1,0,0,0,0,1,0,0}, {0,0,1,0,1,1,1,0,0,1,1,1,0,1,1}, {1,1,0,0,1,1,1,0,1,1,0,0,0,1,0}, {0,0,1,0,1,1,1,0,0,1,1,1,0,1,1}, {1,1,0,0,1,1,1,0,1,1,0,0,0,1,0}, {0,0,0,0,1,1,0,1,0,0,0,0,1,0,0}, {0,0,0,0,1,1,0,1,0,0,0,0,1,0,0}, {0,1,1,0,1,1,1,1,1,1,1,0,0,0,0}})) -- Glider on a 15x14 board -- 840 distinct generation -- loop afterward -> return -1 -- takes ~4-5 seconds on the same bad laptop print(f({{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,1,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,1,0,0,0,0,0,0,0,0,0}, {0,0,0,1,1,1,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}})) ``` [Answer] # Perl, ~~154~~ ~~151~~ ~~144~~ ~~140~~ ~~137~~ ~~133~~ 129 bytes Includes +3 for `-ap0` Run with the input as a line of groups of digits separated by space ``` life.pl <<< "0000 0001 0111 0010" ``` This is only really needed in case the input is immediately stable. In all other cases you can also more conveniently give it as seperate lines of digits: ``` life.pl 0000 0001 0111 0010 ^D ``` Giving input this way would however give 1 instead of 0 for an immediately stable configuration. `life.pl`: ``` #!/usr/bin/perl -ap0 map{@f=map$F[$_%@F]x3,$i-1..++$i;s%.%"0+($&+33)=~grep\$_,map{(//g)[@--1..@+]}\@f"%eeg}@Q=@F;$_=/@Q/?keys%n:$n{$_="@Q"}--||redo ``` Almost beating Mathematica on this one... Only on older perl versions (where you could use a constant as a variable) does this 126 byte solution work: ``` #!/usr/bin/perl -p0a map{@f=map$F[$_++%@F]x2,-1..1;s%.%"0+($&+33)=~grep\$_,map{(//g)[@--1..@+]}\@f"%eeg}@Q=@F;$_=/@Q/?keys%n:$n{$_="@Q"}--||redo ``` In case there are certain to be at least 2 rows this 123 byte solution works on all perl versions: ``` #!/usr/bin/perl -p0a @F=@F[-$#F..!s%.%"0+($&+33)=~grep\$_,map{(//g,//g)[@--1..@+]}\@F[-1..1]"%eeg]for@Q=@F;$_=/@Q/?keys%n:$n{$_="@Q"}--||redo ``` [Answer] # Jelly, ~~26~~ 25 bytes ``` ṙ-r1¤SZµ⁺_|=3 ÇÐĿ-LiṪÇ$$? ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmZLXIxwqRTWsK14oG6X3w9MwrDh8OQxL8tTGnhuarDhyQkPw&input=&args=W1swLDAsMF0sCiBbMCwxLDFdLAogWzAsMSwwXV0) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmZLXIxwqRTWsK14oG6X3w9MwrDh8OQxL8tTGnhuarDhyQkPwrDh-KCrEc&input=&args=WwogIFtbMCwwLDBdLAogICBbMCwxLDFdLAogICBbMCwxLDBdXSwKCiAgW1swLDAsMSwxXSwKICAgWzAsMSwxLDFdLAogICBbMCwxLDAsMF0sCiAgIFswLDEsMSwxXV0sCgogIFtbMCwxLDAsMF0sCiAgIFswLDEsMCwwXSwKICAgWzAsMSwwLDBdLAogICBbMCwwLDAsMF1dLAoKICBbWzAsMCwwLDBdLAogICBbMCwwLDAsMV0sCiAgIFswLDEsMSwxXSwKICAgWzAsMCwxLDBdXSwKCiAgW1swLDAsMCwwXSwKICAgWzAsMSwxLDBdLAogICBbMCwxLDEsMF0sCiAgIFswLDAsMCwwXV0KXQ). Larger test cases (from [@Katenkyo's answer](https://codegolf.stackexchange.com/a/77760)): [15×15 stable](http://jelly.tryitonline.net/#code=4bmZLXIxwqRTWsK14oG6X3w9MwrDh8OQxL8tTGnhuarDhyQkPw&input=&args=W1swLDAsMCwwLDEsMSwwLDEsMCwwLDAsMCwxLDAsMF0sCiBbMCwxLDEsMCwxLDEsMSwxLDEsMSwxLDAsMCwwLDBdLAogWzAsMSwxLDEsMCwxLDAsMSwwLDAsMCwwLDEsMCwwXSwKIFswLDAsMSwwLDEsMSwxLDAsMCwxLDEsMSwwLDEsMV0sCiBbMSwxLDAsMCwxLDEsMSwwLDEsMSwwLDAsMCwxLDBdLAogWzAsMCwwLDAsMSwxLDAsMSwwLDAsMCwwLDEsMCwwXSwKIFswLDEsMSwwLDEsMSwxLDEsMSwxLDEsMCwwLDAsMF0sCiBbMCwxLDEsMSwwLDEsMCwxLDAsMCwwLDAsMSwwLDBdLAogWzAsMCwxLDAsMSwxLDEsMCwwLDEsMSwxLDAsMSwxXSwKIFsxLDEsMCwwLDEsMSwxLDAsMSwxLDAsMCwwLDEsMF0sCiBbMCwwLDEsMCwxLDEsMSwwLDAsMSwxLDEsMCwxLDFdLAogWzEsMSwwLDAsMSwxLDEsMCwxLDEsMCwwLDAsMSwwXSwKIFswLDAsMCwwLDEsMSwwLDEsMCwwLDAsMCwxLDAsMF0sCiBbMCwwLDAsMCwxLDEsMCwxLDAsMCwwLDAsMSwwLDBdLAogWzAsMSwxLDAsMSwxLDEsMSwxLDEsMSwwLDAsMCwwXV0) | [15×14 glider](http://jelly.tryitonline.net/#code=4bmZLXIxwqRTWsK14oG6X3w9MwrDh8OQxL8tTGnhuarDhyQkPw&input=&args=W1swLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMF0sCiBbMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDBdLAogWzAsMCwwLDAsMSwwLDAsMCwwLDAsMCwwLDAsMCwwXSwKIFswLDAsMCwwLDAsMSwwLDAsMCwwLDAsMCwwLDAsMF0sCiBbMCwwLDAsMSwxLDEsMCwwLDAsMCwwLDAsMCwwLDBdLAogWzAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwXSwKIFswLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMF0sCiBbMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDBdLAogWzAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwXSwKIFswLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMF0sCiBbMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDBdLAogWzAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwXSwKIFswLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMF0sCiBbMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDBdXQ) ### How it works ``` ṙ-r1¤SZµ⁺_|=3 Helper link. Argument: G (grid) This link computes the next state of G. ¤ Evaluate the three links to the left as a niladic chain. - Yield -1. 1 Yield 1. r Range; yield [-1, 0, 1]. ṛ Rotate the rows of G -1, 0 and 1 units up. S Compute the sum of the three resulting grids. Essentially, this adds the rows directly above and below each given row to that row. Z Zip; transpose rows and columns. µ Convert the preceding chain into a link and begin a new chain. ⁺ Apply the preceding chain once more. This zips back and adds the surrounding columns to each column. _ Subtract G from the result. Each cell now contains the number of lit cells that surround it. | That the bitwise OR of the result and G. Notably, 3|0 = 3|1 = 2|1 = 3. =3 Compare each resulting number with 3. ÇÐĿ-LiṪÇ$$? Main link. Argument: G (grid) ÇÐL Repeatedly apply the helper link until the results are no longer unique. Collect all unique results in a list. $ Evaluate the two links to the left as a monadic chain: $ Evaluate the two links to the left as a monadic chain: Ṫ Pop the last element of the list of grids. Ç Apply the helper link to get the next iteration. i Get the index of the grid to the right (the first non-unique one) in the popped list of grids. This yields 0 iff the popped list doesn't contain that grid, i.e., the grid reached a stable state. ? If the index is non-zero: - Return -1. L Else, return the length of the popped list of grids. ``` [Answer] # Julia, ~~92~~ 88 bytes ``` f(x,r...)=x∈r?(r[k=end]==x)k-1:f(sum(i->circshift(x,[i÷3,i%3]-1),0:8)-x|x.==3,r...,x) ``` ### Verification ``` julia> f(x,r...)=x∈r?(r[k=end]==x)k-1:f(sum(i->circshift(x,[i÷3,i%3]-1),0:8)-x|x.==3,r...,x) f (generic function with 1 method) julia> f([0 0 0;0 1 1;0 1 0]) 2 julia> f([0 0 1 1;0 1 1 1;0 1 0 0;0 1 1 1]) 2 julia> f([0 1 0 0;0 1 0 0;0 1 0 0;0 0 0 0]) -1 julia> f([0 0 0 0;0 0 0 1;0 1 1 1;0 0 1 0]) 4 julia> f([0 0 0 0;0 1 1 0;0 1 1 0;0 0 0 0]) 0 julia> f([0 0 0 0 1 1 0 1 0 0 0 0 1 0 0;0 1 1 0 1 1 1 1 1 1 1 0 0 0 0;0 1 1 1 0 1 0 1 0 0 0 0 1 0 0;0 0 1 0 1 1 1 0 0 1 1 1 0 1 1;1 1 0 0 1 1 1 0 1 1 0 0 0 1 0;0 0 0 0 1 1 0 1 0 0 0 0 1 0 0;0 1 1 0 1 1 1 1 1 1 1 0 0 0 0;0 1 1 1 0 1 0 1 0 0 0 0 1 0 0;0 0 1 0 1 1 1 0 0 1 1 1 0 1 1;1 1 0 0 1 1 1 0 1 1 0 0 0 1 0;0 0 1 0 1 1 1 0 0 1 1 1 0 1 1;1 1 0 0 1 1 1 0 1 1 0 0 0 1 0;0 0 0 0 1 1 0 1 0 0 0 0 1 0 0;0 0 0 0 1 1 0 1 0 0 0 0 1 0 0;0 1 1 0 1 1 1 1 1 1 1 0 0 0 0]) 53 julia> f([0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 1 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 1 0 0 0 0 0 0 0 0 0;0 0 0 1 1 1 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]) -1 ``` [Answer] # ruby, 207 bytes ``` ->a{r=[];(r<<a;a=(0...a.size).map{|i|(0...a[i].size).map{|j|n=0;(-1..1).map{|u|(-1..1).map{|v|n+=a[(i+u)%a.size][(j+v)%a[i].size]}};[n==3,n>2&&n<5][a[i][j]]?1:0}})while(!r.index(a));(a==r[-1])?r.index(a):-1} ``` I keep a history of each board, so if I get a board I have seen before I know one of two thing happened. first it could be that we have found a stable position, in which case it will be the most resent in our history. the other possibility is that we have a loop. [Answer] # Python 3.8, 268 262 260 bytes Had fun w a little convolution. Code stores prev generations as byte array. Cuts off at 1000 iterations for the sake of not chasing an infinite starting matrix, but can be easily changed to any number of iterations or removed. note: There's a deprecation for scipy arrays coming in scipy 2.0.0 so this only works on previous versions. ``` import scipy as s def g(b,n=0,L=[0]): if n>1e3:return-1 b=s.array(b);j=b.tobytes() if j==L[-1]:return n-1 if j in L: return-1 L+=[j];f=[[1]*3]*3;f[1][1]=0 x=s.ndimage.convolve(b,f,mode='wrap') b[x<2]=0;b[x>3]=0;b[x==3]=1 n=g(b,n+1,L) return n ``` I'm sure there's more to shave off, please lmk! [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~275~~ ~~213~~ ~~206~~ 202 bytes Implementation. Saved 73 bytes thanks to the comment of @ceilingcat --- Golfed version. [Try it online!](https://tio.run/##5VHNaoQwEL73KXIqCY2Q7N4c5knEw7JGiNRoN1pU@u42xrrG1qU/UCiUIc6M389MSHVuTs9qHPPWnBtdGWIxpx2DGpMU8uriehFLdQSdE23VU3t6pB2vGUSRhYtq2osBZTJISm5StHpQtMcancMk1ijj0leFqwwM2FHNCwYWbVvSjpZVRnV0iDUv2YPkU1u4tuDGtYzGjEUD9F6DFvFwPyDKF1cd/dTpdNj7bDGSUzFm2tY0p4kgLkAQSaT/ipSxuxBcgCthoRO5pa7QNvt477pCofvuAuvAMN9ynQnz8Lc@MJgnXWNrv@g@akWgFSRkS9j5t6rh7271Wzf68X33HnM34Guo/EQrb6Kbtb4995@g7rnGVw) ``` function s=f(x);p=[];for s=0:1e3;if isequal(x,p);--s;return;end;[m,n]=size(y=p=x);for i=1:m;for j=1:n;z=x(i,j);s=sum(x(mod(i-2:i,m)+1,mod(j-2:j,n)+1)(:))-z;y(i,j)=s==2&z==1|s==3;end;end;x=y;end;s=-1;end ``` Ungolfed version. [Try it online!](https://tio.run/##5VLbjpswEH3PV8zLSqBNJNi@BeVLogg5MASnYFNsUrraf09nwNy2RN2tVKlSZclmfOacMzNGJ1bc8H7PGpVYqRUYi5WBA2Re628AStHG0mItGOT7MAiCCOAJDFoQjEMhS2nBauLqCqTKpCIKFFpXhiSqGm9xS9TjKaIw0/VoEuyX@gQDyAykwW@NKLx269h@h0BPPHT7LozcZY22qRV0Eaq0O0fTts/iT4WtjS@onBs1yFjPGCoiVW4ulSkobUlaJDm1aaw4F8gHNfZd2lyqd6PZsM5mHOOPVT8yOpZbUCdCjXxFVwInv2KtjcegP0xJ8rj3ZVc/x9cuVq7rJ0h0o2juOYJqyjPWoDN6ixuFKC/5WddmC1Z8lepCj0LPI5KJYXXdGDC5qNDpjSQemlfq1JO7l73cQuk/h7TTxZUurlzhc@gPwyfrmE3jOd80pTfG3t73YUeapHUdefTK7gYO1Bb3Q1dcWoJFQX8ACJZ12TSjIXnV8QAv8Pb2APoyeGJhcMUoRZF@2GcSc39af/Le/QGbTSpN5WXeMQBaUUC9hd0enHx/AQ7AmDCkQ7hMnaDl2a33qhM0V18tYDKcn49U@4Te3MUzgd5pXEv5gfcrN5hxA5hnh9HK3cSO/t2q/lZHf9zv2mOuruhjaPgbbvgQXZT1ad//BKXnut9/Ag) ``` function steps = f(x) max_iterations = 1000; % set a max limit to stop infinite loops prev_x = []; for steps = 0:max_iterations if isequal(x, prev_x) steps=steps-1; return end prev_x = x; x = next_generation(x); end steps = -1; % did not reach a stable state within max_iterations end function y = next_generation(x) [m, n] = size(x); y = zeros(m, n); for i = 1:m for j = 1:n % count the number of live neighbors, taking into account the torus shape neighbors = x(mod(i-2:i, m)+1, mod(j-2:j, n)+1); num_live_neighbors = sum(neighbors(:)) - x(i, j); if x(i, j) == 1 % if the cell is alive y(i, j) = num_live_neighbors == 2 || num_live_neighbors == 3; else % if the cell is dead y(i, j) = num_live_neighbors == 3; end end end end disp(f([0 0 0;0 1 1;0 1 0])) disp(f([0 0 1 1;0 1 1 1;0 1 0 0;0 1 1 1])) disp(f([0 1 0 0;0 1 0 0;0 1 0 0;0 0 0 0])) disp(f([0 0 0 0;0 0 0 1;0 1 1 1;0 0 1 0])) disp(f([0 0 0 0;0 1 1 0;0 1 1 0;0 0 0 0])) disp(f([0 0 0 0 1 1 0 1 0 0 0 0 1 0 0;0 1 1 0 1 1 1 1 1 1 1 0 0 0 0;0 1 1 1 0 1 0 1 0 0 0 0 1 0 0;0 0 1 0 1 1 1 0 0 1 1 1 0 1 1;1 1 0 0 1 1 1 0 1 1 0 0 0 1 0;0 0 0 0 1 1 0 1 0 0 0 0 1 0 0;0 1 1 0 1 1 1 1 1 1 1 0 0 0 0;0 1 1 1 0 1 0 1 0 0 0 0 1 0 0;0 0 1 0 1 1 1 0 0 1 1 1 0 1 1;1 1 0 0 1 1 1 0 1 1 0 0 0 1 0;0 0 1 0 1 1 1 0 0 1 1 1 0 1 1;1 1 0 0 1 1 1 0 1 1 0 0 0 1 0;0 0 0 0 1 1 0 1 0 0 0 0 1 0 0;0 0 0 0 1 1 0 1 0 0 0 0 1 0 0;0 1 1 0 1 1 1 1 1 1 1 0 0 0 0])) disp(f([0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 1 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 1 0 0 0 0 0 0 0 0 0;0 0 0 1 1 1 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0])) ``` ]
[Question] [ Sometimes when I'm bored, I take some text and fill the "holes" in the letters. But isn't filling the holes the most boring thing you can do? I think we should [automate it](http://xkcd.com/1319/), so we could use our time better. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. # Input A string containing sequence of alphanumeric characters (a-z, A-Z, 0-9) and spaces. # Output Image containing string rendered and holes on it filled. You can use any human readable font as long as it still requires filling the holes. You can either save image to file `i.png` (in png format) or just display the image. Image properties: * Black text * White or transparent background * Padding: + The dimensions of the image can be maximum two times the dimensions of the text + Padding should be same color as background, either white or transparent # Example Input: `Example text` Output: [![Example output](https://i.stack.imgur.com/cR6rO.png)](https://i.stack.imgur.com/cR6rO.png) [Answer] ## Bash, 135 bytes ``` convert +antialias -pointsize 99 label:$1 -fill red -draw 'color 0,0 floodfill' -fill black -opaque white -fill white -opaque red i.png ``` Uses ImageMagick (`convert`). Sample output: ![sample](https://i.stack.imgur.com/ZyDQt.png) ``` convert +antialias # disable antialiasing -pointsize 99 # annoyingly necessary (see below) label:$1 # draw input text -fill red -draw 'color 0,0 floodfill' # flood fill from (0,0) with red -fill black -opaque white # replace all white with black -fill white -opaque red # replace all red with white i.png ``` Disabling antialiasing is required because otherwise antialiased interior parts of the letters wouldn't flood fill. Setting the font to a large size is also required because some fonts have "gaps" in letters that should have "holes" in them at small font sizes (in my tests, the `a` wasn't filled at the default small font size). [Answer] ## Mathematica, 83 bytes ``` ImageSubtract[s=Binarize@Rasterize@Style[#,FontSize->99],DeleteBorderComponents@s]& ``` [![enter image description here](https://i.stack.imgur.com/M92kp.png)](https://i.stack.imgur.com/M92kp.png) An unnamed function that takes a string as input and returns an image object. The idea is to use `DeleteBorderComponents` to keep *only* the holes and then subtract those from the original image. [Answer] # SmileBASIC, 38 bytes ``` ??INPUT S$GPUTCHR.,2,S$,2,2,8GPAINT.,0 ``` Draws black\* text on the black background, then uses the built in "paint bucket" function to fill everything outside the text with white. \*(actually I used `00000008`, which looks identical to transparent, but is treated as a different color) [![enter image description here](https://i.stack.imgur.com/L8NSW.jpg)](https://i.stack.imgur.com/L8NSW.jpg) [Answer] Eats away at the text a bit, but there's also a canvas-based solution: ## JS, 610 bytes ``` function o(a,b){return a[b]+a[b+1]+a[b+2]}x=prompt();l=x.length;c=document.createElement("canvas");document.body.appendChild(c);h=33;w=18*l;c.height=h;c.width=w;n=255;m=764;t=c.getContext("2d");t.fillStyle="white";t.fillRect(0,0,w,h);t.fillStyle="red";t.fillRect(0,2,w,h);t.font="900 30px Courier";t.fillStyle="black";t.fillText(x,0,25);d=t.getImageData(0,0,w,h);f=0;q=d.data.length;for(i=0;i<20;i++){for(j=0;j<q;j+=4){f=d.data;if(o(f,j)>0&&(o(f,j-w*4)>m||o(f,j+w*4)>m||o(f,j-4)>m||o(f,j+4)>m)){f[j]=n;f[j+1]=n;f[j+2]=n}}}for(k=0;k<q;k+=4){f=d.data;if(f[k+1]<1){f[k]=0;f[k+1]=0;f[k+2]=0}}t.putImageData(d,0,0) ``` [![enter image description here](https://i.stack.imgur.com/LjtMM.png)](https://i.stack.imgur.com/LjtMM.png) [Answer] ## Postscript 273 [was originally posted to the [related challenge](https://codegolf.stackexchange.com/q/34742/2381), but I never implemented the counting.] Renders each character normally, to get the correct spacing to advance, then takes all the curves which describe the glyph and fills each one. Normally the interior and exterior curves are described with different orientations, so a fill will leave the interior empty, regardless of whether it's using the non-zero winding rule or even-odd rule. Filling separately, it all gets filled. ``` /Courier 9 selectfont 9 9 moveto{( ) dup 0 4 3 roll put currentpoint 3 2 roll dup show currentpoint 3 2 roll 5 3 roll moveto true charpath[[{/moveto cvx}{/lineto cvx}{/curveto cvx}{/closepath cvx]cvx[}pathforall pop]]{exec currentpoint fill moveto}forall pop moveto}forall ``` Indented: ``` /Courier 9 selectfont 9 9 moveto { ( ) dup 0 4 3 roll put currentpoint 3 2 roll dup show currentpoint 3 2 roll 5 3 roll moveto true charpath [ [{/moveto cvx}{/lineto cvx}{/curveto cvx}{/closepath cvx]cvx[} pathforall pop] ] { exec currentpoint fill moveto } forall pop moveto } forall ``` Usage. String object is expected to be on the stack when the program starts. Extra scaling just to make it visible. ``` $ gs -c '7 7 scale(Example Text)' -f courier.ps ``` ![snip from output](https://i.stack.imgur.com/W4NQ9.png) ]
[Question] [ Write a [Manufactoria](http://pleasingfungus.com/Manufactoria/) program that will accept the empty input tape. But don't do it quickly! I mean, write the program quickly, but don't let it run quickly. The slower the program, the better, as long as it terminates eventually. The example program below takes 3:51 (the "total time" reported by the simulator). ![enter image description here](https://i.stack.imgur.com/7RDeH.png) <http://pleasingfungus.com/Manufactoria/?lvl=36&code=g12:5f3;r9:8f1;p12:9f3;c13:9f0;r11:9f0;r10:9f0;r9:9f1;b11:8f0;b10:8f1;r9:7f2;c10:7f2;c11:7f2;c12:7f3;q12:8f3;y13:8f2;y14:8f2;y15:8f1;y15:7f0;y14:7f0;y13:7f0;g12:6f3;&ctm=Slow_Accepter!;Generate_the_slowest_possible_accepting_machine;:;7;3;0>; Your program starts with the empty tape. It must doodle around a bit, but eventually reach the output square. You may leave data on the tape if you wish. The slowest program on the 7x7 Manufactoria board wins! Your right arrow key is your friend, it speeds up the simulator. Bonus points for crashing the simulator! [Answer] ## ~1023 iterations ~~~1015 iterations~~ ~~~108 iterations~~ ![Manufactoria setup](https://i.stack.imgur.com/C0Rbz.png) <http://pleasingfungus.com/Manufactoria/?lvl=32&code=g9:7f2;b12:8f2;p13:8f5;p11:8f3;r14:8f0;q11:10f3;q13:7f1;y13:9f1;r10:10f1;c12:9f2;c9:9f2;i11:9f7;i10:9f4;c9:8f3;i10:8f2;c14:9f0;c15:9f0;c15:8f3;c15:7f3;c14:7f2;g12:7f0;c11:7f3;c10:7f2;q9:6f7;r10:6f1;r9:5f3;c11:6f0;r10:5f2;r11:5f1;r9:4f3;r10:4f0;r11:4f0;y12:5f2;y13:5f2;y14:5f3;y14:6f0;y13:6f0;y12:6f0;&ctm=Slow_Accepter!;Generate_the_slowest_possible_accepting_machine;:;7;3;0>; The machine is basically an odometer running in base three, using the red, blue and yellow symbols to stand for the digits 0, 1, and 2 respectively. The green symbol is used to mark the end of the number. At the start, the tape is initialized with 49 red symbols. This is done by the parts in the top three rows of the machine. The bottom four rows handle the task of incrementing the number in a loop. On each iteration, the two branch cells on left-hand side work out how to apply the increment to current number, and then the branch cells on the right-hand side copy the remaining, unaffected digits. Previously I've tried to estimate the machine's running time, were it allowed to run to completion, but at this level it makes more sense to just go by the number of iterations. Roughly speaking, it takes about a minute to complete one iteration -- but even if it took a second that would only decrease the running time by a single order of magnitude. [Answer] ## 603:25 ![](https://i.stack.imgur.com/VSfq6.jpg) [Online test](http://pleasingfungus.com/Manufactoria/?lvl=32&code=g12:5f2;g13:5f1;g13:4f2;g14:4f2;g15:4f3;g15:5f0;g14:5f3;g14:6f2;g15:6f3;c15:7f3;c15:8f0;c14:8f3;c14:9f2;c15:9f3;c15:10f0;c14:10f0;c13:10f1;c13:9f1;c13:8f1;i13:7f3;c13:6f0;c12:6f0;q10:6f4;y10:5f0;y9:5f1;y9:4f2;y10:4f2;y11:4f3;y11:5f3;r10:7f2;c12:7f2;c14:7f2;i11:6f1;c9:6f3;c9:7f3;c9:8f3;c9:9f2;p10:9f2;b10:8f2;y10:10f0;c9:10f1;q11:9f7;c11:10f2;c12:9f1;c11:7f3;c11:8f2;c12:8f1;&ctm=Slow_Accepter!;Generate_the_slowest_possible_accepting_machine;:;7;3;0;) I was re-reading through the Manufactoria questions today, and suddenly had an idea which would dramatically slow down the process: instead of just having 50 values and changing colours 3 times, the new program does that, but then after that, it decrements the number of values by 1, and goes through the colour-changing again, until there is an empty tape at which time the program stops. The queue won't store any more than 50 values at one time, so there's no use trying to push too many values onto the tape - they just get pushed off straight away. As before, the conveyor belts aim to maximise the time taken for the thing to run. In fact, there was minimal tweaking down to achieve a tremendous increase in run-time. Still nowhere near [breadbox's answer](https://codegolf.stackexchange.com/a/12069/7911) though. [Answer] # 33:33 Worked on this for quite a while ([Volatility](https://codegolf.stackexchange.com/a/12048/1700) set the bar pretty high), but once I hit 33:33, I thought it was a neat time to stop at. The strategy is pretty blunt: basically fill up the tape with one colour, then another, then another, and always try to traverse as many cells as possible between each write (or group of writes). I'm sure there are ways to be found that we can go a lot further with this. ![Busy Beaver](https://i.stack.imgur.com/3zVsq.png) [Level link](http://pleasingfungus.com/Manufactoria/?lvl=37&code=b15:5f3;b15:6f3;b15:7f3;c14:9f1;c14:8f1;c14:7f1;c14:6f0;c13:6f0;c12:6f0;c11:6f0;p10:6f0;r10:5f2;r11:5f1;r11:4f0;r10:4f0;r9:5f3;c9:6f3;c9:7f3;c9:8f2;i10:8f7;i12:8f7;c13:10f2;y10:7f3;y10:10f0;c9:10f1;c9:9f1;q11:8f6;r9:4f3;p12:7f2;b13:7f3;c11:7f2;b15:4f3;c13:8f3;c13:9f3;g12:9f0;i10:9f1;i11:9f1;c11:10f2;b14:4f2;b13:4f2;b13:5f1;b12:5f2;c15:10f1;c15:9f0;b15:8f0;c14:10f2;&ctm=Code_Golf;Busy_Beaver;:*;7;3;0;) [Answer] # 3^49\*c in 5x5 ``` ?lvl=33&code=c10:7f2;c10:8f1;r10:9f2;i11:7f7;p11:8f3;q11:9f5;r12:6f0;y12:7f2;b12:8f2;r13:6f0;q13:7f3;p13:8f5;r13:9f1;r14:7f1;r14:8f3;r14:9f0;r14:6f1;r14:5f0;r13:5f3;i11:6f6;c10:6f1;c10:5f2;g11:5f3;&ctm=Long_Runtime;Level_description!;:*;5;3;0; ``` [![enter image description here](https://i.stack.imgur.com/xOFLr.png)](https://i.stack.imgur.com/xOFLr.png) * Red = 0 * Blue = 1 * Yellow = 2 * After a few cycles, tape is full and, erasing one red add at most one red, the red path(right-up) do nop * Left-top circle only add some cycles ]
[Question] [ Good Evening Golfers! Your challenge is to completely unsort a series of numbers. # Input Exactly 100 integers will be fed to your program. Your program may accept the input either as a file, or via stdin. Each integer will be separated by a newline character. Those 100 integers will range from the minimal to the maximal values of a signed integer in your chosen language. There will be no duplicate values. The values may be ordered, unordered or partially ordered - your program should be able to handle each case. # Output The output must be each of the 100 integers, completely unsorted, each separated by a newline character. The output may be via stdout, or to a file. *Completely Unsorted* means that no value is adjacent to any value which it would be adjacent to if the list were completely sorted in an ordered sequence. # Score 1 point per character, and lowest score wins. There is a bonus of -100 for any solution using no built in or library sorting functions. There is a bonus of -20 for any solutions using no built in random number functions. I have tried to define this question as completely as possible. If you have any questions, please ask. If you have any comments on how I could do better next time, please let me know. Fore! [Answer] ## GolfScript (score 27 - 120 = -93) ``` ~].,{{.2$<{\}*}*]}*.(;+2%n* ``` Note: that `$` is referencing an element on the stack. There is sorting, but it's done with an manually coded bubble sort. Thanks to Howard, for -90 => -92; and Ilmari, who inspired -92 => -93. [Answer] # Python -26 (94-120): New, crude approach. Keep popping lowest elements into new list to get the elements sorted, then iterate: ``` t=l=[] i=N=100 exec't=t+[input()];'*N+'l+=[t.pop(t.index(min(t)))];'*N+'print l[i%N];i+=3;'*N ``` # Python -13 (107-120): First approach: Removes four lowest elements at a time, then print these four in another order: ``` exec'l=[]'+'+[input()]'*100 while l: a,b,c,d=eval('l.pop(l.index(min(l))),'*4) for e in[b,d,a,c]:print e ``` [Answer] # C: 11 (131 - 120) The programm reads from stdin and does a simple insert sort, after that it prints the nth together with th n+50th number, like many of the other solutions. ``` main(){int*i,a[101],*j=a;while(scanf("%d",a)>0)for(i=++j;i-->a;)i[1]=*i>=*a?*i:*(i=a);while(a<(i=j-50))printf("%d\n%d\n",*i,*j--);} ``` [Answer] # Mathematica -56 44 4 (95-120) = -25 **Edit**: This version relies on neither built-in functions for sorting lists, nor randomization functions. ``` Riffle[RotateLeft[#[[All, 2]], 2], #[[All, 1]]] & [Partition[l //. {x___, a_, b_, y___} /; b < a :> {x, b, a, y}, 2]] ``` [Answer] ## J, -63 (57-120) characters Since everyone else is going down the self-written sort route... ``` ,50(}.,.{.)($:@([-.m),~m=.]#~]=<./)^:(0<#),".[;._2[1!:1[3 ``` Doesn't use any random number function, nor any built-in sort. Uses a simple recursive selection sort to sort the input. [Answer] # Ruby 1.9, -59 ### (61-120) Recursion! This one does in fact, unlike my previous Ruby attempts, unsort the list regardless of their original order. ``` p *(f=->l{l[1]&&f[l-m=l.minmax]+m||[]})[$<.map &:to_i].rotate ``` ### Previous attempts Cute one-liner, now using builtin sort to work properly: ``` $<.map(&:to_i).sort.each_slice(4){|a,b,c,d|p b,d,a,c} ``` First one -- Didn't necessarily unsort the last 4 values: ``` l=$<.map &:to_i 48.times{l-=p *l.minmax} a,b,c,d=l p b,d,a,c ``` [Answer] ## Python 2: 90 char ``` n=100 s=sorted(int(raw_input())for i in range(n)) for i in range(n):print s[(4*i+4*i/n)%n] ``` lazy attempt but just for starters [Answer] # Python 48 = (148 - 100) ``` from random import* x=[input()for i in range(100)] while any(abs(x[i]-x[i+1])>1 for i in range(99)):n=randint(1,99);x=x[n:]+x[:n] for j in x:print j ``` Haven't tested this because it isn't guaranteed (or likely) to run in any reasonable amount of time, but should work in theory given infinite time. [Answer] # Python 27 (147 - 100 - 20) ``` R=range def S(L): for i in R(len(L)-1): if L[i]>L[i+1]:L[i:i+2]=[L[i+1],L[i]];S(L) a=map(input,['']*100);S(a) for i in R(100):print a[i/2+i%2*50] ``` Note: the spaces before `if L[i]>...` should be a tab but apparently show up as spaces in a code block. [Answer] # Perl 5: 95 - 120 = -25 chars Counting the following command line: ``` perl -ne '$n=$_;splice@n,(grep{$n[$_]>$n}0..@n),0,$n}{print for map{@n[$_,$#n/2+$_+1]}0..$#n/2' ``` [Answer] # Ruby: -50 (70 chars - 120) I did the same as many other answers: iteratively remove the max and min from the input list and append them to the output. However, I realized that if the 2 numbers on either side of the median are themselves consecutive, the output will be incorrect (because those 2 consecutive numbers will appear together at the end of the output). To fix this, I rotate the "unsorted" list right by 1 element: ``` n=$*.map &:to_i;u=[];50.times{u+=n.minmax;n-=u.last 2};p *u.rotate(-1) ``` Or, to work with arbitrarily many inputs (using only 4 more characters): ``` n=$*.map &:to_i;u=[];(u+=n.minmax;n-=u.last 2)while n.any?;p *u.rotate(-1) ``` *Note: Some fewer-char Ruby answers have already been posted, but those solutions did not address the median issue (and/or assumed a sorted input list).* [Answer] ## J 37 - 100 = -63 ``` ({~?~@#)^:(+./@(1=|)@(2&(-/\))@/:)^:_ ``` Uses no sort (though does use rank up) Uses random numbers. Explanation: ``` ({~?~@#) NB. Randomizes the array ^: foobar ^:_ NB. as long as foo =: +./@(1 = |) NB. as any 1 == absolute value of bar =: (2&(-/\))@/: NB. differences between adjacent ranks foobar =: foo@bar ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 22 bytes - 120 = -98 ``` ṇịᵐpX¬{p≤₁s₂.&s₂p}∧Xẉᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO9oe7ux9unVAQcWhNdcGjziWPmhqLHzU16amByILaRx3LIx7u6gSq@P9fyZDLgMuIy5jLgsuMy9KAy9BUCQA "Brachylog – Try It Online") The TIO link only has an input of eight integers, rather than one hundred, because this is so dreadfully slow that it can't handle any more in 60 seconds. The reason for this is that, among other things, rather than implement some simple but normal sorting algorithm for the mandatory bonus, I for the sake of brevity used what amounts to a deterministic bogosort: `p≤₁` backtracks through every permutation of the input until it finds one which is non-decreasing. Although a larger reason would probably be that it employs a similar degree of brute force to find the output, and that it recomputes the sorted version every time... I attempted to test it on an actual input of size 100, but I'm not sure just how many days it will take. An overall better version: # [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes - 20 = -6 ``` p.¬{os₂.&s₂p}∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bG8v8FeofWVOcXP2pq0lMDkQW1jzqW//8fbahjpGOsY2KkY6JjqmOmY6ATb2gaCwA "Brachylog – Try It Online") This ignores the antiquated I/O requirements for brevity, and neglects to take the -100 bonus so it can possibly be tested without a supercomputer (although as of writing this, I've had it running on only 20 items for several minutes and it still hasn't given me anything). ``` . The output is p a permutation of the input ¬{ }∧ such that it cannot be proven that s₂ a pair of adjacent values in & the output . p is a permutation of s₂ a pair of adjacent values in o the output sorted. ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 79 - 120 = -21 bytes ``` : f 100 0 do dup i 2 mod 4 * 2 - i + i 99 = i 0 = - 3 * + cells + @ . cr loop ; ``` [Try it online!](https://tio.run/##hVHLasMwELznK6bXBhf3cUlKoNCP6MUXYa1sgawV0qqB/ry7sdqQU7sC7SKNZmZXjrPM3eQuaV2PcHjse/SwDFsTvK4nLGzxgnutOuz15HDASVOve4dnvdhjpBCK5jc8YMwIzAmv65jJCEGoyMbbUCYEFtzGgPeGNIhmIQtjbaai0GhRSGCKt4SSzEhQrxuZj0IT5bI7Yrp1/GvFo5xNwt2PmYvKB2cLYTgfgmo1PnZaTv6TIor/Ipy9zFdyuMyLsuujuLv2MeHPGJqAzIQ2AdukGoHDvzGgxqJfsvXPVVIV6DxqkPUb "Forth (gforth) – Try It Online") Ignore antiquated input requirements and takes input as an address in memory where the numbers are stored. ### Explanation Loops through all numbers from 0 to 99. For each number (n): * If n is 0: + output the value at array address + 1 * Else If n is 99: + output the value at array address + 98 * Else If n is odd: + output the value at array address + (n + 2) * Else (n is even): + output the value at array address + (n - 2) * Output a newline ### Code Explanation ``` : f \ start new word definition 100 0 do \ loop from 0 to 99 dup \ duplicate the array address i \ place the loop index on the stack 2 mod 4 * 2 - \ convert to 2 if it's odd and -2 if it's even i + \ add the result to the the loop index i 99 = \ if i = 99 place -1 on top of the stack, else place a 0 i 0 = \ i i = 0 place -1 on top of the stack, else place 0 - 3 * \ subtract previous two results from each other and multiply by 3 \ the above line is used to avoid writing if/then by instead using math to get 98 and 1 + \ add result to existing result from above cells \ multiply by the size of a single integer in memory + \ add to the array's starting address @ . cr \ get the value at the calculated address, print it, then print a newline loop \ end the loop ; \ end the word definition ``` ]
[Question] [ In the hovertext of [this xkcd](https://xkcd.com/2637/): ![100he100k out th1s 1nno5at4e str1ng en100o501ng 15e been 500e5e50op1ng! 1t's 6rtua100y perfe100t! ...hang on, what's a "virtuacy"?](https://imgs.xkcd.com/comics/roman_numerals.png "100he100k out th1s 1nno5at4e str1ng en100o501ng 15e been 500e5e50op1ng! 1t's 6rtua100y perfe100t! ...hang on, what's a \"virtuacy\"?") There's an "encoding" based on replacing runs of roman numerals with their sums. To do this: * Find all runs of at least 1 roman numeral (`IVXLCDM`) * Replace them with their sums, as numbers The Roman Numerals are `IVXLCDM`, corresponding respectively to `1, 5, 10, 50, 100, 500, 1000`. You should match them in either case. For example, if we take `encoding`, `c` is the roman numeral 100, so it gets replaced with 100, leaving `en100oding`. Then, `di` are both roman numerals, respectively 500 and 1, so it gets replaced with their sum, 501, leaving `en100o501ng`. Your challenge is to implement this, given a string. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! Note: the xkcd implements some more complex rules regarding consecutive characters like `iv`. This can create some ambiguities so I'm going with this simpler version. ## Testcases ``` xkcd -> 10k600 encodingish -> en100o501ng1sh Hello, World! -> He100o, Wor550! Potatoes are green -> Potatoes are green Divide -> 1007e bacillicidic -> ba904 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 9 bytes ``` ƛøṘ∨;⁽-ḊṠ ``` [Try it online](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwixpvDuOG5mOKIqDvigb0t4biK4bmgIiwiIiwiSGVsbG8sIFdvcmxkISJd) or [run a test suite](https://vyxal.pythonanywhere.com/#WyJhaiIsIsabIiwixpvDuOG5mOKIqDvigb0t4biK4bmgIiwi4oiRXCJgID0+IGBqIiwieGtjZFxuZW5jb2Rpbmdpc2hcbkhlbGxvLCBXb3JsZCFcblBvdGF0b2VzIGFyZSBncmVlblxuRGl2aWRlXG5iYWNpbGxpY2lkaWMiXQ==). ``` ƛøṘ∨;⁽-ḊṠ ƛ # Map, and for each character: øṘ # Convert from roman numeral to a number, or 0 if invalid ∨ # Logical OR with the character: if it's 0, then use the character instead ; # Close map Ḋ # Group results where the same result appears consecutively... ⁽- # ...with subtracting it by itself. Subtracting a number by itself is 0, # but subtracting a string by itself is "". These are two different values, so it works as a type check. Ṡ # Sum each. Summing a list of characters will turn it into a string, but lists of numbers will simply sum. # The s flag joins the list together into a string before outputting. ``` [Answer] # [Factor](https://factorcode.org/) + `grouping.extras math.unicode roman`, ~~100~~ 99 bytes ``` [ 1 group [ [ roman> ] try ] map [ real? ] group-by values [ [ Σ >dec ] try ] map flatten concat ] ``` Needs modern Factor for [>dec](https://docs.factorcode.org/content/word-__gt__dec,math.parser.html). Here's a version that runs on TIO for 3 more bytes, though: [Try it online!](https://tio.run/##bZJRb9QwDMff@yl8fWa9duJuu00aL5MYEkKIgXiYeHATt42ai0uSjqsQn4bvw1e6Oa00boK0al3793dcxw2qyP745f7dh7dX0HoeB@PaZ6OgQ/QYAENgFSDQ95GcogCe9@hgj7EDTfXYtuShJ@/IwuApxmnwxsVkB5K34b/aQhMNs7QYnVGsCa6z7GcGsvJDr3QOL9cKzm6gKvttWS6QpGEt1ZnQ5S8gclVZ8qasXFuFboHvyFp@BV/ZW73KT@A7SvAc2WzK1UJ/5IiR5QfRk3SByOUL/W9gEdyaR6Mp/1/B5QUtTI3KWGuU0Ublp0yNu/J19is7PkC19Bwe5JqbewPfIPpJnntMbk9o38jXjJ3VEzyiHaWeJPjz@7nTp6LGYozkQLFTKKFjcjoLBShL6LNsBfdE0MU4hKv1Oh1Fy7YpQkTV00F16FoqFO/XuD4/Ly8vt@vdxa7aQsMefnQTCOg0ep3Ot5MxqaUtkAamIw1SouSgIRqWSaEQsE3tc3qWxs4EkJt7nAop5PP769tPknBsmuSexyclGaOgBDzGQcwkkB14AG5mv8aIMNcL2EQZwuRsRqfmXQVXaC3p4vgE "Factor – Try It Online") #### How? This answer relies on `try` in order to process heterogeneous arrays relatively succinctly, as `roman>` blows up on non- roman numbers and `sum` blows up on arrays of strings. ``` ! "encodingish" 1 group ! { "e" "n" "c" "o" "d" "i" "n" "g" "i" "s" "h" } [ [ roman> ] try ] map ! { "e" "n" 100 "o" 500 1 "n" "g" 1 "s" "h" } [ real? ] group-by values ! { V{ "e" "n" } V{ 100 } V{ "o" } V{ 500 1 } V{ "n" "g" } V{ 1 } V{ "s" "h" } } [ [ Σ >dec ] try ] map ! { V{ "e" "n" } "100" V{ "o" } "501" V{ "n" "g" } "1" V{ "s" "h" } } flatten ! { "e" "n" "100" "o" "501" "n" "g" "1" "s" "h" } concat ! "en100o501ng1sh" ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 91 bytes ``` s=>s.replace(/[ivxlcdm]+/gi,s=>Buffer(s).map(c=>t-=~[9,4,,99,499,49,999][c%32%24%7],t=0)|t) ``` [Try it online!](https://tio.run/##bY@xboMwEIb3PoVjCQlUB0wKjRjIUHXI2K0DYnDsg1zj2Mh2UYaqr07TdEloTrrTL/3fN9yHGIWXDoewNFbB1NWTrzc@dTBoISHOGhxPWqpj@5j1yM7dy2fXgYt9kh7FEMt6E5b1d1OxgrHqfC97TlXbyOhpFa2KaN2yUPPkKySTtMZbDam2fdzF9HSQipKbSRKSZSTnh2fOH2Y4GGkVmh79nt7gYHLObclz0@d@P9e2oLVl5N06rRb0StvCr3ZpypIv5t6bDSJY8EQ4IL0DMPTP@1/M1VccUQG99xhfw5zeCYlao0SFkl7TO1HxYvoB "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org), 146 bytes ``` \(s){`!`=is.na T=tapply r=as.roman(t<-el(strsplit(s,""))) a=T(r,i<-rep(seq(a=x<-rle(!r)$l),x),sum) a[!a]<-T(t,i,g<-\(x)Reduce(paste0,x))[!a] g(a)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Zc_PSsNAEAbwe54iiR5mYVM2YP0DiScPPYoEPFih02SaLt3uxt2tRMSX8OolCr6O976NiQ0ieBq--X6Hmbd3232s8s-dXyXn-9c5OPa8iBa5dBONQZF7bBr1FNgc3cSaLWrwWUIKnLeuUdKD43HMGAswL8BymSWWGnD0AJi3fVAEkWXHivGWcbfb9vAuwvssKcBzyessmUPLbqjalQQNOk-il2wwQQ3IXsbLvlYQky5NJXUds6BP7aasYnYUJpdhKjanQgR_iHTrsSOdCmGmItV16taDmZFShoe3xqoqGtWMBvWznE5FNLBr49EbciFaCmtLpEf7vxj4lXyUFf0eJM5o2C6xlErJUlayHLslXoiTw1ddd5jf) Definitely not the best tool for the job, despite built-in `roman` numerals. ### Explanation outline: 1. Split string to characters (stored in `t`; this part could be omitted if we took input as a vector of characters). 2. Convert to type `roman` - successful for Roman digits, otherwise `NA` (stored in `r`). 3. Build index `i` for spitting on consecutive runs of `NA`s or not `NA`s. 4. Tapply (`split`+`sapply`) sum on Roman numerals. 5. Fill `NA`s with chunks from original string. 6. Collapse vector to one string. [Answer] # [Ret1na 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 45 bytes ``` i(`m dd d 5$*c c ll l 5$*x x vv v 5$*i i+ $.& ``` [Try 1t on51ne!](https://tio.run/##FcYxCgIxEAXQ/p8iwiKiy3bewMLSztY4M6wfxwSyIeT2kX3VK1aZ4hg8vX5QheI6nQUCd/j@jo7W0PYTvGBajmP0rygsSVamldsHd3PPc3jm4nrAI9dYs20hFgtrMUu4sVEN7yh0p1Apfw "Retina 0.8.2 – Try It Online") 51nk 1n150u500es test 100ases. E10p50anat1on: ``` i(` ``` Run the who50e s100r1pt 100ase-1nsens1t6e50y. ``` m dd ``` 1000 = 2 \* 500. ``` d 5$*c ``` 500 = 5 \* 100. ``` c ll ``` 100 = 2 \* 50. ``` l 5$*x ``` 50 = 5 \* 10. ``` x vv ``` 10 = 2 \* 5. ``` v 5$*i ``` 5 = 5 \* 1. ``` i+ $.& ``` 100on5ert to 500e1101a50. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .γu.vd}εDSu.v©àdi®O]J ``` [Try it online](https://tio.run/##yy9OTMpM/f9f79zmUr2ylNpzW12CgYxDKw8vSMk8tM4/1uv//4rs5BTHJAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXSf71zm0v1ylJqz211CQYyDq08vCAl89A6/1iv/0p6YTr/o5UqspNTlHSUUvOS81My89IzizOAPI/UnJx8HYXw/KKcFEUgPyC/JLEkP7VYIbEoVSG9KDU1DyjoklmWmZIKZCQlJmfm5GQmZ6ZkJgO5IBMdk5RiAQ). Or alternatively, with I/O as character array: ``` u.vøεΣa}н}.γd}ε¤diO]S ``` [Try it online](https://tio.run/##yy9OTMpM/f@/VK/s8I5zW88tTqy9sLdW79zmlNpzWw8tScn0jw3@/z9aqUJJRykbiJOBOAWIHYE4SSkWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWwi9L/Ur2ywzvObT23OLH2wt5avXObU2rPbT20JCXTPzb4v5JemJfO/2iliuzkFCUdpdS85PyUzLz0zOIMIM8jNScnX0chPL8oJ0URyA/IL0ksyU8tVkgsSlVIL0pNzQMKumSWZaakAhlJicmZOTmZyZkpmclALshExySlWAA). Can definitely be golfed a bit. But despite having a Roman Number builtin, the functionality of some builtins are nowhere near as versatile as the Vyxal answer.. Why you might ask? 1. The Roman Number builtin only works on uppercase letters (probably a bug..), so preserving the casing costs quite a few bytes. 2. Sum given an error on letters in the new 05AB1E version, so explicit checks before summing are unfortunately necessary. **Explanation:** ``` .γ # Adjacent group by the (implicit) input-string: u # Convert to uppercase .v # Convert from letter to Roman Number d # Check if this is a (non-negative) integer }ε # After the adjacent group-by: map over each group: D # Duplicate the current group S # Convert it to a list of characters u # Uppercase each .v # Convert it to a Roman Number # (it will remain an uppercase character if invalid) © # Store this list in variable `®` (without popping) àdi # If this list contains an integer: ®O # Push and sum list `®` ] # Close the if-statement and map J # Join everything together to a single string # (which is output implicitly as result) ``` ``` u # Uppercase each character in the (implicit) input-list .v # Convert each to a Roman Number # (it will remain an uppercase character if invalid) ø # Pair each with the characters of (implicit) input-list ε # Map over each pair: Σ # (Stable) sort the pair by: a # Check if it's a letter (0 if number; 1 if letter) }н # After the sort-by: pop and push the first character }.γ # After the map: adjacent group by: d # Is it a (non-negative) integer }ε # After the adjacent group-by: map over each group: ¤ # Push the first item (without popping the group list) di # If it's a (non-negative) integer: O # Sum the group together ] # Close the if-statement and map S # Convert the numbers and remaining groups to a flattened list # of characters # (which is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` ≔⁰θF⊞O⪪S¹ω«≔⌕⪪IVXLCDM¹↥ιη¿⊕η≧⁺×Xχ÷η²⊕×⁴﹪η²θ«⁺∨θωι≔⁰θ ``` [Try it online!](https://tio.run/##VZBNawMhEIbP7q@wOY1goSm99VQSShe6ZGn6dZV1sgpGjbrJoeS3W2X30B7mIDw@874zKBEGJ0zOTzHq0cIdpyf22BxcoNBPUe08BpFcgL03OkFr/ZT2KWg7AuN0XebCGP1pyPL/WVu5sKv28/t1s@1WM/fhi2oQEUGz8lRlC9EHWpRDwCPahBJUcXXCz643PaoEvZkip@/6iBF6d8EA65KxtWmrz1oiKE7vq@@vZqYfOO2cnIxbmErVbgRNxBqZ9KXHvAF2AU61C6clXWHI/3uQa3PN@QWNcZx@uWDkTZNvz@YX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁰θ ``` Start with a running total of `0`. ``` F⊞O⪪S¹ω« ``` Loop over the input characters, but include a trailing empty string. ``` ≔⌕⪪IVXLCDM¹↥ιη ``` Get the index of the uppercase character in the list of Roman numerals. ``` ¿⊕η ``` If this is a Roman numeral, then... ``` ≧⁺×Xχ÷η²⊕×⁴﹪η²θ« ``` ... use the index to convert it to decimal and add it to the running total, otherwise: ``` ⁺∨θωι ``` Prefix the running total, if any, to the character before printing it. ``` ≔⁰θ ``` Clear the running total. [Answer] # [Python](https://docs.python.org/3.8/), ~~130~~ ~~122~~ 117 bytes *-8 bytes by porting Arnauld's formula* *-5 bytes thanks to movatica* ``` lambda s:re.sub('[ivxlcdm]+',lambda M:str(sum(1+[9,4,0,99,499,49,999][ord(i)%32%24%7]for i in M[0])),s,0,2) import re ``` [Try it online!](https://tio.run/##LY49a8MwEIZ3/wrVYCIRUVIn0NqQrUOXQLcOroezJCdH9WFOinF/veuIDsc973McvNNvugV/fJtoHc/fqwU3aGCxJfMc7wPfdTgvVmnX73fy/3hpYyIe746/7LtGnuRBNtvKs1HTd4E0R1Ed66o@Va/9GIghQ88u3aEXQsbtoxYFuilQYmTWZGKK565g5fKjdCk3MF4Fjf6K8Zbzh7E2SPYVyOqnbD5DghRMZECGXckYn/U7zqhNxgEUWosKNaosEGZYwIICDa4s@uLRLD2a5QZtwSZCn/jIkxDrHw "Python 3.8 (pre-release) – Try It Online") Matches runs of roman numerals and replaces them with their sum. The `2` at the end is equivalent to `re.IGNORECASE`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~150~~ ~~159~~ ~~152~~ ~~137~~ ~~133~~ 126 bytes * +9 to handle either case * -7 thanks to emanresu A * -22 thanks to ceilingcat * -4 thanks to Neil Processes a string, looking for Roman numerals. If it finds one, the value is added to the total consecutive run. Once a non-numeral is found, the total is printed if it is greater than zero (and the total is reset), then the non-numeral is printed. Finally, the total is printed if the end of string is encountered in case the final character was a Roman numeral. ``` char*n="ivxlcdm",*d;t;f(char*s){for(t=0;t=!(d=index(n,*s|32))?t&&printf("%d",t),*s&&!putchar(*s):t+L"\1\5\n2dǴϨ"[d-n],*s++;);} ``` [Try it online!](https://tio.run/##PU/LTsMwELznK7ZGRHbiIijigkk5UCQqKm48pLaHYDupJdeu4m1BKvkfPoB/4MgfEdxWQtrDzszu7I7s11J2nVyUTeYKYjbvVqol4ZkSKCq65wPbVr6hWJwKLHpUFcYp/U4dz8LH@YCxa0zTVWMcVpQcK8KRRSVNe6s17vZpNLjEfEJmZ7OLmRuo76@fTzJVfTePc3kumGi7I@OkXSsNVwGV8SeLYZJER1iWxtGNN4rBNgHY@UEWpvNiS17ub0aEE@2kV8bVJiwiutPWeg7PvrGqF/HKY4leBygbDXWjtYvkaPw0Ht3G5rWUxlojjTKS8IfHyaTlkGUo4qlYh9RBQGQgpgmUEHZ4BOA/cYBiCCTuIRN7paIZ5vketEnb/crKlnXo@m9/ "C (gcc) – Try It Online") ]
[Question] [ > > The main purpose of the RGB (Red Green Blue) color model is for the sensing, representation and display of images in electronic systems, such as televisions and computers > > > HSL (Hue Saturation Lightness) is an alternative color model, designed in the 1970s by computer graphics researchers to more closely align with the way human vision perceives color-making attributes > > > Here are the wiki articles for [RGB](https://en.wikipedia.org/wiki/RGB_color_model) and [HSL](https://en.wikipedia.org/wiki/HSL_and_HSV). It is common for graphics programs to do the calculations in HSL, and later convert to the preferred format for most screens: RGB. The task is to write a function/program that takes HSL as an input and outputs RGB. You can pick your preferred representation for I/O, as long as its consistent between them. For example, they can be an array/tuple with 3 elements or an object with 3 properties named `h`, `s`, and `l`, but I'll accept other clever variations, like receiving the hsl as an integer (losing precision) and outputting an rgb integer. The input can be assumed to be safe in range and format, both of which you can decide. I strongly suggest either the ranges `0-1 0-1 0-1` or `0-360 0-100 0-100` for hsl, and `0-1 0-1 0-1` or `0-255 0-255 0-255` for rgb. Each answer is required to specify both of the above, and do put various variations in your answers if you're particularly proud of them, even if they don't have less characters than your other variations. Put the smallest on top. Pseudo test cases for `0-360 0-100 0-100` → `0-255 0-255 0-255` ``` h s l → r g b 0 0 0 → 0 0 0 90 56 17 → 43 68 19 202 19 39 → 81 104 118 72 55 26 → 88 103 30 ``` The formulae for the conversion can be found [here](http://www.rapidtables.com/convert/color/hsl-to-rgb.htm): ![](https://i.stack.imgur.com/SZ6Yc.png) This as a nice way to visualize the conversion: ![](https://upload.wikimedia.org/wikipedia/en/b/b6/HSL_RGB_Comparison.png) [Answer] # JavaScript (ES6), ~~98~~ ~~95~~ 94 bytes Takes **H** in **[0,360)** and **S**/**L** in **[0,1)**. Outputs **R**, **G** and **B** as an array of 3 floats in **[0,1)**. ``` (H,S,L)=>[5,3,1].map(i=>A(L*2)*S*([1,Y,0,0,Y,1][(i-~H)%6]-.5)+L,Y=(A=n=>n>1?2-n:n)((H/=60)%2)) ``` ### Test cases This snippet converts the results back into **[0,255]**. ``` let f = (H,S,L)=>[5,3,1].map(i=>A(L*2)*S*([1,Y,0,0,Y,1][(i-~H)%6]-.5)+L,Y=(A=n=>n>1?2-n:n)((H/=60)%2)) format = a => JSON.stringify(a.map(v => v * 255 + 0.5 | 0)) console.log(format(f( 0, 0.00, 0.00))) // 0 0 0 console.log(format(f( 90, 0.56, 0.17))) // 43 68 19 console.log(format(f(202, 0.19, 0.39))) // 81 104 118 console.log(format(f( 72, 0.55, 0.26))) // 88 103 30 ``` ### How? **Initialization code** ``` Y = ( // we compute Y = 1 - |(H/60) mod 2 - 1| = X / C A = n => // A = function that returns 1 - |n - 1| n > 1 ? // first compare n with 1 2 - n // which allows to simplify the formula to either 2 - n : // or n // just n )((H /= 60) % 2) // divide H by 60 and compute Y = A(H % 2) ``` **Main code** ``` [5, 3, 1].map(i => // for each i in (5, 3, 1): A(L * 2) * S * ( // compute (1 - |2L - 1|) * S (this is C), and multiply it by: [1, Y, 0, 0, Y, 1] // either 0, 1 or Y (let's call this factor K), picked from [(i - ~H) % 6] // a cyclic sequence of period 6, using i and ~H (-6 ≤ ~H ≤ -1) - .5 // minus 1/2 ) // this gives: C(K - 1/2) = CK - C/2, where CK = 0, C or X + L // we add L, leading to CK - C/2 + L = CK + m ) // end of map() --> returns [R, G, B] ``` **Permutations of (0,C,X)** The slightly tricky part is to generate the correct permutation of **(0,C,X)** according to the angle of the hue component. As shown in the following figure, each column value is picked from the same cycling sequence of period **6**, starting at different offsets. In the above code, we're using **-~H** instead of just **+H** because we need to coerce **H** to an integer. Hence the offsets **(5,3,1)** instead of **(0,4,2)**. ``` C,X,0,0,X,C,C,X,0,0,X,C, ... +------> C,X,0,0,X,C <---------> offset = 0, (0 - 1) mod 6 = 5 | +----> X,C,C,X,0,0 <---------> offset = 4, (4 - 1) mod 6 = 3 | | +--> 0,0,X,C,C,X <---------> offset = 2, (2 - 1) mod 6 = 1 | | | (C,X,0) for 0 ≤ H < 60 (X,C,0) for 60 ≤ H < 120 (0,C,X) for 120 ≤ H < 180 (0,X,C) for 180 ≤ H < 240 (X,0,C) for 240 ≤ H < 300 (C,0,X) for 300 ≤ H < 360 ``` [Answer] # [Python 2](https://docs.python.org/2/), 32 bytes ``` from colorsys import*;hls_to_rgb ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1chOT8nv6i4slghM7cgv6hEyzojpzi@JD@@KD3pf0FRZl6JAkJAQyszr6C0RENT83@0npGpjp6huY6eqVksAA "Python 2 – Try It Online") This functionality is actually built into Python via the `hls_to_rgb` inside of the `colorsys` library. The format mine inputs is a 0-1 range of HLS (instead of HSL, both are common acronyms for the same thing [albeit, HSL is more common]). And mine outputs RGB values in a tuple with a range from 0 to 1. **Credits** Thanks to Jonathan Allan for pointing out that I just need to import it (and then further helping me reduce byte count). [Answer] # Mathematica, 155 bytes ``` (x~Clear~c;d=Piecewise@Table[{(P=Permutations)[P@{c,x,0}][[42,i]],(i-1)<=#<i*p},{i,6}];c=(1-Abs[2#3-1])#2;x=c(1-Abs[Mod[#/(p=60),2]-1]);m=#3-c/2;(m+d)255)& ``` [Try it online!](https://tio.run/##RcrBa8IwGAXw@/6Nwkjc15p@LpUSAx07D3LYLeQQ08gCRqXtWKHUf72LoMg7vd970Q4/PtohOLsc5ELG6@fR2@7qRCtV8M7/hd4333Z/9HoiSirfxd8h/c@nnmrVTA5GYLPR@h0hGAMk5CXdyWwXVpcZpgDVbISTpMw/9r3GbJOXhmYoRunu9nVudbYmF1kxCmhuu4gyHd0aBYlvLUXO6euiunAamoNmkGJeHrVmUPAKinL7NGSYoIZiUz9xm4xzKLAyyz8 "Wolfram Language (Mathematica) – Try It Online") [Answer] ## C++, ~~228~~ 221 bytes -7 bytes thanks to Zacharý ``` #define S(o,n)r[t[int(h[0])/60*3+o]+o-2]=(n+h[2]-c/2)*255; void C(float*h,int*r){float g=2*h[2]-1,c=(g<0?1+g:1-g)*h[1],a=int(h[0])%120/60.f-1;int t[]={2,2,2,3,1,2,3,3,0,4,2,0,4,1,1,2,3,1};S(0,c)S(1,c*(a<0?1+a:1-a))S(2,0)} ``` The arguments are both arrays that have a minimum size of 3 elements ( i.e. `float hsl[3]` and `int rgb[3]` Okay. Now, how does that work ? What is that long array ? Well, it's not a long array, it's a `int` array. Joke aside, the array indicates by how many position we right shift C X and 0 when we want to select the correct permutation, + 2. Remember how R', G' and B' are selected ? [![How R',G' and B' are selected](https://i.stack.imgur.com/c6KIk.png)](https://i.stack.imgur.com/c6KIk.png) Let's say we have a "normal" order that is {C, X, 0} Now, when the first permutation (i.e. {C,X,0}) is selected, you need to not shift, which is exactly the same thing as right shifting by 0. So the first 3 elements of the array are 0,0 and 0 For the second permutation ( {X,C,0} ), we need to right shift C by 1, and left shift X by -1, so the fourth, fifth and sixth element of the array are 1,-1 and 0 And so on... With the case of the 3rd and 4th permutation, i need to left shift the 0 by 2, so right shift by -2. Since there are more that 2 numbers that are negative, i rather add 2 to each elements in the array and substract 2 at the runtime ( for golfing reasons, to have only whole numbers in the array ). [Answer] # [Python 2](https://docs.python.org/2/), ~~119~~ 112 bytes ``` def f(h,s,l):c=(1-abs(2*l-1))*s;m=l-c/2;x=c*(1-abs(h%2-1))+m;c+=m;return[c,m,x,c,m,x,m,c,x,m][7-int(h)*5%9:][:3] ``` [Try it online!](https://tio.run/##TY1BCoMwEEX3PUU3QhITNSMqGnIScdGmSgrGilqwp08n1NIu5g28P5@ZX5t9TOD9rR/OA7F85SNtjCZSXK4rATYKSSlbldOjMCmoXRt2hDaCEMZOmVg7tfTbc5lawx3f@YcON7JrK3GfNmIpK6K66dom7/y8oMKXWZLxY@jpK2VSoChKhKx@GjJI0jLcyhqR1/8NCI1Qg5L6Nw "Python 2 – Try It Online") Takes input as `H=[0,6[, S=[0,1], L=[0,1]` [Answer] ## HTML + JavaScript (ES6), 8 + 88 = 96 bytes ``` f= (h,s,l)=>(p.style.color=`hsl(${h},${s}%,${l}%)`,getComputedStyle(p).color.match(/\d+/g)) ``` ``` <div oninput=o.textContent=f(h.value,s.value,l.value)>H: <input type=number min=0 max=360 value=0 id=h>°<br>S: <input type=number min=0 max=100 value=0 id=s>%<br>L: <input type=number min=0 max=100 value=0 id=l>%<pre id=o>0,0,0</pre> <p id=p> ``` Takes input as an angle and two percentages. I'm scoring the HTML snippet `<p id=p>` and the JavaScript arrow function. I don't know what rounding browsers use, so my answers might differ slightly from yours. [Answer] # Swift 4, 218 bytes Accepts HSL values in the range [0,1] as arguments, and returns an array containing the RGB values in the same range: ``` import Cocoa;typealias F=CGFloat;func f(h:F,s:F,l:F)->[F]{var r=F(),g=F(),b=F(),x=s*min(1-l,l),n=2*x/max(l+x,1e-9);NSColor(hue:h,saturation:n,brightness:l+x,alpha:1).getRed(&r,green:&g,blue:&b,alpha:nil);return[r,g,b]} ``` The idea is to first convert the input from HSL to HSB, then using the HSB constructor of the built-in color object in Cocoa to retrieve the RGB values. The UIKit version is the exact same length, as the only replacements are: * `Cocoa` → `UIKit` * `NSColor` → `UIColor` ### Ungolfed: ``` #if os(iOS) import UIKit typealias Color = UIColor #elseif os(OSX) import Cocoa typealias Color = NSColor #endif typealias F = CGFloat func f(h: F,s: F,l: F) -> [F] { var r = F(), g = F(), b = F() let x = s * min(1 - l, l) let n = 2 * x / max(l + x, 1e-9) let color = Color(hue: h, saturation: n, brightness: l + x, alpha: 1) color.getRed(&r, green: &g,blue: &b, alpha: nil) return [r, g, b] } ``` The following snippet can be used for testing, by just replacing the values of `h`, `s`, and `l`: ``` let h: CGFloat = 0 let s: CGFloat = 0 let l: CGFloat = 0 let result = f(h: h/360, s: s/100, l: l/100).map { Int(round($0*255)) } print(result) ``` --- Unfortunately I can't provide a link to an online sandbox, since all of them run on Linux, which doesn't include Cocoa. [Answer] # GLSL (GL\_ES) ~~160 144 134~~ 131 bytes Hue is in range 0-6 (saves 3 bytes) Sat,light and rgb are 0-1 ``` vec3 f(vec3 c){return mix(c.bbb,mix(clamp(vec3(-1,2,2)-abs(c.r-vec3(3,2,4))*vec3(-1,1,1),0.,1.),vec3(c.b>.5),abs(.5-c.b)*2.),c.g);} ``` [Try it on book of shaders](http://thebookofshaders.com/edit.php?log=171212202804) Used colorpicker tool on a printscreen to test the output which was correct, except a small error on 202 19 39 → 81 104 118 , which gave 80 104 118 [Answer] # [R](https://www.r-project.org/), 88 bytes ``` function(h,s,l){v=(2*l+s*(1-abs(2*l-1)))/2;col2rgb(hsv(h,ifelse(v==0,v,(2*(v-l))/v),v))} ``` [Try it online!](https://tio.run/##PYpBCsIwEEX3nsLlTJ3YJKUpQXIYWxpbCC00Ohvx7DGzUD48@I93lBhKfG3Tc903WChTwjcHsE265AaMuo9ZjjKI2NrbtCd7PEZYMtd6jXPKM3AImphqB6xS7RiJET8lgqY6PEXwuu2cprO@9k5oBrFW2582Xth50cPf9r3QOixf "R – Try It Online") This function takes as input the H, S, and L values as 0-1 ranged values and outputs the RGB values as 0-255 ranged values. It converts the HSL representation to an HSV representation, then uses `hsv()` to convert the HSV representation to an R color (i.e. hex representation -- #rrggbb), then uses `col2rgb()` to convert the R color to RGB values. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~39~~ 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) (`%2` is just `Ḃ`) -1 and/or inspiration for -4 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) too! ``` Ḥ;Ḃ’ACש"⁵×\;0+³_®H¤⁴Ḟị336Œ?¤¤œ? ``` A full program taking three command line arguments: * `L`, `H`, `S` in the ranges `[0,1)`, `[0,6)`, and `[0,1)` respectively which prints a list giving the RGB format as * `[R, G, B]` with each of the three values in the range `[0,1]` Note: `H` may also wrap just like `[0,360)` would. **[Try it online!](https://tio.run/##AU4Asf9qZWxsef//4bikO@G4guKAmUFDw5fCqSLigbXDl1w7MCvCs1/CrkjCpOKBtOG4nuG7izMzNsWSP8KkwqTFkz////8wLjE3/zEuNf8uNTY "Jelly – Try It Online")** ### How? ``` Ḥ;Ḃ’ACש"⁵×\;0+³_®H¤⁴Ḟị336Œ?¤¤œ? - Main link: number, L (in [0,1]); number, H (in [0,6)) Ḥ - double = 2L Ḃ - modulo by 2 = H%2 ; - concatenate = [ 2L , H%2] ’ - decrement = [ 2L-1 , H%2-1] A - absolute = [ |2L-1|, |H%2-1|] C - complement = [1-|2L-1|,1-|H%2-1|] - = [C/S ,C/X] ⁵ - 3rd program argument = S (in [0,1]) " - zip with: × - multiplication = [C,C/X] © - (copy the result, C, to the register) \ - cumulative reduce with: × - multiplication = [C, C/X*C] = [C,X] ;0 - concatenate zero = [C,X,0] ³ - 1st program argument = L + - add (vectorises) = [C+L,X+L,L] ¤ - nilad followed by link(s) as a nilad: ® - recall from register = C H - halve = C/2 _ - subtract = [C+L-C/2,X+L-C/2,L-C/2] ¤ - nilad followed by link(s) as a nilad: ⁴ - 2nd program argument = H Ḟ - floor = floor(H) ¤ - nilad followed by link(s) as a nilad: 336 - literal 336 Œ? - Shortest permutation of natural numbers with a - lexicographical index of 336 in all permutations - thereof = [3,5,6,4,2,1] ị - index into (1-indexed & modular) œ? - get that permutation of [C+L-C/2,X+L-C/2,L-C/2] - implicit print ``` ]
[Question] [ Write code to evaluate whether a chain of inequalities is true or false. An example input is the string `3<=4!=9>3==3` This is true because each of its components is true: `(3<=4) and (4!=9) and (9>3) and (3==3)` **Input:** A string that represents a chain of one or more inequalities. The allowed comparison operators are ``` == equals != does not equal > is greater than >= is greater than or equal to < is less than <= is less than or equal to ``` The allowed numbers are single-digit numbers `0` through `9`. There won't be any spaces, parentheses, or other symbols. **Output:** The correctness of the inequality as a consistent [Truthy or Falsey](http://meta.codegolf.stackexchange.com/q/2190/20260) value. Consistent means every Truthy output is the same and every Falsey output is the same. **Restriction:** The intent of this challenge is for you to write code that processes the inequalities, rather than have them be evaluating them as code, even for a single inequality in the chain. As such, methods like Python's `eval` and `exec` that evaluate or execute code are banned. So are functions which look up a method or operator given its name as a string. Nor is it allowed to launching processes or programs to do the evaluation for you. **Test cases:** ``` 3<=4!=9>3==3 True 3<=4!=4 False 5>5 False 8==8<9>0!=2>=1 True ``` [Answer] # Ruby, 71 + 1 = 72 With command-line flag `-n`, run ``` p (0..99).none?{|i|~/#{a=i%10}(#{%w/!=|. <?=* >?=*/[a<=>b=i/10]})#{b}/} ``` Generates all possible failing regular expressions, and checks whether the input string matches any of them. Outputs `true` if none do, else `false`. Takes input via STDIN, separated by newlines. Tricks: * We get all possible pairs of digits by looping from 0 to 99 and extracting the 10s and 1s digits. * The only actual comparison we do is `a<=>b`, which returns -1,0,or 1 for less than, equal to, or greater. These all slice to different elements of a three-string array, finding the regular expression for comparisons that don't match. [Answer] # Perl, 82 ``` $_=<>;($'<=>$&)-61+ord$1&&($2&&$&==$')^('$'lt$1)&&die"\n"while/\d(.)(=?)/g;print 1 ``` Prints 1 when true and a blank line when false, since the empty string is Perl's main falsey value. The while loop goes over the string matching the regex `\d(.)(=?)`. Then the variables `$1` and `$2` correspond to the characters of the operator, and the special variables `$&` and `$'` will behave as the two operands in a numerical context. The operands are compared with `<=>` and the result matched against the first character of the operator. Then equality and inequality is dealt with specially. [Answer] # CJam, 60 bytes This code seems a bit ugly and potentially not fully optimized, but it's the best I've got so far. [Try it online.](http://cjam.aditsu.net/#code=q_A%2CsSer_S%25%40%40-(%5D)1%5C%40z%7B~%3AX%5C%3A%5Ei%5B'%3D%22)%3C%22P%22(%3E%22P'%3C'%5E'%3EPPP%5D%3D~e%26X%7D%2F%3B&input=8%3D%3D8%3C9%3E0!%3D2%3E%3D1) ``` q_A,sSer_S%@@-(])1\@z{~:X\:^i['=")<"P"(>"P'<'^'>PPP]=~e&X}/; ``` ### Explanation ``` q "Read the input"; _A,sSer "Copy the input and replace each digit with a space"; _S% "Split around spaces to obtain the operation list"; @@- "Remove operations from the input to obtain the operand list"; (])1\@z "Remove the first operand from the list to be the initial left operand, initialize the result to 1 (true), and pair up the operations and remaining operands"; { "For each operation-operand pair:"; ~:X "Let the operand be the right operand of this operation"; \:^i "Hash the operation (bitwise XOR of all characters)"; [ "Begin cases:"; '= " 0: Equals"; ")<" " 1: Less than or equal to"; P " 2: (Invalid)"; "(>" " 3: Greater than or equal to"; P " 4: (Invalid)"; '< " 5: Less than"; '^ " 6: Bitwise XOR (stand-in for not equal to)"; '> " 7: Greater than"; P " 8: (Invalid)"; P " 9: (Invalid)"; P "10: (Invalid)"; ]=~ "Execute the case selected by the operation hash modulo 11"; e& "Compute the logical AND of the result and the value produced by this operation to be the new result"; X "Let the right operand be the new left operand"; }/ "End for each"; ; "Clean up and implicitly print result"; ``` [Answer] # Haskell, 156 bytes ``` r a=read[a]::Int l"!"=(/=) l"="=(==) l">"=(>=) l"<"=(<=) k">"=(>) k"<"=(<) []#_=1<2 (a:'=':b:c)#i=l[a]i(r b)&&c#r b (a:b:c)#i=k[a]i(r b)&&c#r b f(h:t)=t#r h ``` Usage example: ``` f "3<=4!=9>3==3" -> True f "3<=4!=4" -> False f "5>5" -> False f "8==8<9>0!=2>=1" -> True ``` Ungolfed version: ``` digitToInt d = read [d] :: Int lookup2 "!" = (/=) lookup2 "=" = (==) lookup2 ">" = (>=) lookup2 "<" = (<=) lookup1 ">" = (>) lookup1 "<" = (<) eval [] _ = True eval (op:'=':d:rest) i = lookup2 [op] i (digitToInt d) && eval rest (digitToInt d) eval (op:d:rest) i = lookup1 [op] i (digitToInt d) && eval rest (digitToInt d) evalChain (hd:rest) = eval rest (digitToInt hd) ``` `eval` takes two arguments: the string to parse (starting always with a comparison operator) and a number `i` which is the left argument for comparison (and was the right argument in the previous round). The operator is returned by `lookup2` if it's a two character operator (check only 1st char, because 2nd is always `=`) and by `lookup1` if it's just a single character. `eval` calls itself recursively and combines all return values with logical and `&&`. [Answer] # JavaScript (ES6) 110 ~~116~~ Straightforward:scan string, c is current digit, l is last digit, o is operator. ``` F=x=>(l='',[for(c of x)10-c?(v=!l||v&&(o<'<'?l!=c:(o[1]&&c==l)||(o<'='?l<c:o<'>'?c==l:l>c)),l=c,o=''):o+=c],v) ``` **Test** In Firefox / FireBug console ``` ;['3<=4!=9>3==3','3<=4!=4','5>5','8==8<9>0!=2>=1'] .forEach(s=>console.log(s,F(s))) ``` > > 3<=4!=9>3==3 true > > 3<=4!=4 false > > 5>5 false > > 8==8<9>0!=2>=1 true > > > [Answer] # Common Lisp - ~~300~~ ~~185~~ ~~169~~ 165 ``` (lambda(s)(loop for(a o b)on(mapcar'read-from-string(cdr(ppcre:split"([0-9]+)"s :with-registers-p t)))by #'cddr always(if o(funcall(case o(=='=)(!='/=)(t o))a b)t))) ``` # Example ``` (mapcar (lambda(s) ...) '("2<=3<=6>2<10!=3" "3<=4!=9>3==3" "3<=4!=4" "5>5" "8==8<9>0!=2>=1")) => (T T NIL NIL T) ``` # Explanation ``` (lambda (s) (loop for (a o b) on (mapcar 'read-from-string (cdr (cl-ppcre:split "([0-9]+)" s :with-registers-p t))) by #'cddr always (if o (funcall (case o (== '=) (!= '/=) (t o)) a b) t))) ``` * `ppcre:split` splits on digits; for example: ``` (ppcre:split "([0-9]+)" "2<=3<=6>2<10!=3" :with-registers-p t) => ("" "2" "<=" "3" "<=" "6" ">" "2" "<" "10" "!=" "3") ``` Notice the first empty string, which is discarded using `cdr` * Mapping `read-from-string` to this list calls the `read` function for each strings, which returns symbols and numbers. * `loop for (a op b) on '(3 < 5 > 2) by #'cddr` iterates over the list by a step of **2** and thus binds `a`, `op` and `b` as follows, for each successive pass. ``` a op b ---------- 3 < 5 5 > 2 2 nil nil ``` * `always` checks whether the next expression is always true: either the operator is `nil` (see above) or the result of the comparison holds (see below). * the `case` selects a Common-Lisp comparison function, according to the symbol previously read; since some operators are identical in Lisp and the given language we can simply return `o` in the default case. [Answer] # Python 2, ~~95~~ 102 ``` t=1 n=o=3 for c in map(ord,raw_input()): o+=c if 47<c<58:t&=627>>(o-c+3*cmp(n,c))%13;n=c;o=0 print t ``` The loop is a straightforward pass through the string one character at a time. The `t&=...` part is where the magic happens. Basically, I hash the operator together with the value of `cmp(lhs,rhs)` (-1, 0, or 1 depending on if `lhs` is less, equal, or greater than `rhs`). The result is a key into a lookup table that gives 0 or 1 depending on whether the numbers compare properly given that operator. What lookup table, you ask? It's the number 627 = `0001001110011` in binary. Bitwise operators do the rest. This works on the four given test cases; let me know if you find an error for another case. I haven't tested it very rigorously. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` þS¡¦Uþü.S"=<!>"2×Sć«'<š'>ª3ôÀsèXδåÅ\P ``` [Try it online](https://tio.run/##AUsAtP9vc2FiaWX//8O@U8KhwqZVw77DvC5TIj08IT4iMsOXU8SHwqsnPMWhJz7CqjPDtMOAc8OoWM60w6XDhVxQ//8zPD00IT05PjM9PTM) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l4Qn/D@8LPrTw0LLQw/sO79ELVrK1UbRTMjo8PfhI@6HV6jZHF6rbHVplfHjL4Ybiwysizm05vPRwa0zAf53/xja2Joq2lnbGtrbGXBCOCZepnSmXha2thY2lnYGirZGdrSEA). **Explanation:** ``` þ # Only leave the digits of the (implicit) input-string # i.e. "3<=4!=9>3==3" → "34933" S # Convert it to a list of digits # → [3,4,9,3,3] ¡ # Split the (implicit) input-string by those, to have a list of the comparisons # → ["","<=","!=",">","==",""] ¦ # Remove the first item (which is an empty string) # → ["<=","!=",">","==",""] # (it also contains a trailing empty string, but we'll ignore that) U # Pop and store it in variable `X` þ # Only leave the digits of the (implicit) input-string again ü # For each overlapping pair of digits: .S # Compare them: -1 if a<b; 0 if a==b; 1 if a>b # → [[3,4],[4,9],[9,3],[3,3]] → [-1,-1,1,0] "=<!>" # Push string "=<!>" 2× # Double it to "=<!>=<!>" S # Convert it to a list of characters: ["=","<","!",">","=","<","!",">"] ć # Extract the head: pop and push remainder-list and head separately « # Append this "=" to each: ["<=","!=",">=","==","<=","!=",">="] '<š'>ª # Prepend a "<" and append a ">": ["<","<=","!=",">=","==","<=","!=",">=",">"] 3ô # Split it into parts of size 3: [["<","<=","!="],[">=","==","<="],["!=",">=",">"]] À # Rotate this list once left: [[">=","==","<="],["!=",">=",">"],["<","<=","!="]] sè # Index the digit-comparisons into it (where the -1 indexes into the last item) # → [["<","<=","!="],["<","<=","!="],["!=",">=",">"],[">=","==","<="]] X # Push the input-comparisons from variable `X` again δ # Apply double-vectorized: å # Check if the current comparison is in the current list # → [[1,1,0,0,0],[1,1,0,0,0],[0,1,1,0,0],[1,0,0,1,0]] Å\ # Leave the main diagonal of these double-vectorized checks # → [1,1,1,1] P # And check if all are truthy by taking their product # → 1 # (after which the result is output implicitly) ``` [Answer] # Javascript 101 bytes a different approach from the js solution posted here ``` F=(s,i=0,l=o="")=>[...s].every(c=>c>=0?[l^c,l==c,,l<c,l>c,l<=c,,l>=c]["!==<><=>=".search(o,l=c,o="")]:o+=c,l=o="") console.log(F("3<=4!=9>3==3")==true) console.log(F("3<=4!=4")==false) console.log(F("5>5")==false) console.log(F("8==8<9>0!=2>=1")==true) ``` [Answer] # Java 8, ~~283~~ 270 bytes ``` s->{String[]a=s.split("\\d"),b=s.split("\\D+");int i=0,r=1,x,y;for(;i<a.length-1;y=new Byte(b[++i]),r-=a[i].equals("==")&x!=y|a[i].equals("!=")&x==y|a[i].equals(">")&x<=y|a[i].equals(">=")&x<y|a[i].equals("<")&x>=y|a[i].equals("<=")&x>y?1:0)x=new Byte(b[i]);return r>0;} ``` -13 bytes thanks to *@ceilingcat*. **Explanation:** [Try it here.](https://tio.run/##hZBBb4IwFIDv/ooHhwUiEJia6MrrkmXXefGoHgpWV4eF0eIkjt/OKrrEuYNJe@j3vqQv35btmZ8XXG5XH22aMaXgjQl57AEIqXm5ZimH6ekJkOR5xpmE1JnpUsgNKJeYQWOuOUozLVKYggSEVvn0eLbmS4YqUEUmtGMvFivb9ZJr8Nq3XWL@AoGhV2LkHbyarPPSISJmQcblRr/7EalR8i94qTV3knm/L5auV/rI5mIZ8M@KZcqxEW334WBh/f0HWx3GW0xPNP5HOzm@ofEJ0ls37lxaP0dPoXu43s9sR0quq1JCSUPStOTcqKiSzDS6pNrnYgU7U9v5LQXMPaee1UrzXZBXOijMSGfSkUHq2IMYhxZO6ABxYLtd/nvy8K43oqO7zhhxHE9oaOEjxeiiN72m/QE) ``` s->{ // Method with String parameter and boolean return-type String[]a=s.split("\\d"), // All the inequalities b=s.split("\\D+"); // All the digits int i=0, // Index-integer (starting at 0) r=1, // Flag integer for the result, starting at 1 x,y; // Temp integer `x` and `y` for(;i<a.length-1 // Loop `i` in the range [0, length]: ; // After every iteration: y=new Byte(b[++i]), // Convert the `i+1`'th digit from String to integer, // and store it in `y` r-= // Decrease the result by: a[i].equals("==")&x!=y // If "==" and `x` and `y` are not equal |a[i].equals("!=")&x==y// or if "!=" and `x` and `y` are equal |a[i].equals(">")&x<=y // or if ">" and `x` is smaller than or equal to `y` |a[i].equals(">=")&x<y // or if ">=" and `x` is smaller than `y` |a[i].equals("<")&x>=y // or if "<" and `x` is larger than o equal to `y` |a[i].equals("<=")&x>y // or if "<=" and `x` is larger than `y`: 1 // Decrease the result by 1 :0; // Else: keep it the same by decreasing with 0 x=new Byte(b[i]); // Convert the `i`'th digit from String to integer, // and store it in `x` return r>0;} // Return whether the result is still 1 ``` ]
[Question] [ **This question already has answers here**: [Aligning Lines!](/questions/57786/aligning-lines) (27 answers) Closed 3 years ago. Perhaps something like this is here already, but I couldn't find it. It is not the same as [Aligning Lines!](https://codegolf.stackexchange.com/questions/57786/aligning-lines). ## Example: ### Input: ``` 98.6 $2,750.17 -$23 -86 3,120,487.19 ``` ### Output: ``` 98.6 $2,750.17 -$23 -86 3,120,487.19 ``` Note that `.6` isn't right-padded to `.60` or `.6` . ## Input: * A list/array of strings (or lines from stdin), each one containing a number, without leading or trailing whitespace * Some may begin with begin with a negative sign (`-`), and/or a currency symbol (`$`), in that order * Some may contain a decimal mark (`.`) * Digits before the decimal mark will sometimes be grouped into threes and separated by commas ## Output: * A list/array (or stdout) * Each entry is left padded with spaces so that the actual or implied decimal marks align * No trailing whitespace This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. --- ## Update: This first attempt has turned into a valuable learning experience: **always use the sandbox**. * My first version was overly complicated, and I trimmed it down a lot before actually posting. * I simplified it again in response to the quite valid comments that soon arrived. * Unfortunately, the resulting question ended up too simple (effectively a duplicate of the question that I said wasn't), with most of the description of the input becoming irrelevant. * Somewhere in there I managed to lose the original intent, which was to process only what are valid numbers while leaving other strings alone. (The idea came from a function in an existing program that does just that, its purpose being to turn all strings into something that will look good if everything is printed left-justified.) When posing a problem, take more time to think it through, and as I said: **always use the sandbox**. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ ~~18~~ ~~15~~ 10 bytes Code: ``` '.©«®δkZαú ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fXe/QykOrD607tyU76tzGw7v@H9r9P1rJ0kLPTElHScVIx9zUQM/QHMjWVTEyBlEWIAljHUMjAx0TC3M9Q0ulWAA "05AB1E – Try It Online") Explanation: ``` '.©« # append . to each element ®δk # Find index of . for all elements Z # Get the largest α # Get the absolute difference between the indices ú # Pad by that much ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 23 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) Anonymous tacit prefix function taking and returning a list of strings. ``` ⊢,¨⍨' '⍴¨⍨∘(⌈/-⊢)⍳¨∘'.' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/8f/6htQvWjvqlewf5@j3oXqDvn5xYkJpeoGzzq3QVCMJmttQqPeucqlBclFhSkFimk5RcpgCQUPPX9/z/qWqRzaMWj3hXqCuqPereAmY86Zmg86unQ1wVKaj7q3XwIJKKup/4/DWjho96@R13Nj3rXgFSvN37UNhFoT3CQM5AM8fAM/p@mEK@gHq1kaaFnpqSjpGKkY25qoGdoDmTrqhgZgygLkISxjqGRgY6JhbmeoaVSrDoA "APL (Dyalog Unicode) – Try It Online") `⊢` the strings `,¨⍨` each prepended with `' '` space `⍴⍨¨` **r**eshaped to each of the shapes `∘(`…`)` of:  `⌈/` the maximum (lit. larger-value reduction)  `-` minus  `⊢` the values of `⍳¨` the index (1+length if not found) in each `∘` of:  `'.'` a decimal mark [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 12 bytes ``` mP^`^[^.\n]+ ``` [Try it online!](https://tio.run/##K0otycxLNPz/PzcgLiEuOk4vJi9W@/9/Sws9My4VIx1zUwM9Q3MuXRUjYy5dCzMuYx1DIwMdEwtzPUNLAA "Retina – Try It Online") Explanation: ``` m`^[^.\n]+ ``` Match up to the first `.` or the end of each line. ``` P^` ``` Pad matches on the left with spaces to the same length. [Answer] # Kakoune, 11 bytes ``` s^[^\n.]+<ret>& ``` (`<ret>` is the return key) [![asciicast](https://asciinema.org/a/3Pz4ifGOdAya92FxCEjcyRpEF.svg)](https://asciinema.org/a/3Pz4ifGOdAya92FxCEjcyRpEF) This solution assumes the input is in the default buffer, and the entire buffer being selected. `%` can be prepended to the solution if the entire buffer is not selected. Explanation: ``` s <ret> Search for this regex in the current selection, reduce the selection to the matches ^[^\n.]+ The regex to search for, it matches every line until the end or a decimal point & Align all selections ``` [Answer] # [J](http://jsoftware.com/), 29 27 bytes ``` ((,~#&' ')&.>>./-])i.&'.'&> ``` [Try it online!](https://tio.run/##bYxBb4JAFITv/IqJNawkyytgK2grh5p4MI0H701D4SFr7EKXtbQX/zoVvXaSuXyZ@Q79iESJ5QICEgEWl/qE1e513U8m8nznCgjPpTSle//NU@QKEm7ae06xJDw/0XsoME9ohnEk48eAwhj@OJrCT2aYyjAK5EMSUzgXjsN5VaPAkO0LQenmZG@wvOIBZrrt2Eh81D/cwvDXSRkuLltsYGs0hr9ZW1iTqaPSe3SVstw2Wc43U3p1DSatcj7@oqzNZ2YtFxKdstV/z/4P "J – Try It Online") *-2 thanks to xash* Inspired by Adam's APL answer. [Answer] # [R](https://www.r-project.org/), 61 bytes ``` function(n)paste0(strrep(" ",max(x<-regexpr("\\.|$",n))-x),n) ``` [Try it online!](https://tio.run/##FclBCsMgEEDRq8iQxQyMoklbDaQ3ySYELV3Uihpw0bvbZPU@/NyDWKTo4Yh7fX8jRkpbqV5jqTn7hCCAP1vDtsjsX76ljLCu6jcARyLZ6KTvW8WAO8Ls1AMYhpHtXStjz5bDOF24a0xsRs03Z5WZgYiLT09YI1D/Aw "R – Try It Online") ``` function(n) # function: paste0( # concatenate strrep(" ", # " " repeated this many times: max( # (the max of x<-regexpr("\\.|$",n) # the position of the first "." OR the end of the line )-x) # minus the position of the first "." OR the end of the line) ,n) # with n # and return ``` [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), 54 bytes ``` ->s{s.map{|e|' '*-((e=~r=/\.|$/)-s.map{_1=~r}.max)+e}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ulgvN7Gguia1Rl1BXUtXQyPVtq7IVj9Gr0ZFX1MXKplckwwUrQVyKjS1U2tr/xeUlhQrpEVHKxkaGeuZmCrpABlAQlfFUM/IGMoH0mbmSrGx/wE "Ruby – Try It Online") TIO uses an older version of Ruby, so `_1` is replaced with `|c|c` for 2 extra bytes. [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I/O as an array. ``` ®q.ÃÕvù Õ®f q. ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cVI&code=rnEuw9V2%2bSDVrmYgcS4&input=Ijk4LjYKJDIsNzUwLjE3Ci0kMjMKLTg2CjMsMTIwLDQ4Ny4xOSIKLVI) ``` ®q.ÃÕvù Õ®f q. :Implicit input of array ® :Map q. : Split on "." Ã :End map Õ :Transpose v :Modify first element ù : Left pad with spaces to the length of the longest Õ :Transpose ® :Map f : Filter ('Cause transposing arrays fills gaps with null) q. : Join with "." ``` [Answer] # [Perl 5](https://www.perl.org/) `-00pa` `-MList::Util+max`, 54 bytes ``` s~^[^. ]+~$"x(max(map{/\.|$/;"@-"}@F)-length$&).$&~mge ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4Li46To8rVrtORalCIzcRhAuq9WP0alT0rZUcdJVqHdw0dXNS89JLMlTUNPVU1Opy01P//7e00DPjUjHSMTc10DM059JVMTLm0rUw4zLWMTQy0DGxMNcztOTiArK5DA3@5ReUZObnFf/XNTAoSPyv6@uTWVxiZRVakpmjDbQRAA "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 63 bytes ``` lambda a:[(max(map(len,a))-(s+'.').find('.'))*' '+s for s in a] ``` [Try it online!](https://tio.run/##JYxBCoMwFET3PcVfCD@pMWjSNir0JNZFRIMBjUEttKdPEzowzGMGxn/PeXMymOcrLHodRg267ciqP9GeLJNjmtKCHDlypNxYN5JE9IqA@QFm2@EA60D3IbF7r8O0p8KQDpuaP5BhJpi6l7xSkYtMyBR1GiSrRMluteJVgz1tLxDld@tO8j@i4Qc "Python 3 – Try It Online") Pad decimals to the length of the longest string in the input array. This results in leading whitespace. --- # [Python 3](https://docs.python.org/3/), 80 bytes ``` lambda a:[(max((s+'.').find('.')for s in a)-(s+'.').find('.'))*' '+s for s in a] ``` [Try it online!](https://tio.run/##ZYzNDoIwEITvPsUeSHYrpeFHpZD4JMihBBua2EIoJvr0lcaDB@cyX2Yms7y3aXZV0NdbeCg7jApU25FVLyKfokAmtHEjRdLzCh6MA8Wyv5IdETD18Bv1IbJ72uG@xkBTh40UF@SYlLw@56Kod86SsoomY1Hxosz5SdaiaLBn7QF2LatxG32PWPgA "Python 3 – Try It Online") If leading whitespace were not allowed. [Answer] # [Husk](https://github.com/barbuz/Husk), 24 bytes ``` mṠ+(R' ≠▲m₂¹₂ ?€'.o→L€'. ``` [Try it online!](https://tio.run/##yygtzv7/qKnx0Lb/uQ93LtDWCFJXeNS54NG0TbmPmpoO7QQSXPaPmtao6@U/apvkA2b9///f0kLPjEvFSMfc1EDP0JxLV8XImEvXwozLWMfQyEDHxMJcz9ASAA "Husk – Try It Online") Now corrected. ## Explanation ``` Function ₂: location of dot in string if exists, else length - 1 ?€'.o→L€'. Main function: mṠ+(R' ≠▲m₂¹₂ m map each string to the following: ₂ take current dot position ▲m₂¹ take the highest dot position ≠ and take absolute difference with it R' repeat space that many times Ṡ+( prepend this to the string ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 82 bytes ``` ""<>{" "~Table~#,#2}&~MapThread~{Max[x=#&@@@StringLength@StringSplit[#,"."]]-x,#}& ``` [Try it online!](https://tio.run/##LcnRCoIwFIDhV5Ez8eq0dFYqZOwBEgK9Ey9ONaagIrILQdyrr5Kufj7@gUyrBjLdi5zOHcD1toIHtqJnryxDJrbAFjRV7azobdeClnrJWSClLM3cjfquRm3aP8qp70zNEDg0zWFBtgXu8R3mKLX0VshSfgH0wBeYnEMeJT8cfBHvTfcXYyRCPKUJjzLYnPsA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~105~~ ~~91~~ 76 bytes -14 bytes thanks to Giuseppe's [answer](https://codegolf.stackexchange.com/a/215036/83605) -15 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)!! ``` a=>a.map((w,i)=>''.padEnd(Math.max(...b=a.map(s=>s.search(/\.|$/)))-b[i])+w) ``` [Try it online!](https://tio.run/##JYpLDoIwFAD3nIOkfbE8fiqwKDuXngBIqHykBFtCibjw7lVxNZnMjOIpTLPIefWUbjvbcyt4LvAhZko3JoHnhOAs2otq6VWsw7e8KCLe@H8yPDdoOrE0A/VLfLs@AHi3QlZw2MA2Whk9dTjpO@1p4ZAsxTNhDnEjlpwCDJOfeG4U70z3FrMwCtgxTTDMiFMBjlqqulQ12A8 "JavaScript (Node.js) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 132 bytes ``` func[b][m: 0 foreach s b[m: max m index? any[find s"."tail s]]forall b[t: tail b/1 pad/left b/1 m - 1 + offset? any[find b/1"."t]t]] ``` [Try it online!](https://tio.run/##TU05DoMwEOx5xciiC5chCUeTP6S1tjBgK0jmEHYk8npiaJJt5tLMrqrfn6oXFOgGu35PnWhJjA0y6HlVsnvBoj2MUW4YMUy92h6Q00doz2FZwpwcDCyRL0hjgla4BqfXphyL7FOjtDvFiBgcF8xaW@X@Znx4DJEj2n9/NQSrq@TOwMI8Km9ZwkvP4zAvDqiOoIh4nkXXqkx4zUgE8Lesw@RgA9q/ "Red – Try It Online") [Answer] # C, ~~163~~ ~~141~~ 137 bytes ``` #define f(k)for(char**j=i;*j;++j){char*c=strchr(*j,46);u=c?c-*j:strlen(*j);k;} u,v;a(char**i){f(v=v>u?v:u)f(printf("%*s%s\n",v-u,"",*j))} ``` [Try it online!](https://tio.run/##VYzfbsIgGMXveQqCmgDSpq3OVgnzQbZdNFgm6HCBwk3TZ@/wTzI9N985v5PzyexbymmaHTqlbQcVPhF1cVgeW0epEZpTw5dLQ4YbkcL3Th4dpoatN4QHIfcyo2aX8LmzCRN@4iMILPL28USTQeEo4nvYx10gCv86bXuF0YL6hf@0iMUsMIRYGpMRgFTCn1ZbTOAAYNL1DZQX63sKrf/4guJRXIW2Tb5B7D/PK1a/FXlZP8NsXq1ecvOyWbGyKti6qfNy@8SLux357bTYenK3ruuDs7DgYJymPw) Sadly C isn't the best at strings. Requires a null entry after the last passed in strung to denote end of array. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` WS⊞υ⮌⪪ι.←⮌Eυ⮌⊟ι↘→Eυ∧ι⁺.⊟ι ``` [Try it online!](https://tio.run/##TY3LCoMwFET3@YogLm4gio/WV1eFbgoVRL9A2tQEQgya6OenVgp2NwPnzDx5Pz3HXjq3ciEZhrvS1nRmEmoAQnBjZw6W4pYtbJoZdFoKA4JiL/QIIRfUbKSB6sHe5qDqXv9LzahBELLz9bgwqG7jqloxcHMs7JXin3pVr@9LI@0M29WWjg3nyiLMkJ/Q/ByFcY4CP0lRUGQopXES0VORh3GJXLDIDw "Charcoal – Try It Online") Link is to verbose version of code. Input list needs to be newline-terminated. Assumes a maximum of one `.` in each element. Explanation: ``` WS ``` Loop through each element of the input list. ``` ⊞υ⮌⪪ι. ``` Reverse split each of them on `.`, so that the part to be padded is the last part of the split. ``` ←⮌Eυ⮌⊟ι ``` Extract the parts to be padded, reverse them, reverse the whole list, and then print the result upside-down. This is almost the same as printing them in order, except that the output is now right-aligned rather than left-aligned. ``` ↘ ``` Move the cursor so that the decimal portions can be printed. ``` →Eυ∧ι⁺.⊟ι ``` For each element, print its decimal portion if any, otherwise skip that line (actually by printing an empty array, but fortunately that has the same output as an empty string.) [Answer] # [Factor](https://factorcode.org/), 159 bytes ``` : f ( b -- b ) dup dup [ 46 suffix 46 swap index ] map [ [ [ length ] map ] dip [ - ] 2map ] keep 0 [ max ] reduce [ + ] curry map 32 [ pad-head ] curry 2map ; ``` [Try it online!](https://tio.run/##PY9Na8MwDIbv@RUi9LCxOOSjbdL01NPopZex09jBjZXUNHFcf7CWsd@eyRkMI/nV8yJZ7njrJjO/vx1Prw1wa6fWwsjdBa5oFA6LTicj0IDFm0fVogWrB@mcVD1og849tJHKwT46nho4DLJXjLNBWsemjik/ntHYuYEOnuAMjFF6BuF1iOgD1luwvuvkfVFfXINUAu/wSW8HP5wBVU87LYiykJogI1X8gSuijjJiIw@NBoVvkcoXKlpvzGOZVRaENBfsglz8O8uI/fwN8a5OtzHEqyKpNlmaV6TZqijDVQejTPIiS9Z1lea7GH7oQ@n8Cw "Factor – Try It Online") As if my [Red solution](https://codegolf.stackexchange.com/a/215063/75681) wasn't long enough :) # [Factor](https://factorcode.org/), 200 bytes ``` : f ( b -- b ) [ "."split ] map [ [ first ] map ] [ [ rest concat ] map ] bi [ dup [ length ] [ max ] map-reduce 32 [ pad-head ] 2curry map ] dip zip [ dup last { } = [ concat ] [ "."join ] if ] map ; ``` [Try it online!](https://tio.run/##RY5BT4QwEIXv/IoJ2YMmlCygwrLx4MnsZS/G08ZDaQeoQqltSVw3/nYckKyX6fR7r@@15sIPdnp9ORyfS@DODcLBB1qNHfTct/FgJVpw@DmiFujAmU55r3QDxqL3Z2OV9rAPDscSnjrVaMZZp5xnQ8302Fdo3VRCDTdQAWM0buEEYRwuOfBGJSY4EaqVdeud5kwsEhCDFvyfV4rMcjQkd6gb3y7enn/9OZhFOQoMspSo4ZK1yCVJqRitPa8ZUhn4VmYN6ji1XOAHHunJtW354vugNO2qXuv30wXCXRE/hBBu0ii/38ZJTjvbpNl8FLOQRUm6je6KPE52IcXWEE@/ "Factor – Try It Online") Here I wanted to try a different approach: I split all strings at ".", find the longest integer part and pad all such parts with as many spaces, then zip and join (or concat in case of empty fractional part) with ".". ]
[Question] [ ## A Bit of Background The [exterior algebra](https://en.wikipedia.org/wiki/Exterior_algebra) is a central object in topology and physics (for the physics concept cf. [fermion](https://en.wikipedia.org/wiki/Fermion)). The basic rule dictating the behavior of the exterior algebra is that \$yx = -xy\$ (and consequently \$x^2 = -x^2 = 0\$). Applying this rule twice we see that \$yzx = -yxz = xyz\$. The product of two monomials is 0 if any repeated variable occurs, e.g. \$vxyz \* stuv = 0\$ because \$v\$ is repeated. Otherwise, we want to put the variables into some standard order, say alphabetical order, and there is a sign introduced that counts how many variables we passed by each other, so for example \$tvy \* suxz = +stuvxyz\$ because it takes a total of six crossings to put \$tvysuxz\$ into alphabetical order (on each line I have highlighted the most recently swapped pair): $$tvy \* suxz = +\, tvy\;suxz\\ \phantom{tvy \* suxz } {}= -tv\mathbf{\large sy}uxz\\ \phantom{tvy \* suxz } {}= +t\mathbf{\large sv}yuxz\\ \phantom{tvy \* suxz } {}= -\mathbf{\large st}vyuxz\\ \phantom{tvy \* suxz } {}= +stv\mathbf{\large uy}xz\\ \phantom{tvy \* suxz } {}= -st\mathbf{\large uv}yxz\\ \phantom{tvy \* suxz } {}= +stuv\mathbf{\large xy}z\\ $$ Your task will be to compute this sign. This is a special case of the Koszul Sign Rule which determines the sign of the terms in many sums in math. If you are familiar with determinants, the sign in the determinant formula is an example. ## Task You will take as input two 32 bit integers \$a\$ and \$b\$, which we will interpret as bitflags. You may assume that \$a\$ and \$b\$ have no common bits set, in other words that \$a\mathrel{\&}b = 0\$. Say a pair of integers \$(i, j)\$ where \$0\leq i,j < 32\$ is an "out of order pair in \$(a,b)\$" when: 1. \$i < j\$, 2. bit \$i\$ is set in \$b\$, and 3. bit \$j\$ is set in \$a\$. Your goal is to determine whether the number of out of order pairs in \$(a,b)\$ is even or odd. You should output `true` if the number of out of order pairs is odd, `false` if it is even. **Input** A pair of 32 bit integers. If you would like your input instead to be a list of 0's and 1's or the list of bits set in each integer, that's fine. **Output** `true` or any truthy value if the number of out of order pairs is odd, `false` or any falsey value if it is even. Alternatively, it is fine to output any pair of distinct values for the two cases. It is also fine to output any falsey value when the number of out of order pairs is odd and any truthy value when the number of out of order pairs is even. ## Metric This is code golf so shortest code in bytes wins. ## Test cases ``` a = 0b000000 b = 0b101101 output = false // If one number is 0, the output is always false. a = 0b11 b = 0b10 output = UNDEFINED // a & b != 0 so the behavior is unspecified. a = 0b01 b = 0b10 output = true // 1 out of order pair (1,2). 1 is odd. a = 0b011 b = 0b100 output = false // 2 out of order pairs (1,2) and (1,3). 2 is even. a = 0b0101 b = 0b1010 output = true // 3 out of order pairs (1,2), (1,4), (3,4). 3 is odd. a = 0b0101010 // The example from the introduction b = 0b1010101 output = false // 6 out of order pairs (1,2), (1,4), (1,6), (3,4), (3,6), (5,6). a = 33957418 b = 135299136 output = false a = 2149811776 b = 1293180930 output = false a = 101843025 b = 2147562240 output = false a = 1174713364 b = 2154431232 output = true a = 2289372170 b = 637559376 output = false a = 2927666276 b = 17825795 output = true a = 1962983666 b = 2147814409 output = true // Some asymmetric cases: a = 2214669314 b = 1804730945 output = true a = 1804730945 b = 2214669314 output = false a = 285343744 b = 68786674 output = false a = 68786674 b = 285343744 output = true a = 847773792 b = 139415 output = false ``` [Answer] # [COW](https://bigzaphod.github.io/COW/), ~~363~~ 285 bytes ``` moOoommoOmoOmoOoomMOOmoOmOoMOOMOomOoMoOmoOMMMMOOMMMMOomOoMOomoOmoOMoOmOoMMMOOOmooMMMmoomoOMMMOOOmOoMMMmOoMOOmOoMMMmoOmoOmoOMMMMOOMOomoOMMMMOOMMMMOoMOoMMMOOOmooMMMMoOmOomoomOomOoOOOmoomOomOoMOOMOomoOMoOmOoMMMMOOMMMMOomoOMOomOomOoMoOmoOMMMOOOmooMMMmoomOoMMMOOOmoOMMMmoOmoOmoOmoomoOmoOOOM ``` [Try it online!](https://tio.run/##XU5BDoMgELzzin1AD21tifUHPRDeQJWDB1wjtMbX48Ji1BIyGWaXmWlxjtGhRnSEfIkrnblGIkpjInmk6GjGLBKyzstpSM9ECHk/KXnEboVvWcVQ45@5Oruxf/LMuay70mH7vnXYG2Ipf@x/arin6GMrLu9SjorXBuzPDuLWAHadEO9h/AboPZgBjF@cs2HqW2iNtxcI0wIBwc9mBEMbHXxiJe919RJS1o@nXAE "COW – Try It Online") A major change! (It's faster but still test cases exceed the 60 seconds timeout on TIO) Now I like it better, it's cleaner, symmetric and I've brute forced the memory cells disposition for least number of movements. The idea is to directly operate in terms of parity. Information in both LSB will be used in each iteration and then `a` and `b` will be halved, until `b=0`. * Every `a%2` is calculated (during *repeated subtraction*) alternating `+1` and `-1` in one memory cell, so that their partial sum `p` is available. * When a '1' is found in `b`, the parity (the answer) is toggled `p` many times. ## Detailed Explanation: ``` moo ] mOo < MOo - OOO * OOM i MOO [ moO > MoO + MMM = oom o [0]: a/2 [1]: a [2]: Sum(a%2) [3]: b%2 [4]: b [5]: b/2 [6]: parity >i>>>i ; Read a in [1] and b in [5] [ ; Loop while [5] is non-zero >< ; Just 2 instructions for free cause COW doesn't handle consecutive parethesis :D [ ; Loop while [5] is non-zero -<+>=[=-<->>+<=*]= ; SECTION B ] ; [5] is 0, [3] is b%2, [5] is b/2 >=*<= ; Copy [5] in [4], delete [5] < ; Point to [3] [ ; Loop if [3] is non-zero. '1' it's been found in b, parity gets updated <=>>>= ; Copy [2] in [5] [ ; Loop while [5] is non zero - ; Decrement [5] >=[=--=*]=+< ; TOGGLE [6] ] ; <<* ; Delete [3] (to exit the loop) ] ; << ; Point to [1] [ ; Loop while [1] is non-zero ->+<=[=->-<<+>=*]= ; SECTION A ] ; [1] is 0, a%2 is added in [2], [0] is a/2 <=*>= ; Copy [0] in [1], delete [0] >>> ; Point to [5] ] ; a's and b's LSB have been treated. Now a=a/2 and b=b/2 >>o ; Print [6] ``` `SECTION A` ≈ `SECTION B` is *repeated subtraction* that divide \$n\$ (`a` or `b`, resp.) by \$2\$. This can't be done in one single step (i.e. `--`), because \$0\$ can't be surpassed in order to stop (so it'd be `-[- =*]=`). These sections contextually produce \$n\bmod 2\$ (LSB). `TOGGLE` is a toggling method: When target is **0** it fails the condition and simply `+1` is done. When target is **1** it passes the condition and it's set to **-1** so that `+1` on exit makes it **0**. *Copy*, *delete*, and *paste* in the same memory cell is a tecnique to treat a *while loop* like an *if loop*, also the seemgly useless *copy-paste* at the beginning of these (`=[=`) serves to balance the ending one (`=*]=`) in case *if condition* fails. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 9 bytes Port of my Python answer. Takes `a` and `b` in reverse order, output is 1 for a odd number of out-of-order pairs, 0 for an even number. -2 bytes thanks to *@CommandMaster* ! ``` тÝo÷&bSOÉ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//YtPhufmHt6slBfsf7vz/38jQxNzC0MTEwJLL0NLMyNLC2MzMjIsrtaIgNbkkNUUhv7SkoLTESqGkqDQVAA "05AB1E – Try It Online") ### Explanation ``` Code Comment (Example) Stack # implicit input a, b т # push 100 a, b, 100 Ý # inclusive range a, b, [0,1,...,100] o # 2**x a, b, [1,2,...,2**100] ÷ # integer divide a, [b//1,b//2,...,b//2**100] & # bitwise and [a&b//1, a&b//2, ..., a&b//2**100] b # convert to binary [000100, ... , 00101001001, ..., 0] S # convert to a list of chars ["0", "0", "0", "1", ..., "0"] O # sum (as integers) 4 (number of "out of order pairs") É # is this odd? 0 # implicit output ``` [Answer] # [J](http://jsoftware.com/), 13 bytes ``` 2|[:+/@,>/&I. ``` [Try it online!](https://tio.run/##VY5PSwNBDMXv@ymCit3Fujv5M8lkYKUgCIInr8VLpUW8eLBHv/s6u20HZTKHvPfySz6nq351gDHDCtYQIJd/38Pj68vTRD/bfDds1g/D7XM/dc1x/30ce9hm2L9/fEE7wmHYtC3TDXXX@a3rmibAHCoM2mHAUtDgSaJdaWb1kpmFkxL@Zs6p/7nlnfUFejGZPZpgAuRI7shax1A8IZopIDljCs6VWRhJOFCcYxaVSOoRZUYMmVWKGUUYialSKTkboQVQthhLo/V6J1NVmjdaomgeK9OVPHFxl4UJRYJPvw "J – Try It Online") Take our input as lists of ones and zeros. * `&I.` Convert both `a` and `b` to a lists of the indexes of the ones. * `>/` Create a function table of all pairs of those indexes, where a cell will be `1` when the `a` index is greater than the `b` index. * `[:+/@,` Flatten the table and sum all the ones. * `2|` Remainder when you divide 2 into that sum. Will be 1 (true) exactly when the sum is odd. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` :Ƭ2&BSSḂ ``` A dyadic Link accepting an integer, \$b\$, on the left and an integer, \$a\$, on the right which yields `0` (even) or `1` (odd). **[Try it online!](https://tio.run/##y0rNyan8/9/q2BojNafg4Ic7mv7//29h@t/ECAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##RY49TgNBDIX7nGIkJKqVGP/bKSngAClXWyCySKAoTURBm8ukyQEo6BDcAy4yeDYFhWXrfc9@fpl3u7fW1t9nvL7dbH7ej@3r4/N083s832XdtzaOLEOp02oYcSg0lavyut/OT8/7eVseHw7zBUA3cDdkhzoU6YPnKuMikWAEkKaFQozBFxmDwGtQbiBwOICZLmHAJorISaCCM1WUCxBmAqSeCsYGRMqdKJlIkGUGoueAYMvjYI5ikc9goKkq/mc4MNfIU6EYTgmn1fQH "Jelly – Try It Online"). ### How? ``` :Ƭ2&BSSḂ - Link: integer b, integer a 2 - literal two Ƭ - starting with b, collect up while results are distinct, applying: : - integer division & - bitwise AND (vectorises) with a B - convert to binary (vectorises) S - sum S - sum Ḃ - least significant bit (i.e. mod 2) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~49~~ 46 bytes -3 bytes thanks to Arnauld (and Noodle9)! ``` f=lambda a,b:b and~int(bin(a&b),13)&1^f(a,b/2) ``` [Try it online!](https://tio.run/##ZZJNa8MwDIbv@RW6tE7AbJZsx3Ehg14Kgx0G3a10YNOUBdq0NOlhjO2vd@rX1g9jcKLn1SsZef3Zfawa2u3m5SIs4yxAkHEQITSzn7rp0lg3aejHTKLO@vg@Txk/UrbrqrZroYRJApCqqA5LgoqokLeEUVi0VSZPGI9IwttmexE9hdWd/Jxwn6KOwSO8raS1t85gIQG1Je9R51ec0PgC0TkOI3mNhfL6ujpbFkYrshJY7WxOZG4U6IxDrXOzl1hjNJKmyz6JCq8doePEXDtr@e@mEU8uz3M6NOIKss7bSwf0OflCs@TYRoHGKH9SJNMk6VaaYt3xBMTXQPH3t3iYrzbL0CUJnzxFiBI2VbtddFA3cJjXgK3XGx4riAClkHBySUP2T@IViRekfGKwfwHA7wHEpNdOBfQgFa/D8VhAPT/XK8uzDCq@MojR8PlF/DntfgE "Python 2 – Try It Online") [Answer] # JavaScript (ES6), ~~42~~ 39 bytes Takes input as `(a)(b)`. Almost identical to [ovs' answer](https://codegolf.stackexchange.com/a/203931/58563). ``` a=>g=(b,n=a&b)=>n?!g(b,n&n-1):b&&g(b/2) ``` [Try it online!](https://tio.run/##dY4/b8IwEMX3fAp3SWzVpD7/iWMqgyqVSlUrdWBEDA4kKRVKUJJ2qfrZU0NgoFDLw92937t7H@7Ltatms@tGVb3O@8L2zk5KizNaWRdmxE6q6U25b8NqBGSchaHv7jjp7xcBQgvEMnZ41FfAwH@KCrdtc7SkJwAGkaKu@TybHwV2xXIyXbOxYTzIlxeFMEpLSCkCobgxIJI/BAdpUgCtvQDcCEiZEX9T@MWpFIwruue1SjiXFwxoqUGIRO4hJaUALvh5Ys5TIzQH7c2J0Er57iKQ4TpJEn4IpFOutFHnW8Ak3KTCQ0OcFKRk5sQEyyAu6mbmVu8YLxxFGUVN3i4JshP07Res6qqtt3m8rUvs4q6ed82mKjGJd24971zTYWDE2/6XbgvsCM58dSyQtfsbaIqit5cIjVH09PD8OnuMSPBD@l8 "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` NθNη﹪Σ⭆φ⍘&×θX²ι粦² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5AcUZeaVaPjmp5Tm5GsEl@ZqBJcARdJ9Ews00nQUnBKLUyECGk6ZJeGZxamOeSkaIZm5qcUahToKAfnlQGOMdBQyNTV1FDKA2EhTE0Ja//9vyGX0X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` for true, nothing for false. Port of @ovs's Python answer. Works for somewhat more than 32 bits. Explanation: ``` Nθ Input `a` as a number Nη Input `b` as a number ⭆φ Loop from 0 to 999 and join ×θX²ι Left shift `a` that many times & η Bitwise And with `b` ⍘ ² Convert to base 2 as a string Σ Count total number of bits ﹪ ² Reduce modulo 2 Implicitly print ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 52 bytes ``` +`.(.*)¶.(.*)$ $&¶¶$1¶$2 (.+¶0|¶1).*¶¶ M`1 [13579]$ ``` [Try it online!](https://tio.run/##K0otycxL/P9fO0FPQ09L89A2MKXCpaJ2aNuhbSqGQGzEpaGnfWibQc2hbYaaelogcS4u3wRDrmhDY1Nzy1iV//8NDLkMDQA "Retina 0.8.2 – Try It Online") Takes input in padded binary. Explanation: ``` +`.(.*)¶.(.*)$ $&¶¶$1¶$2 ``` Generate all of the pairs of suffixes of the inputs. ``` (.+¶0|¶1).*¶¶ ``` Delete the pairs of suffixes if the suffix of `b` starts with `0`, otherwise just delete the suffixes of `b`. ``` M`1 ``` Count the total number of bits of suffixes of `a` remaining. ``` [13579]$ ``` Check whether the total is odd. [Answer] # [Io](http://iolanguage.org/), 88 bytes Port of the 05AB1E answer. ``` method(a,b,Range 0 to(100)map(x,((a/2**x)floor&b)asBinary)join removeSeq("0")size isOdd) ``` [Try it online!](https://tio.run/##BcFBCsIwEADAryw9yG4JmMQSW8GLHxD06iWlqaa02ZoEqX4@znguI5zO8CiLyy8e0Ipe3Gx4OpCQGZWUtNgVN4Fo97quNxpn5rjryaaLDzZ@aWIfILqFP@7u3ljJipL/OfDpOgxURtSqObaqaWQnVGd01x6MMQRr9CHPofwB "Io – Try It Online") ]
[Question] [ Imagine a path made up of `<` and `>` and ending in a `@`, e.g. ``` ><>@ ``` A walker starts on the left-most cell. He will traverse the path as follows: * If the walker is on a `@` cell, he's reached the goal and is done. * If the walker is on a `>` cell, the entire path shifts one step to the right, *cyclically, taking the walker with it*. * If the walker is on a `<` cell, the entire path shifts one step to the left, *cyclically, taking the walker with it*. * Afterwards, the walker takes a single step. If he's at either end of the path, he moves away from the end. Otherwise he keeps moving in the direction he moved on the last step (ignoring the rotation), walking right initially. Let's work through the above example. The walker's position is marked with `^`: ``` ><>@ --rotate--> @><> ^ ^ step right (first step): @><> --rotate--> ><>@ ^ ^ step right: ><>@ --rotate--> @><> ^ ^ step left (dead end): @><> --rotate--> ><>@ ^ ^ step left: ><>@ --rotate--> @><> ^ ^ step left: @><> Goal reached! ^ ``` The walker visited **6** cells in the process (including the starting cell as well as the `@`, and counting each cell as often as it's visited). Here is a small example, where the walker is transported across the edges by a rotation: ``` >>@ --rotate--> @>> ^ ^ step right (first step): @>> --rotate--> >@> ^ ^ step right (dead end): >@> Goal reached! ^ ``` This time the walker visited **3** cells. We can easily turn this into an integer sequence: * You're given a positive integer **N**, e.g. `9`. * You compute the the binary representation of this integer, e.g. `1001`. * Then turn `1` into `>` and `0` into `<` and append a `@`: `><<>@`. * We associate with **N** the number of cells visited by the walker in the number constructed this way. The first few elements of the resulting sequence are: ``` 2, 3, 3, 4, 6, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 10, 6, 10, 8, 8, 6, 10, 8, 8, 6, 6, 6, 6, 7, 7 ``` This may seem quite arbitrary, but the resulting sequence actually turns out to have a lot of structure: [![enter image description here](https://i.stack.imgur.com/JMq7c.png)](https://i.stack.imgur.com/JMq7c.png) For reference, you can find the first 2048 numbers of the sequence [in this pastebin](http://pastebin.com/4uuhdUuF). ## The Challenge You guessed it: you're to compute the above sequence. You can do that one of three ways: * You can produce an infinite sequence (while memory permits), either by continuously outputting (separated by non-numeric characters) values or by using some form of infinite generator in languages that support them. If you print an infinite stream to STDOUT, you don't have to print the numbers one by one, but make sure that every number would be printed after a finite amount of time (and in order). If you use this option, you should not take any input. * You can take an integer **N** as input and produce the **N**th term of the sequence. * You can take an integer **N** as input and produce everything *up to* the **N**th term of the sequence, either as a list or string using an unambiguous separator. Since I don't want to penalise languages which can't easily convert between bases, instead of the integer **N** you may instead take the binary representation of **N**, using `0`s and `1`s as usual (as a list or string), with the most-significant bit first. 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. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ### Background This actually computes the number of "ticks" a straight-forward interpreter of my esoteric programming language [Labyrinth](https://github.com/mbuettner/labyrinth) would need to interpret the "path" as source code. In that case, the "walker" is simply the instruction pointer (which has a position and a direction), the `@` command terminates the program and `<` and `>` are source-code modification commands. [Answer] ## Matlab (score=230,n=inf) ``` function w(s,f),b=[];e=0;for i=s:f,a=dec2bin(i);c=find(a=='1');g=numel(a)+1;if numel(c)>=g/2;if mod(g,2)==1,fprintf('%d ',g);else,d=c(g/2);fprintf('%d ',2*d);end,else,fprintf('%d ',g);end,e=e+1;if(e==100),e=0;fprintf('\n');end;end ``` * The function takes s as starting index and f as ending (type `inf` if you want to keep on to infinite). * The function can go forever without any remarkable time-lag between any two outputs type `h=1000000000000000000000000000000000000000000000000000;w(h,h+1)` to make sure. * The algorithm follows a mathematical approach that i will explain later, and it does confirm Martin's referenced list, basing on this program: ``` stored=[2, 3, 3, 4, 6, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 10, 6, 10, 8, 8, 6, 10, 8, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 14, 8, 8, 8, 14, 8, 14, 12, 12, 8, 8, 8, 14, 8, 14, 12, 12, 8, 14, 12, 12, 10, 10, 10, 10, 8, 8, 8, 14, 8, 14, 12, 12, 8, 14, 12, 12, 10, 10, 10, 10, 8, 14, 12, 12, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13]; b=[];for i=1:numel(stored) a=dec2bin(i); c=find(a=='1'); if numel(c)>=(numel(a)+1)/2 if mod(numel(a)+1,2)==1 b=[b numel(a)+1]; else d=c((numel(a)+1)/2); b=[b 2*d]; end else b=[b numel(a)+1]; end end for i=1:numel(stored) if (b(i)) if b(i)~=stored(i) 'error', end end end ``` * Since the algorithm verifies 2048 first testcases, I will blindly assume it would for any test case, so my algorithm works regarding few properties i discovered in this process without the pain of shifting and moving pointer: 1- if the twice the number of 1's in binary translation doesnt exceed the length of the sequnce `L` so the output is`L+1` 2- if the sequence length is even and the previous condition isnt set so the output is same `L+1` 3- otherwise, the output is twice the `L/2`th index of 1. [Answer] # Python, 122 119 113 110 108 107 103 bytes ``` def l(b): p=e=w=len(b);d=i=1 while e:p+=1-2*b[w-e];d*=2*(1!=d-p>~w)-1;p-=d;e=(e-d)%-~w;i+=1 return i ``` Takes input as a list of binary digits. Helper function to test: ``` b = lambda n: [int(d) for d in bin(n)[2:]] ``` Credit to Lynn for saving 7 bytes. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ð+\ḤiḤoµL‘ ``` This function accepts a single integer in form of the list of its binary digits as input. The algorithm is equivalent to the one from [@Agawa001's answer](https://codegolf.stackexchange.com/a/78753). [Try it online!](http://jelly.tryitonline.net/#code=w7ArXOG4pGnhuKRvwrVM4oCY&input=&args=WzEsIDAsIDAsIDEsIDAsIDEsIDFd) or [generate the first 2048 numbers](http://jelly.tryitonline.net/#code=K1zhuKTDsGnhuKRvwrVM4oCYCjIwNDhSQsOH4oKsczMyRw&input=). ### Background Enumerate the positions underneath the path from **0** to **L**, giving a total of **L + 1** positions. **L** coincides the number of binary digits of the number **N** that encodes the path. With this notation, the walker starts at position **0**, the goal at position **L**. With each step the walker takes, he gets one step closer to the goal (in the direction he's currently walking). Also, with each shift-step, depending on whether he walks with or against the shifting direction, he either increments or decrements his position by **2** modulo **L + 1**, or he stays in the current position. To change direction, he has to land on position **L - 1** (facing **L**) or position **1** (facing **0**), then get shifted in his direction. The next step he takes will bring him back to his previous position, facing the opposite direction. * If **L** is even, **L - 1** is odd, so he cannot advance from his initial position to **L - 1** directly. The only way to reach it is to pass through **L**, getting carried to **0** and taking the next step to land on **1**, then advancing to the right. This requires advancing **2L** positions, which can be done in no less than **L** steps. However, after taking **L** steps without changing direction, he will have reached the goal. Adding one for the starting cell, we get a total of **L + 1** visited cells in this case. * If **L** is odd, **L - 1** is even, so he can reach that position by getting shifted **(L - 1) / 2** times to the right. If position **L - 1** is underneath a **1** at that time, he will get shifted to position **L**, turn around, and step on position **L - 1** (facing leftwards). This may or may not happen before he reaches his goal, so there are two cases to analyze: + If there are less than **(L + 1) / 2** occurrences of **1** in the binary expansion of **N**, taking **L** steps will not suffice to turn direction. Since these **L** steps bring the walker to his goal, adding one for the starting cell, we get a total of **L + 1** visited cells in this case. + If there are at least **(L + 1) / 2** occurrences of **1** in the binary expansion of **N**, advancing to the **((L + 1) / 2)**th occurrence will require **I** steps, where **I** is the initial position of that occurrence of **1**. Thus, after taking **I** steps, the walker is in position **L - 1**, facing leftwards. To turn directions again, he would have to walk advance leftwards to position **1**. However, as in the even case, since **(L - 1) - 1** is odd, this will require going through **0** and taking no less tha **L** steps. Since the initial distance to the goal in the left direction is **1**, after taking **I** steps, the walker finds himself at distance of **I + 1** from the goal after changing directions. Since **I < L**, we have that **I + 1 ≤ L**, so the next **I + 1** steps will bring him to the goal. This gives a total of **I + I + 1 = 2I + 1** taken steps. Adding one for the starting cell, we get a total of **2I + 1 + 1 = 2(I + 1)** visited cells in this case. ### How it works ``` ð+\ḤiḤoµL‘ Main link. Argument: x (list of binary digits of N) µ Monadic chain. Argument: x L Compute L, the length of x. ‘ Increment to yield L + 1. ð Dyadic chain. Left argument: x. Right argument: L + 1 +\ Compute the cumulative sum of x. This replaces the k-th one (and all zeroes to its right) with k. Ḥ Unhalve; multiply all partial sums by 2. i Find the first index of L + 1. This either gives I + 1, the 1-based index of the ((L + 1) / 2)-th one or 0 if the list doesn't contain L + 1. The result will be 0 if x contains less than (L + 1) / 2 ones or if L + 1 is an odd integer. Ḥ Unhalve; yield either 2(I + 1) or 0. o Logical OR with L + 1; if the previous operation returned a falsy value (i.e., if it yielded 0), replace that value with L + 1. ``` [Answer] # Python 2, 99 bytes ``` def l(b):l=len(b);return(l>=sum(b)*2or l%2<1)and-~l or[i+1for i,c in enumerate(b)if b[i]][l/2]*2 ``` Python port of Agawa001's brilliant answer. Readable version: ``` def l(b): if len(b) >= 2*sum(b) or len(b)%2 == 0: return len(b) + 1 return 2*[i+1 for i, c in enumerate(b) if b[i]][len(b)//2] ``` [Answer] # MATL, ~~31~~, 25 bytes ``` BXHnQtHsy2/<w2\+~?2/Hfw)E ``` This is just a MATL version of Agawa001's algorithm, except it takes an integer input N and returns the N-th term in the sequence. It was tricky keeping up with all the elements in the stack! I had to resort to using a clipboard to avoid going insane. You can [Try it online!](http://matl.tryitonline.net/#code=QlhIblF0SHN5Mi88dzJcK34_Mi9IZncpRQ&input=NDQ) Can be made into a loop printing the first N terms by adding `:"@` before the code, and `]D` after. Thanks to Luis Mendo for saving 6 whole bytes! [Answer] # Julia 0.4, 4̷4̷ 42 bytes ``` x->(k=endof(x)+1;try k=2find(x)[k/2]end;k) ``` This function accepts a single integer in form of the list of its binary digits as input. The algorithm is equivalent to the one from [@Agawa001's answer](https://codegolf.stackexchange.com/a/78753) and [my Jelly answer](https://codegolf.stackexchange.com/a/78782). [Try it online!](http://julia.tryitonline.net/#code=ZiA9IHgtPihrPWVuZG9mKHgpKzE7dHJ5IGs9MmZpbmQoeClbay8yXWVuZDtrKQoKQmFzZS5zaG93YXJyYXkoU1RET1VULCByZXNoYXBlKFtmKHJldmVyc2UoZGlnaXRzKE4sIDIpKSkgZm9yIE4gaW4gMToyMDQ4XSwgKDMyLCA2NCkpJyk&input=) ### How it works `find(x)` returns the 1-based indices of all non-zero elements of **x**. We attempt to access the resulting array at index **k / 2** and, if successful, overwrite **k** with twice the selected index. This will fail if and only if one of the following is true: * **k / 2** is a non-integral float, so and *InexactError* is raised. * The index array has less than **k / 2** elements, so a *BoundsError* is raised. In either case, overwriting **k** will fail, so its original value will be returned. [Answer] ## JavaScript (ES6), 65 bytes ``` s=>(l=s.length+1)%2|!(m=s.match(`(0*1){$l/2}}`))?l:m[0].length*2 ``` Accepts a binary string. Uses the bounce check from the various other answers. [Answer] # Python 2, 74 bytes ``` def f(x):k=len(x)+1;print next((i*2for i in range(k)if k==2*sum(x[:i])),k) ``` This function accepts a single integer in form of the list of its binary digits as input. The algorithm is equivalent to the one from [@Agawa001's answer](https://codegolf.stackexchange.com/a/78753) and [my Jelly answer](https://codegolf.stackexchange.com/a/78782). [Test it on Ideone](http://ideone.com/AohqyB). ### How it works `next` attempts to find the first integer **2i** for which `k==2*sum(x[:i])` returns true. Since `x[:i]` contains **i** elements, this gives the 1-based index of the **(k / 2)**th **1**. `next` will fail if **k/2** is non-integral or if **x** contains less than **k / 2** ones. In this case, the default value **k** is returned. [Answer] ## [><>](https://esolangs.org/wiki/Fish), 63 bytes ``` 2r11&>}:?v{1->:l2-%?vr{{$>1+$}$:2=$@&101. +&?!^&n;>{1+^ .0+bf< ``` From the moment I saw the example pattern in this challenge, I knew which language to use :) Using **N** to get the **N**th term. Input assumed to be in binary at the stack. Rather than moving the walker around, this solution relies mostly on moving the tape under the walker. [Try it online!](https://www.fishlanguage.com/playground) ]
[Question] [ ## NOTE This problem was taken from [this reddit thread](http://www.reddit.com/r/dailyprogrammer/comments/27h53e/662014_challenge_165_hard_simulated_ecology_the/) (spoiler alert!), and I have adjusted it to make it fit with this site's format. All credit goes to reddit user "Coder\_d00d". In this problem, we will simulate a forest. For this simulated forest we will be dealing with 3 aspects. * Trees which can be a Sapling, Tree or Elder Tree. * Lumberjacks (He chops down down trees, he eats his lunch and goes to the Lava-try) * Bears (He mauls the lumberjacks who smells like pancakes) A fore-warning: these rules are most probably not perfect. See them as a guideline, and if you need to tweak anything slightly that is fine (spawning rates have been pointed out as an issue, see [kuroi neko](https://codegolf.stackexchange.com/users/16991/kuroi-neko)'s answer as an example of this. ## Cycle of time: The simulation will simulate by months. You will progessive forward in time with a "tick". Each "tick" represents a month. Every 12 "ticks" represents a year. Our forest will change and be in constant change. We will record the progress of our forest and analyze what happens to it. ## Forest: The forest will be a two dimensional forest. We will require an input of N to represent the size of the forest in a grid that is N x N in size. At each location you can hold Trees, Bears or Lumberjacks. **They can occupy the same spot** but often events occur when they occupy the same spot. Our forest will be spawned randomly based on the size. For example if your value of N = 10. You will have a 10 by 10 forest and 100 spots. * 10% of the Forest will hold a Lumberjack in 10 random spots. (using our 100 spot forest this should be 10 lumberjacks) * 50% of the Forest will hold Trees (Trees can be one of 3 kinds and will start off as the middle one of "Tree") in random spots. * 2% of the Forest will hold Bears. How you receive the size of the forest is up to you (read from stdin, a file, or hardcode it in). I would recommend keeping N like 5 or higher. Small Forests are not much fun. ## Events: During the simulation there will be events. The events occur based on some logic which I will explain below. I will describe the events below in each description of the 3 elements of our forest. The events follow the order of trees first, lumberjacks second and bears last. ## Trees: * Every month a Tree has a 10% chance to spawn a new "Sapling". In a random open space adjacent to a Tree you have a 10% chance to create a "Sapling". * For example a Tree in the middle of the forest has 8 other spots around it. One of these (if they are empty) will become a "Sapling". * After 12 months of being in existence a "Sapling" will be upgrade to a "Tree". A "Sapling" cannot spawn other trees until it has matured into a "Tree". * Once a "Sapling" becomes a tree it can spawn other new "Saplings". * When a "Tree" has been around for 120 months (10 years) it will become an "Elder Tree". * Elder Trees have a 20% chance to spawn a new "Sapling" instead of 10%. * If there are no open adjacent spots to a Tree or Elder Tree it will not spawn any new Trees. ## Lumberjacks: Lumberjacks cut down trees, they skip and jump they like to press wild flowers. * Each month lumberjacks will wander. They will move up to 3 times to a randomly picked spot that is adjacent in any direction. So for example a Lumberjack in the middle of your grid has 8 spots to move to. He will wander to a random spot. Then again. And finally for a third time. NB: This can be **any** spot (so they can walk into bears, resulting in a maul). * When the lumberjack moves, if he encounters a Tree (not a sapling), he will stop and his wandering for that month comes to an end. He will then harvest the Tree for lumber. Remove the tree. Gain 1 piece of lumber. * Lumberjacks will not harvest "Saplings". * Lumberacks also harvest Elder Trees. Elder Trees are worth 2 pieces of lumber. ## Lumber Tracking: Every 12 months the amount of lumber harvested is compared to the number of lumberjacks in the forest. * If the lumber collected equals or exceeds the amount of lumberjacks in the forest a number of new lumberjacks are hired and randomly spawned in the forest. * Work out the number of lumberjacks to hire with: `floor(lumber_collected / number_of_lumberjacks)` * However if after a 12 month span the amount of lumber collected is below the number of lumberjacks then a lumberjack is let go to save money and 1 random lumberjack is removed from the forest. Note that you will never reduce your Lumberjack labor force below 0. ## Bears: Bears wander the forest much like a lumberjack. However instead of 3 spaces a Bear will roam up to 5 spaces. * If a bear comes across a Lumberjack he will stop his wandering for the month. (For example after 2 moves the bear lands on a space with a lumberjack he will not make any more moves for this month) * Lumberjacks smell like pancakes. Bears love pancakes. Therefore the Bear will unfortunately maul and hurt the lumberjack. The lumberjack will be removed from the forest (He will go home and shop on wednesdays and have buttered scones for tea). * We will track this as a "Maul" accident. * Note that the lumberjack population can never drop below 1 - so if the last lumberjack is mauled just spawn another one in. ## Maul Tracking: * During the course of 12 months if there 0 "Maul" accidents then the Bear population will increase by 1. If however there are any "Maul" accidents the Lumberjacks will hire a Zoo to trap and take a Bear away. Remove 1 random Bear. Note that if your Bear population reaches 0 bears then there will be no "Maul" accidents in the next year and so you will spawn 1 new Bear next year. * If there is only 1 lumberjack in the forest and he gets Mauled, he will be sent home, but a new one will be hired immediately and respawned somewhere else in the forest. The lumberjack population can never drop below 1. ## Time: The simulation occurs for 4800 months (400 years), or until no Saplings, Trees or Elder Trees exist. ## Output: Every month you will print out a map of the forest - perhaps using an ASCII map, or using graphics and colours. ## Optional Extras * You could output the populations of trees, lumberjacks and bears each tick. * You could output whenever an event occurs (e.g: "A bear mauled a lumberjack.") ## Scoring This is a popularity contest, so most upvotes wins! EDIT - People have pointed out a number of flaws in my rules, and while you can feel free to ask me questions, it is also okay to tweak the rules a bit to suit your own program, or interpretation of the program. [Answer] # Javascript+HTML - [try it](http://petiteleve.free.fr/SO/bear_forest2.html) ## Updated as per popular request ![forest and graph](https://i.stack.imgur.com/2hoWz.png) ## General behaviour The program is now somewhat interactive. The source code is completely parametrized, so you can tweak a few more internal parameters with your favourite text editor. You can change the forest size. A minimum of 2 is required to have enough room to place a tree, a lumberjack and a bear on 3 different spots, and the max is arbitrarily fixed to 100 (which will make your average computer crawl). You can also change the simulation speed. Display is updated every 20 ms, so a greater time step will produce finer animations. The buttons allow to stop/start the simulation, or run it for a month or a year. Movement of the forest dwellers is now somewhat animated. Mauling and tree cutting events are also figured. A log of some events is also displayed. Some more messages are available if you change the verbosity level, but that would flood you with "Bob cuts yet another tree" notifications. I would rather not do it if I were you, but I ain't, so... Beside the playground, a set of auto-scaled graphics are drawn: * bears and lumberjacks populations * total number of trees, divided in saplings, mature and elder trees The legend also displays current quantities of each item. ## System stability The graphs show that the initial conditions do not scale that gracefully. If the forest is too big, too many bears decimate the lumberjack population until enough of the pancake lovers have been put behind bars. This causes an initial explosion of elder trees, that in turn helps the lumberjack population to recover. It seems 15 is the minimal size for the forest to survive. A forest of size 10 will usually get razed after a few hundred years. Any size above 30 will produce a map nearly full of trees. Between 15 and 30, you can see the tree population oscillating significantly. ## Some debatable rule points In the comments of the original post, it seems various bipeds are not supposed to occupy the same spot. This contradicts somehow the rule about a redneck wandering into a pancake amateur. At any rate, I did not follow that guideline. Any forest cell can hold any number of inhyabitants (and exactly zero or one tree). This might have some consequences on the lumberjack efficiency: I suspect it allows them to dig into a clump of elder trees more easily. As for bears, I don't expect this to make a lot of difference. I also opted for having always at least one lumberjack in the forest, despite the point stating that the redneck population could reach zero (firing the last lumberjack on the map if the harvest was really poor, which will never happen anyway unless the forest has been chopped down to extinction). ## Tweaking In order to achieve stability, I added two tweaking parameters : 1) lumberjacks growth rate a coefficient applied to the formula that gives the number of extra lumberjacks hired when there is enough timber. Set to 1 to get back to original definition, but I found a value of about .5 allowed the forest (esp. elder trees) to develop better. 2) bear removal criterion a coefficient that defines the minimal percentage of mauled lumberjacks to send a bear to the zoo. Set to 0 to go back to original definition, but this drastic bear elimination will basically limit the population to a 0-1 oscillation cycle. I set it to .15 (i.e. a bear is removed only if 15% or more of the lumberjacks have been mauled this year). This allows for a moderate bear population, sufficient to prevent the rednecks from wiping the area clean but still allowing a sizeable part of the forest to be chopped. As a side note, the simulation never stops (even past the required 400 years). It could easily do so, but it doesn't. ## The code The code is entirely contained in a single HTML page. It **must be UTF-8 encoded** to display the proper unicode symbols for bears and lumberjacks. ***For the Unicode impaired systems*** (e.g. Ubuntu): find the following lines: ``` jack :{ pic: '🙎', color:'#bc0e11' }, bear :{ pic: '🐻', color:'#422f1e' }}, ``` and change the pictograms for characters easier to display (`#`, `*`, whatever) ``` <!doctype html> <meta charset=utf-8> <title>Of jacks and bears</title> <body onload='init();'> <style> #log p { margin-top: 0; margin-bottom: 0; } </style> <div id='main'> </div> <table> <tr> <td><canvas id='forest'></canvas></td> <td> <table> <tr> <td colspan=2> <div>Forest size <input type='text' size=10 onchange='create_forest(this.value);'> </div> <div>Simulation tick <input type='text' size= 5 onchange='set_tick(this.value);' > (ms)</div> <div> <input type='button' value='◾' onclick='stop();'> <input type='button' value='▸' onclick='start();'> <input type='button' value='1 month' onclick='start(1);'> <input type='button' value='1 year' onclick='start(12);'> </div> </td> </tr> <tr> <td id='log' colspan=2> </td> </tr> <tr> <td><canvas id='graphs'></canvas></td> <td id='legend'></td> </tr> <tr> <td align='center'>evolution over 60 years</td> <td id='counters'></td> </tr> </table> </td> </tr> </table> <script> // ================================================================================================== // Global parameters // ================================================================================================== var Prm = { // ------------------------------------ // as defined in the original challenge // ------------------------------------ // forest size forest_size: 45, // 2025 cells // simulation duration duration: 400*12, // 400 years // initial populations populate: { trees: .5, jacks:.1, bears:.02 }, // tree ages age: { mature:12, elder:120 }, // tree spawning probabilities spawn: { sapling:0, mature:.1, elder:.2 }, // tree lumber yields lumber: { mature:1, elder:2 }, // walking distances distance: { jack:3, bear:5 }, // ------------------------------------ // extra tweaks // ------------------------------------ // lumberjacks growth rate // (set to 1 in original contest parameters) jacks_growth: 1, // .5, // minimal fraction of lumberjacks mauled to send a bear to the zoo // (set to 0 in original contest parameters) mauling_threshold: .15, // 0, // ------------------------------------ // internal helpers // ------------------------------------ // offsets to neighbouring cells neighbours: [ {x:-1, y:-1}, {x: 0, y:-1}, {x: 1, y:-1}, {x:-1, y: 0}, {x: 1, y: 0}, {x:-1, y: 1}, {x: 0, y: 1}, {x: 1, y: 1}], // ------------------------------------ // goodies // ------------------------------------ // bear and people names names: { bear: ["Art", "Ursula", "Arthur", "Barney", "Bernard", "Bernie", "Bjorn", "Orson", "Osborn", "Torben", "Bernadette", "Nita", "Uschi"], jack: ["Bob", "Tom", "Jack", "Fred", "Paul", "Abe", "Roy", "Chuck", "Rob", "Alf", "Tim", "Tex", "Mel", "Chris", "Dave", "Elmer", "Ian", "Kyle", "Leroy", "Matt", "Nick", "Olson", "Sam"] }, // months month: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], // ------------------------------------ // graphics // ------------------------------------ // messages verbosity (set to 2 to be flooded, -1 to have no trace at all) verbosity: 1, // pixel sizes icon_size: 100, canvas_f_size: 600, // forest canvas size canvas_g_width : 400, // graphs canvas size canvas_g_height: 200, // graphical representation graph: { soil: { color: '#82641e' }, sapling:{ radius:.1, color:'#52e311', next:'mature'}, mature :{ radius:.3, color:'#48b717', next:'elder' }, elder :{ radius:.5, color:'#8cb717', next:'elder' }, jack :{ pic: '🙎', color:'#2244ff' }, bear :{ pic: '🐻', color:'#422f1e' }, mauling:{ pic: '★', color:'#ff1111' }, cutting:{ pic: '●', color:'#441111' }}, // animation tick tick:100 // ms }; // ================================================================================================== // Utilities // ================================================================================================== function int_rand (num) { return Math.floor (Math.random() * num); } function shuffle (arr) { for ( var j, x, i = arr.length; i; j = int_rand (i), x = arr[--i], arr[i] = arr[j], arr[j] = x); } function pick (arr) { return arr[int_rand(arr.length)]; } function message (str, level) { level = level || 0; if (level <= Prm.verbosity) { while (Gg.log.childNodes.length > 10) Gg.log.removeChild(Gg.log.childNodes[0]); var line = document.createElement ('p'); line.innerHTML = Prm.month[Forest.date%12]+" "+Math.floor(Forest.date/12)+": "+str; Gg.log.appendChild (line); } } // ================================================================================================== // Forest // ================================================================================================== // -------------------------------------------------------------------------------------------------- // a forest cell // -------------------------------------------------------------------------------------------------- function cell() { this.contents = []; } cell.prototype = { add: function (elt) { this.contents.push (elt); }, remove: function (elt) { var i = this.contents.indexOf (elt); this.contents.splice (i, 1); }, contains: function (type) { for (var i = 0 ; i != this.contents.length ; i++) { if (this.contents[i].type == type) { return this.contents[i]; } } return null; } } // -------------------------------------------------------------------------------------------------- // an entity (tree, jack, bear) // -------------------------------------------------------------------------------------------------- function entity (x, y, type) { this.age = 0; switch (type) { case "jack": this.name = pick (Prm.names.jack); break; case "bear": this.name = pick (Prm.names.bear); break; case "tree": this.name = "sapling"; Forest.t.low++; break; } this.x = this.old_x = x; this.y = this.old_y = y; this.type = type; } entity.prototype = { move: function () { Forest.remove (this); var n = neighbours (this); this.x = n[0].x; this.y = n[0].y; return Forest.add (this); } }; // -------------------------------------------------------------------------------------------------- // a list of entities (trees, jacks, bears) // -------------------------------------------------------------------------------------------------- function elt_list (type) { this.type = type; this.list = []; } elt_list.prototype = { add: function (x, y) { if (x === undefined) x = int_rand (Forest.size); if (y === undefined) y = int_rand (Forest.size); var e = new entity (x, y, this.type); Forest.add (e); this.list.push (e); return e; }, remove: function (elt) { var i; if (elt) // remove a specific element (e.g. a mauled lumberjack) { i = this.list.indexOf (elt); } else // pick a random element (e.g. a bear punished for the collective pancake rampage) { i = int_rand(this.list.length); elt = this.list[i]; } this.list.splice (i, 1); Forest.remove (elt); if (elt.name == "mature") Forest.t.mid--; if (elt.name == "elder" ) Forest.t.old--; return elt; } }; // -------------------------------------------------------------------------------------------------- // global forest handling // -------------------------------------------------------------------------------------------------- function forest (size) { // initial parameters this.size = size; this.surface = size * size; this.date = 0; this.mauling = this.lumber = 0; this.t = { low:0, mid:0, old:0 }; // initialize cells this.cells = new Array (size); for (var i = 0 ; i != size ; i++) { this.cells[i] = new Array(size); for (var j = 0 ; j != size ; j++) { this.cells[i][j] = new cell; } } // initialize entities lists this.trees = new elt_list ("tree"); this.jacks = new elt_list ("jack"); this.bears = new elt_list ("bear"); this.events = []; } forest.prototype = { populate: function () { function fill (num, list) { for (var i = 0 ; i < num ; i++) { var coords = pick[i_pick++]; list.add (coords.x, coords.y); } } // shuffle forest cells var pick = new Array (this.surface); for (var i = 0 ; i != this.surface ; i++) { pick[i] = { x:i%this.size, y:Math.floor(i/this.size)}; } shuffle (pick); var i_pick = 0; // populate the lists fill (Prm.populate.jacks * this.surface, this.jacks); fill (Prm.populate.bears * this.surface, this.bears); fill (Prm.populate.trees * this.surface, this.trees); this.trees.list.forEach (function (elt) { elt.age = Prm.age.mature; }); }, add: function (elt) { var cell = this.cells[elt.x][elt.y]; cell.add (elt); return cell; }, remove: function (elt) { var cell = this.cells[elt.x][elt.y]; cell.remove (elt); }, evt_mauling: function (jack, bear) { message (bear.name+" sniffs a delicious scent of pancake, unfortunately for "+jack.name, 1); this.jacks.remove (jack); this.mauling++; Gg.counter.mauling.innerHTML = this.mauling; this.register_event ("mauling", jack); }, evt_cutting: function (jack, tree) { if (tree.name == 'sapling') return; // too young to be chopped down message (jack.name+" cuts a "+tree.name+" tree: lumber "+this.lumber+" (+"+Prm.lumber[tree.name]+")", 2); this.trees.remove (tree); this.lumber += Prm.lumber[tree.name]; Gg.counter.cutting.innerHTML = this.lumber; this.register_event ("cutting", jack); }, register_event: function (type, position) { this.events.push ({ type:type, x:position.x, y:position.y}); }, tick: function() { this.date++; this.events = []; // monthly updates this.trees.list.forEach (b_tree); this.jacks.list.forEach (b_jack); this.bears.list.forEach (b_bear); // feed graphics Gg.graphs.trees.add (this.trees.list.length); Gg.graphs.jacks.add (this.jacks.list.length); Gg.graphs.bears.add (this.bears.list.length); Gg.graphs.sapling.add (this.t.low); Gg.graphs.mature .add (this.t.mid); Gg.graphs.elder .add (this.t.old); // yearly updates if (!(this.date % 12)) { // update jacks if (this.jacks.list.length == 0) { message ("An extra lumberjack is hired after a bear rampage"); this.jacks.add (); } if (this.lumber >= this.jacks.list.length) { var extra_jacks = Math.floor (this.lumber / this.jacks.list.length * Prm.jacks_growth); message ("A good lumbering year. Lumberjacks +"+extra_jacks, 1); for (var i = 0 ; i != extra_jacks ; i++) this.jacks.add (); } else if (this.jacks.list.length > 1) { var fired = this.jacks.remove(); message (fired.name+" has been chopped", 1); } // update bears if (this.mauling > this.jacks.list.length * Prm.mauling_threshold) { var bear = this.bears.remove(); message (bear.name+" will now eat pancakes in a zoo", 1); } else { var bear = this.bears.add(); message (bear.name+" starts a quest for pancakes", 1); } // reset counters this.mauling = this.lumber = 0; } } } function neighbours (elt) { var ofs,x,y; var list = []; for (ofs in Prm.neighbours) { var o = Prm.neighbours[ofs]; x = elt.x + o.x; y = elt.y + o.y; if ( x < 0 || x >= Forest.size || y < 0 || y >= Forest.size) continue; list.push ({x:x, y:y}); } shuffle (list); return list; } // -------------------------------------------------------------------------------------------------- // entities behaviour // -------------------------------------------------------------------------------------------------- function b_tree (tree) { // update tree age and category if (tree.age == Prm.age.mature) { tree.name = "mature"; Forest.t.low--; Forest.t.mid++; } else if (tree.age == Prm.age.elder ) { tree.name = "elder" ; Forest.t.mid--; Forest.t.old++; } tree.age++; // see if we can spawn something if (Math.random() < Prm.spawn[tree.name]) { var n = neighbours (tree); for (var i = 0 ; i != n.length ; i++) { var coords = n[i]; var cell = Forest.cells[coords.x][coords.y]; if (cell.contains("tree")) continue; Forest.trees.add (coords.x, coords.y); break; } } } function b_jack (jack) { jack.old_x = jack.x; jack.old_y = jack.y; for (var i = 0 ; i != Prm.distance.jack ; i++) { // move var cell = jack.move (); // see if we stumbled upon a bear var bear = cell.contains ("bear"); if (bear) { Forest.evt_mauling (jack, bear); break; } // see if we reached an harvestable tree var tree = cell.contains ("tree"); if (tree) { Forest.evt_cutting (jack, tree); break; } } } function b_bear (bear) { bear.old_x = bear.x; bear.old_y = bear.y; for (var i = 0 ; i != Prm.distance.bear ; i++) { var cell = bear.move (); var jack = cell.contains ("jack"); if (jack) { Forest.evt_mauling (jack, bear); break; // one pancake hunt per month is enough } } } // -------------------------------------------------------------------------------------------------- // Graphics // -------------------------------------------------------------------------------------------------- function init() { function create_counter (desc) { var counter = document.createElement ('span'); var item = document.createElement ('p'); item.innerHTML = desc.name+"&nbsp;"; item.style.color = desc.color; item.appendChild (counter); return { item:item, counter:counter }; } // initialize forest canvas Gf = { period:20, tick:0 }; Gf.canvas = document.getElementById ('forest'); Gf.canvas.width = Gf.canvas.height = Prm.canvas_f_size; Gf.ctx = Gf.canvas.getContext ('2d'); Gf.ctx.textBaseline = 'Top'; // initialize graphs canvas Gg = { counter:[] }; Gg.canvas = document.getElementById ('graphs'); Gg.canvas.width = Prm.canvas_g_width; Gg.canvas.height = Prm.canvas_g_height; Gg.ctx = Gg.canvas.getContext ('2d'); // initialize graphs Gg.graphs = { jacks: new graphic({ name:"lumberjacks" , color:Prm.graph.jack.color }), bears: new graphic({ name:"bears" , color:Prm.graph.bear.color, ref:'jacks' }), trees: new graphic({ name:"trees" , color:'#0F0' }), sapling: new graphic({ name:"saplings" , color:Prm.graph.sapling.color, ref:'trees' }), mature: new graphic({ name:"mature trees", color:Prm.graph.mature .color, ref:'trees' }), elder: new graphic({ name:"elder trees" , color:Prm.graph.elder .color, ref:'trees' }) }; Gg.legend = document.getElementById ('legend'); for (g in Gg.graphs) { var gr = Gg.graphs[g]; var c = create_counter (gr); gr.counter = c.counter; Gg.legend.appendChild (c.item); } // initialize counters var counters = document.getElementById ('counters'); var def = [ "mauling", "cutting" ]; var d; for (d in def) { var c = create_counter ({ name:def[d], color:Prm.graph[def[d]].color }); counters.appendChild (c.item); Gg.counter[def[d]] = c.counter; } // initialize log Gg.log = document.getElementById ('log'); // create our forest create_forest(Prm.forest_size); start(); } function create_forest (size) { if (size < 2) size = 2; if (size > 100) size = 100; Forest = new forest (size); Prm.icon_size = Prm.canvas_f_size / size; Gf.ctx.font = 'Bold '+Prm.icon_size+'px Arial'; Forest.populate (); draw_forest(); var g; for (g in Gg.graphs) Gg.graphs[g].reset(); draw_graphs(); } function animate() { if (Gf.tick % Prm.tick == 0) { Forest.tick(); draw_graphs(); } draw_forest(); Gf.tick+= Gf.period; if (Gf.tick == Gf.stop_date) stop(); } function draw_forest () { function draw_dweller (dweller) { var type = Prm.graph[dweller.type]; Gf.ctx.fillStyle = type.color; var x = dweller.x * time_fraction + dweller.old_x * (1 - time_fraction); var y = dweller.y * time_fraction + dweller.old_y * (1 - time_fraction); Gf.ctx.fillText (type.pic, x * Prm.icon_size, (y+1) * Prm.icon_size); } function draw_event (evt) { var gr = Prm.graph[evt.type]; Gf.ctx.fillStyle = gr.color; Gf.ctx.fillText (gr.pic, evt.x * Prm.icon_size, (evt.y+1) * Prm.icon_size); } function draw_tree (tree) { // trees grow from one category to the next var type = Prm.graph[tree.name]; var next = Prm.graph[type.next]; var radius = (type.radius + (next.radius - type.radius) / Prm.age[type.next] * tree.age) * Prm.icon_size; Gf.ctx.fillStyle = Prm.graph[tree.name].color; Gf.ctx.beginPath(); Gf.ctx.arc((tree.x+.5) * Prm.icon_size, (tree.y+.5) * Prm.icon_size, radius, 0, 2*Math.PI); Gf.ctx.fill(); } // background Gf.ctx.fillStyle = Prm.graph.soil.color; Gf.ctx.fillRect (0, 0, Gf.canvas.width, Gf.canvas.height); // time fraction to animate displacements var time_fraction = (Gf.tick % Prm.tick) / (Prm.tick-Gf.period); // entities Forest.trees.list.forEach (draw_tree); Forest.jacks.list.forEach (draw_dweller); Forest.bears.list.forEach (draw_dweller); Forest.events.forEach (draw_event); } // -------------------------------------------------------------------------------------------------- // Graphs // -------------------------------------------------------------------------------------------------- function graphic (prm) { this.name = prm.name || '?'; this.color = prm.color || '#FFF'; this.size = prm.size || 720; this.ref = prm.ref; this.values = []; this.counter = document.getElement } graphic.prototype = { draw: function () { Gg.ctx.strokeStyle = this.color; Gg.ctx.beginPath(); for (var i = 0 ; i != this.values.length ; i++) { var x = (i + this.size - this.values.length) / this.size * Gg.canvas.width; var y = (1-(this.values[i] - this.min) / this.rng) * Gg.canvas.height; if (i == 0) Gg.ctx.moveTo (x, y); else Gg.ctx.lineTo (x, y); } Gg.ctx.stroke(); }, add: function (value) { // store value this.values.push (value); this.counter.innerHTML = value; // cleanup history while (this.values.length > this.size) this.values.splice (0,1); // compute min and max this.min = Math.min.apply(Math, this.values); if (this.min > 0) this.min = 0; this.max = this.ref ? Gg.graphs[this.ref].max : Math.max.apply(Math, this.values); this.rng = this.max - this.min; if (this.rng == 0) this.rng = 1; }, reset: function() { this.values = []; } } function draw_graphs () { function draw_graph (graph) { graph.draw(); } // background Gg.ctx.fillStyle = '#000'; Gg.ctx.fillRect (0, 0, Gg.canvas.width, Gg.canvas.height); // graphs var g; for (g in Gg.graphs) { var gr = Gg.graphs[g]; gr.draw(); } } // -------------------------------------------------------------------------------------------------- // User interface // -------------------------------------------------------------------------------------------------- function set_tick(value) { value = Math.round (value / Gf.period); if (value < 2) value = 2; value *= Gf.period; Prm.tick = value; return value; } function start (duration) { if (Prm.timer) stop(); Gf.stop_date = duration ? Gf.tick + duration*Prm.tick : -1; Prm.timer = setInterval (animate, Gf.period); } function stop () { if (Prm.timer) { clearInterval (Prm.timer); Prm.timer = null; } Gf.stop_date = -1; } </script> </body> ``` ## What next? More remarks are still welcome. N.B: I'm aware sapling/mature/elder trees count is still a bit messy, but to hell with it. Also, I find document.getElementById more readable than $, so no need to complain about the lack of jQueryisms. It's jQuery free on purpose. To Each his own, right? [Answer] ## AngularJS [Here is my version](http://jsfiddle.net/Blackhole/K8AYT/), which is still a Work In Progress: the code is a bit… well… ugly. And quite slow. I also plan to add more options to parametrize the evolution and to analyse the state of the forest. Comments and amelioration proposals are welcome! ![Screenshot of the forest](https://i.stack.imgur.com/CWB7H.png) [**Demonstration**](http://jsfiddle.net/Blackhole/K8AYT/show/) ``` <div ng-app="ForestApp" ng-controller="ForestController"> <form name="parametersForm" ng-hide="evolutionInProgress" autocomplete="off" novalidate> <div class="line"> <label for="forestSize">Size of the forest:</label> <input type="number" ng-model="Parameters.forestSize" id="forestSize" min="5" ng-pattern="/^[0-9]+$/" required /> </div> <div class="line"> <label for="simulationInterval">Number of milliseconds between each tick</label> <input type="number" ng-model="Parameters.simulationInterval" id="simulationInterval" min="10" ng-pattern="/^[0-9]+$/" required /> </div> <div class="line"> <label for="animationsEnabled">Animations enabled? <br /><small>(>= 300 ms between each tick is advisable)</small> </label> <input type="checkbox" ng-model="Parameters.animationsEnabled" id="animationsEnabled" /> </div> <div class="line"> <button ng-disabled="parametersForm.$invalid || evolutionInProgress" ng-click="launchEvolution()">Launch the evolution!</button> </div> </form> <div id="forest" ng-style="{width: side = (20*Parameters.forestSize) + 'px', height: side, 'transition-duration': transitionDuration = (Parameters.animationsEnabled ? 0.8*Parameters.simulationInterval : 0) + 'ms', '-webkit-transition-duration': transitionDuration}"> <div ng-repeat="bear in Forest.bearsList" class="entity entity--bear" ng-style="{left: (20*bear.x) + 'px', top: (20*bear.y) + 'px'}"></div> <div ng-repeat="lumberjack in Forest.lumberjacksList" class="entity entity--lumberjack" ng-style="{left: (20*lumberjack.x) + 'px', top: (20*lumberjack.y) + 'px'}"></div> <div ng-repeat="tree in Forest.treesList" class="entity entity--tree" ng-class="'entity--tree--' + tree.stage" ng-style="{left: (20*tree.x) + 'px', top: (20*tree.y) + 'px'}"></div> </div> <div class="line"><em>Age of the forest:</em><samp>{{floor(Forest.age/12)}} year{{floor(Forest.age/12) > 1 ? 's' : ''}} and {{Forest.age%12}} month{{Forest.age%12 > 1 ? 's' : ''}}</samp></div> <div class="line"><em>Number of bears:</em><samp>{{Forest.bearsList.length}}</samp></div> <div class="line"><em>Number of lumberjacks:</em><samp>{{Forest.lumberjacksList.length}}</samp></div> <br /> <div class="line"><em>Number of lumbers collected:</em><samp>{{Forest.numberOfLumbers}}</samp></div> <div class="line"><em>Number of mauls:</em><samp>{{Forest.numberOfMauls}}</samp></div> </div> ``` ``` /** @link http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array */ function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } var forestApp = angular.module('ForestApp', ['ngAnimate']); forestApp.value('Parameters', { /** @var int[] Maximal number of moves by species */ speed: { bear: 5, lumberjack: 3, }, /** @var int[] Initial percentage of each species in the forest */ initialPercentage: { bear: 2, lumberjack: 10, tree: 50, }, /** @var int[] Spawing rate, in percentage, of new saplings around an existing tree */ spawningPercentage: { 0: 0, 1: 10, 2: 20, }, /** @var int[] Age of growth for an existing tree */ ageOfGrowth: { sapling: 12, tree: 120, }, /** @var int[] Lumber collected on an existing tree */ numberOfLumbers: { tree: 1, elderTree: 2, }, /** @var int Size of each side of the forest */ forestSize: 20, /** @var int Number of milliseconds between each tick (month in the forest) */ simulationInterval: 50, }); forestApp.constant('TREE_STAGE', { SAPLING: 0, TREE: 1, ELDER_TREE: 2, }); forestApp.factory('Tree', ['Forest', 'Parameters', 'TREE_STAGE', function (Forest, Parameters, TREE_STAGE) { // Classes which represents a tree var Tree = function (stage, x, y) { /** @var TREE_STAGE Current stage of the tree */ this.stage = stage; /** @var int Current age of the tree, in month */ this.age = 0; /** @var int X coordinates of the tree */ this.x = x; /** @var int Y coordinates of the tree */ this.y = y; this.tick = function () { if (Math.random() < Parameters.spawningPercentage[this.stage] / 100) { var freePositionsList = shuffle(Forest.getFreePositionsAround(this.x, this.y)); if (freePositionsList.length > 0) { var saplingPosition = freePositionsList[0]; Tree.create(TREE_STAGE.SAPLING, saplingPosition[0], saplingPosition[1]); } } ++this.age; if (this.stage === TREE_STAGE.SAPLING && this.age == Parameters.ageOfGrowth.sapling) { this.stage = TREE_STAGE.TREE; } else if (this.stage === TREE_STAGE.TREE && this.age == Parameters.ageOfGrowth.tree) { this.stage = TREE_STAGE.ELDER_TREE; } }; /** * Remove the entity */ this.remove = function () { var index = Forest.treesList.indexOf(this); Forest.treesList.splice(index, 1); }; }; Tree.create = function (stage, x, y) { Forest.add.tree(new Tree(stage, x, y)); }; return Tree; }]); forestApp.factory('Lumberjack', ['Forest', 'Parameters', 'TREE_STAGE', function (Forest, Parameters, TREE_STAGE) { // Classes which represents a lumberjack var Lumberjack = function (x, y) { /** @var int X coordinates of the lumberjack */ this.x = x; /** @var int Y coordinates of the lumberjack */ this.y = y; this.tick = function () { for (movement = Parameters.speed.lumberjack; movement > 0; --movement) { var positionsList = shuffle(Forest.getPositionsAround(this.x, this.y)); var newPosition = positionsList[0]; this.x = newPosition[0]; this.y = newPosition[1]; var tree = Forest.getTreeAt(this.x, this.y); if (tree !== null) { if (tree.stage === TREE_STAGE.SAPLING) { return; } else if (tree.stage === TREE_STAGE.TREE) { Forest.numberOfLumbers += Parameters.numberOfLumbers.tree; } else { Forest.numberOfLumbers += Parameters.numberOfLumbers.elderTree; } tree.remove(); movement = 0; }; } }; /** * Remove the entity */ this.remove = function () { if (Forest.lumberjacksList.length === 1) { this.x = Math.floor(Math.random() * Parameters.forestSize); this.y = Math.floor(Math.random() * Parameters.forestSize); } else { var index = Forest.lumberjacksList.indexOf(this); Forest.lumberjacksList.splice(index, 1); } }; }; Lumberjack.create = function (x, y) { Forest.add.lumberjack(new Lumberjack(x, y)); }; return Lumberjack; }]); forestApp.factory('Bear', ['Forest', 'Parameters', function (Forest, Parameters) { // Classes which represents a bear var Bear = function (x, y) { /** @var int X coordinates of the bear */ this.x = x; /** @var int Y coordinates of the bear */ this.y = y; this.tick = function () { for (movement = Parameters.speed.bear; movement > 0; --movement) { var positionsList = shuffle(Forest.getPositionsAround(this.x, this.y)); var newPosition = positionsList[0]; this.x = newPosition[0]; this.y = newPosition[1]; angular.forEach(Forest.getLumberjacksListAt(this.x, this.y), function (lumberjack) { lumberjack.remove(); ++Forest.numberOfMauls; movement = 0; }); } }; /** * Remove the entity */ this.remove = function () { var index = Forest.bearsList.indexOf(this); Forest.bearsList.splice(index, 1); }; }; Bear.create = function (x, y) { Forest.add.bear(new Bear(x, y)); }; return Bear; }]); forestApp.service('Forest', ['Parameters', function (Parameters) { var forest = this; this.age = 0; this.numberOfLumbers = 0; this.numberOfMauls = 0; this.bearsList = []; this.lumberjacksList = []; this.treesList = []; this.getEntitiesList = function () { return forest.bearsList.concat(forest.lumberjacksList, forest.treesList); }; /** * Age the forest by one month */ this.tick = function () { angular.forEach(forest.getEntitiesList(), function (entity) { entity.tick(); }); ++forest.age; }; this.add = { bear: function (bear) { forest.bearsList.push(bear); }, lumberjack: function (lumberjack) { forest.lumberjacksList.push(lumberjack); }, tree: function (tree) { forest.treesList.push(tree); }, }; /** * @return Tree|null Tree at this position, or NULL if there is no tree. */ this.getTreeAt = function (x, y) { var numberOfTrees = forest.treesList.length; for (treeId = 0; treeId < numberOfTrees; ++treeId) { var tree = forest.treesList[treeId]; if (tree.x === x && tree.y === y) { return tree; } } return null; }; /** * @return Lumberjack[] List of the lumberjacks at this position */ this.getLumberjacksListAt = function (x, y) { var lumberjacksList = []; angular.forEach(forest.lumberjacksList, function (lumberjack) { if (lumberjack.x === x && lumberjack.y === y) { lumberjacksList.push(lumberjack); } }); return lumberjacksList; }; /** * @return int[] Positions around this position */ this.getPositionsAround = function (x, y) { var positionsList = [ [x - 1, y - 1], [x, y - 1], [x + 1, y - 1], [x - 1, y], [x + 1, y], [x - 1, y + 1], [x, y + 1], [x + 1, y + 1] ]; return positionsList.filter(function (position) { return (position[0] >= 0 && position[1] >= 0 && position[0] < Parameters.forestSize && position[1] < Parameters.forestSize); }); }; /** * @return int[] Positions without tree around this position */ this.getFreePositionsAround = function (x, y) { var positionsList = forest.getPositionsAround(x, y); return positionsList.filter(function (position) { return forest.getTreeAt(position[0], position[1]) === null; }); }; }]); forestApp.controller('ForestController', ['$interval', '$scope', 'Bear', 'Forest', 'Lumberjack', 'Parameters', 'Tree', 'TREE_STAGE', function ($interval, $scope, Bear, Forest, Lumberjack, Parameters, Tree, TREE_STAGE) { $scope.Forest = Forest; $scope.Parameters = Parameters; $scope.evolutionInProgress = false; $scope.floor = Math.floor; var positionsList = []; /** * Start the evolution of the forest */ $scope.launchEvolution = function () { $scope.evolutionInProgress = true; for (var x = 0; x < Parameters.forestSize; ++x) { for (var y = 0; y < Parameters.forestSize; ++y) { positionsList.push([x, y]); } } shuffle(positionsList); var numberOfBears = Parameters.initialPercentage.bear * Math.pow(Parameters.forestSize, 2) / 100; for (var bearId = 0; bearId < numberOfBears; ++bearId) { Bear.create(positionsList[bearId][0], positionsList[bearId][1]); } shuffle(positionsList); var numberOfLumberjacks = Parameters.initialPercentage.lumberjack * Math.pow(Parameters.forestSize, 2) / 100; for (var lumberjackId = 0; lumberjackId < numberOfLumberjacks; ++lumberjackId) { Lumberjack.create(positionsList[lumberjackId][0], positionsList[lumberjackId][1]); } shuffle(positionsList); var numberOfTrees = Parameters.initialPercentage.tree * Math.pow(Parameters.forestSize, 2) / 100; for (var treeId = 0; treeId < numberOfTrees; ++treeId) { Tree.create(TREE_STAGE.TREE, positionsList[treeId][0], positionsList[treeId][1]); } $interval(function () { Forest.tick(); if (Forest.age % 12 === 0) { // Hire or fire lumberjacks if (Forest.numberOfLumbers >= Forest.lumberjacksList.length) { shuffle(positionsList); var numberOfLumberjacks = Math.floor(Forest.numberOfLumbers / Forest.lumberjacksList.length); for (var lumberjackId = 0; lumberjackId < numberOfLumberjacks; ++lumberjackId) { Lumberjack.create(positionsList[lumberjackId][0], positionsList[lumberjackId][1]); } } else { shuffle(Forest.lumberjacksList); Forest.lumberjacksList[0].remove(); } // Hire or fire bears if (Forest.numberOfMauls === 0) { shuffle(positionsList); Bear.create(positionsList[0][0], positionsList[0][1]); } else { Forest.bearsList[0].remove(); } Forest.numberOfLumbers = 0; Forest.numberOfMauls = 0; } }, Parameters.simulationInterval); }; }]); ``` [Answer] # Javascript I think this mostly works. There's some wonky behavior where I spawn all the new bears/lumberjacks in sync and right next to each other because laziness in insertions. This implementation does not allow lumberjacks to stand on saplings, cause you know, trampling saplings is bad. Fiddle art uses colored rectangles by default, change the second line to false to use letters to draw. [fiddle](http://jsfiddle.net/q47LH/4/) HTML: ``` <canvas id="c" width="1" height="1"></canvas> <div id="p1"></div> <div id="p2"></div> <div id="p3"></div> <div id="p4"></div> ``` Js: ``` var n = 10; // Size of the grid var drawUsingColor = true; // If true, draws colors for each entity instead :D var intervalTime = 1000; // how often each tick happens, in milliseconds var jackRatio = 0.1; var treeRatio = 0.5; var bearRatio = 0.02; var size = 48; // Pixels allocated (in size x size) for each entity var font = "30px Lucida Console"; // if drawUsingColor is false var bearColor = '#8B4513'; // Saddlebrown var elderColor = '#556B2F'; // DarkOliveGreen var lumberjackColor = '#B22222'; // Firebrick var treeColor = '#008000'; // Green var saplingColor = '#ADFF2F'; // GreenYellow // Game rules: var spawnSaplingChance = 0.1; var elderTreeAge = 120; var elderSaplingChance = 0.2; var treeAge = 12; var lumberjackRange = 3; var bearRange = 5; var zooPeriod = 12; // If a maul happens within this period var lumberPeriod = 12; // New lumberjacks hired in this period var time = 1; var world; var n2 = n * n; //because one saved keystroke var zooqueue = []; var lumberqueue = []; var canvas = document.getElementById('c'); // Needs more jquery var context = canvas.getContext('2d'); context.font = font; // various statistics var treesAlive = 0; var jacksAlive = 0; var bearsAlive = 0; var currentLumber = 0; var lumberjacksMauled = 0; var recentEvents = ''; // Entity is a bear, eldertree, lumberjack, tree, sapling, with age. aka belts. function Entity(belts, birthday) { this.type = belts; this.age = 0; this.birthday = birthday; } function initWorld() { canvas.height = size * n; canvas.width = size * n; world = new Array(n2); // One pass spawning algorithm: numEntity = number of entity left to spawn // If rand() in range [0,numtrees), spawn tree // if rand() in range [numtrees, numtrees+numjacks), spawn lumberjack // if rand() in range [numtrees+numjacks, numtrees+numjacks+numbears), spawn bear var numTrees = treeRatio * n2; var numJacks = jackRatio * n2; var numBears = bearRatio * n2; var godseed = new Array(n2); for (var i = 0; i < n2; i++) { godseed[i] = i; } shuffle(godseed); for (var i = 0; i < n2; i++) { var god = godseed.pop(); if (god < numTrees) { world[i] = new Entity('T', 0); treesAlive++; } else if (god < numTrees + numJacks) { world[i] = new Entity('L', 0); jacksAlive++; } else if (god < numTrees + numJacks + numBears) { world[i] = new Entity('B', 0); bearsAlive++; } // console.log(world, i); } // populate zoo array, lumber array for (var i = 0; i < zooPeriod; i++) { zooqueue.push(0); } for (var i = 0; i < lumberPeriod; i++) { lumberqueue.push(0); } } animateWorld = function () { recentEvents = ''; computeWorld(); drawWorld(); time++; $('#p1').text(treesAlive + ' trees alive'); $('#p2').text(bearsAlive + ' bears alive'); $('#p3').text(jacksAlive + ' lumberjacks alive'); $('#p4').text(recentEvents); }; function computeWorld() { zooqueue.push(lumberjacksMauled); lumberqueue.push(currentLumber); // Calculate entity positions for (var i = 0; i < n2; i++) { if (world[i]) { switch (world[i].type) { case 'B': bearStuff(i); break; case 'E': elderStuff(i); break; case 'L': lumberjackStuff(i); break; case 'T': treeStuff(i); break; case 'S': saplingStuff(i); break; } } } // Pop the # mauls from zooPeriod's ago, if lumberjacksMauled > oldmauls, then someone was eaten. var oldmauls = zooqueue.shift(); if (time % zooPeriod === 0) { if (lumberjacksMauled > oldmauls) { if (remove('B') == 1) { bearsAlive--; recentEvents += 'Bear sent to zoo! '; } } else { bearsAlive++; spawn('B'); recentEvents += 'New bear appeared! '; } } var oldLumber = lumberqueue.shift(); if (time % lumberPeriod === 0) { // # lumberjack to hire var hire = Math.floor((currentLumber - oldLumber) / jacksAlive); if (hire > 0) { recentEvents += 'Lumber jack hired! (' + hire + ') '; while (hire > 0) { jacksAlive++; spawn('L'); hire--; } } else { if (remove('L') == 1) { recentEvents += 'Lumber jack fired! '; jacksAlive--; } else { } } } // Ensure > 1 lumberjack if (jacksAlive === 0) { jacksAlive++; spawn('L'); recentEvent += 'Lumberjack spontaneously appeared'; } } // Not the job of spawn/remove to keep track of whatever was spawned/removed function spawn(type) { var index = findEmpty(type); if (index != -1) { world[index] = new Entity(type, time); } // recentEvents += 'Spawned a ' + type + '\n'; } function remove(type) { var index = findByType(type); if (index != -1) { world[index] = null; return 1; } return -1; // recentEvents += 'Removed a ' + type + '\n'; } // Searches in world for an entity with type=type. Currently implemented as // linear scan, which isn't very random function findByType(type) { for (var i = 0; i < n2; i++) { if (world[i] && world[i].type == type) return i; } return -1; } // Also linear scan function findEmpty(type) { for (var i = 0; i < n2; i++) { if (!world[i]) { return i; } } return -1; } function bearStuff(index) { if (world[index].birthday == time) { return; } // Wander around var tindex = index; for (var i = 0; i < lumberjackRange; i++) { var neighbors = get8Neighbor(tindex); var mov = neighbors[Math.floor(Math.random() * neighbors.length)]; if (world[mov] && world[mov].type == 'L') { recentEvents += 'Bear (' + index % 10 + ',' + Math.floor(index / 10) + ') mauled a Lumberjack (' + mov % 10 + ',' + Math.floor(mov / 10) + ') !'; lumberjacksMauled++; jacksAlive--; world[mov] = new Entity('B', time); world[mov].age = ++world[index].age; world[index] = null; return; } tindex = mov; } if (!world[tindex]) { world[tindex] = new Entity('B', time); world[tindex].age = ++world[index].age; world[index] = null; } } function elderStuff(index) { if (world[index].birthday == time) { return; } neighbors = get8Neighbor(index); // spawn saplings for (var i = 0; i < neighbors.length; i++) { if (!world[neighbors[i]]) { if (Math.random() < elderSaplingChance) { world[neighbors[i]] = new Entity('S', time); treesAlive++; } } } // become older world[index].age++; } function lumberjackStuff(index) { if (world[index].birthday == time) { return; } // Wander around var tindex = index; for (var i = 0; i < lumberjackRange; i++) { var neighbors = get8Neighbor(tindex); var mov = neighbors[Math.floor(Math.random() * neighbors.length)]; if (world[mov] && (world[mov].type == 'T' || world[mov].type == 'E')) { world[mov].type == 'T' ? currentLumber++ : currentLumber += 2; treesAlive--; world[mov] = new Entity('L', time); world[mov].age = ++world[index].age; world[index] = null; return; } tindex = mov; } if (!world[tindex]) { world[tindex] = new Entity('L', time); world[tindex].age = ++world[index].age; world[index] = null; } } function treeStuff(index) { if (world[index].birthday == time) { return; } neighbors = get8Neighbor(index); // spawn saplings for (var i = 0; i < neighbors.length; i++) { if (!world[neighbors[i]]) { if (Math.random() < spawnSaplingChance) { world[neighbors[i]] = new Entity('S', time); treesAlive++; } } } // promote to elder tree? if (world[index].age >= elderTreeAge) { world[index] = new Entity('E', time); return; } // become older world[index].age++; } function saplingStuff(index) { if (world[index].birthday == time) { return; } // promote to tree? if (world[index].age > treeAge) { world[index] = new Entity('T', time); return; } world[index].age++; } // Returns array containing up to 8 valid neighbors. // Prolly gonna break for n < 3 but oh well function get8Neighbor(index) { neighbors = []; if (index % n != 0) { neighbors.push(index - n - 1); neighbors.push(index - 1); neighbors.push(index + n - 1); } if (index % n != n - 1) { neighbors.push(index - n + 1); neighbors.push(index + 1); neighbors.push(index + n + 1); } neighbors.push(index - n); neighbors.push(index + n); return neighbors.filter(function (val, ind, arr) { return (0 <= val && val < n2) }); } // Each entity allocated 5x5px for their art function drawWorld() { context.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i < n2; i++) { if (world[i]) { var x = i % n; var y = Math.floor(i / n); switch (world[i].type) { case 'B': drawBear(x, y); break; case 'E': drawElder(x, y); break; case 'L': drawJack(x, y); break; case 'T': drawTree(x, y); break; case 'S': drawSapling(x, y); break; } } } } function drawBear(x, y) { if (drawUsingColor) { drawRect(x * size, y * size, size, size, bearColor); } else { drawLetter(x * size, y * size, 'B'); } } function drawElder(x, y) { if (drawUsingColor) { drawRect(x * size, y * size, size, size, elderColor); } else { drawLetter(x * size, y * size, 'E'); } } function drawJack(x, y) { if (drawUsingColor) { drawRect(x * size, y * size, size, size, lumberjackColor); } else { drawLetter(x * size, y * size, 'J'); } } function drawTree(x, y) { if (drawUsingColor) { drawRect(x * size, y * size, size, size, treeColor); } else { drawLetter(x * size, y * size, 'T'); } } function drawSapling(x, y) { if (drawUsingColor) { drawRect(x * size, y * size, size, size, saplingColor); } else { drawLetter(x * size, y * size, 'S'); } } function drawLine(x1, y1, x2, y2, c) { context.beginPath(); context.moveTo(x1, y1); context.lineTo(x2, y2); context.lineWidth = 3; context.strokeStyle = c; context.stroke(); } function drawRect(x, y, w, h, c) { context.fillStyle = c; context.fillRect(x, y, w, h); } function drawLetter(x, y, l) { context.fillText(l, x, y); } $(document).ready(function () { initWorld(); intervalID = window.setInterval(animateWorld, intervalTime); /*$('#s').click(function() { animateWorld(); })*/ }); // http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } ``` [Answer] # Python Nothing fancy. I kept on adding stuff, so refactoring might be in order. (And I didn't do unitest so bugs might still be present). I gave random names to lumberjacks and bears. Trees are `i`, then `I`, then `#`, Lumberjacks are `x`, Bears are `o` ``` import os from random import randint, choice, shuffle from time import sleep NGRID = 15 SLEEPTIME = 0.0125 DURATION = 4800 VERBOSE = True ###init grid = [[[] for _ in range(NGRID)] for _ in range(NGRID)] #Money earned this year n_lumbers = 0 #Lumberjacks killed this year n_maul = 0 tick = 0 events = [] #total number of d_total = {'trees':0, 'lumberjacks': 0, 'bears': 0, 'cut': 0, 'maul': 0, 'capture': 0, 'lumbers': 0, 'fired': 0} d_oldest = {'tree': 0, 'lumberjack': (0, ""), 'bear': (0, "")} d_most = {'n_maul': (0, ""), 'n_lumber': (0, ""), 'n_cut': (0, "")} d_year = {'n_maul': 0, 'n_lumber': 0} ###Classes class Tree(object): """Represent a Sapling, Tree, or Elder Tree""" def __init__(self, coords, m=0, t='Sapling'): self.months = m self.typeof = t self.coords = coords def grow(self, m=1): """the tree grows 1 month and its type might change""" self.months = self.months + m if self.months == 12: self.typeof = 'Tree' elif self.months == 480: self.typeof = 'Elder Tree' def __str__(self): if self.typeof == 'Sapling': return 'i' elif self.typeof == 'Tree': return 'I' else: return '#' class Animated(object): """Animated beings can move""" def __init__(self, coords): self.coords = coords self.old_coords = None self.months = 0 def where(self): return c_neighbors(self.coords) def choose_new_coords(self): self.old_coords = self.coords possible = self.where() if possible: direction = choice(self.where()) self.coords = [(self.coords[i]+direction[i]) % NGRID for i in range(2)] # def __del__(self): # print "died at "+ str(self.coords) class Lumberjack(Animated): """Lumberjacks chop down trees""" def __init__(self, coords): super(Lumberjack, self).__init__(coords) self.nb_cut = 0 self.nb_lumber = 0 self.name = gen_name("l") def __str__(self): return "x" class Bear(Animated): """Bears maul""" def __init__(self, coords): super(Bear, self).__init__(coords) self.nb_maul = 0 self.name = gen_name("b") def where(self): return c_land_neighbors(self.coords) def __str__(self): return "o" ###list of coords def c_neighbors(coords): """returns the list of coordinates of adjacent cells""" return [[(coords[0] + i) % NGRID, (coords[1] + j) % NGRID] \ for i in [-1, 0, 1] \ for j in [-1, 0, 1] \ if (i,j) != (0, 0)] def c_empty_neighbors(coords): """returns the list of coordinates of adjacent cells that are empty """ return [[i, j] for [i,j] in c_neighbors(coords) if grid[i][j] == []] def c_land_neighbors(coords): """returns the list of coordinates of adjacent cells that contain not Trees for bears""" return [[i, j] for [i,j] in c_neighbors(coords)\ if (grid[i][j] == []) or (not isinstance(grid[i][j][0], Tree))] def c_empty_cells(): """returns list of coords of empty cells in the grid""" return [[i, j] for i in range(NGRID) for j in range(NGRID) if grid[i][j] == []] def c_not_bear_cells(): """returns list of coords of cells without bear""" return [[i, j] for i in range(NGRID) for j in range(NGRID) \ if not isinstance(grid[i][j], Bear)] ###one less def maul(lumberjack): """a lumberjack will die""" global n_maul n_maul = n_maul + 1 d_total['maul'] = d_total['maul'] + 1 remove_from_grid(lumberjack.coords, lumberjack) return lumberjack.name + " is sent to hospital" + check_lumberjacks() def capture_bear(): """too many mauls, a Zoo traps a bear""" d_total['capture'] = d_total['capture'] + 1 bear = choice(get_bears()) remove_from_grid(bear.coords, bear) return bear.name + " has been captured" def fire_lumberjack(): """the job is not done correctly, one lumberjack is let go""" d_total['fired'] = d_total['fired'] + 1 lumberjack = choice(get_lumberjacks()) remove_from_grid(lumberjack.coords, lumberjack) return lumberjack.name + " has been fired" + check_lumberjacks() def remove_from_grid(coords, item): """remove item from the grid at the coords""" grid[coords[0]][coords[1]].remove(item) del item ###one more def new_animate(class_): """a new lumberjack or bear joins the forest""" if class_==Bear: d_total['bears'] = d_total['bears'] + 1 x, y = choice(c_empty_cells()) else: d_total['lumberjacks'] = d_total['lumberjacks'] + 1 x, y = choice(c_not_bear_cells()) new_being = class_([x,y]) grid[x][y].append(new_being) return "a new " + class_.__name__ + " enters the forest: " + new_being.name def check_lumberjacks(): """we will never reduce our Lumberjack labor force below 0""" if len(get_lumberjacks())==0: return " - no more lumberjack, " + new_animate(Lumberjack) return "" ###movements def move_on_grid(being): [x, y] = being.old_coords grid[x][y].remove(being) [x, y] = being.coords grid[x][y].append(being) def move_lumberjack(lumberjack): """Lumberjacks move 3 times if they don't encounter a (Elder) Tree or a Bear""" global n_lumbers for _ in range(3): lumberjack.choose_new_coords() move_on_grid(lumberjack) [x, y] = lumberjack.coords #is there something at the new coordinate? #move append so this lumberjack is at the end if grid[x][y][:-1] != []: if isinstance(grid[x][y][0], Tree): the_tree = grid[x][y][0] price = worth(the_tree) if price > 0: lumberjack.nb_cut = lumberjack.nb_cut + 1 d_most['n_cut'] = max((lumberjack.nb_cut, lumberjack.name), \ d_most['n_cut']) d_total['cut'] = d_total['cut'] + 1 n_lumbers = n_lumbers + price d_total['lumbers'] = d_total['lumbers'] + 1 lumberjack.nb_lumber = lumberjack.nb_lumber + price d_most['n_lumber'] = max(d_most['n_lumber'], \ (lumberjack.nb_lumber, lumberjack.name)) remove_from_grid([x, y], the_tree) return lumberjack.name + " cuts 1 " + the_tree.typeof #if there is a bear, all lumberjacks have been sent to hospital if isinstance(grid[x][y][0], Bear): #the first bear is the killer b = grid[x][y][0] b.nb_maul = b.nb_maul + 1 d_most['n_maul'] = max((b.nb_maul, b.name), d_most['n_maul']) return maul(lumberjack) return None def move_bear(bear): """Bears move 5 times if they don't encounter a Lumberjack""" for _ in range(5): bear.choose_new_coords() move_on_grid(bear) [x, y] = bear.coords there_was_something = (grid[x][y][:-1] != []) if there_was_something: #bears wander where there is no tree #so it's either a lumberjack or another bear #can't be both. if isinstance(grid[x][y][0], Lumberjack): bear.nb_maul = bear.nb_maul + 1 d_most['n_maul'] = max((bear.nb_maul, bear.name), \ d_most['n_maul']) return maul(grid[x][y][0]) return None ###get objects def get_objects(class_): """get a list of instances in the grid""" l = [] for i in range(NGRID): for j in range(NGRID): if grid[i][j]: for k in grid[i][j]: if isinstance(k, class_): l.append(k) return l def get_trees(): """list of trees""" return get_objects(Tree) def get_bears(): """list of bears""" return get_objects(Bear) def get_lumberjacks(): """list of lumberjacks""" return get_objects(Lumberjack) ###utils def gen_name(which="l"): """generate random name""" name = "" for _ in range(randint(1,4)): name = name + choice("bcdfghjklmnprstvwxz") + choice("auiey") if which == "b": name = name[::-1] return name.capitalize() def worth(tree): """pieces for a tree""" if tree.typeof == 'Elder Tree': return 2 if tree.typeof == 'Tree': return 1 return 0 def one_month(): """a step of one month""" events = [] global tick tick = tick + 1 #each Tree can spawn a new sapling for t in get_trees(): l_empty_spaces = c_empty_neighbors(t.coords) percent = 10 if t.typeof == 'Tree' else \ 20 if t.typeof == 'Elder Tree' else 0 if (randint(1,100) < percent): if l_empty_spaces: [x, y] = choice(l_empty_spaces) grid[x][y] = [Tree([x,y])] d_total['trees'] = d_total['trees'] + 1 t.grow() d_oldest['tree'] = max(t.months, d_oldest['tree']) #each lumberjack/bear moves for l in get_lumberjacks(): l.months = l.months + 1 d_oldest['lumberjack'] = max((l.months, l.name), \ d_oldest['lumberjack']) event = move_lumberjack(l) if event: events.append(event) for b in get_bears(): b.months = b.months + 1 d_oldest['bear'] = max((b.months, b.name), d_oldest['bear']) event = move_bear(b) if event: events.append(event) return events def print_grid(): """print the grid if more than 1 thing is at a place, print the last. At 1 place, there is - at most a tree and possibly several lumberjack - or 1 bear """ print "-" * 2 * NGRID print '\n'.join([' '.join([str(i[-1]) if i != [] else ' ' \ for i in line]) \ for line in grid]) print "-" * 2 * NGRID def clean(): """clear the console""" os.system('cls' if os.name == 'nt' else 'clear') def print_grid_and_events(): """print grid and list of events""" clean() print_grid() if VERBOSE: print '\n'.join(events) print "-" * 2 * NGRID ###populate the forest l = c_empty_cells() shuffle(l) for x, y in l[:((NGRID*NGRID) / 2)]: grid[x][y] = [Tree([x, y], 12, 'Tree')] d_total['trees'] = d_total['trees'] + 1 l = c_empty_cells() shuffle(l) for x, y in l[:((NGRID*NGRID) / 10)]: grid[x][y] = [Lumberjack([x, y])] d_total['lumberjacks'] = d_total['lumberjacks'] + 1 l = c_empty_cells() shuffle(l) for x, y in l[:((NGRID*NGRID) / 10)]: grid[x][y] = [Bear([x, y])] d_total['bears'] = d_total['bears'] + 1 ###time goes on while (tick <= DURATION and len(get_trees())>0): events = one_month() #end of the year if (tick % 12)==0: events.append("End of the year") #lumber tracking nlumberjacks = len(get_lumberjacks()) events.append(str(n_lumbers) + " lumbers VS " +\ str(nlumberjacks) + " Lumberjacks") if n_lumbers >= nlumberjacks: n_hire = n_lumbers/nlumberjacks events.append("we hire " + str(n_hire) +\ " new Lumberjack" + ("s" if (n_hire > 1) else "")) for _ in range(n_hire): events.append(new_animate(Lumberjack)) else: events.append(fire_lumberjack()) d_year['n_lumber'] = max(d_year['n_lumber'], n_lumbers) n_lumbers = 0 #maul tracking events.append("maul this year: " + str(n_maul)) if n_maul == 0: events.append(new_animate(Bear)) else: events.append(capture_bear()) d_year['n_maul'] = max(d_year['n_maul'], n_maul) n_maul = 0 print_grid_and_events() sleep(SLEEPTIME) print "-"*70 print "End of the game" print "-"*70 print "month:" + str(tick - 1) print "number of trees still alive: " + str(len(get_trees())) print "number of lumberjacks still alive: " + str(len(get_lumberjacks())) print "number of bears still alive: " + str(len(get_bears())) print "-"*70 print "oldest Tree ever is/was: " + str(d_oldest['tree']) print "oldest Lumberjack ever is/was: " + str(d_oldest['lumberjack'][0]) + \ " yo " + d_oldest['lumberjack'][1] print "oldest Bear ever is/was: " + str(d_oldest['bear'][0]) + \ " yo " + d_oldest['bear'][1] print "-"*70 print "max cut by a Lumberjack: " + str(d_most['n_cut'][0]) + \ " by " + str(d_most['n_cut'][1]) print "max lumber by a Lumberjack: " + str(d_most['n_lumber'][0]) + \ " by " + str(d_most['n_lumber'][1]) print "max maul by a Bear: " + str(d_most['n_maul'][0]) + \ " by " + str(d_most['n_maul'][1]) print "-"*70 print "max lumber in a year: " + str(d_year['n_lumber']) print "max maul in a year: " + str(d_year['n_maul']) print "-"*70 print "Total of:" for i, j in d_total.items(): print i, str(j) ``` Some outputs: ``` ------------------------------ x I I x i I i i i i I I x i i I I i I I i i o i i I I I i i I x i I I I I I I i x ------------------------------ Dy is sent to hospital Lehuniru cuts 1 Tree ------------------------------ ``` End of the year ``` ------------------------------ x x i I I i I x I i i x I I i I i I i i I i I i x i I i I o x ------------------------------ Fuha cuts 1 Tree Ka cuts 1 Tree Ky is sent to hospital End of the year 11 lumbers VS 4 Lumberjacks we hire 2 new Lumberjacks a new Lumberjack enters the forest: Di a new Lumberjack enters the forest: Dy maul this year: 6 Evykut has been captured ------------------------------ ``` End of the game ``` ------------------------------ x i x x x x x i x i I I i x x I i x x i i x i i i i I i i I I i I i I i i i i x i I i I I I x i I I x ------------------------------ Vanabixy cuts 1 Tree Fasiguvy cuts 1 Tree ------------------------------ ---------------------------------------------------------------------- End of the game ---------------------------------------------------------------------- month:4800 number of trees still alive: 36 number of lumberjacks still alive: 15 number of bears still alive: 0 ---------------------------------------------------------------------- oldest Tree ever is/was: 129 oldest Lumberjack ever is/was: 308 yo Cejuka oldest Bear ever is/was: 288 yo Ekyx ---------------------------------------------------------------------- max cut by a Lumberjack: 44 by Cejuka max lumber by a Lumberjack: 44 by Cejuka max maul by a Bear: 52 by Ekyx ---------------------------------------------------------------------- max lumber in a year: 84 max maul in a year: 86 ---------------------------------------------------------------------- Total of: bears 211 cut 5054 fired 67 capture 211 lumberjacks 1177 lumbers 5054 maul 1095 trees 5090 ``` ]
[Question] [ # Context In [APL](https://aplwiki.com), trains are tacit sequences of monadic/dyadic functions that can be called with one or two arguments. We'll code something to check if a given train follows the correct structure we need in order to have a sound train. # Task Given the sequence of function arities in the train, determine if the train is valid as a monad and/or as a dyad. Don't forget that APL reads from right to left, so when I mention the "start" I mean the end of the array! A train is valid as a monad if * is starts with an arbitrary number of `DM` (0 or more) and then ends in 1 or 2 monadic functions; e.g. `MM`, `MDM`, `MMDM` and `MDMDM` are valid monadic trains. A dyadic train is valid if * the train starts with an odd number of dyadic functions, possibly ending with a monadic function; e.g. `D`, `MDDD` and `DDDDD` are valid dyadic trains. # Input Your input is going to be a non-empty list of the arities of the functions in the train, where said list contains up to 3 different elements; one for purely monadic functions, another for purely dyadic functions and another for functions that can be either monadic or dyadic, depending on usage. The input list can be taken in any sensible format and likewise the elements can be whatever 3 distinct elements you choose. E.g. take a string with the letters `MDB` or take a list of integers `0,1,2`. I don't mind you play around with this, just let us know what your answer uses. APL reads from right to left and we will embody this in the challenge; input *cannot* be reversed. # Output Your function should adhere to one of the two output formats: * output one of 4 distinct values; one for a train that only works monadically, one for a train that works dyadically, one for a train that works both ways and yet another one for a train that doesn't work in any way; any consistent 4 distinct values will do; * output two Truthy/Falsy values, with respect to the standard Truthy/Falsy defaults of your language, where the first value flags if the train works monadically and the second to flag if the train works dyadically, or vice-versa. # Test cases: The pair `(a, b)` is used, where `a` says if the train is valid to be used monadically and `b` says if the train is valid dyadically. ``` DB (False, False) DD (False, False) DM (False, False) MBDBMDD (False, False) DDBB (False, False) DMMDDM (False, False) DBDDBDMMD (False, False) BMDBDD (False, False) MMMDD (False, False) MMBMBMMBM (False, False) DDBBMDDMMD (False, False) DDMB (False, False) D (False, True) MD (False, True) BD (False, True) BBBDBDDBD (False, True) MDBBBBDB (False, True) M (True, False) MM (True, False) BM (True, False) MMDM (True, False) MDM (True, False) BDM (True, False) MMBBDMDB (True, False) MBM (True, False) B (True, True) MB (True, True) BB (True, True) BBB (True, True) BBBB (True, True) BBBBB (True, True) MBBBBBBB (True, True) BDBBBBBDB (True, True) ``` Generated and tested with [this Python code](https://tio.run/##lVLNagMhEL77FCI9aFmWhhwKhRAQr/sEIQ1md9K1zeri2kCg777V0dCQUGg9zJ8z3/yO59A7u5xnM4zOB@q17dxALhoQki31BNDx56UgpIMDbT3oALvgtbFcvBAa3xHsW@jpqmDUiRkb@LKiiyeBLh7Cp7eUsfrdxcDi2PbOtMBZoyQT9OA83VFjE8wb8IwqSl4z7QZndWdajrlL6oK7d@7IPdSDDm3PPXvlzZcUSNacq4ssHh9YRXP8D253/h/sOgNmqu5hA0xhitPYbElIjDXxl6lEZCIN6k2WsxktEi0SLQplleXs3xSemSysBF3xKGAPKURGtwzVSCmvvJRUKmeKokRDBi/ylqRtYEtpIyGPBTur9TiC7XgeWEX53Wqqu6mKNJeb/cbTKKiYZXVzWvh10vEKWoiff8rye5EF6FJGiJZUyRRvPV43hlT0A86rox72nY4N07BZbEuFo0/nHMSVchLz/A0). Feel free to use the TIO link and edit the final printing loop to print all the test cases in a format that is easier for you to use in your answer. [Answer] # [Haskell](https://www.haskell.org/), 61 bytes ``` f t=[and$zipWith(/=)t$[2|even$length t]++cycle[x,0]|x<-[2,0]] ``` [Try it online!](https://tio.run/##bZBBa4NAEIXv/oo5CCoxNPVaN4dh6Sl7K/QgHrZxE6W6FbMtacl/t7M2hMYRBWe/9/bNw1qf3k3bjuMBnCi0rcKfpn9tXB0/iMSFRXYxX8aGrbFHV4MrV6v99741xTndlJdzvi4yGsqx040FAdVHANAaBx1EKhKbJz9gJB6nQUYiI90N3pyvodM94TzcwtG4XWMNibFO3xIvDkZXO0ukHxrrID5c7wkBBXnKhCS/dZQYxM@6PZkUpk8SSMmImhOFEtWCUSKPU2RkARLJ66W5QLHIg5VSSxDpoXephl@qFgoqXvAGXoZPHzsHyADiX392EydpjoPYD/96zwByh2SIEeQeRduV33@PWf7NcS04OyM7c7BAWCouUJz@Ecp7/As "Haskell – Try It Online") Takes a list of: `0` for monad, `1` for both, `2` for dyad. Returns `[a,b]`. The valid monad trains are: ``` M MM MDM MMDM MDMDM MMDMDM ... ``` And the valid dyad trains are: ``` D MD DDD MDDD DDDDD MDDDDD ... ``` So we check the input against this pattern, first for `x=M` and then `x=D`: ``` x Mx xDx MxDx xDxDx MxDxDx ... ``` To generate the pattern, we start with `M` if the length is even, then alternate `x` and `D`. (Haskell's laziness lets me use `cycle`, which creates an infinite alternating list, rather than specify how long to alternate for: `zipWith` will only consume the pattern until it hits the end of `t`.) I use `(/=)` and invert the pattern to support `B` as a wildcard. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 59 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) Anonymous tacit prefix function. Returns `[]` if invalid, `[[]]` if dyadic, `[0]` if monadic, and `[0,[]]` if both. ``` R←'\pL'⎕R'[&B]' ((R'^M(DM)*M?$')⎕S 3,(R'^D(D{2})*M?$')⎕S⍬)⌽ ``` [Try it online!](https://tio.run/##TU47CgIxEO09xRZisqKFegBhTKHiKOza@QFBtBG0FbESthBXtPAWgo2tjUfJRdbJZkYlIS/vzZs3M9usqvPtbLVeZllkk4sab3rKnm@RGpVgogpaR2qK2mBYxmZRhVSKg0bFqUabXX3/p9v0HtrTK1tQTo2Ebjzoa5ue7fFAJZs@34@GTa7OGrXoHbY7cZgtAmVAFRwYD5gDggEUyQBbkCRfN0Cq4zkjK7AZEb8/oEP3G@K6UTKRM72XcxgAfD7XIBc84Wgey0yWZgThSH0onewWxpNkoODvI0b4EchXcbt8AA "APL (Dyalog Unicode) – Try It Online") `R←` define helper function to expand regexes: `'\pL'⎕R`… PCRE **R**eplace characters with the **p**roperty **L**etter with…  `'[&B]` with open-bracket, the letter, "b", close-bracket (makes any letter represent itself or "B") `⌽` reverse the train (to work from right to left) `(`…`,`…`)` concatenate the results of applying the following two functions:  1. `(`…`)⎕S 3` PCRE **S**earch for the following regex (`[0]` if found, else `[]`):    `R'^M(DM)*M?$'` the function `R` applied to the string: `^[MB]([DB][MB])*[MB]?$`  2. `(`…`)⎕S⍬` PCRE **S**earch for the following regex (`[[]]` if found, else `[]`):    `R'^D(D{2})*M?$'` the function `R` applied to the string: `^[DB]([DB]{2})*[MB]?$` [Answer] # JavaScript (ES6), ~~67 64~~ 61 bytes Expects an integer with `123` for `MDB`. Returns **1** for monadic, **2** for dyadic, **3** for both, or **0** for neither. ``` f=(n,d=2,q=m=1)=>n<4?q&n|(n^m&&d):f(n/10,d&n%5,n%5&m&&q,m^=3) ``` [Try it online!](https://tio.run/##jZNNT4NAEIbv/IrNJsJuxMVWvRi3JpPqbfXiTa1BoKZNWdrSGhP1t@MApdIPFvgIYfdh5p15h6n/6afBcjJfnekkjLJsLJl2Q9l3FzKWPS4H@ubydmHrH6ZHsW2H/HrMtNc7d0Nbn1y5eNu4vHDjkbzg2SpKV0SSlMgB@bYI0fjysI7foyV7FkKkryL25yzIt@mbGgIVEx1GX49jFnAupslEM8fhHL8MEp0ms0jMkg@Wirkf3umQ9fqcnBIUgMivZdUZ596fpRHxSPF0uJVLYRRTkM3BCfE8wop9t8S21LATpbpQCoagyoDGjFApM2bESGVWEwUYLUepiUJRsKnTpF6pqhlGCvDEi7bVmOtHYUZKGTux6/KLrnx@Wq5rNm@d2QuSU1vVTS7XIegEAZRNp8Z0UHD0eKT9uvLVg/FVB3Xl2IEbtB2CLhBapWgr9P8fGNJ1gXCCkKt36BgExkgNbdyZDmjo4o5bQFsZ6MQA7cAA7cAAbdMMFdYcp5jCYgwPmewP "JavaScript (Node.js) – Try It Online") ### How? We use the following variables: * \$n\$ is the input, which is divided by \$10\$ between each iteration. (The result is not rounded to save a few bytes, but the rest of the code was tuned to behave as if it were.) * \$d\$ is a flag initialized to \$2\$ and set to \$0\$ as soon as a monadic-only function is extracted, thus breaking a dyadic train. * \$q\$ is a flag initialized to \$1\$ and set to \$0\$ as soon as the dyadic/monadic pattern is no longer met, thus breaking a monadic train. * \$m\$ is a mask initialized to \$1\$ and switching between \$1\$ and \$2\$ between each iteration. It is used to update \$q\$ and for the final test of the dyadic train. In order to save two bytes on the update of \$d\$ and \$q\$, we use the fact that: $$(n\bmod 10) \operatorname{AND} 3 = (n\bmod 5) \operatorname{AND} 3,\:n\bmod 10<4$$ We stop the recursion as soon as there's only one digit left, which is therefore stored in the final value of \$n\$. The train is monadic if: > > \$q\$ is still set to \$1\$ and \$n\$ is odd > > > The train is dyadic if: > > \$d\$ is still set to \$2\$ and \$n\$ is not equal to \$m\$ > > > This last condition (\$n\neq m\$) can be interpreted as follows: * If \$m=n=1\$, it means that we had an even number of dyadic functions so far and the last function is monadic-only. * If \$m=n=2\$, it means that we had an odd number of dyadic functions so far and the last function is dyadic-only. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ ~~34~~ ~~30~~ 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` $DgÈić≠s}WĀs2Å€É}¬_sDÔQ*‚* ``` Input as a string where `D=1,M=0,B=2`, output as a pair of truthy/falsey values `[isDyadic, isMonadic]`. [Try it online](https://tio.run/##yy9OTMpM/f9fxSX9cEfmkfZHnQuKa8OPNBQbHW591LTmcGftkYZDa@KLXQ5PCdR61DBL6/9/I0MjEDA0AgA) or [verify all test cases](https://tio.run/##PU5LCsJADL1KmWWpkOQC3fQCguBCRBSkdOViQOiiUAS13YoguPIAXXgGpyeZi4wzk7R0SF6S9@lJ7w/V0Z3rXCX29khU7rAuStNV4932H92sx1aTudrLYPpmbH/DThfmuUxt@06d@a7qcmFeeeY2CklliUKMFUIFQgJZIPEZ/CIekfwujGHwNGIiAEyA/OffJA9CEDNgs8hjA65EbMsHinPE7MhRjOUXuZFM4AUgEiYKZnfJkDZ34dCMKUaH7O0f). **Explanation:** ``` $ # Push 1 and the input Dg # Duplicate the input, and pop and push its length Èi # If this length is even: ć # Extract head; pop and push remainder-string and head separated ≠ # Check that this head is NOT 1 (thus NOT "D") s # Swap so the remainder-string is at the top }W # After the if-statement: get the smallest digit (without popping) Ā # Check that this digit is NOT 0 (thus NOT "M") (0 if 0; 1 if 1 or 2) s # Swap so the string is at the top again 2Å€ # For every 2nd digit (0-based indices 0,2,4,etc.): É # Replace all 2s with 0s ("B" to "M"), by checking whether the # digit is odd (1 if 1; 0 if 0 or 2) } # Close the even-map, which changed the string to a digit-list Ā # Replace all remaining 2s with 1s ("B" to "D"), by python-style # truthifying each digit (1 if 1 or 2; 0 if 0) ¬ # Get the first digit (without popping the list itself) _ # Check that it's equal to 0 (thus "M") s # Swap so the list is at the top again D # Duplicate this list Ô # Connected uniquify; remove any digits equal to its neighbor Q # Check that the two lists are equal (thus it was alternating) * # Multiply it by the head=="M" ‚ # Pair it together with the minimum!="M" * # And multiply both to the head!="D" # or the 1 we pushed initially with `$` if the length was odd # (after which the result is output implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 25 bytes ``` LḂ ¹;2ṙ1ƊÇ?µnJḂ$Ạð,µḢnÇaẠ ``` [Try it online!](https://tio.run/##XU8xDsIwDNz7DkYPiVcGdsQPqg4MLKjqztolEj9gQ8wMLJVaxkbiH@EjIYntJEJV49ydz76cT31/8f7g5rFZly265aY/V2t26zTsA7lx77t9wTq5@TFYcwzQW/Mdn963TasBO4hFU1GxKEAIAijIfITcqYinVp1a6UxCJMmJ4lZiEYD8p7OaL4NlDgFaS14ezwU5JwfgFkDIUqJ4LSeTEPmtWiRdROQHyQgJKoj35xglT30t5uqTXfiXs/sB "Jelly – Try It Online") Input is a list of numbers: 0 = M, 1 = D, 2 (or any other number) = B. Output is a pair of 0 or 1, representing the possibility of a monad/dyad respectively. I really wanted to beat the 05AB1E submission and it seems that I succeeded. ## Explanation ``` LḂ Auxiliary link L Length Ḃ Parity ¹;2ṙ1ƊÇ?µnJḂ$Ạð,µḢnÇaẠ Main link accepting a list L ? If Ç previous link (the length of L is odd) ¹ then do nothing Ɗ else ( ;2 Append 2 ṙ1 Rotate left by 1 ) µ Now we have a new list L' JḂ$ The parities of indices of L' ([1,0,1,0,...]) n Doesn't equal L' (for each element) Ạ All? ð, Pair this all with µ the following: Ḣ Head of L [removing it from L] n Doesn't equal Ç previous link (the parity of the length of [the new] L) a And Ạ all elements of [the new] L are truthy ``` *-1 byte by extracting an auxiliary link. Sometimes you need to follow good coding practices even in code golf…* [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes ``` ^(?=(\S\S?(\D\S)*$))?(?=(\S?\D(\D\D)*$))?.* $#1$#3 ``` [Try it online!](https://tio.run/##JU0xDgIxDNvzCqQWqXcDAjGjSlFWT2Ws0DEwsDAg/l/sa5u4iR0339fv/XmOY7lvHtjS4Twepd5Kb73V0qO3Zc3LUidXe4iLyZ1Wy@mS03WMcIuwgMHDoTKcFFjCwtmpNkqsDeKJzsvYhzUJ@UCfaZbhPr3sfW@MG8BviFrGdL2gBqlUhHTKrJwgch4afP71Bw "Retina 0.8.2 – Try It Online") Takes input as a string of characters where `#` represents `B`, represents `D` and `0` represents `M`, however the link's header translates `BDM` for you if necessary. Output is a pair of bits. Explanation: ``` (?=(\S\S?(\D\S)*$))? ``` Try to match a monadic chain. ``` (?=(\S?\D(\D\D)*$))? ``` Try to match a dyadic chain. ``` ^.* $#1$#3 ``` Replace the input with the results of the two match attempts. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 49 bytes ``` 'MD'∘.{''≡(∊'^[MB]?(['⍺'B][DB])*['⍺'B]$')⎕R''⊢⍵}⊂ ``` [Try it online!](https://tio.run/##RU6xagJBEO39ihTC3AkKIR8gTLaIwhjw0h0nCEGbg9iK2CiIHqxoEUgb60AabSzzKfMjl7nbGWWXffvevHkz41nefp@P849pWQI54O1XZwHAu@@ItwWMUsKsG6XA/gqYpQ6zuGWsCTHvP4fiLk7sL0suVuWEN4dHUfvJ6yBiv@dizf6H/fnv94k3R6kkw2d53156SVxOHsAhNCpwAagGQodkkkO1kEih7lDUitdMrKhmIrr9UI7cW0jVTZZJmhm8mqOAGPK1hrUQiEbrWGW2tCIaJ@kj61S3MZ1kAw3vHzPinWC9SrXLPw "APL (Dyalog Unicode) – Try It Online") Testing harness borrowed from [Adám's answer](https://codegolf.stackexchange.com/a/213880/95792), which you should upvote. Outputs `[0, 0]` for invalid trains, `[0, 1]` for dyadic trains, `[1, 0]` for monadic trains, and `[1, 1]` for trains that could be both. This basically just checks if it matches the regex `/^[MB]?([aB][DB])*[aB]$/`, where `a` is `M` or `D`. ]
[Question] [ Your task is to create a plain hunt (a bell ringing pattern) with *n* bells. An example with 6 bells: ``` 123456 214365 241635 426153 462513 645231 654321 563412 536142 351624 315264 132546 123456 ``` Each number "bounces" off the side of the grid. [From Wikipedia](https://en.wikipedia.org/wiki/Plain_hunt): > > Each bell moves one position at each succeeding change, unless they reach the first or last position, when they remain there for two changes then proceed to the other end of the sequence. > > > In other words, you swap the bells in adjacent pairs, alternating between taking pairs starting from the the first bell and from the second bell. (Thanks to @xnor for this explanation.) You finish in the same order as the start. This rule be applied to *any* number of bells, taken as input. Standard loopholes are forbidden. ## Test Cases 6 ``` 123456 214365 241635 426153 462513 645231 654321 563412 536142 351624 315264 132546 123456 ``` 3 ``` 123 213 231 321 312 132 123 ``` 2 ``` 12 21 21 12 ``` 1 ``` 1 ``` 0: Falls in to "I don't care" situation. [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes ``` lambda n:[[.5+abs((n+j-i*(-1)**(i+j))%(2*n)-n+.5)for j in range(n)]for i in range(2*n+(n>2))] ``` [Try it online!](https://tio.run/##VY/LasMwEEX38xXaFCQbB@a5MLQ/kmbh0LhRSJXguoR@vWtXA6U76XJ17tH9ez7fCi3j8@tyHT6Ob0Mo/X6/03Y4fsZY2kuXm9hhapqY20tKT5GakrrS7jSNtylcQi5hGsr7KZZ02JL8l6zVNpYXSumwPM75egrYQ9hK0@2x1caYy/1rjin19ymXecsh/B4BkFjUTIUJgVDYVI0FCUjQWJUNhUDIUJkVjQTESJEZlUzARIkRmVQMKqcyoXIqEyqnMqFyKhMqpzKhcirzv5vf3NHt3MuN3MUtfN@XfdPXfMeZy/pzWF//AA "Python 2 – Try It Online") Outputs a list of lists of integer-valued floats. The map `(i,j) -> j-i*(-1)**(i+j)` is very similar to [multiplication in the dihedral group](https://codegolf.stackexchange.com/a/185154/20260). This isn't a coincidence. If we let \$a\$ represent swapping every other element starting from the first, and \$b\$ doing so starting from the second, then these generate the dihedral group \$D\_{2n}\$ gives by relations \$a^2 = b^2 =(ab)^n =1 \$. Note that the sequence we're asked to output has us alternate applying \$a\$ and \$b\$, and the fact that \$ (ab)^n =1 \$ confirms that we return to where we started after \$2n\$ total steps. We can see the dihedral connection more clearly if we extend the top row to \$2n\$ elements rather than \$n\$, and write it zero-indexed. Doing the alternating swaps as usual gives a pattern like below for \$n=3\$. This is almost a multiplication table for the dihedral group \$D\_{2n}\$, except that we invert the first group element before multiplying \$g,h \to g^{-1} h \$, giving zeroes (identity) on the diagonal \$g=h\$. ``` 012345 +------ 0|012345 1|103254 2|430521 3|345012 4|254103 5|521430 ``` To return the values back into the range `[0,1,2]`, we need to map back `3->2, 4->1, 5->0`. In the code, surprisingly many characters as spent on the simple-looking mapping doing modular indexing into the palindromic "bouncing" list `[1,2,...,n-1,n,n,n-1,...,2,1]`, We implement this as `.5+abs((n+k)%(2*n)-n+.5)`. The Python 3.8 walrus can save at least 2 bytes, though I haven't optimized it. [Answer] ## Haskell, 83 bytes ``` f(a:b:c)=b:a:f c f c=c q l|a:b<-f l=l:f l:q(a:f b) g n=take(2*n+sum[1|n>2])$q[1..n] ``` [Try it online!](https://tio.run/##bYqxDoIwGAb3PsU3MLQaScDEobG@gU9AiCmVIuHvDxXcePdad4db7u5l16knSslLqzvtlOm01R5OZIwTEbTncD15kKEcSEf5GzolBrDZ7NTL@sDH9ROaaudb3aoiNlVZcpuCHRkGz1kAwS73B5b3yBsKDDj/cZf0BQ "Haskell – Try It Online") [Answer] # [PHP](https://php.net/), 120 bytes ``` for($b=$a=range(1,$argn);print join($b)." ",$a[1]&&!$i||$a!=$b;)for($j=$i++%2;$n=$b[++$j];$b[$j-2]=$n)$b[$j++]=$b[$j-2]; ``` [Try it online!](https://tio.run/##NYuxCoMwFEX3fkWVWzG8WtChS/pw8yckQ4TWJsNLSB399qZB6HI5nMON75gfYyz7CqnFwrCcrKzPtr/CplWUjsnJdvbBSenqVp/qUubeNE0Ft@@wFWPR6vh7hiO6DBpS5EwEb3QB@G4wDFEHExn@S53z/Rvi5oJ8cjf9AA "PHP – Try It Online") ``` for( $b=$a=range(1,$argn); // set $a and $b to an array of [1...n] print join($b)."\n", // on start of each iteration print $b $a[1]&& // stop when input is 1 (we only print a single 1 for input of 1) !$i|| // allows first iteration to happen since $a==$b on first iteration $a!=$b; // stop when $a and $b are equal again ) for( $j=$i++%2; // set $j to 0 or 1 (alternates each time) $n=$b[++$j]; // increment $j by one and set $n to // last number of next pair in $b, stop if it doesn't exist $b[$j-2]=$n // swap one of bells in $b ) $b[$j++]=$b[$j-2]; // increment $j by one and swap one of bells in $b ``` [Answer] # [Zsh](https://www.zsh.org/), ~~75~~ 95 bytes ``` s(){echo $a;a=;for x y;a+=($y $x)} a=({1..$1}) (($1-1))&&repeat $1 s $a&&s '' $a (($1-2))&&s $a ``` ~~[Try it online!](https://tio.run/##HYwxDoAgDAD3vqJDI21MTBh0ITymMRA3DTiohLcjut0Nd0/eWmThlllKWLcdSZ16F/eEF95OR890I11SQT0XO01kq0AKR9ATyWLuxTBkNKYDfNYEIOIM/67T0l4 "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##JY3BCsMgEETvfsUcFrNLacCeCuLHSFFyS4kekorfbt329hhm3nzKNjILj8LS0mvbQdHH4PN@4MTl4y0wXaBTuomBm1tXcl0MM7m7E7H2SO8UK8ihzK21Bcsy4d94aEPzIUaVNZWKn@XZBc0AGaThJH03fXwB "Zsh – Try It Online") Defines a function `s` which swaps each pair of arguments and assigns them to `a`. `s` is called once normally `ABCD -> BADC` and then once with an empty element prepended: `ABCD -> ACBD`; repeated `n` times. `s` is called once more at the end, just to print out the array once more. `echo $a` is used instead of `<<<$a` to suppress the empty element causing extra space. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` s2UF RÇŻÇfƊƭƬmn2$Ṃṭ$⁸>2¤¡ ``` A monadic Link accepting a non-negative integer which yields a list of lists of non-negative integers. **[Try it online!](https://tio.run/##ATYAyf9qZWxsef//czJVRgpSw4fFu8OHZsaKxq3GrG1uMiThuYLhua0k4oG4PjLCpMKh/8OHR///MTY "Jelly – Try It Online")** (The footer calls the Link and formats the result as a grid) ### How? ``` s2UF - helper Link: list e.g. [4, 2, 5, 1, 3] s2 - split into chunks of length two [[4, 2], [5, 1], [3]] U - reverse each [[2, 4], [1, 5], [3]] F - flatten [2, 4, 1, 5, 3] RÇŻÇfƊƭƬmn2$Ṃṭ$⁸>2¤¡ - Main Link: non-negative integer, N R - range = [1,2,...,N] Ƭ - collect up while unique, applying (starting with X = range result): ƭ - apply previous (default 2) links in turn each time called: Ç - 1) call helper link as a monad Ɗ - 2) last three links as a monad - i.e. g(X): Ż - prefix a zero Ç - call helper link as a monad f - filter keep only those values in X (i.e. remove the zero) $ - last two links as a monad: 2 - literal two n - not equal (N)? m - modulo slice (m1 gives every element back, m0 performs reflection, which is required when N = 2) [m0 reflecting is a very nice behaviour decision by Dennis IMO] ¡ - repeat... ¤ - ...number of times: nilad followed by link(s) as a nilad: ⁸ - chain's left argument, N >2 - greater than 2? $ - ...action: last two links as a monad: Ṃ - minimum (always [1,2,...,N]) ṭ - tack (appending the final peel for N>2) ``` [Answer] A much nicer approach if I can ignore case 1: # [J](http://jsoftware.com/), 42 bytes ``` [:/:"{i.+/\@|:@,.(2*-/\@i.)|."{[:(,-)i.<<: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o630rZSqM/W09WMcaqwcdPQ0jLR0gexMPc0aPaXqaCsNHV3NTD0bG6v/mlypyRn5CmkKhgp@TnoKaYmZOcUQIXV1mJQRuoDZfwA "J – Try It Online") --- # official [J](http://jsoftware.com/), ~~68~~ ~~62~~ 59 bytes ``` [:>[:(]C.~_2<\(}.i.@#))&.>/@:|.\<@:>:@i.,(0;1)$~+:-1#.<&2 3 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63soq00Yp316uKNbGI0avUy9RyUNTXV9Oz0Haxq9GJsHKzsrBwy9XQ0DKwNNVXqtK10DZX1bNSMFIz/a3KlJmfkK6QpGEIY6uowASN0AbP/AA "J – Try It Online") 51 bytes if `1` case is allowed to return 2 lines: [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63soq00Yp316uKNbGI0avUy9RyUNTXV9Oz0Haxq9GLsrBwy9aw1DKwNNVXqtK10bdSM/2typSZn5CukKRhCGOrqMAEjdAGz/wA "J – Try It Online") [Another 48 byte solution which fails only case 1](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62sdawcMvU0YnU0nPWqrTQ11fTs9B1q9Bysta1U4o00bGJ0rNRsgFStnqZmpt5/Ta7U5Ix8hTQFQwhDXR0mYIQqABQx@w8A "J – Try It Online") --- ## how for official answer Could likely be golfed more but I was happy with the idea. Essentially, everything flows from noting that to get from one element to the next, you apply 1 of two cyclic permutations: For example, in this case of n=6, to get from a row with an even index to the next row you apply: ``` ┌───┬───┬───┐ │1 2│3 4│5 6│ └───┴───┴───┘ ``` To get from an odd row to an even you apply: ``` ┌─┬───┬───┬─┐ │1│2 3│4 5│6│ └─┴───┴───┴─┘ ``` Once you set that up, the result is just a right to left scan over those alternating permutations. Everything else is the boring details of constructing the permutations and the list to apply them to. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes ``` NθFθ«Jι⁰≔⁻⁶∧‹⁺ι¬﹪ι²θ∨﹪ι²±¹ηF⎇‹θ³×θθ⊕⊗θ«✳ηI⊕ι≧⁺⁻¬ⅈ⁼⊕ⅈθη ``` [Try it online!](https://tio.run/##VU9NS8QwED23vyLHCURwFb14WlwPu9h1kR68ZtuxDaRJ8yWI7G@PkxbEPYQk8z7mvW6UvrNS57w3c4rHNJ3Rg@NP9af1jB7sp64OaZpbC0qwWwKqbQhqMNAokwI8CrY1PbxiCHDSNCDW0UZobJ/0ornjnAvm6Lz5qzERcZARYcMXyljMl7UteiP99@rqBLsntFUTLp/itDedxwlNxB52Np013a64lLjVySsTYac8dlFZAyMpnmWI8F@miE37qkbOa6F3NYxx6SDY2q30@IAS7cUlqcOVfgXcX/BLfcn5Id986V8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` Fθ« ``` Loop over each bell. ``` Jι⁰ ``` Jump to its starting position. ``` ≔⁻⁶∧‹⁺ι¬﹪ι²θ∨﹪ι²±¹η ``` Calculate its starting direction. For odd bells this is normally 7 (south east) and for even bells this is normally 5 (south west) but if the last bell its odd then its staring direction is 6 (south). ``` F⎇‹θ³×θθ⊕⊗θ« ``` Loop over each row, either `n²` for `n<3` or `2n+1` for `n>3`. ``` ✳ηI⊕ι ``` Print the current bell and move in the current direction. ``` ≧⁺⁻¬ⅈ⁼⊕ⅈθη ``` Adjust the direction if the bell has reached the side so that it bounces. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 52 bytes ``` {$_,|({S:g:p($++%2)/(.)(.)/$1$0/}...$_)}o{[~] 1..$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiVep0ajOtgq3apAQ0VbW9VIU19DTxOI9FUMVQz0a/X09FTiNWvzq6PrYhUMQZza/8WJlQppGkBhvaz8zDwNpZg8JU2FtPwiBTMdBWMdBaP/AA "Perl 6 – Try It Online") ### Explanation ``` {[~] 1..$_} # Concat numbers 1..n { }o # Feed into block $_, # Start with first string ... # Sequence constructor { } # Compute next item by S:g / / / # replacing globally :p($++%2) # starting at alternating positions 0, 1, 0, 1, ... (.)(.) # any two chars $1$0 # swapped $_ # Until item equals original string |( ) # Flatten into result list ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~110~~ 104 bytes ``` n=input() R=range s=R(1,n+1) for k in R(n*2-2/n+1): print s for i in R(k%2,n-1,2):s[i:i+2]=s[i+1],s[i] ``` [Try it online!](https://tio.run/##JY69bsJAEIRr5im2iWzHRmSPnySWroQ2kkWHXBDnAidHa2t9KPD05gzN7Gj0aWf6Wzh3Ysam@3FkKUmSUayX/hLSDJXVo5wcBlulXEjOGX47pZa8UJXKq5mbxZSWoF69BBpAE@CfQPtiCplzYbJyOPjS56a20eRcF/HUYyzD/9n/OdrrxZWYBb1Fnbmra2gaFP3jL2LUuD7Q9mu3Ve10or7VHVuMDIMlVlhjg3d84BP8BmawAS/BK/D6Dg "Python 2 – Try It Online") Full program that prints a list of integers for each "change" in the "hunt". [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 128 bytes ``` x=>{var m=Enumerable.Range(1,x).ToList();for(int i=0,j=0;i<x*2+1-2/x;j=++i%2)for(Print(m);j<x-1;)(m[j],m[++j])=(m[j],m[~-j++]);} ``` [Try it online!](https://tio.run/##Xc0xC8IwFATgvb8ii5Bn2tpWcHlNwcGtg4jgIB1qSeQFk0JaJSD612sdXBzv@I7rhqQbaNp2I/WOleTGSsspyOr5aD2zcufuVvn2clPpoXVXxfM4QHrsaxpGDqh7z@cNI5nFRmZIZVgWIk@KVUAjhaBFAV@z97PiFtCUIckRuD2bJrZnIUwD8pfeiRGiAXxNyDTjG8Do5GlUNTk1n0War/@raHYF4PQB "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes ``` ¹©Rµ¬ɼks€2UFµ⁺⁻J$п;@WẋL’ẸƊƊ ``` [Try it online!](https://tio.run/##AT0Awv9qZWxsef//wrnCqVLCtcKsybxrc@KCrDJVRsK14oG64oG7SiTDkMK/O0BX4bqLTOKAmeG6uMaKxor///82 "Jelly – Try It Online") A monadic link that takes an integer as its input and returns a list of lists of integers. Could be 16 bytes if only needed to handle numbers 3 and above, and 22 if only 2 and above. [Answer] # JavaScript (ES6), 99 bytes ``` n=>(z=0,g=a=>[a=a.map((v,i)=>v?a[i+=i+z&1||-1]||v:i+1),...z++^2*n^'027'[n]?g(a):[]])([...Array(n)]) ``` [Try it online!](https://tio.run/##VYzRCoJAEEV/ZZ5yp9VFewmqUfqBfmBZYbCUjZoVDSGzb7d97elcOJdz54nHZvD9K5Nwva0trUKlmilPO2IqLRObJ/dKTalHKqeKrdfk9bwpliUr3LJMB68LTI0xs9b1bit1ku/2iRVXdYrxYJ1DZaM@DwO/laDDtQ2DEiAojiBwiszj0BrhA02QMTxu5hE6lVziJwENgsc/0cYMwnf9AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` n => ( // n = input z = 0, // z = counter g = a => [ // g = recursive function taking the list of bells a[] a = // update a[] and append it as a new entry a.map((v, i) => // for each value v at position i in a[]: v ? // if v is defined: a[ // take the bell i += // at position: i + z & 1 // i + 1 if i + z is odd || -1 // i - 1 if i + z is even ] // || v // or leave it unchanged if the above value is undefined : // else: i + 1 // the array is not yet initialized: set the bell to i + 1 ), // end of map() ...z++ ^ 2 * n // we stop when z = 2n, except for ^ '027'[n] // n = 1 (2n xor 2 -> z = 0) and n = 2 (2n xor 7 -> z = 3) ? // if the above result is not equal to 0: g(a) // do a recursive call : // else: [] // stop ] // )([...Array(n)]) // initial call to g with a[] = array of n entries ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~270~~ ~~224~~ ~~206~~ 190 bytes Not a "winning" answer but a fun challenge. Thanks @ceilingcat for some good cleanup. Learned something new. Update: further golfed based on how I now know the game to be played. Further golfed by @ceilingcat ``` #define w(x)for(i=x;i<n;i++) #define pb w(0)printf(b+i);puts(""); i,x,n;z(int*b){n=*b;w(0)b[i+n*4]=b[i]=i+49;do{if(n-1)pb;w(x++%2+1)b[i++-1]^=b[i]^=b[i-1]^=b[i];}while(bcmp(b,b+n*4,n*4));pb} ``` [Try it online!](https://tio.run/##PY7tasMwDEV/108RMjrk2IFmlMFw/STBg8pJNsGqmn7Q0JBnz@TAhrHx5RykG@uvGJflpesH4r54wKiH8wXIj44O7MgYrf5gQuE7nS7EtwHQkHbpfrtCWWqnyI6W3ROEVagn9hW6bGNLhqt98PIJnsz@w3XniQbgutEpO6Mx2zfTrKapm/C5quv7n9z8@KafHjCeEqDFPNLK1VIB50WWFqcjMWg1qU1O7NTmGo88QLntSlu8snRcCbZcyQkSsd0Fn80noOB5eVe/ "C (gcc) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 159 bytes ``` func[n][r: collect[repeat i n[keep i]]repeat i either n < 3[n * n][2 * n + 1][print r: head r r: skip r i + 1 % 2 until[move r next r(index? r: skip r 2)> n]]] ``` [Try it online!](https://tio.run/##TY3NCsIwEITveYq5CP5Q0Aoeiug7eF1yKM2GBus2xFQK0mePKUrxNB/DtzuBTbqxIa1shWQHaUg0hQpN33XcRArsuY5wELozezitl4pdbDlAcMaRBFvk03IO7HDQ5IOTiFCplmuDkAnPu/OZ3CxghRKDRNfRo39xroXH7K@dGB6vf3q5ueTXWqdl@QSyOb4L70mrHxVFMSmLffoA "Red – Try It Online") If two `1`s are allowed as a solution for `1`: # [Red](http://www.red-lang.org), 155 bytes ``` func[n][r: collect[repeat i n[keep i]]b: copy r t: on until[print b if t: not t[b: next b]until[move b next b(index? b: skip b 2)> n]r = b: head b]print b] ``` [Try it online!](https://tio.run/##PY4xDsIwDEX3nuKPMFRCDAyVgDuwRh7axhERxYlCiopQzx5ctWKy9f6z9RPbcmNrqHINihulN0ImNejDMHCfTeLIbYaHmAdzhCfqljR@kJAbBMEo2Q8mJi8ZHbxTXEnIyEZN4Ukprc4zvFmVle28WJ6uUOn18FH5cX@BUMJ5YXdurR5ub6n8i5xgnI41@M5UbVtd13PlcCg/ "Red – Try It Online") [Answer] # [Icon](https://github.com/gtownsend/icon), 119 bytes ``` procedure f(n) a:="";a||:=1to n&\z;b:=a n>1&o:=|(0|1)&write(b)&b[o+(k:=seq(1,2)\n)]:=:b[o+k+1]&b==a write(b);return end ``` [Try it online!](https://tio.run/##TY7BCsIwEETv@YqQQ8hSD8aDhy3rj9gekjZCKW5sTBEk/16jUPA6vJk30xB52x4pDmFcU5A3wyAcklKtKwXJ5ihZd@/WIznBF6sjUjHHYkG/0pSD8aD9NTZmRnqGxdjDCTqGHgm/8dzYXnuq3Z1uU8hrYhF4/PPe3cQGhJT1gZVVet73lYLq/@Ef "Icon – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ≠iL[ˆ¯DÁ2£ËNĀ*#θNÈi2ôëćs2ôsš}ε¸˜}í˜ ``` [Try it online](https://tio.run/##AUIAvf9vc2FiaWX//@KJoGlMW8uGwq9Ew4EywqPDi07EgCojzrhOw4hpMsO0w6vEh3Myw7RzxaF9zrXCuMucfcOty5z//zE) or [verify all test cases](https://tio.run/##AWIAnf9vc2FiaWX/dnk/IiDihpIgIj95RP/iiaBpTFvLhsKvRMOBMsKjw4tOxIAqI864TsOIaTLDtMOrxIdzMsO0c8Whfc61wrjLnH3Drcuc/319LMK2P8K0/1sxMiw2LDMsMiwxXQ). Not too happy with it.. I have the feeling the duplicated `2ô` could be golfed somehow, and some of the workarounds could be more elegant (/shorter). Could be [33 bytes](https://tio.run/##AVwAo/9vc2FiaWX/dnk/IiDihpIgIj95/0xby4bCr0TDgTLCo8OLTsSAKiPOuE7DiGkyw7TDq8SHczLDtHPFoX3OtcK4y5x9w63LnP99LMK2P8K0/1sxMiw2LDMsMiwxXQ) if `[1,1]` instead of `1` is allowed as output; and could be [28 bytes](https://tio.run/##AVIArf9vc2FiaWX/dnk/IiDihpIgIj95/0xby4bCr8OQw5nDiiPOuE7DiGkyw7TDq8SHczLDtHPFoX3OtcK4y5x9w63LnP99LMK2P8K0/1sxMiw2LDNd) if we'd only had to handle \$\geq3\$. **Explanation (of the 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) version):** ``` ≠i # If the (implicit) input is NOT 1: L # Create a list in the range [1, (implicit) input] [ # Start an infinite loop: ˆ # Add the top list to the global array ¯D # Push the entire global array twice Á # Rotate the copy once towards the right 2£ # Then only leave the first two items Ë # Check whether those two items are NOT the same N # Push the current loop-index Ā # Check whether it is NOT 0 (so not the first iteration) * # If both checks are truthy: # # Stop the infinite loop # (after which the TOS global array is output implicitly as result) θ # Only leave the last list of the global array NÈi # If the loop-index is even: 2ô # Split the list into parts of size 2 ë # Else (the loop-index is odd): ć # Extract head; pop and push the remainder-list and first item separated s # Swap so the remainder-list is at the top of the stack 2ô # Split it into parts of size 2 s # Swap to get the extracted first item again š # And prepend it back in front of the list }ε # After the if-else: map over the pairs (and potentially loose items): ¸ # Wrap them into a list ˜ # And flatten them # (this is a workaround to wrap multi-digit integers into an inner list, # otherwise an integer like 10 would be reversed to "01"..) }í # After this map: reverse each inner pair ˜ # And flatten it to a single list again for the next iteration ``` [Answer] # [Ruby](https://www.ruby-lang.org/) -p, 72 bytes ``` puts$_=s=[*?1..$_]*'' puts$_ until s[gsub /\B{#{1&$.+=1}}(.)(.)/,'\2\1'] ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFgl3rbYNlrL3lBPTyU@VktdnQsiqlCaV5KZo1AcnV5cmqSgH@NUrVxtqKaip21rWFuroacJRPo66jFGMYbqsf//m/3LLyjJzM8r/q9bAAA "Ruby – Try It Online") Alternately replaces using the regexps `/\B{0}(.)(.)/` and `/\B{1}(.)(.)/`. The latter matches any two characters other than at the beginning of the string, while the former just matches any two characters--`{0}` means "repeated zero times" turning the `\B` into a no-op. [Answer] # [Husk](https://github.com/barbuz/Husk), 22 bytes ``` -;1ḟΓ€ḣ`Goṁ↔`C¢Se:1∞2ḣ ``` [Try it online!](https://tio.run/##yygtzv7/X9fa8OGO@ecmP2pa83DH4gT3/Ic7Gx@1TUlwPrQoONXK8FHHPCOg@P///40B "Husk – Try It Online") ## Explanation ``` -;1ḟΓ€ḣ`Goṁ↔`C¢Se:1∞2ḣ Implicit input, say n=5 ḣ Range: [1,2,3,4,5] ∞2 Infinite list of 2s. Se Pair it with :1 prepend 1: [[2,2,2,2..],[1,2,2,2..]] ¢ Cycle: [[2,2,2..],[1,2,2..],[2,2,2..],[1,2,2..]..] `G Cumulative reduce this list using the range as a starting point with the following function: `C Split into chunks of given lengths: [[1,2],[3,4],[5]] oṁ↔ Reverse each and concatenate: [2,1,4,3,5] Result is infinite list [[1,2,3,4,5],[2,1,4,3,5],[2,4,1,5,3],[4,2,5,1,3]..] ḣ Prefixes: [[[1,2,3,4,5]],[[1,2,3,4,5],[2,1,4,3,5]]..] ḟ Find the first one that satisfies this: Γ€ The first element occurs in the tail. The result is the plain hunt, except for n=1, which gives [[1],[1]] -;1 Remove an occurrence of [1] to account for it. ``` ]
[Question] [ Given a \$n\$-dimensional vector \$v\$ with real entries, find a closest permutation \$p\$ of \$(1,2,...,n)\$ with respect to the \$l\_1\$-distance. ### Details * If it is more convenient, you can use permutations of \$(0,1,...,n-1)\$ instead. If there are multiple closest permutations, you can output any one or alternatively all of them. * The \$l\_1\$ distance between two vectors \$u,v\$ is defined as $$d(u,v) = \sum\_i \vert u\_i-v\_i\vert.$$ * If you want, you can assume that the input solely consists of integers. ### Examples ``` [0.5 1] -> [1 2], [2 1] c*[1 1 ... 1] -> any permutation [1 4 2 6 2] -> [1 4 3 5 2], [1 4 2 5 3] [1 3 5 4 1] -> [2 3 5 4 1], [1 3 5 4 2] [7 7 3 2 5 6 4 2] -> [8 7 3 2 5 6 4 1], [8 7 3 1 5 6 4 2], [7 8 3 2 5 6 4 1], [7 8 3 1 5 6 4 2] [-2 4 5 7 -1 9 3] -> [1 4 5 6 2 7 3], [2 4 5 6 1 7 3], [1 4 5 7 2 6 3], [2 4 5 7 1 6 3] [0 4 2 10 -1 10 5] -> [1 4 2 6 3 7 5], [1 4 3 6 2 7 5], [2 4 3 6 1 7 5], [3 4 2 6 1 7 5], [1 4 2 7 3 6 5], [1 4 3 7 2 6 5], [2 4 3 7 1 6 5], [3 4 2 7 1 6 5] ``` [Octave script](https://tio.run/##VY4xDsMgDEV3TsEWW6JDMnRIRG@Q3IEW0loJBAGpcntqNepQL/b7/1v29ijm7WodpZbXQRzckgmWYFStGnEQlnIEb0qXS4IDUUwcWV14lhfjICJjdMlnaPuJOWw8s5Z3D@aeIV4OVB0bXnsK8LWZiCMzBXsKWvvfqeZya1DMW5KLpkZIrr8XIiyqR@S4C/ZcCbt3KxBirR8) for generating more examples. [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` def f(l):z=zip(l,range(len(l)));print map(sorted(z).index,z) ``` [Try it online!](https://tio.run/##NctBCsIwEAXQvafocgZGaWLTgtKTSBeFJBqI0xCzsLl8TBQ3A//9P2FPj41lKdrYzoLHS56zC@Aprnw34A1XRLyG6Dh1zzXAa4vJaMh4cqzNmzIWCzdBA0kaSS54qHGiic4VVKXhj2PrqS1VLcUP@@@j6Oko2lULlg8 "Python 2 – Try It Online") Uses zero-indexing. A fast algorithm with a simple idea. If we instead need to permute the input list to make it as close to \$(1,2,...,n)\$ as possible, we should just sort it, as proven below. Since we're instead permuting \$(1,2,...,n)\$, we choose the permutation that's ordered the same way as the input list, like in my challenge [Imitate an ordering](https://codegolf.stackexchange.com/questions/62587/imitate-an-ordering?rq=1) (except the input may have repeats). (Edit: miles pointed out [this more identical challenge](https://codegolf.stackexchange.com/questions/85835/ordering-a-list), where Dennis has [this same answer](https://codegolf.stackexchange.com/a/85872/20260).) > > **Claim:** A permutation of the list \$l\$ that minimizes its distance to \$(1,2,...,n)\$ is \$l\$ sorted. > > > **Proof:** Consider some other permutation \$l'\$ of \$l\$. We'll prove it can't be better than \$l\$ sorted. > > > Pick two indices \$i,j\$ that \$l'\$ has out-of-order, that is where \$i<j\$ but \$l'\_i > l'\_j\$. We show that swapping them can't increase the distance to \$(1,2,...,n)\$. We note that swap changes the contribution these two elements as follows: > $$ |l'\_i - i | + |l'\_j - j | \to |l'\_i - j | + |l'\_j - i|.$$ > > > Here's a neat way to show this can't be an increase. Consider two people walking on a number line, one going from \$l'\_i\$ to \$i\$ and the other from \$l'\_j\$ to \$j\$. The total distance they walk is the expression on the left. Since \$i<j\$ but \$l'\_i > l'\_j\$, they switch who is higher on the number line, which means they must cross at some point during their walks, call it \$p\$. But when they reach \$p\$, they could then swap their destinations and walk the same total distance. And then, it can't be worse for them to have walked to their swapped destinations from the start rather than using \$p\$ as a waypoint, which gives the total distance on the right-hand side. > > > So, sorting two out-of-order elements in \$l'\$ makes its distance to \$(1,2,...,n)\$ smaller or the same. Repeating this process will sort \$l\$ eventually. So, \$l\$ sorted is at least as good as \$l'\$ for any choice of \$l'\$, which means it as optimal or tied for optimal. > > > Note that the only property of \$(1,2,...,n)\$ that we used is that it's sorted, so the same algorithm would work to permute any given list to minimize its distance to any fixed list. In the code, the only purpose of `z=zip(l,range(len(l)))` is to make the input elements distinct, that is to avoid ties, while keeping the same comparisons between unequal elements. If the input we guaranteed to have no repeats, we could remove this and just have `lambda l:map(sorted(l).index,l)`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` āœΣαO}н ``` [Try it online!](https://tio.run/##yy9OTMpM/f//SOPRyecWn9voX3th7///0SZ6ZjqmOsY6RjqGsQA "05AB1E – Try It Online") --- ### Explanation ``` ā # get the numbers 1 to len(input) + 1 œ # Permutations of this Σ } # Sort by ... α # Absolute difference O # Sum these н # And get the first one # implicitly print ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 44 bytes ``` {permutations(+$_).min((*[]Z-$_)>>.abs.sum)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7ogtSi3tCSxJDM/r1hDWyVeUy83M09DQys6NkoXyLOz00tMKtYrLs3VrP1fnFipkKag5xrm6KOQll@kkJOZl1r8P9pAz1RHwTCWK9pQBwhjuWyMFAwVjBVMFEwVDO24bIyBPFMFIygPTIPlTe0A "Perl 6 – Try It Online") Anonymous codeblock that returns the first minimum permutation with 0 indexing. ### Explanation: ``` { } # Anonymous code block permutations(+$_) # From the permutations with the same length .min( ) # Find the minimum by .sum # The sum of >>.abs # The absolute values of (*[]Z-$_) # The zip subtraction with the input ``` I think I might also be able to get rid of the `.sum` and sort by just the list of absolute values, but I'm not sure this is actually corret, though it passes my current test cases. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` LŒ!ạS¥ÐṂ ``` [Try it online!](https://tio.run/##y0rNyan8/9/n6CTFh7sWBh9aenjCw51N/w@3H530cOeM//@jDXQUTHQUjHQUDIEsXUMIbRoLAA "Jelly – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œ¿œ?J ``` A monadic Link accepting a list of numbers which yields a list of integers. **[Try it online!](https://tio.run/##y0rNyan8///opEP7j0629/r//3@0rpGOgomOgqmOgrmOgq6hjoKljoJxLAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##bY/NSsNAFIX3fYoD3U5DM82PutC9C3ErIdBBp21KkpHMVOiuuHFfNy70DXwBQRCUPIh9kXhnhoZSHC5zczLnuz9LWZbrrmu331/t88Vl137@PO0e39vt78cLZYqlTZtXjM6x27zddN0QV8pImIUwdBUaFKKZrypZG/s9KxptIB9EuRJG3kFoXK/NQtUMWhEhMR1OoY1oDG5VZTF9NshwdLJxEDOEOTAkEYLnA4b/TtZ7jhxZSLwP7xD1GveyqVZGmELVUDNXGBNEh6jlIgbOkNDdDxCRLybNvOAkJsfYhCF28H4m7qCItMO8sKtkKUPqAO6YxPf0WBAEZE9xQkBISLKHRtzZYseOqOEplSCmH9F6OVL6yWwVQsb7ZcKxR2yOD/twt1pCnVJ68Fz@Bw "Jelly – Try It Online"). ### How? ``` Œ¿œ?J - Link: list of numbers, X Œ¿ - Index of X in a lexicographically sorted list of all permutations of X's items J - range of length of X œ? - Permutation at the index given on the left of the items given on the right ``` N.B. `L` (length of) would work in place of `J` since `œ?` given an integer, `n`, on the right would implicitly make the range `[1..n]` to work with, but `J` is explicit. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~63~~ 60 bytes ``` ->v{[*1..v.size].permutation.max_by{|p|eval [p,0]*'*%p+'%v}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166sOlrLUE@vTK84syo1Vq8gtSi3tCSxJDM/Ty83sSI@qbK6pqAmtSwxRyG6QMcgVktdS7VAW121rLb2f4FCWnS0gY6JjpGOoYGOriGINI2N5QKLG@ooGOgheHpmOgpGsbH/AQ "Ruby – Try It Online") There's a math trick here that could be helpful in other answers too--instead of minimizing the sum of the absolute values of the differences, we *maximize* the sum of the products. Why does that work? Minimizing the sum of `(x-y) squared` isn't equivalent to minimizing the sum of `|x-y|`, but it will always give a valid answer, it just prioritizes reducing large differences over small ones whereas the actual challenge is indifferent between the two. But `(x-y)*(x-y)` = `x*x+y*y-2*x*y`. Since the square terms will always show up somewhere in the sum for any permutation, they don't affect the result, so we can simplify to `-2*x*y`. The `2` factors out, so we can simplify to `-x*y`. Then if we change minimizing to maximizing, we can simplify to `x*y`. Intuitively, this is similar to observing that if you're trying to maximize square footage using a set of horizontal walls and a set of vertical ones, you're best off pairing walls that are close in size to each other to create rooms that are as close to square as possible. `3*3 + 4*4 = 25`, while `3*4 + 4*3 = 24`. Edit: Saved three bytes by generating and evaluating a format string instead of using zip and sum. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 13 bytes ``` e:l┅f⟪D†Σ⟫∫ₔ( ``` [Try it online!](https://tio.run/##AS0A0v9nYWlh//9lOmzilIVm4p@qROKAoM6j4p@r4oir4oKUKP//WzEgNCAyIDYgMl0 "Gaia – Try It Online") ``` e: | eval and dup input l┅f | push permutations of [1..length(input)] ⟪ ⟫∫ₔ | iterate over the permutations, sorting with minimum first D†Σ | the sum of the absolute difference of the paired elements ( | and select the first (minimum) ``` [Answer] # JavaScript (ES6), 61 bytes Based on [xnor's insight](https://codegolf.stackexchange.com/a/192822/58563). ``` a=>[...a].map(g=n=>g[n]=a.sort((a,b)=>a-b).indexOf(n,g[n])+1) ``` [Try it online!](https://tio.run/##bZBNboMwEIX3OYWXHnVwYn5CuzBX6AEQi0kCiCixEbhVe3o6JoSwqBeWPO99b2Z8pW8az0PX@8i6Sz01ZiJTlEopqtSdetkaa4q2tJUhNbrBS0l4AlNQdALV2Uv989lIi8EBbxomX49eGEHCFOLs7Ohutbq5VjaSAHa7IMvyoDLUFYjN2e9FqTGuFodG/Y@D7K/o6@H@5cl3zq7eFGM8Mgwbr@QdQCxihskrOeFnuk3fuh/iOkeOOZdCwHEuw9ad4zuLehUXJor5lTEYafzgxvDcLp2dcYisHhnP/5iH1IdA8J0x8uoS0hLmNHPZwk1/ "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array [...a] // create a copy of a[] (unsorted) .map(g = n => // let g be in a object; for each value n in the copy of a[]: g[n] = // update g[n]: a.sort( // sort a[] ... (a, b) => a - b // ... in ascending order ).indexOf( // and find the position n, // of n in this sorted array, g[n] // starting at g[n] (interpreted as 0 if undefined) ) + 1 // add 1 ) // end of map() ``` --- # JavaScript (ES6), ~~130~~ 128 bytes There ~~must be~~ *definitely is* a more direct way... 0-indexed. ``` a=>(m=g=(k,p=[])=>1/a[k]?(h=i=>i>k||g(k+1,b=[...p],b.splice(i,0,k),h(-~i)))``:p.map((v,i)=>k+=(v-=a[i])*v)|k>m||(R=p,m=k))(0)&&R ``` [Try it online!](https://tio.run/##bY/dboJAEEbvfYq9Mjt1WFkUbZsMfQdvCYlbi7pdgY1Qkiakr0538SfSlAuS@eacD@ZTtarenbVtgrL6yPs99YoSXtCBuEFLaQaUyLlKTfbGj6Qp0YnpugM3M4nvlAohbIbvorYnvcu5xhAN4JEHPxoAtttXKwplOW9RuyIzI94GpFKdwVMLnUmKruMbsliQAeAhTKebvsnrhhFTjBK2q8q6OuXiVB34nisY2kq/KdmMSYDJxOM8DUWMMgP28MznLJUYZVdCovyHUOU3s/m5@GpUo6vyzi4xwpWTYdy2xAXGLmbcXQ532ofLx3ZPR/d4RK9x7RaRW638V7zj6edR/McJIpfFjggkvuDi5sghdb/p3bERDhfI0BvuHTvlZvjDFs6Is9tFlwY/R9dZXuahsf8F "JavaScript (Node.js) – Try It Online") (with 1-indexed output) ### How? The helper function \$g\$ computes all permutations of \$(0,...,n-1)\$, where \$n\$ is the implicit length of the input array \$a[\;]\$. For each permutation \$p\$, we compute: $$k=n-1+\sum\_{i=0}^{n-1}(p\_i-a\_i)^2$$ The only reason for the leading \$n-1\$ is that we re-use the internal counter of \$g\$ to save a few bytes, but it has no impact on the final result. We eventually return the permutation that leads to the smallest \$k\$. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes ``` #@*#&@Ordering ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9lBS1nNwb8oJbUoMy/9fwCQLIlW1rVLc1COVdN3qOaqNtAz1TGs1eGqNtSBQgjHRMdIx0zHCMIx1jEFCoBlzHXMgVwjoIAZSA1ISNcIyDIFiusa6ljqGIOEDMD6DQ1AQkDStJar9j8A "Wolfram Language (Mathematica) – Try It Online") Based on [xnor's insight](https://codegolf.stackexchange.com/a/192822/81203). [Answer] # [Python 2](https://docs.python.org/2/), ~~149~~ ~~126~~ 112 bytes *-23 bytes thanks to Mr. Xcoder* *-14 bytes thanks to xnor* ``` from itertools import* f=lambda a:min(permutations(range(len(a))),key=lambda x:sum(abs(a-b)for a,b in zip(x,a))) ``` [Try it online!](https://tio.run/##XYzLCsIwFET3/Yosb@QW2toHFPwScXGDqQabB0kKrT8fG0FBN7OYc2bcFu/WNClN3mqmovTR2jkwpZ318VBMp5m0uBKjUSsDTnq9RIrKmgCezE3CLA0Q5xwfcvvI6xgWDSQCUCn4ZD0jFEwZ9lQOVsx6cl6ZCBOca2yxwR6bC@fFtx1wwOPedztp/1ifbcy7bnfqH1a93@oKyzpnt8P0Ag "Python 2 – Try It Online") Uses permutations of (0 ... n-1). [Answer] w/o any permutation package # [Python 3](https://docs.python.org/3/), 238 bytes ``` def p(a,r,l): if r==[]:l+=[a];return for i in range(len(r)): p(a+[r[i]],r[:i]+r[i+1:],l) def m(l): s=(float("inf"),0);q=[];p([],list(range(len(l))),q) for t in q:D=sum(abs(e-f)for e,f in zip(l,t));s=(D,t)if D<s[0]else s return s[1] ``` [Try it online!](https://tio.run/##VY/BbsMgDIbveQqrJ1vxpqRdWykZt7wF4pBpsCFRkgA9bC@fAZ007YBl/eb7f3v9Sp@LP@1OSPl8ZoBecSP7juH/qyrDC8OR4ZLrr3BiOFe5cleGa9WOVb48AKX2d21gxZkDOxoasAaCEFINrhVyVmPQ6R58A2YJYMF6CLP/0Oi0x0AFKHArg7RKcZCDVW3u235Q2a8p5jesxlGgccuc8GC9ORB3NG45Z1xR5q82JvxzdkTEGz1SU0ndhknE@w3nt4j6yVAZaDZl9G1XdJyIxhwx5SafML1G2SntoobYwOMGiLJXe1PIEqcL6/Jia7A@Yd6yiET7Dw "Python 3 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes ``` f@n_:=MinimalBy[Permutations@Range@Length@n,Tr@Abs[n-#]&] ``` [Try it online!](https://tio.run/##RYzBCsIwEER/ZaHgKdG2mhYFJXpWKOKtBImStgGzQhsPUvrtMU0VLzvDm5k10jbKSKvv0rmK43WzPWnURj4O77JQrXlZHz6x42eJteJHhbVtOJJLy/e3rkQaiZlwRavRlhHQHVRlJATMYMGh7@M5I5AMBPrE69@uCKQEMn@/YEmABRwaOYE8sDTgbBqMCU2DZ6FA/XDte2MQ/54m8RSMyobBfQA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Êõ á ñÈíaU x ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=yvUg4SDxyO1hVSB4&input=WzcgNyAzIDIgNSA2IDQgMl0) For 0-indexed, replace the first 2 bytes with `m,` to map the array to its indices instead. ``` Êõ á ñÈíaU x :Implicit input of array U Ê :Length õ :Range [0,Ê] á :Permutations ñÈ :Sort by í U : Interleave with U a : Reduce each pair by absolute difference x : Reduce resulting array by addition :Implicit output of first sub-array ``` [Answer] # [J](http://jsoftware.com/), ~~25~~ 8 bytes ``` #\/:@/:] ``` [Try it online!](https://tio.run/##VVDLTsMwELznK0ZwaCPcNGvHpUSqxEPihDhwBlWhddMglEgkCPj6sH7UbWXZ0szOzK73Y7zIJjVWJSYQyFHynWV4eHl6HC9f5@XtvHwb0yR5vmdyX7W1wdCBZu9Vb7Zo2q35bdoafYcfg03V4rtnxZ6v6QcmetNj23yZzfD5l@ywykC4Qp0kZrPvMN0hzzQohbEFKUpIUKyRPa42bbJFijvvbjJ1IinYsoAMEQUUNDOc5Esap2JbLEKmPCAv9kBG8TUf5QIWlneW5RlHIhB0EAmGyzNFGZgoiflryVBzeU24gYrzW520sQIyQPKQgsH@V7lVeUwWHxfqvk25zeVXx2BnY7kWYU@@j/Z9VOjDUAUxHcVuIKai108RvX4IzUOpoHZ4/Ac "J – Try It Online") Much shorter answer based xnor's brilliant idea. ## original answer ## [J](http://jsoftware.com/), 25 bytes ``` (0{]/:1#.|@-"1)i.@!@#A.#\ ``` [Try it online!](https://tio.run/##VZBBT8MwDIXv/IrHelgrslAnTRmRkDohceLEGbQD2kS58APgvxc79rJNUSs9@3vPTr6XlV8f8ZSxhkOPzN/G4/nt9WVp@9@P@0yN/5s2K@pmP91Ozc4370t3c/j8@kF7RO8TqMPBgxBcRgDVHskpvXb2Y4edQHeYfbxABraMCBYxICJxhZO0lXAJS3OwzHBSCqsIFX7gE0vAKPVi2V7VyFmBTpBjub0islUqUvP3gWXi9p7wiFj3Fy5IrEMwSSrJDHLfWJ5KNYk@P2i5NvWSy/9Ug4uN8eTsnXRO0jnR5rCMBtMZLgtxqXp1i@rVJRIvFY0uevkH "J – Try It Online") ]
[Question] [ Given a single integer `x` where `0 <= x <= 91` output a stack of bottles of beer with that many bottles (and shelves) missing. For simplicity sake I'll only show the first 6 bottles and what it would be for each of the first inputs. Here's the stack of bottles, each number is the bottle you should remove for that input (1-indexed): <https://pastebin.com/wSpZRMV6> --- *Note, we're using 91 instead of 99 because 99 would result in an unstable stack of bottles.* --- # Example With 0 bottles missing (`x=0`): ``` |=| | | | | / \ . . |-----| | | |-----| |_____| ============= |=| |=| | | | | | | | | / \ / \ . . . . |-----| |-----| | | | | |-----| |-----| |_____| |_____| ===================== |=| |=| |=| | | | | | | | | | | | | / \ / \ / \ . . . . . . |-----| |-----| |-----| | | | | | | |-----| |-----| |-----| |_____| |_____| |_____| ============================= [THERE ARE MORE UNDER THIS] ``` *For the full output of 0, see here: <https://pastebin.com/ZuXkuH6s>* --- With `1` bottle missing (`x=1`): ``` |=| |=| | | | | | | | | / \ / \ . . . . |-----| |-----| | | | | |-----| |-----| |_____| |_____| ===================== |=| |=| |=| | | | | | | | | | | | | / \ / \ / \ . . . . . . |-----| |-----| |-----| | | | | | | |-----| |-----| |-----| |_____| |_____| |_____| ============================= [THERE ARE MORE UNDER THIS] ``` *Once again, this is the first two rows from here: <https://pastebin.com/ZuXkuH6s> (with 1 removed)...* --- With 2 bottles missing: ``` |=| | | | | / \ . . |-----| | | |-----| |_____| ===================== |=| |=| |=| | | | | | | | | | | | | / \ / \ / \ . . . . . . |-----| |-----| |-----| | | | | | | |-----| |-----| |-----| |_____| |_____| |_____| ============================= [THERE ARE MORE UNDER THIS] ``` --- # [ADDITIONAL INPUTS REMOVED] --- With 91 bottles missing (`n = 91`): ``` :( ``` You must output an unhappy face, because you're out of beer. --- # Rules * Bottles are to be removed left to right. * Shelves are removed when no beer remains on the top of the shelves. * For an input of 0, you are outputting 91 bottles stacked in a triangle. + The bottom row has 13 bottles, the top has 1. * 1 space between each bottle on each shelf. * Shelves must be input between each row of bottles. + Shelves may use `=`, `-` or `#` as the character. + Shelves must be 3 wider (on each side) than the bottles they hold. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~99~~ 91 bytes ``` A⁻⁹¹NθA¹³η:(Wθ«A⌊⟦θη⟧ζA⁻θζθA⁻η¹ηFζ«↑⁴↖.\↑²←|=↓³←↙¹↓.P⁶↓²P⁶↓¹P______←| »¿θ«M⁹↑M³→×=⁻×⁸ζ³↑M⁴← ``` [Try it online!](https://tio.run/##jZFNa8MwDIbPya8QPtnglqUpY83oYbDLYBljbKd1jLY4tSFxPpy00C2/3XPtliTtDvVNrx69sqQ1X1brfJlq/aCU2EgcC9koPAsoPMmiqV@abMUqTAiFktz7RygIKXATvlZC1hhFGJlgx0XKAJcEfnyvcxNZk@HP0hR8GZO9Ab1Bq/IgOvdhglMIiOvjJXkFeG@dPdc0@igoTA@5TnhmSU0BjRcLNExQmPSFI/c7H2CP@U5SCK0U51vmuHPC1QaXhWjs3OImrUVhM7eX1OQKJjhn0Ld96L8ZwKqt74nktHv3@xkFM3k3jTlZ9CY2vD/Ru8iYwmiOKLidO@HOnSQkpLeMvtfUeJ2W0/qt1jd6tNUjlf4B "Charcoal – Try It Online") Link is to verbose version of code. Actually the [real version](https://tio.run/##hZBPT8MwDMXP7aewcnKkbKL7p61oNy4gWvUAt0moTBmraJuoTcYB9tlD2gQoFGk3v@efny3vj3mzF3lpzEE0gNGSQl8UFDLdHlEzeKXXYdYUtUISI7GiB5Ki1i1uIga3tdQq1dUzb5BSCu9h0BOpUJgJidqbwZ2uJM4ZpPwlVxw31GYFgYt@KCreItkSBllpg5cMnLW2hg9xfCJOHONH@SMWDOJ7flCdcw59oCUYLDrrW3cMAzLd7cgvn8FsoD31sR1CN@KtZjDvHLf/a9@g7waj0RSZ9kmJLlUh@8ZqxMwuEtEfwj/syT5sRf85n4xuPRtzZSYnM2nLTw "Charcoal – Try It Online") is only ~~83~~ 70 bytes: ``` F¹⁵Fι⊞υκ:(F⁻⁹¹N«F¬⊟υ«M³±⁹×=⁺⁵×⁸⊟υ↑M⁴←»↑⁴↖.\↑²←|=↓³←↙¹↓.P⁶↓²P⁶↓¹P×_⁶←|← ``` Explanation: ``` F¹⁵Fι⊞υκ ``` Populate an array providing information as to where the shelves go and how long they are. ``` :( ``` Print an unhappy face, although this will be immediately overwritten by the first bottle of beer (if any). ``` F⁻⁹¹N« ``` Loop through the remaining bottles of beer. ``` F¬⊟υ« ``` Check to see whether a shelf needs to be drawn. ``` M³±⁹×=⁺⁵×⁸⊟υ↑M⁴←» ``` Print the shelf and position ready to draw the next bottle above it. ``` ↑⁴↖.\↑²←|=↓³←↙¹↓.P⁶↓²P⁶↓¹P×_⁶←|← ``` Draw a bottle and position ready to draw another bottle. [Answer] # [Python 3](https://docs.python.org/3.6), 306 299 265 253 255 252 247 244 bytes Quick attempt, could be optimised **Edit:** -2 bytes thanks to [@MrXcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) **Edit:** -32 bytes as trailing spaces is not needed **Edit:** -12 bytes by combining the two functions **Edit:** -5 bytes thanks to [@musicman523](https://codegolf.stackexchange.com/users/69054/musicman523) **Edit:** +7 bytes to remove the shelf after the last row **Edit:** -3 bytes **Edit:** -5 bytes due to a lambda function only being used once in a map **Edit:** -3 bytes by using the string function `center` ``` def l(y,x=13,z=" "):b=min(x,91-y);A,D=" |%s| ","|-----|";print(y<91and(l(y+x,x-1)or"".join(map(lambda t:((t+z)*b)[:-1].center(103)+"\n",(A%"=",A%z,A%z," / \ ",". .",D,"| |",D,"|_____|")))+z*(49-4*x)+"="*(x*8+5)*(x<13))or(x>12)*":(") ``` [Try it online!](https://tio.run/##JY7RaoQwEEV/ZRgQZmJim7qF1d0UhP2LbilaLd1Fo9g8RMm/27g9MMxlHs6daXE/o823re2@oadFeqNzuRoE5LIxw82Sl4VWC58qeYlnCMlvAECJQe0EPE3zzTpazoWubUtRknrpleZxRszuY1QM9UR9PTRtDa4kcunKouH3UumP7KuzrptJP@ec4tWipCpBg7JK1scgPAHAdW/MYCdDeYntjxz@8@dOQGZOV0GHQh2EjzaDgrw4pq8c91nnHF8i/6ZfWGBJyFtPhebtDw) [Answer] ## JavaScript (ES6), ~~251~~ 256 bytes **Edit:** *Saved 2 bytes thanks to [@dzaima](https://codegolf.stackexchange.com/users/59183/dzaima).* **Edit:** *Added 7 bytes to fix issue with parameter. `:(`* ``` c=>(f=(c,w=13)=>c>0&&f(c-w,w-1)+(c=c<w?c:w,r=(n,s=' ')=>s.repeat(n),a='\n'+r(52-w*4),' |=| 0 | | 0 | | 0 / \\ 0. .0|-----|0| |0|-----|0|_____|'.split(0).map(x=>a+r((w-c)*8+2)+r(c,' '+x)).join('')+a+r(w*8+5,'#')),(c=91-c)?f(c).slice(6):':(') ``` Here's the (mostly) ungolfed version: ``` function (consumed) { let remaining = 91 - consumed; function inner (count, width = 13) { if (count <= 0) return false; function repeat (count, string = ' ') { return string.repeat(count); } const pattern = [ ' |=| ', ' | | ', ' | | ', ' / \\ ', '. .', '|-----|', '| |', '|-----|', '|_____|' ]; let clamped = Math.min(count, width); let alignment = '\n' + repeat((13 - width) * 4); let empty = alignment + repeat((width - clamped) * 8 + 2); let shelf = alignment + repeat((width * 8) + 5, '#'); let bottles = pattern.map(row => empty + repeat(clamped, ' ' + row)); return inner(count - width, width - 1) + bottles.join('') + shelf; } return (remaining) ? inner(remaining).slice(6) : ':('; } ``` ### Test code ``` const golfed = c=>(f=(c,w=13)=>c>0&&f(c-w,w-1)+(c=c<w?c:w,r=(n,s=' ')=>s.repeat(n),a='\n'+r(52-w*4),' |=| 0 | | 0 | | 0 / \\ 0. .0|-----|0| |0|-----|0|_____|'.split(0).map(x=>a+r((w-c)*8+2)+r(c,' '+x)).join('')+a+r(w*8+5,'#')),(c=91-c)?f(c).slice(6):':(') console.log(golfed(91)); // :( console.log(golfed(72)); // |=| |=| |=| |=| |=| |=| // | | | | | | | | | | | | // | | | | | | | | | | | | // / \ / \ / \ / \ / \ / \ // . . . . . . . . . . . . // |-----| |-----| |-----| |-----| |-----| |-----| // | | | | | | | | | | | | // |-----| |-----| |-----| |-----| |-----| |-----| // |_____| |_____| |_____| |_____| |_____| |_____| // ##################################################################################################### // |=| |=| |=| |=| |=| |=| |=| |=| |=| |=| |=| |=| |=| // | | | | | | | | | | | | | | | | | | | | | | | | | | // | | | | | | | | | | | | | | | | | | | | | | | | | | // / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ // . . . . . . . . . . . . . . . . . . . . . . . . . . // |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| // | | | | | | | | | | | | | | | | | | | | | | | | | | // |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| |-----| // |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| |_____| // ############################################################################################################# ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 360 358 bytes ``` #define P printf( r,i,j;char*b[]={" |=| "," | | "," | | "," / \\ ",". .","|-----|","| |","|-----|","|_____|"};w(n){P"%*c",n,' ');}main(n,a)char**a;{(n=-atoi(a[1]))<-90?P":(\n"):({while(++r<14)if((n+=r)>0){for(j=0;j<9;++j){w(4*(13-r)+1);for(i=r;i>0;)--i<n?P b[j]),w(1):w(8);P"\n");}if(r<13){w(4*(13-r)-2);for(i=0;++i<8*r+6;)P"=");P"\n");}}});} ``` [Try it online!](https://tio.run/##ZY7BasMwEETv/YpFpWTXklK7SUtiWckv@B6borh2I9MqRQR8sP3trhUobegclscsO7OVfK@qabp/qxvrasjhy1t3afDOCytaVZ2Mj46HUvcMYNADABOB4B89AkBRBFxC0HKmQQYNga7ecOu9Bg1sVB066nP2EFVMOLGABanx01iHThi6vhAZ1aPT0lzOFs0hKYkyuY33OUuxcIxS7LuT/aiRc58la7INouPa0y6mvjl7bHWs2myrOG@p73AdYbKSnnhCKqyt9sruYkVS2sztczge2pJEhwmlHW5I5SzUqHEOngtWfzPk009GPMfbbBN5/qIoZ5r93o3jPKZpeo6/AQ "C (gcc) – Try It Online") **Explanation:** ``` #define P printf( r,i,j; char*b[]={ " |=| ", " | | ", " | | ", " / \\ ", ". .", "|-----|", "| |", "|-----|", "|_____|"}; // function to print `n` spaces: w(n){P"%*c",n,' ');} main(n,a)char**a; { // no beer left? (n=-atoi(a[1]))<-90 // sad face ?P":(\n") // else create stack // using GCC extension "expression statement" `({ <statement> })` here, // shorter than if-else or a function call :({ // loop over 13 rows while(++r<14) // found non-empty row? if((n+=r)>0) { // loop over text lines of beer bottles for(j=0;j<9;++j) { w(4*(13-r)+1); // for each bottle for(i=r;i>0;) // print either 8 spaces or line of the bottle --i<n?P b[j]),w(1):w(8);P"\n"); } // except for last row, ... if(r<13) { // ... print shelf w(4*(13-r)-2); for(i=0;++i<8*r+6;) P"="); P"\n"); } } }); } ``` [Answer] # Python 2, 436 bytes *Yikes!!* My method is too verbose, but anyway: it essentially 'draws' each row of bottles, adds in the spaces, and then 'erases' whatever necessary, printing whatever is left. ``` B=[' |=| ',' | | ',' | | ',' / \\ ','. . ','|-----| ','| | ','|-----| ','|_____| '] N=lambda r:sum(n for n in range(1,r+1)) n=input() R=0 while N(R)<n:R+=1 L=R-n+N(R-1) e=range(1,R)+([R],[])[L!=0] for r in range(1,14): if r in e:continue if(r-1 in e)<1:print('',' '*(1+(13-r)*4)+'='*(r*8-3))[r!=1] i=(0,R-L)[r==R];w=(8*i+(13-r)*4,0)[i==0];print'\n'.join([' '*w+((13-r)*4*' '+l*r)[w:]for l in B]) if n=91:print':(' ``` Halvard Hummel's is much better. ]
[Question] [ [Wise](https://github.com/Wheatwizard/Wise) is a simple bitwise language I designed a while back. It is based around [Python's bitwise operations](https://wiki.python.org/moin/BitwiseOperators). It has several operations most of these are the same or very similar to the equivalent symbol in Python. * `:` Duplicate the top of the stack * `?` Rotate the top of the stack to the bottom * `!` Rotate the bottom of the stack to the top * `[` `]` loop while the top of the stack is not zero * `~` not the top of the stack (*`-(n+1)`*) * `-` negate the top of the stack (*`-n`*) * `>` bitshift the top of the stack once to the right (*`n//2`*) * `<` bitshift the top of the stack once to the left (*`n*2`*) * `^` xor the top two items of the stack (*Same as Python*) * `|` or the top two items of the stack (*Same as Python*) * `&` and the top two items of the stack (*Same as Python*) --- Making an integer in Wise is pretty simple you can make zero with `::^` and increment it with `~-` so you make zero and increment it a bunch of times. However if we remove the `-` things become a little more interesting. We can still make every number using the remaining operations. For example here is 3 ``` ~<<~ ``` [TIO](https://tio.run/nexus/wise#@19nZ2djU/f/PwA) This works because `~` turns zero, an infinite string of `0` bits, into negative one, an infinite string of `1` bits, each `<` appends a `0` bit to the end, when we are done we do `~` which turns each it into a string of `0`s followed by a two `1`s, or as most people call it 3. --- # Task Write a program that when given a positive integer will output a Wise program that will create the number `n` without any `-` in its source (the source of the output, you may use `-` in your own source). You may assume that there is already a zero on the top of the stack. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") *not* [meta-golf](/questions/tagged/meta-golf "show questions tagged 'meta-golf'") so you should aim to minimize the generating source code *not* necessarily the output. # Example outputs *This list is not exhaustive they are simply possible outputs* ``` 1 -> ~<~ 2 -> ~<~< 3 -> ~<<~ 4 -> ~<~<< 5 -> ~<~:<<| 6 -> ~<<~< 7 -> ~<<<~ 8 -> ~<~<<< 9 -> ~<~:<<<| 10 -> ~<~:<<|< 11 -> ~<<~:><<<| 12 -> ~<<~<< 13 -> ~<<~:<<<|> 14 -> ~<<<~< 15 -> ~<<<<~ 16 -> ~<~<<<< ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 bytes ``` ¤d0'<1"~<~ ``` [Try it online!](https://tio.run/nexus/japt#@39oSYqBuo2hUp1N3f//JiYA "Japt – TIO Nexus") Basic idea: take the binary representation of the number, and map `0` to `<` and `1` to `~<~`. Outputs for 1-10: ``` 1: ~<~ 2: ~<~< 3: ~<~~<~ 4: ~<~<< 5: ~<~<~<~ 6: ~<~~<~< 7: ~<~~<~~<~ 8: ~<~<<< 9: ~<~<<~<~ 10: ~<~<~<~< ``` [Answer] ## JavaScript (ES6), ~~34~~ 33 bytes ``` f=n=>n?f(n&1?~n:n/2)+'<~'[n&1]:'' ``` ``` <input type=number oninput=o.textContent=f(this.value)><pre id=o> ``` Works for any 32-bit integer. [Answer] # [Haskell](https://www.haskell.org/), 38 bytes I feel like PPCG is really improving my Haskell. *Strokes white cat.* ``` f n=mapM(["<","~<~"]<$f)[1..n]!!n>>=id ``` `f` takes an `Int` and returns a `String`. [Try it online!](https://tio.run/nexus/haskell#DchNCoMwEAbQq3wGFwpl6PjXCok36AnERWgSCNRpiUp3Xj3tW77VRjFRdp/scy8PeUXxG632UwVK3rqavu/kthwg5r@PalZaXdSpT7XoMtQzE8lSFDJNJrqcGQ1adOgx4IY7RvAVzOAG3II7cA8efg "Haskell – TIO Nexus") (I'm referring to that `<$f` by the way. It saves a character over `\_->`.) > > In the `Functor` instance for `(->) a` (functions from type `a`), we have: `x <$ f = fmap (const x) f = const x . f = const x`. The only limitation is that `f` and the final `const x` must use the same source type `a`. The instance is completely lazy so this never even evaluates `f`. > > > Alternatively, same length but less evil (`(l!!)` is an anonymous function): ``` (l!!) l=(++)<$>"":tail l<*>["<","~<~"] ``` [Try it online!](https://tio.run/nexus/haskell#BcFLDsIgFAXQuau4fekArCG@/vwEuhHjgFiakFA0FOOsW8dzVuuj8TG7ZF@5/sbgo9vUaj9iUcnZWarfO81bWYwIVSUPwYimkbqeiO7Z@oCgj9ODNJ1o1zs9S2G06NBjwIgLrriBz2AGt@AO3IMH8PgH "Haskell – TIO Nexus") Both of these use the same representation as @ETHproductions' Japt answer, although especially the first one may give some redundant `<`s at the beginning. The first one calculates all combinations of `n` `"<"` and `"~<~"` strings, then indexes into the resulting list. The second one recursively calculates an infinite list formed by starting with `""` and then constructing new elements by appending `"<"` and `"~<~"` strings to each element already in the list (actually it was slightly shorter to also let the `""` get turned into `"<"`.) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~118~~ ~~116~~ ~~109~~ ~~107~~ ~~105~~ 91 bytes Saved 2 bytes thanks to cyoce! ``` ->n{o={0=>""} o.dup.map{|c,k|["~~c","<c*2"].map{|t|o[eval t[1..9]]=k+t[0]}}until o[n] o[n]} ``` [Try it online!](https://tio.run/nexus/ruby#JcixDoIwEADQna9oblRsgLiYWH7kvBhSwTRgr8HDpS2/XmNc3vAmcyun3kc2sTE9QK5YP7agX0OIydZzQth3CzVc7aED@r8kxvEzLEqw1fpCZOajYEM5b17cohg9VT9yCavzoiZ8jvLWwndH5dx2Xw "Ruby – TIO Nexus") This is a function that takes the integer as input and returns the string that represents that integer in Wise. You can find an ungolfed version **[here](https://gist.github.com/ConorOBrien-Foxx/771c36bf38a714c98816c528750d7a7b)**, which tests this program on all integers from 1 up. The basic idea is to record a "pool" of constants. Then, with each "step", constants are added to the pool for each possible function. I have chosen the functions `~`, `<`, and `>`, which I believe are sufficient to represent every number. (At least, every number under 10,000.) [Answer] # Python2, ~~54~~ ~~52~~ 51 bytes. ``` lambda x:'<'.join('>~<~'*int(i)for i in bin(x)[2:]) ``` Thanks to Wheat Wizard for saving 2 bytes, and Ørjan Johansen for one byte! This uses the same idea as ETHproduction's Japt answer, but with different replacement strings (i.e. using the binary representation) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` bS'<…~<~‚èJ ``` [Try it online!](https://tio.run/nexus/05ab1e#@58UrG7zqGFZnU3do4ZZh1d4/f9vAgA) Similar to ETHproductions' Japt answer. Saved 4 bytes thanks to @Adnan! [Answer] # [Python 2](https://docs.python.org/2/), ~~123~~ 110 bytes ``` def w(x):a=map(int,bin(x)[2:]);return x%2*("~<~:<"+"<".join(":"*e for e in a[-2::-1])+"|"*sum(a))or w(x/2)+"<" ``` [Try it online!](https://tio.run/nexus/python2#FY3BCsIwEER/ZVkQsqlVsl5kjV9SeoiYQoSmJbbYg/TX43p9M2@mPuMAH7ORhPsYZpPycnykrKBj6elW4rKWDNuBrcHd7@KxQY@n16QlFLQRhqlAhJQhdC2LtK6nBr9o3@toApGmun9m@nt1LvqgwF346pjqDw "Python 2 – TIO Nexus") Also as a `lambda` ``` w=lambda x:x%2*("~<~:<"+"<".join(":"*int(e)for e in bin(x)[-2:2:-1])+"|"*sum(map(int,bin(x)[2:])))or w(x/2)+"<" ``` [Try it online!](https://tio.run/nexus/python2#LcxBCsIwEIXhq4QBYSa1SsaNDPEk0kWKFSImLa3SLKRXjyO4/fneq@vlGVJ/C6ZI2bFF2PwmHhrwcHiMMSMI2JhfONB9nM1gYja95kLXloWldR018AG7vBOmMKHa/R@wdESkqxXLken3WadZgQZ34rNjql8) Could be shorter but here is my solution. It takes the binary representation and turns it into the code. [Answer] # [Japt](https://github.com/ETHproductions/japt), 23 bytes ``` ?Uu ?ß~U +'~:ßU/2 +'<:P ``` [Try it online!](https://tio.run/nexus/japt#@28fWqpgf3h@XaiCtnqd1eH5ofpGQJaNVcD//2YA "Japt – TIO Nexus") [Answer] # Jelly, ~~11~~ 10 bytes ``` Bị“~<~“<”F ``` This is a ported version of ETHproductions' Japt answer. Speaking of ETHproductions, they saved me one byte! ]
[Question] [ In my time on PPCG, I've noticed that quine problems and polyglot problems are quite popular. Also, meta-solutions to problems, that is, scripts which generate a program which is the solution to a problem, tend to get a lot of positive feedback from the community. Therefore, I have created this challenge, which implements these three ideas. Your task then, reader and [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") enthusiast, is to create as short as possible a script which can run in two languages A and B to generate quines for A and B. When your program is run in language A, it should generate a program that is a quine in language B **but not in language A** and vice versa. The languages A and B can be different version of the same language, provided you keep in mind that the generated quines should only work in one of the versions. Keep in mind that the [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/10033) should be considered closed and only [proper quines](http://meta.codegolf.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) are allowed. Good luck, fewest characters wins! [Answer] ## CJam / Fission, 22 bytes ``` "'!+OR'")5-"{'_'~}_~"; ``` [Try it in CJam.](http://cjam.tryitonline.net/#code=IichK09SJyIpNS0ieydfJ359X34iOw&input=) [Try it in Fission.](http://fission2.tryitonline.net/#code=IichK09SJyIpNS0ieydfJ359X34iOw&input=) In CJam, this prints [the standard Fission quine](https://codegolf.stackexchange.com/a/50968/8478): ``` '!+OR" ``` [Try the Fission quine.](http://fission2.tryitonline.net/#code=JyErT1Ii&input=) In Fission, this prints a `"`-less variant of the standard CJam quine: ``` {'_'~}_~ ``` [Try the CJam quine.](http://cjam.tryitonline.net/#code=eydfJ359X34&input=) This also works for 22 bytes (printing the same quines): ``` "& *NQ!":)R"{'_'~}_~"; ``` ### Explanation In CJam: ``` "'!+OR'" e# Push this string. ) e# Pull off the last character. 5- e# Subtract 5, turning ' into ". "{'_'~}_~" e# Push this string. ; e# And discard it again. ``` So at the end of the program, the stack contains the string `"'!+OR"` and the character `"`, both of which are implicitly printed. In Fission, program flow starts at the `R` with a right-going atom. `'"` just changes the atoms mass, `)`, `5` and `-` are ignored for various reasons. Then the atom enters print mode at the `"` and prints `{'_'~}_~`. `;` destroys the atom and terminates the program. [Answer] # Clojure / Common Lisp, 274 bytes ``` (defmacro t []"((fn [s] (print (list s (list (quote quote) s)))) (quote (fn [s] (print (list s (list (quote quote) s))))))")(if '()(print(let[s clojure.string/replace](.toUpperCase(s(s(s(s(s(t)"fn""lambda")"[s]""(s)")"(quote ""'")"e)""e")")))))""))))"))))(eval '(princ(t)))) ``` Some spaces added for readability ``` (defmacro t []"((fn [s] (print (list s (list (quote quote) s)))) (quote (fn [s] (print (list s (list (quote quote) s))))))") (if '()(print(let[s clojure.string/replace](.toUpperCase (s(s(s(s(s(t)"fn""lambda")"[s]""(s)")"(quote ""'")"e)""e")")))))""))))")))) (eval '(princ(t)))) ``` Basically defines a macro which returns a quine in Clojure. Clojure requires parameters for macro definition provided as vector (`[]`) whereas Common Lisp (thankfully) just ignores it. After that we differ 2 languages by evaluating `'()` which equals to `nil` and thus falsey in Common Lisp and is `true` in Clojure. Then we do string manipulations using Clojure which Common Lisp doesn't even try to evaluate as it goes in another `if` branch. Clojure on the other hand tries to check if another branch is at least correct before executing so had to use `eval` there to both be correct in Clojure and output correct string in Common Lisp. Note: just returning two different string might probably be shorter but then it won't be different to a polyglot challenges about outputing different strings in different languages. ¯\\_(ツ)\_/¯ Clojure original source run: <https://ideone.com/SiQhPf> Common Lisp original source run: <https://ideone.com/huLcty> Clojure output : `((LAMBDA (S) (PRINT (LIST S (LIST 'QUOTE S)))) '(LAMBDA (S) (PRINT (LIST S (LIST 'QUOTE S)))))` Common Lisp output : `((fn [s] (print (list s (list (quote quote) s)))) (quote (fn [s] (print (list s (list (quote quote) s))))))` Clojure output run in Common Lisp: <https://ideone.com/T1DF7H> Vice versa: <https://ideone.com/Fezayq> [Answer] # CJam 0.6.6 dev / GolfScript, ~~15~~ ~~14~~ 12 bytes ``` "0$p"0$~a:n; ``` *Thanks to @jimmy23013 for golfing off 2 bytes!* Rest to be updated. ### Verification Since the submission involves significant whitespace, it's best to compare hexdumps. ``` $ xxd -g 1 mpquine 0000000: 22 60 30 24 7e 22 30 24 7e 4e 4d 3a 6e 3b "`0$~"0$~NM:n; $ $ cjam mpquine | tee quine.gs | xxd -g 1 0000000: 22 60 30 24 7e 22 60 30 24 7e 0a "`0$~"`0$~. $ golfscript quine.gs | xxd -g 1 0000000: 22 60 30 24 7e 22 60 30 24 7e 0a "`0$~"`0$~. $ cjam quine.gs | xxd -g 1 0000000: 22 60 30 24 7e 22 60 30 24 7e "`0$~"`0$~ $ $ golfscript mpquine | tee quine.cjam | xxd -g 1 0000000: 22 60 30 24 7e 22 60 30 24 7e "`0$~"`0$~ $ cjam quine.cjam | xxd -g 1 0000000: 22 60 30 24 7e 22 60 30 24 7e "`0$~"`0$~ $ golfscript quine.cjam | xxd -g 1 0000000: 22 60 30 24 7e 22 60 30 24 7e 0a "`0$~"`0$~. ``` ## CJam CJam prints `"`0$~"0$~` and a trailing linefeed. [Try it online!](http://cjam.tryitonline.net/#code=ImAwJH4iMCR-Tk06bjs&input=) The generated program prints `"`0$~"0$~` with the trailing linefeed in GolfScript ([Try it online!](http://golfscript.tryitonline.net/#code=ImAwJH4iYDAkfgo&input=)), but without the linefeed in CJam ([Try it online!](http://cjam.tryitonline.net/#code=ImAwJH4iYDAkfgo&input=)). ### How the metaquine works ``` "`0$~" e# Push that string on the stack. 0$~ e# Push a copy and evaluate it: e# ` Inspect the string, pushing "\"`0$~\"". e# 0$ Push a copy. e# ~ Evaluate, pushing "`0$~". e# Both "\"`0$~\"" and "`0$~" are now on the stack. NM e# Push "\n" and "". :n; e# Map print over the elements of "" (none) and pop the result. e# "\"`0$~\"", "`0$~", and "\n" are now on the stack, and the e# characters they represent will be printed implicitly. ``` ### How the quine works ``` "`0$~" # Push that string on the stack. 0$~ # As in CJam. <LF> # Does nothing. # "\"`0$~\"" and "`0$~" are now on the stack, and the characters # they represent will be printed implicitly, plus a linefeed. ``` Unlike GolfScript, CJam doesn't print a trailing linefeed by default, so this is not a quine in CJam. ## GolfScript GolfScript prints `"`0$~"0$~`, without trailing whitespace. [Try it online!](http://golfscript.tryitonline.net/#code=ImAwJH4iMCR-Tk06bjs&input=) The generated program prints `"`0$~"0$~` without trailing whitespace in CJam ([Try it online!](http://cjam.tryitonline.net/#code=ImAwJH4iYDAkfg&input=)), but GolfScript appends a linefeed ([Try it online!](http://golfscript.tryitonline.net/#code=ImAwJH4iYDAkfg&input=)). ### How the metaquine works ``` "`0$~"0$~ # As in CJam. NM # Unrecognized token. Does nothing. :n # Store the top of the stack – "`0$~" – in the variable n. n holds # "\n" by default. When the program finishes, the interpreter # prints n implicitly, usually resulting in a trailing linefeed. # By redefining n, it will print "0$~" instead. ; # Pop the string from the stack so it won't be printed twice. ``` ### How the quine works ``` "`0$~"0$~ e# Works as in GolfScript. ``` Unlike CJam, GolfScript will append a linefeed to the contents of the stack, so this is not a quine in GolfScript. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) / GolfScript, ~~18~~ 16 bytes ``` 0000000: 3a 6e 22 ff cc cc 22 7d 7f fe 22 3a 6e 60 ff 3b :n"..."}..":n`.; ``` ### Verification Testing all involved programs with the exact byte streams can only be done locally. ``` $ LANG=en_US # Latin-1. Jelly doesn't care about the exact encoding, $ # as longs as it's not UTF-8. $ $ xxd -g 1 mpquine 0000000: 3a 6e 22 ff cc cc 22 7d 7f fe 22 3a 6e 60 ff 3b :n"..."}..":n`.; $ $ jelly f mpquine | tee quine.gs | xxd -g 1 0000000: 22 3a 6e 60 22 3a 6e 60 ":n`":n` $ golfscript quine.gs | xxd -g 1 0000000: 22 3a 6e 60 22 3a 6e 60 ":n`":n` $ jelly f quine.gs 2> /dev/null | xxd -g 1 $ $ golfscript mpquine | tee quine.jelly | xxd -g 1 0000000: ff cc cc ... $ jelly f quine.jelly | xxd -g 1 0000000: ff cc cc ... $ golfscript quine.jelly | xxd -g 1 0000000: 0a ``` ## Jelly With [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page), the program looks as follows. ``` :n"”ṘṘ"} “":n`”; ``` This prints ([Try it online!](http://jelly.tryitonline.net/#code=Om4i4oCd4bmY4bmYIn0K4oCcIjpuYOKAnTs&input=)) ``` ":n`":n` ``` which is a quine in GolfScript ([Try it online!](http://golfscript.tryitonline.net/#code=IjpuYCI6bmA&input=)), but a parser error in Jelly ([Try it online!](http://jelly.tryitonline.net/#code=IjpuYCI6bmA&input=)). ## GolfScript In Latin-1, the program looks as follows, with an unprintable DEL character between `}` and `þ`. ``` :n"ÿÌÌ"} þ":n`ÿ; ``` This prints ([Try it online!](http://golfscript.tryitonline.net/#code=Om4iw7_DjMOMIn1_w74iOm5gw787&input=)) ``` ÿÌÌ ``` or, visualized with Jelly's code page, ``` ”ṘṘ ``` which is a quine in Jelly ([Try it online!](http://jelly.tryitonline.net/#code=4oCd4bmY4bmY&input=)), but only prints a linefeed in GolfScript ([Try it online!](http://golfscript.tryitonline.net/#code=w7_DjMOM&input=)). [Answer] # JavaScript / C 278 bytes At a staggering 278 bytes: ``` //\ console.log('int main(){char*A="int main(){char*A=%c%s%c;printf(A,34,A,34);}";printf(A,34,A,34);}');/* int main(){puts("A='A=;B=String.fromCharCode(39);console.log(A.slice(0,2)+B+A+B+A.slice(2));';B=String.fromCharCode(39);console.log(A.slice(0,2)+B+A+B+A.slice(2));");}//*/ ``` The C quine: `int main(){char*A="int main(){char*A=%c%s%c;printf(A,34,A,34);}";printf(A,34,A,34);}` The JavaScript quine: `A='A=;B=String.fromCharCode(39);console.log(A.slice(0,2)+B+A+B+A.slice(2));';B=String.fromCharCode(39);console.log(A.slice(0,2)+B+A+B+A.slice(2));` [Answer] # Befunge / Fission, 35 bytes ``` "$TQ-#'">,#-:#2_@;"+1_@#`+66:,g0:"L ``` [Try it in Befunge](http://befunge.tryitonline.net/#code=IiRUUS0jJyI-LCMtOiMyX0A7IisxX0AjYCs2NjosZzA6Ikw&input=) | [Try it in Fission](http://fission.tryitonline.net/#code=IiRUUS0jJyI-LCMtOiMyX0A7IisxX0AjYCs2NjosZzA6Ikw&input=) In Befunge this produces the [Fission quine](https://codegolf.stackexchange.com/a/50968/8478): ``` '!+OR" ``` In Fission this produces the [Befunge quine](http://rosettacode.org/wiki/Quine#Befunge): ``` :0g,:66+`#@_1+ ``` [Answer] # Python / Retina, ~~70~~ ~~65~~ ~~64~~ 66 bytes I used the same strategy I used in [my previous Python / Retina polyglot](https://codegolf.stackexchange.com/a/56011/34718). ``` # print"\nS`((.+))"*2+"\n\n" #? #_='_=%r;%_\n';_ #?; #;print _% # ``` [**Try in Python**](https://repl.it/EU80/3) | [**Try in Retina**](http://retina.tryitonline.net/#code=IwpwcmludCJcblNgKCguKykpIioyKyJcblxuIgojPwojXz0nXz0lcjslX1xuJztfCiM_OwojO3ByaW50IF8lCiMK&input=) `#` is a comment in Python, so it simply prints the Retina quine in Python. In Retina, the first stage (2 lines) does nothing, because no `#` will be found in the input. The next stage replaces nothing with the basis of the Python quine. The third stage replaces each semicolon with the `#print _%` piece. The last stage removes all `#`'s. --- **Quine in Retina:** ``` S`((.+)) S`((.+)) ``` **Quine in Python:** ``` _='_=%r;print _%%_\n';print _%_ ``` The quines used may be seen in [this challenge](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good). The Retina quine is an error in Python, and the Python quine has no output in Retina. [Answer] # Python 3 / Python 2, 62 bytes ``` _='_=%r;print(_%%_['+'~'*-~int(-1/2)+'int(-1/2):])';print(_%_) ``` Try it in [Python 2](https://tio.run/nexus/python3#@x9vqx5vq1pkXVCUmVeiEa@qGh@trq1ep66lWwcS0DXUN9LUVoczrWI11eFq4zX//wcA "Python 2 – TIO Nexus"), [Python 3](https://tio.run/nexus/python3#@x9vqx5vq1pkXVCUmVeiEa@qGh@trq1ep66lWwcS0DXUN9LUVoczrWI11eFq4zX//wcA "Python 3 – TIO Nexus"). Based on the Python quine [here](https://codegolf.stackexchange.com/a/115/16766). The distinguishing factor between the two versions is what they do with `int(-1/2)`: in Python 2, `/` is integer division (rounding down), with a result of `-1`; in Python 3, `/` is floating point division (`-0.5`), which `int` truncates to `0`. We build a string `_` in three parts. `'_=%r;print(_%%_['` and `'int(-1/2):])'` are always the same. The interesting part is `'~'*-~int(-1/2)`: * In Python 2, `-~int(-1/2)` is `0`, and the tilde is not added to the string; * In Python 3, `-~int(-1/2)` is `1`, and the tilde is added to the string. Thus, Python 2 outputs the [Python 3 quine](https://tio.run/nexus/python3#@x9vqx5vq1pkXVCUmVeiEa@qGh8NYuga6htpWsVqqsMlUMX//wcA) ``` _='_=%r;print(_%%_[int(-1/2):])';print(_%_[int(-1/2):]) ``` and Python 3 outputs the [Python 2 quine](https://tio.run/nexus/python2#@x9vqx5vq1pkXVCUmVeiEa@qGh9dB2LpGuobaVrFaqrDZdAk/v8HAA) ``` _='_=%r;print(_%%_[~int(-1/2):])';print(_%_[~int(-1/2):]) ``` In each version, the expression inside `[ :]` evaluates to `0`, which makes the slice include the entire string, whereas in the wrong language it evaluates to `-1`, which makes the slice include only the last character, truncating the output so it's not a full quine. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), [brainfuck](https://github.com/TryItOnline/tio-transpilers) ~~4617~~ 4009 bytes ``` ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()()()())))()())[()()])))()()())[()()])))())[()])[()()()()])))))))))))))))))))))))))))))))))))))))))))()()())()())[()()()()])()()())[()()])()())[()()()()])()()()))()()())[()()])[()()()()])))))))))))))))))))()())))()()())[()()()()])()()()()())[()()]))()())[()()()])()())[()()])))()()())[()()])))())[()()])[()()()])))))))))))))))))))))))))))))))))))))))))))()()()())[()()()])()()()())[()()])[()()()]))()()()())[()()()])()()()())[()()])[()()()])()()()())[()()()])()()()())[()()])[()()()]))))))))))))))()()()())[()()()])()()()())[()()])[()()()]))()()()())[()()()])()()()())[()()])[()()()])))))))))))))))))))))))))))))()()()())[()()()])()()()())[()()])[()()()]))()()()())[()()()])()()()()()))))))[()()()])[()])()()))))()()){({}<>)<>}<>([]){({}[()]<(({}[()]<((((((()()()){}())){}{}){}())<>)>)<>){({}[()]<({}()())>){({}[()]<({}())>){({}[()]<({}((()()()){}()){})>){({}[()]<({}()())>){({}[()]<({}(((()()()){}()){}){}())>){(<{}({}()())>)}}}}}}{}([]<({}<{({}<>)<>}<>>)>){({}[()]<({}<>)<>>)}{}{({}[()]<(({}))>)}{}(((({})(((()()())){}{}){}())))<>>)}{}{<>({}<>)}{+++++++>>>+>>>+++++++>>>++++++++>>>+++>>>++++>>>++>>>+++>>>++++>>>++++++++>>>+++>>>++++>>>+>>>+++++>>>++++++>>>++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>+++>>>+>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>+++>>>+>>>+>>>+>>>+>>>+>>>+>>>+>>>+>>>+>>>++>>>+>>>++>>>+>>>++>>>+>>>++>>>+>>>++>>>++>>>+++++++>>>++++++++>>>++>>>+++++++>>>++++++++>>>++>>>+++++++>>>++++++++>>>++>>>+++>>>++++>>>++>>>++>>>+>>>++>>>++>>>++>>>++++>>>++>>>+++>>>++++>>>++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>+++>>>+>>>+++++++>>>++++++++>>>+>>>++>>>++>>>++++>>>++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>+++>>>+>>>+++++++>>>++++++++>>>+>>>+>>>+>>>+>>>++>>>+>>>++>>>+>>>++>>>++>>>++>>>+++++++>>>++++++++>>>+++++++>>>++++++++>>>++>>>+++++++>>>++++++++>>>+>>>++>>>++>>>++++>>>++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>+++>>>+>>>+++++++>>>++++++++>>>+>>>++>>>+>>>++>>>++>>>++++>>>++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>+++>>>+>>>+++++++>>>++++++++>>>+>>>+>>>+>>>+>>>++>>>+>>>++>>>+>>>++>>>++>>>+++++++>>>++++++++>>>+>>>++>>>++>>>+++++++>>>++++++++>>>++>>>+++++++>>>++++++++>>>+>>>++>>>++>>>++++>>>++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>+++>>>+>>>+++++++>>>++++++++>>>+>>>++>>>+>>>++>>>++>>>++++>>>++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>+++>>>+>>>+++++++>>>++++++++>>>+>>>+>>>+>>>+>>>++>>>+>>>++>>>+>>>++>>>+>>>++>>>+>>>++>>>++>>>++>>>+++++++>>>++++++++>>>+++++++>>>++++++++>>>++>>>+++++++>>>++++++++>>>++>>>++++>>>++>>>+++++++>>>+>>>+++>>>+++++++>>>++++++++>>>+>>>+++++++>>>++++++++>>>+>>>++>>>+>>>++>>>++>>>++++>>>++>>>++++++++>>>++++++++>>>++++++++>>>++++++++>>>++++++++>>>++++++++>>>++++++++>>>+++++++>>>++++++++>>>+>>>+++++>>>++++++>>>+++>>>+>>>+++++++>>>++++++++>>>+++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++>>>++++>>>++>>>+++>>>++++>>>++++++++>>>+++>>>++++>>>++++>>>++>>>++++>>>++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>+++>>>+>>>+++++++>>>++++++++>>>+++>>>++++>>>++>>>+++>>>++++>>>++++>>>++>>>++++++++>>>+++++++>>>++++++++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>+++>>>+>>>+>>>+>>>+++++++>>>++++++++>>>+++++>>>+>>>++>>>++++++>>>++>>>+>>>++>>>++>>>++>>>++++>>>++>>>++++++++>>>+++++++>>>++++++++>>>+++>>>++++>>>++++>>>++>>>++++++++>>>+++++++>>>++++++++>>>+++>>>++++>>>+++++++>>>+>>>+++++++>>>++++++++>>>+++>>>++++>>>++>>>+++>>>++++>>>++++++++>>>+++>>>++++>>><<<[<<<]>>>[>++++++++++++++++++++++++++++++++++++++++.<[->.+.->+<<]>+.[-]>>]<[<<<]>>>[<++++++++++++++++++++++++++++++++++++++++>-[<+>-[<+++++++++++++++++++>-[<++>-[<+++++++++++++++++++++++++++++>-[<++>-[<++++++++++++++++++++++++++++++>-[<++>-]]]]]]]<.>>>>]}{} ``` [Try it online!](https://tio.run/nexus/brain-flak#7VYLisQgDL2ORfQEQdhziCcRz96J2vpr/XXaHZadDG1jkvdiEsFZyf@Sxf9Q3Efat9pW@drqyht246hsZJHRE@Q5Kt4iqpk/qeSMK6soDVFDxSfp54svk5FT0onYGdpf2M7zHSAbW3DIMLh99JpoA2IBgW8ilVvbKCBRiad@0cZitdHGqwi14ARmzegoTaUhI0S2PsUBEmgBtYAxTnApHQzSAkXB6ewIwXrSsh2Nz4iLmDipewlAbJsjMpp6EUK4J64ydTO4z9FSidx9ISaBD@RMAnKGYH8b3HqGlcY2rnsODT9J2R7KjX0@Bbb28WzWgSn1mjw3k8@V@lc6PdS1b8vvafnTx71bc7t/bzX2VrWyu5mRTAz90h1JP3DM@lutD6VqvOUuniUYuhR7FVwu/TDeBw4IAEh8FKoyBPWEg2SCU84EtVDKJUMCFZlglEkwjHWviq/mnA4LccoLcNyoUPhndV1X9vMC "Brain-Flak – TIO Nexus") [Try it online!](https://tio.run/nexus/brainfuck#7VYLzoMgDL4OxsgJGi5COAnh7P6lKC/l5XTLsr@LWtp@X2lLwlb2WzK5Hwp9pH2rbZWura6cYTf2ykYWGB1BmqPgzaKq@aNKzriSiuIQ1VV8lH68@DwZOyUdiB2hfcN2nu8A29i8Q/rB7aPXTBsQEwh8M6lobaOABSWc@kkbi9VGG6ci1IIjmDWjIzflhoQQ2doUB4inBdQ8xpDgUhIM4gJFxkl2hGA9cdlE4zLiIiSO6p48ENtGREbPToQQ9IRVom4G@hwthcjd52MieEfOKCBl8PaXwbWnW6ls47rn0PCTlPWh3NjnU2BtH89m7ZhSq8ljM/lcqd/S6a6u/bf8npY/fdybNdf791Jjb1ULuxsZycDQL92R8weOWXur5aEUjbfcxaMEXZdiq4LLpR/G@8ABAQCJj0JV@qCWcJCL4DNfxGyhM5cLEqjABL1MYsFYehV8JedwmI9TToDjRoXCP6vr@gc "brainfuck – TIO Nexus") Explanation is on its way I am still golfing this ]
[Question] [ In [long multiplication](http://mathworld.wolfram.com/LongMultiplication.html), after multiplying the numbers, you are left with the partial products, in this challenge you will output those partial products. Because long multiplication is long, to compensate your code will need to be as short as possible. ## Examples ``` 34, 53 102, 1700 48, 38 384, 1440 361, 674 1444, 25270, 216600 0, 0 0 1, 8 8 ``` ## Specifications * Input / Output may be in any reasonable format such as array, comma-separated string (or any other delimiter that's not a digit), list, function arguments, etc. * Partial products must be in increasing order. * If a partial product is `0`, you can choose whether you want to output it or not. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins! [Answer] # Pyth, 12 bytes ``` .e**Qsb^Tk_w ``` [Test suite](https://pyth.herokuapp.com/?code=.e%2a%2aQsb%5ETk_w&test_suite=1&test_suite_input=34%0A53%0A48%0A38%0A361%0A674%0A0%0A0%0A1%0A8&debug=0&input_size=2) Takes input newline separated, e.g. ``` 361 674 ``` **Explanation:** ``` .e**Qsb^Tk_w Implicit: Q = eval(input()),T = 10 w Input the second number as a string. _ Reverse it. .e Enumerated map, where b is the character and k is the index. sb Convert the character to an int. *Q Multiply by Q. * ^Tk Multiply by T ^ k. (10 ^ index) ``` [Answer] # Jelly, 10 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) ``` DU×µLR’⁵*× ``` [Try it online!](http://jelly.tryitonline.net/#code=RFXDl8K1TFLigJnigbUqw5c&input=&args=Njc0+MzYx) ### How it works ``` DU×µLR’⁵*× Left argument: multiplier -- Right argument: multiplicant D Convert the multiplier to base 10 (array of digits). U Reverse the array. × Multiply each digit by the multiplicant. µ Begin a new, monadic chain. Argument: A(array of products) L Get the length of A. R Turn length l into [1, ..., l]. ’ Decrement to yield [0, ..., l-1]. ⁵* Compute 10**i for each i in that range. × Hook; multiply the powers of ten by the corresponding elements of A. ``` [Answer] # JavaScript (ES7), 48 bytes ``` (a,b)=>[...b+""].reverse().map((d,i)=>10**i*a*d) ``` ### ES6 (56 bytes) ``` (a,b)=>[...b+""].reverse().map((d,i)=>a*d+"0".repeat(i)) ``` ## Explanation Returns an array of partial products as numbers. ``` (a,b)=> [...b+""] // convert the multiplier to an array of digits .reverse() // reverse the digits of the multiplier so the output is in the right order .map((d,i)=> // for each digit d of the multiplier 10**i // get the power of ten of the digit *a*d // raise the product of the digit to it ) ``` ## Test Test uses `Math.pow` instead of `**` to make it work in standard browsers. ``` var solution = (a,b)=>[...b+""].reverse().map((d,i)=>Math.pow(10,i)*a*d) ``` ``` A = <input type="text" id="A" value="361" /><br /> B = <input type="text" id="B" value="674" /><br /> <button onclick="result.textContent=solution(+A.value,+B.value)">Go</button> <pre id="result"></pre> ``` [Answer] # Lua, ~~72~~ 68 Bytes ``` b=arg[2]:reverse()for i=1,#b do print(arg[1]*b:sub(i,i)*10^(i-1))end ``` [Answer] # APL, 21 bytes ``` {⍺×x×10*1-⍨⍳≢x←⊖⍎¨⍕⍵} ``` This is a dyadic function that accepts integers on the left and right and returns an array. To call it, assign it to a variable. Explanation: ``` x←⊖⍎¨⍕⍵} ⍝ Define x to be the reversed digits of the right input 10*1-⍨⍳≢ ⍝ Generate all 10^(1-i) for i from 1 to the number of digits {⍺×x× ⍝ Multiply the right input by the digits and the powers of 10 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes Code: ``` VDgUSXFTNmY**=\ ``` Explanation: ``` VDgUSXFTNmY**=\ V # Assign the input to Y D # Duplicate of input, because the stack is empty g # Pushes the length of the last item U # Assign the length to X S # Split the last item X # Pushes X (length of the last item) F # Creates a for loop: for N in range(0, X) TNm # Pushes 10 ^ N Y # Pushes Y (first input) * # Multiplies the last two items * # Multiplies the last two items = # Output the last item \ # Discard the last item ``` [Answer] # Pyth, 26 bytes ``` DcGHKjHTFNJlK*G*@Kt-JN^TN ``` This defines a function `c` such that it accepts `2` arguments, and the function prints the partial products. ``` DcGHKjHTFNJlK*G*@Kt-JN^TN DCGH Define function c(G, H) KjHT Set K to the list of digits converting H to base 10 FNJlK Set J to the length of K and loop with variable N (Implicit: print) *G*@Kt-JN Calculates the partial product ^TN Raising it to the appropriate power of 10 ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 18 bytes ``` ij48-tn:1-P10w^**P ``` The [compiler (5.1.0)](https://github.com/lmendo/MATL/releases) works in Matlab and in Octave. Each number is input on a separate line. ### Example ``` >> matl ij48-tn:1-P10w^**P > 361 > 674 1444 25270 216600 ``` ### Explanation ``` i % input first number (say 361) j % input second number, interpreted as a string (say '674') 48- % subtract '0' to obtain vector of figures (gives [6 7 4]) tn:1-P % vector [n-1, ... 1, 0] where n is the number of figures (gives [2 1 0]) 10w^ % 10 raised to that, element-wise (gives [100 10 1]) * % multiply, element-wise (gives [600 70 4]) * % multiply (gives 361*[600 70 4], or [216600 25270 1444]) P % flip vector ([1444 25270 216600]). Implicitly display ``` [Answer] ## Haskell, ~~60~~ ~~57~~ 54 bytes ``` g x=zipWith(\b->(x*10^b*).read.pure)[0..].reverse.show ``` 5 bytes less (drop the `.show`) if I can take the second number as a string. Usage example: `g 361 674` -> `[1444,25270,216600]`. Multiply every digit of the reverse of `y` with `x` and scale with `10^i` where `i = 0,1,2,...`. Edit: Thanks to @Mauris for 3 bytes! [Answer] # Julia, ~~50~~ 49 bytes ``` f(a,b)=[a*d*10^~-i for(i,d)=enumerate(digits(b))] ``` This is a function that accepts two integers and returns an integer array. The `digits` function returns an array of the input integer's digits in reverse order. We get the index, value pairs using `enumerate` and compute the partial products as the first input times the digits times 10 raised to the power of the digit's index - 1. Saved a byte thanks to Dennis! [Answer] # Python 2, 61 ``` def p(a,b): j=0 while b>0: print`b%10*a`+j*'0';b/=10;j+=1 ``` [Answer] # CJam, ~~19~~ 17 bytes ``` q~W%eef{~~A@#**}p ``` Takes input with the first item being an integer and the second a string (e.g. `34 "53"`). Suggestions are welcome, as I'm sure it can be shorter. Thanks to Dennis for saving two bytes. [Try it online.](http://cjam.aditsu.net/#code=q~W%25eef%7B~~A%40%23**%7Dp&input=34%20%2253%22) ### Explanation ``` q~ e# Get input and evaluate it, x and "y" W% e# Reverse y so it will be properly sorted ee e# Enumerate through y with each character and its index f{ e# For each digit in y... ~~ e# Convert the digit to an integer on the stack A@# e# Take 10 to the power of y's index ** e# Multiply all three together to get the final result } p e# Print the array ``` [Answer] ## Haskell, 37 bytes ``` a%0=[] a%b=b`mod`10*a:(a*10)%div b 10 ``` No stringifying, just arithmetic. Recursively prepends the smallest partial product to the rest, where the last digit of `b` is truncated and a multiplier of 10 is applied. The operator precedence works nicely. [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input in reverse order with the first being a digit array and the second being an integer. If both inputs *must* be of the same type then we can take them both as strings and add `¬` to the beginning. ``` ÔË*V*ApE ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1MsqVipBcEU&input=WzUsM10KMzQ) ``` ¬ÔË*V*ApE :Implicit input of array U & integer V (or strings U & V) ¬ :(Split U, if inputs are strings) Ô :Reverse U Ë :Map each element at 0-based index E *V* : Multiply by V multiplied by A : 10 pE : Raised to the power of E (1eE would also work in place of ApE) ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 11 chars / 23 bytes (non-competitive) ``` ᴙíⓢⓜî*$*Ⅹⁿ_ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=%5B34%2C53%5D&code=%E1%B4%99%C3%AD%E2%93%A2%E2%93%9C%C3%AE*%24*%E2%85%A9%E2%81%BF_)` Found a bug while coding the solution to this problem... # Explanation ``` // Implicit: î = input 1, í = input 2 ᴙíⓢ // reverse í and split it into an array ⓜî*$*Ⅹⁿ_ // multiply î by each individual digit in í and put in previous array // implicit output ``` [Answer] ## [Japt](http://ethproductions.github.io/japt/), 28 bytes ``` I=[]Vs w m@IpApY+1 /A*U*X};I ``` Explanation: ``` I=[]Vs w m@IpApY+1 /A*U*X};I I=[] //that's simple, init an array I Vs //take the second input and convert to string w //reverse it and... m@ } //...map through the chars; X is a char, Y is counter Ip............ //push the following value into I... ApY+1 /A*U*X //10^(Y+1)/10*U*X, U is the first input I //output the resulting array ``` [Answer] ## Python 2, 42 bytes ``` f=lambda a,b:b*[0]and[b%10*a]+f(a*10,b/10) ``` No stringifying, just arithmetic. Recursively appends the smallest partial product to the rest, where the last digit of `b` is truncated and a multiplier of 10 is applied. [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` z*:1İ⁰↔M*d ``` [Try it online!](https://tio.run/##yygtzv7/v0rLyvDIhkeNGx61TfHVSvn//7/hfwsA "Husk – Try It Online") ]
[Question] [ # Electron Configurations Your mission is to accept an element's atomic number as input, and output its [electron configuration](https://en.wikipedia.org/w/index.php?title=Electron_shell&oldid=616749633#List_of_elements_with_electrons_per_shell) (e.g. `2,8,8,2` for calcium). ## Input An atomic number from 1 to 118. You may assume valid input. The atom is not charged (it has as many electrons as protons). You may not expect the input to be stored in a variable, and you must write a complete program. ## Output The number of electrons in each non-empty electron shell. I will be quite lenient with the output format; all of the following are acceptable, i.e. you may use any punctuation or whitespace to separate the numbers, and brackets of any sort are permitted. Please specify which is used. * `2,8,8,2` * `2.8.8.2` * `2, 8, 8, 2,` * `[2,8,8,2]` * `2 8 8 2` * `([2 [8]] [8] 2)` ## How Electrons Work In atoms, electrons are ordered into "shells", which are energy levels. Each shell has a certain capacity, the maximum number of electrons that it is capable of holding. The shells are filled from the inside out, but not evenly. Your task is to determine, given an atomic number, how many electrons there are in each shell, according to [this source](https://en.wikipedia.org/w/index.php?title=Electron_shell&oldid=616749633#List_of_elements_with_electrons_per_shell). Up to and including calcium (atomic number 20), the shells fill evenly and in order; the inner shell is first filled to its capacity of 2, the second to 8, then the third to 8 and the last to 2. The electron configuration of calcium is `2,8,8,2`. After calcium, things get complicated; further electrons go into the third shell, not the last one. To make things worse, vanadium (23) is `2,8,11,2`, while chromium (24) is `2,8,13,1` and manganese (25) is `2,8,13,2`. There are some consistent patterns, however: a noble gas and the seven elements before it will always have the number of electrons in the outer shell increase from 1 to 8. For example: * gold (79): `2,8,18,32,18,1` * mercury (80): `2,8,18,32,18,2` * ... * astatine (85): `2,8,18,32,18,7` * radon (86): `2,8,18,32,18,8` ## Rules * [Standard loopholes](http://tinyurl.com/ppcgloopholes) are forbidden. * Libraries which existed prior to this challenge are permitted. * Any built-in or library features which specifically deal with atoms, molecules or chemistry are banned. * Lowest code length in bytes wins. * In the linked source, configurations of elements 103-118 are marked with *(?)*, as they are predicted, and the elements are too unstable for this to be checked. For this challenge, assume them to be correct. * You may hardcode part or all of your data. * **[NEW RULE]** Please provide a base64 or an xxd dump of your files if you use control characters in them (as many answers seem to be doing) **WINNER: [Dennis's CJam answer at 80 bytes](https://codegolf.stackexchange.com/a/37738/16402)!** [Answer] # CJam, ~~87~~ ~~83~~ ~~82~~ 80 bytes ``` 0"hTHøìð¼Ä¿håêÛ¾ªÔ¼"256b6b5a/4a8**li<{[33:B_B*65_B*1]=\_B%8=B\#*+}/Bb0-` ``` The above code contains unprintable characters. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=0%22hTH%0C%C3%B8%C3%AC%C3%B0%12%C2%BC%C3%84%18%C2%BFh%C3%A5%C3%AA%C3%9B%C2%BE%C2%AA%C3%94%07%C2%86%19%C2%86%C2%BC%11%22256b6b5a%2F4a8**li%3C%7B%5B33%3AB_B*65_B*1%5D%3D%5C_B%258%3DB%5C%23*%2B%7D%2FBb0-%60&input=42). If the link doesn't work for you, copy from this [paste](http://pastebin.com/6a2VuQzk). ### Background To obtain the electron configuration of the *Nth* atom, we start with an atom without electrons and apply *N* transformations to it. To reduce the byte count of the implementation, we represent the electron configuration of an atom as an integer. Each digit of that integer in base 33 corresponds to the number of electrons in a certain shells; the least significant digit represents the outer shell. For example, the electron configuration of Molybdenum (42) is **[2 8 18 13 1]**. This corresponds to the integer **2 × 334 + 8 × 333 + 18 × 332 + 13 × 33 + 1 = 26,79,370**. Palladium (48) is a special case, which we treat as **[2 8 18 18 0]** instead of **[2 8 18 18]**. This convenient representation reduces the aforementioned transformations to simple arithmetic: * `R += 1` (add an electron to the outer shell) * `R += 33` (add an electron to the second outer shell) * `R += 65` (add two electrons to the second outer shell; remove one from the first) * `R += 1089` (add an electron to the third outer shell) * `R += 2145` (add two electrons to the third outer shell; remove one from the second) * `R *= 33, R += 1` (add a new shell containing a single electron) All that's left is to somehow encode which transformation has to be applied to pass from a particular atom to the next. The differences of the integer representations of two consecutive atoms are as follows: ``` [1 1 65 1 1 1 1 1 1 1 2369 1 1 1 1 1 1 1 78401 1 33 33 33 65 1 33 33 33 65 1 1 1 1 1 1 1 2598017 1 33 33 65 33 1 65 33 65 1 1 1 1 1 1 1 1 85745345 1 33 1089 2145 1089 1089 1089 1089 33 2145 1089 1089 1089 1089 1089 33 33 33 33 33 33 33 65 33 1 1 1 1 1 1 1 2830095041 1 33 33 2145 1089 1089 2145 1089 33 2145 1089 1089 1089 1089 1089 65 1 33 33 33 33 33 33 65 1 1 1 1 1 1 1] ``` The unique differences in this array are the following: ``` [1 33 65 1089 2145 2369 78401 2598017 85745345 2830095041] ``` All but the first 5 correspond to instances when a new shell is added; these can be omitted since multiplying by 33 and adding 1 yields the same result as adding the difference. Since we have to add a new shell if and only if the current atom has exactly eight electrons in its outer shell (with the exception of **He (2) ↦ Li (3)**, which can be encoded as *add 65*), we can encode those transformations as *add 1* and determine the need for multiplication on the fly. Thus, if we define ``` X := 0 I := 0 L := [33 1089 65 2145 1] T := [1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 3 1 0 0 0 3 1 1 1 1 1 1 1 1 1 0 0 3 0 1 3 0 3 1 1 1 1 1 1 1 1 1 1 0 2 4 2 2 2 2 0 4 2 2 2 2 2 0 0 0 0 0 0 0 3 0 1 1 1 1 1 1 1 1 1 0 0 4 2 2 4 2 0 4 2 2 2 2 2 3 1 0 0 0 0 0 0 3 1 1 1 1 1 1 1] ``` the electron configuration of the *Nth* atom can be computed as follows: ``` while(X < N): R *= (33 ** (R % 33 == 8)) R += L[T[X]] X += 1 ``` ### How it works ``` " Push 0, the initial value of R; convert the following array into an integer by considering it a base 256 number, then back to the array of its digits in base 6. "; 0"hTHøìð¼Ä¿håêÛ¾ªÔ¼"256b6b " Replace each 5 in the resulting array by [4 4 4 4 4 4 4 4]. This yields the array T from the above section. "; 5a/4a8** " Read an integer N from STDIN and discard all but the first N elements of T. "; li< " For each element Y of the remainder of T, do the following: "; { [33:B_B*65_B*1]=\ " Define B := 33, push L, retrieve L[Y] and swap it with R. "; _B%8=B\#* " Execute R *= 33 ** (R % 33 == 8). "; + " Execute R += L[Y]. "; }/ " Convert R into the array of its digits in base 33, remove eventual zeros (Palladium) and replace the resulting array with its string representation. "; Bb0-` ``` ### Example run ``` $ base64 -d > electrons.cjam <<< MCJoVEgM+OzwErzEGL9o5erbvqrUB4YZhrwRIjI1NmI2YjVhLzRhOCoqbGk8e1szMzpCX0IqNjVfQioxXT1cX0IlOD1CXCMqK30vQmIwLWA= $ cksum electrons.cjam 3709391992 80 electrons.cjam $ for i in {1..118}; do LANG=en_US cjam electrons.cjam <<< $i; echo; done [1] [2] [2 1] [2 2] [2 3] [2 4] [2 5] [2 6] [2 7] [2 8] [2 8 1] [2 8 2] [2 8 3] [2 8 4] [2 8 5] [2 8 6] [2 8 7] [2 8 8] [2 8 8 1] [2 8 8 2] [2 8 9 2] [2 8 10 2] [2 8 11 2] [2 8 13 1] [2 8 13 2] [2 8 14 2] [2 8 15 2] [2 8 16 2] [2 8 18 1] [2 8 18 2] [2 8 18 3] [2 8 18 4] [2 8 18 5] [2 8 18 6] [2 8 18 7] [2 8 18 8] [2 8 18 8 1] [2 8 18 8 2] [2 8 18 9 2] [2 8 18 10 2] [2 8 18 12 1] [2 8 18 13 1] [2 8 18 13 2] [2 8 18 15 1] [2 8 18 16 1] [2 8 18 18] [2 8 18 18 1] [2 8 18 18 2] [2 8 18 18 3] [2 8 18 18 4] [2 8 18 18 5] [2 8 18 18 6] [2 8 18 18 7] [2 8 18 18 8] [2 8 18 18 8 1] [2 8 18 18 8 2] [2 8 18 18 9 2] [2 8 18 19 9 2] [2 8 18 21 8 2] [2 8 18 22 8 2] [2 8 18 23 8 2] [2 8 18 24 8 2] [2 8 18 25 8 2] [2 8 18 25 9 2] [2 8 18 27 8 2] [2 8 18 28 8 2] [2 8 18 29 8 2] [2 8 18 30 8 2] [2 8 18 31 8 2] [2 8 18 32 8 2] [2 8 18 32 9 2] [2 8 18 32 10 2] [2 8 18 32 11 2] [2 8 18 32 12 2] [2 8 18 32 13 2] [2 8 18 32 14 2] [2 8 18 32 15 2] [2 8 18 32 17 1] [2 8 18 32 18 1] [2 8 18 32 18 2] [2 8 18 32 18 3] [2 8 18 32 18 4] [2 8 18 32 18 5] [2 8 18 32 18 6] [2 8 18 32 18 7] [2 8 18 32 18 8] [2 8 18 32 18 8 1] [2 8 18 32 18 8 2] [2 8 18 32 18 9 2] [2 8 18 32 18 10 2] [2 8 18 32 20 9 2] [2 8 18 32 21 9 2] [2 8 18 32 22 9 2] [2 8 18 32 24 8 2] [2 8 18 32 25 8 2] [2 8 18 32 25 9 2] [2 8 18 32 27 8 2] [2 8 18 32 28 8 2] [2 8 18 32 29 8 2] [2 8 18 32 30 8 2] [2 8 18 32 31 8 2] [2 8 18 32 32 8 2] [2 8 18 32 32 10 1] [2 8 18 32 32 10 2] [2 8 18 32 32 11 2] [2 8 18 32 32 12 2] [2 8 18 32 32 13 2] [2 8 18 32 32 14 2] [2 8 18 32 32 15 2] [2 8 18 32 32 16 2] [2 8 18 32 32 18 1] [2 8 18 32 32 18 2] [2 8 18 32 32 18 3] [2 8 18 32 32 18 4] [2 8 18 32 32 18 5] [2 8 18 32 32 18 6] [2 8 18 32 32 18 7] [2 8 18 32 32 18 8] ``` [Answer] ## GolfScript (96 bytes) Output is in the form ``` [2 8 18 18] ``` This uses a magic string which contains non-printable characters, so I'm giving the script in xxd format: ``` 0000000: 7e30 5c27 0193 ca05 528e 6b25 e461 4d12 ~0\'....R.k%.aM. 0000010: 3195 9abf c9a4 bfad 588b d876 5e72 c82a 1.......X..v^r.* 0000020: 2dd3 6e92 4940 e00b 80dc 71f6 fc97 2732 [[email protected]](/cdn-cgi/l/email-protection)...'2 0000030: 3536 6261 7365 2037 6261 7365 3c7b 2731 56base 7base<{'1 0000040: 0a29 0a5c 295c 0a2b 310a 2b29 0a40 2940 .).\)\.+1.+).@)@ 0000050: 400a 402b 5c28 3227 6e2f 3d7e 7d2f 5d60 @.@+\(2'n/=~}/]` ``` For [online testing](http://golfscript.apphb.com/?c=Oyc0NicKCn4wXCJceDAxXHg5M1x4Q0FceDA1Ulx4OEVrJVx4RTRhTVx4MTIxXHg5NVx4OUFceEJGXHhDOVx4QTRceEJGXHhBRFhceDhCXHhEOHZeclx4QzgqLVx4RDNuXHg5MklAXHhFMFx2XHg4MFx4RENxXHhGNlx4RkNceDk3IjI1NmJhc2UgN2Jhc2U8eycxCikKXClcCisxCispCkApQEAKQCtcKDInbi89fn0vXWA%3D) I'm writing the magic string with escapes: ``` "\x01\x93\xCA\x05R\x8Ek%\xE4aM\x121\x95\x9A\xBF\xC9\xA4\xBF\xADX\x8B\xD8v^r\xC8*-\xD3n\x92I@\xE0\v\x80\xDCq\xF6\xFC\x97" ``` but it's equivalent when you're not running into problems of pasting characters into browser textareas. The approach is to build a virtual machine with 7 instructions, each of which manipulates a list of electron counts. Then for element `n` we start with an electron count list of `0` and run the first `n` instructions from the list encoded by the magic string. The instructions are: 1. Add a new shell with 1 electron: `1` 2. Add an electron to the outer shell: `)` 3. Add an electron to the next-to-outer shell: `\)\` 4. Combine the two outer shells and add one electron: `+)`. (This is used only for palladium). 5. Combine the two outer shells and create a new shell with 1 electron: `+1` 6. Add an electron to the third shell in: `@)@@` 7. Add an electron to the third shell and move one from the second shell to the third shell. This only occurs when the outer shell has 2 electrons, so it's implemented as `@+\(2` rather than the longer `@2+@(@` [Answer] # Python 2 (46+271=327) Code: ``` print open('f').read().decode('zip').split(';')[input()] ``` File `f`, containing the following binary garbage (these are the char codes) ``` 120, 156, 101, 146, 219, 21, 195, 32, 12, 67, 87, 233, 8, 193, 188, 204, 201, 254, 123, 21, 40, 46, 146, 253, 65, 163, 171, 10, 98, 199, 188, 233, 149, 87, 62, 243, 247, 179, 158, 121, 174, 50, 87, 157, 171, 205, 213, 231, 210, 181, 118, 66, 119, 70, 119, 74, 119, 78, 119, 82, 119, 86, 127, 233, 147, 183, 29, 182, 103, 156, 103, 122, 76, 36, 19, 249, 68, 167, 56, 78, 49, 81, 77, 52, 19, 118, 110, 210, 235, 100, 19, 197, 68, 53, 209, 76, 116, 19, 250, 23, 247, 36, 56, 107, 192, 139, 30, 208, 114, 211, 183, 96, 172, 121, 87, 123, 253, 6, 90, 175, 66, 23, 118, 66, 15, 216, 6, 118, 130, 205, 96, 63, 216, 18, 119, 197, 141, 185, 222, 6, 146, 36, 76, 138, 16, 101, 162, 66, 84, 29, 225, 153, 157, 254, 163, 90, 100, 32, 229, 135, 136, 106, 201, 226, 104, 16, 225, 136, 22, 38, 70, 97, 204, 140, 133, 177, 50, 246, 251, 33, 23, 170, 71, 97, 204, 140, 133, 177, 50, 54, 198, 206, 168, 14, 253, 155, 195, 187, 135, 55, 220, 103, 145, 199, 69, 230, 188, 157, 225, 63, 44, 207, 121, 25, 53, 26, 110, 75, 247, 9, 95, 170, 27, 187, 248, 201, 75, 28, 126, 152, 255, 111, 232, 41, 56, 62, 147, 130, 35, 193, 201, 193, 41, 193, 169, 193, 105, 193, 209, 80, 79, 172, 153, 111, 72, 188, 36, 241, 158, 196, 171, 18, 111, 203, 185, 16, 95, 151, 67, 8, 97 ``` Base64: ``` eJxlktsVwyAMQ1fpCMG8zMn+exUoLpL9QaOrCmLHvOmVVz7z97Oeea4yV52rzdXn0rV2QndGd0p3 TndSd1Z/6ZO3HbZnnGd6TCQT+USnOE4xUU00E3Zu0utkE8VENdFMdBP6F/ckOGvAix7QctO3YKx5 V3v9BlqvQhd2Qg/YBnaCzWA/2BJ3xY253gaSJEyKEGWiQlQd4Zmd/qNaZCDlh4hqyeJoEOGIFiZG YcyMhbEy9vshF6pHYcyMhbEyNsbOqA79m8O7hzfcZ5HHRea8neE/LM95GTUabkv3CV+qG7v4yUsc fpj/b+gpOD6TgiPBycEpwanBacHRUE+smW9IvCTxnsSrEm/LuRBfl0MIYQ== ``` On request, this is now a full program rather than a function. Old answer: Python (Naive baseline, 422): ``` f=lambda n:'eJxlktsVwyAMQ1fpCMG8zMn+exUoLpL9QaOrCmLHvOmVVz7z97Oeea4yV52rzdXn0rV2QndGd0p3TndSd1Z/6ZO3HbZnnGd6TCQT+USnOE4xUU00E3Zu0utkE8VENdFMdBP6F/ckOGvAix7QctO3YKx5V3v9BlqvQhd2Qg/YBnaCzWA/2BJ3xY253gaSJEyKEGWiQlQd4Zmd/qNaZCDlh4hqyeJoEOGIFiZGYcyMhbEy9vshF6pHYcyMhbEyNsbOqA79m8O7hzfcZ5HHRea8neE/LM95GTUabkv3CV+qG7v4yUscfpj/b+gpOD6TgiPBycEpwanBacHRUE+smW9IvCTxnsSrEm/LuRBfl0MIYQ=='.decode('base64').decode('zip').split(';')[n] ``` Contents of the zip: ``` >>>'eJxlktsVwyAMQ1fpCMG8zMn+exUoLpL9QaOrCmLHvOmVVz7z97Oeea4yV52rzdXn0rV2QndGd0p3TndSd1Z/6ZO3HbZnnGd6TCQT+USnOE4xUU00E3Zu0utkE8VENdFMdBP6F/ckOGvAix7QctO3YKx5V3v9BlqvQhd2Qg/YBnaCzWA/2BJ3xY253gaSJEyKEGWiQlQd4Zmd/qNaZCDlh4hqyeJoEOGIFiZGYcyMhbEy9vshF6pHYcyMhbEyNsbOqA79m8O7hzfcZ5HHRea8neE/LM95GTUabkv3CV+qG7v4yUscfpj/b+gpOD6TgiPBycEpwanBacHRUE+smW9IvCTxnsSrEm/LuRBfl0MIYQ=='.decode('base64').decode('zip') ';1;2;2 1;2 2;2 3;2 4;2 5;2 6;2 7;2 8;2 8 1;2 8 2;2 8 3;2 8 4;2 8 5;2 8 6;2 8 7;2 8 8;2 8 8 1;2 8 8 2;2 8 9 2;2 8 10 2;2 8 11 2;2 8 13 1;2 8 13 2;2 8 14 2;2 8 15 2;2 8 16 2;2 8 18 1;2 8 18 2;2 8 18 3;2 8 18 4;2 8 18 5;2 8 18 6;2 8 18 7;2 8 18 8;2 8 18 8 1;2 8 18 8 2;2 8 18 9 2;2 8 18 10 2;2 8 18 12 1;2 8 18 13 1;2 8 18 13 2;2 8 18 15 1;2 8 18 16 1;2 8 18 18;2 8 18 18 1;2 8 18 18 2;2 8 18 18 3;2 8 18 18 4;2 8 18 18 5;2 8 18 18 6;2 8 18 18 7;2 8 18 18 8;2 8 18 18 8 1;2 8 18 18 8 2;2 8 18 18 9 2;2 8 18 19 9 2;2 8 18 21 8 2;2 8 18 22 8 2;2 8 18 23 8 2;2 8 18 24 8 2;2 8 18 25 8 2;2 8 18 25 9 2;2 8 18 27 8 2;2 8 18 28 8 2;2 8 18 29 8 2;2 8 18 30 8 2;2 8 18 31 8 2;2 8 18 32 8 2;2 8 18 32 9 2;2 8 18 32 10 2;2 8 18 32 11 2;2 8 18 32 12 2;2 8 18 32 13 2;2 8 18 32 14 2;2 8 18 32 15 2;2 8 18 32 17 1;2 8 18 32 18 1;2 8 18 32 18 2;2 8 18 32 18 3;2 8 18 32 18 4;2 8 18 32 18 5;2 8 18 32 18 6;2 8 18 32 18 7;2 8 18 32 18 8;2 8 18 32 18 8 1;2 8 18 32 18 8 2;2 8 18 32 18 9 2;2 8 18 32 18 10 2;2 8 18 32 20 9 2;2 8 18 32 21 9 2;2 8 18 32 22 9 2;2 8 18 32 24 8 2;2 8 18 32 25 8 2;2 8 18 32 25 9 2;2 8 18 32 27 8 2;2 8 18 32 28 8 2;2 8 18 32 29 8 2;2 8 18 32 30 8 2;2 8 18 32 31 8 2;2 8 18 32 32 8 2;2 8 18 32 32 10 1;2 8 18 32 32 10 2;2 8 18 32 32 11 2;2 8 18 32 32 12 2;2 8 18 32 32 13 2;2 8 18 32 32 14 2;2 8 18 32 32 15 2;2 8 18 32 32 16 2;2 8 18 32 32 18 1;2 8 18 32 32 18 2;2 8 18 32 32 18 3;2 8 18 32 32 18 4;2 8 18 32 32 18 5;2 8 18 32 32 18 6;2 8 18 32 32 18 7;2 8 18 32 32 18 8' >>>len(_) 1478 ``` And a quick test: ``` map(f, range(119)) Out[48]: ['', '1', '2', '2 1', '2 2', '2 3', '2 4', '2 5', '2 6', '2 7', '2 8', '2 8 1', '2 8 2', '2 8 3', '2 8 4', '2 8 5', '2 8 6', '2 8 7', '2 8 8', '2 8 8 1', '2 8 8 2', '2 8 9 2', '2 8 10 2', '2 8 11 2', '2 8 13 1', '2 8 13 2', '2 8 14 2', '2 8 15 2', '2 8 16 2', '2 8 18 1', '2 8 18 2', '2 8 18 3', '2 8 18 4', '2 8 18 5', '2 8 18 6', '2 8 18 7', '2 8 18 8', '2 8 18 8 1', '2 8 18 8 2', '2 8 18 9 2', '2 8 18 10 2', '2 8 18 12 1', '2 8 18 13 1', '2 8 18 13 2', '2 8 18 15 1', '2 8 18 16 1', '2 8 18 18', '2 8 18 18 1', '2 8 18 18 2', '2 8 18 18 3', '2 8 18 18 4', '2 8 18 18 5', '2 8 18 18 6', '2 8 18 18 7', '2 8 18 18 8', '2 8 18 18 8 1', '2 8 18 18 8 2', '2 8 18 18 9 2', '2 8 18 19 9 2', '2 8 18 21 8 2', '2 8 18 22 8 2', '2 8 18 23 8 2', '2 8 18 24 8 2', '2 8 18 25 8 2', '2 8 18 25 9 2', '2 8 18 27 8 2', '2 8 18 28 8 2', '2 8 18 29 8 2', '2 8 18 30 8 2', '2 8 18 31 8 2', '2 8 18 32 8 2', '2 8 18 32 9 2', '2 8 18 32 10 2', '2 8 18 32 11 2', '2 8 18 32 12 2', '2 8 18 32 13 2', '2 8 18 32 14 2', '2 8 18 32 15 2', '2 8 18 32 17 1', '2 8 18 32 18 1', '2 8 18 32 18 2', '2 8 18 32 18 3', '2 8 18 32 18 4', '2 8 18 32 18 5', '2 8 18 32 18 6', '2 8 18 32 18 7', '2 8 18 32 18 8', '2 8 18 32 18 8 1', '2 8 18 32 18 8 2', '2 8 18 32 18 9 2', '2 8 18 32 18 10 2', '2 8 18 32 20 9 2', '2 8 18 32 21 9 2', '2 8 18 32 22 9 2', '2 8 18 32 24 8 2', '2 8 18 32 25 8 2', '2 8 18 32 25 9 2', '2 8 18 32 27 8 2', '2 8 18 32 28 8 2', '2 8 18 32 29 8 2', '2 8 18 32 30 8 2', '2 8 18 32 31 8 2', '2 8 18 32 32 8 2', '2 8 18 32 32 10 1', '2 8 18 32 32 10 2', '2 8 18 32 32 11 2', '2 8 18 32 32 12 2', '2 8 18 32 32 13 2', '2 8 18 32 32 14 2', '2 8 18 32 32 15 2', '2 8 18 32 32 16 2', '2 8 18 32 32 18 1', '2 8 18 32 32 18 2', '2 8 18 32 32 18 3', '2 8 18 32 32 18 4', '2 8 18 32 32 18 5', '2 8 18 32 32 18 6', '2 8 18 32 32 18 7', '2 8 18 32 32 18 8'] ``` [Answer] # MATLAB - ~~248~~ ~~244~~ ~~241~~ 178 + 44 = 222 bytes Minified: ``` i=1;a=fread(fopen('a'));b=fix(a/7);a=a-7*b+1;d=0*a;for n=1:input(''),A=a(i);if b(i),m=1;i=i+(d(A)+2>b(i));else A=A-[1;0];m=[2;-1];i=i+1;end;d(A)=d(A)+m;end;fprintf('%d ',d(~~d)); ``` Expanded: ``` i = 1; a = fread( fopen( 'a' ) ); b = fix( a/7 ); a = a-7*b+1; d = 0*a; for n = 1:input('') A = a(i); if b(i) m = 1; i = i + (d(A)+2 > b(i)); else A = A - [1; 0]; m = [2; -1]; i = i + 1; end d(A) = d(A) + m; end fprintf( '%d ', d(~~d) ); ``` Binary File Dependency (Filename '*a*'): ``` 0e 39 3a 11 4f 03 72 03 3b 12 49 04 5e 12 04 73 04 3c 13 43 88 04 b2 43 04 e3 6d 05 82 3d 14 4b 05 9e 05 b3 44 05 e4 06 14 75 06 3e ``` I trust this is a "complete program" in that it can be invoked from the commandline, it reads from `stdin` and outputs to `stdout`. It uses a kind of two-instruction bytecode to build the electron configurations. The two instructions are ``` inc D until N (i.e. increment valence D by 1; advance to next instruction when D = N) ``` and ``` pulldown D (i.e. pull down one electron from valence D, thereby decrementing it by 1 and incrementing valence D-1 by 2) ``` The instructions are encoded in two arrays. The first stores the `D` argument in all cases. The second stores the `N` argument or `0` to indicate a `pulldown` instruction, since `N = 0` is never used as an argument. The complete sequence of instructions is: ``` inc 1 until 2 inc 2 until 8 inc 3 until 8 inc 4 until 2 inc 3 until 11 pulldown 4 inc 3 until 16 pulldown 4 inc 4 until 8 inc 5 until 2 inc 4 until 10 pulldown 5 inc 4 until 13 inc 5 until 2 pulldown 5 inc 4 until 16 pulldown 5 inc 5 until 8 inc 6 until 2 inc 5 until 9 inc 4 until 19 pulldown 5 inc 4 until 25 inc 5 until 9 pulldown 5 inc 4 until 32 inc 5 until 15 pulldown 6 inc 5 until 18 inc 6 until 8 inc 7 until 2 inc 6 until 10 pulldown 6 inc 5 until 22 pulldown 6 inc 5 until 25 inc 6 until 9 pulldown 6 inc 5 until 32 pulldown 7 inc 7 until 2 inc 6 until 16 pulldown 7 inc 7 until 8 ``` ~~It's worth noting that 28 characters can be dropped if we use the MATLAB-specific character set, but I wanted my solution to be representable as plaintext on Stack Exchange, without any external file references.~~ External file references it is. ### Sample Outputs `39`: `2 8 18 9 2` `78`: `2 8 18 32 17 1` `117`: `2 8 18 32 32 18 7` `5`: `2 3` [Answer] # Perl 5, 235 (234 + 1 for -E) Golfed: ``` @a=unpack'C*','ABR3S4sT5tU6';if(($-=<>)~~[unpack'C*',')*,-./9:@NOYZ[\]`g']){$.+=($-~~[46,90]);$p=2+$-/33;$->87|$-~~[57..64]&&($.*=-1);$o[$p]+=$.,$o[$p+1]-=$.}$%=($%=$a[$q]/8)>$-?$-:$%,$o[$a[$q++]&7]+=$%while($--=$%);$,=$";say@o ``` Note: a hex dump is provided at the bottom of this post, as some of the string literals contain control characters (which were entered through a hex editor). Ungolfed with comments: ``` $_=<>; # For each byte, the first 5 bits are the number of spaces to fill at a time, the next 3 bits represent the shell number, minus 1. # Values: 10 41 42 13 52 33 14 53 34 15 73 54 35 16 74 55 36 # The 1st shell takes 2 electrons # Then the 2nd shell take 8, then the third takes 8... @a=unpack'C*','ABR3S4sT5tU6'; # Contains the atomic numbers of abnormal elements # Values: 18 1d 29 2a 2c 2d 2e 2f 39 3a 40 4e 4f 59 5a 5b 5c 5d 60 67 @b=unpack'C*',')*,-./9:@NOYZ[\]`g'; # if abnormal if($_~~@b){ # All abnormals, except element 46 and 90, only displace 1 electron $y=1+($_~~[46,90]); # Abnormals with atomic number less than 33 involve switches between shells 3 and 4 # 33-65: 4 and 5 # 66-98: 5 and 6 # 99+ : 6 and 7 $p = (3 + ~~($_/33)) - 1; # abnormals in these ranges move electrons from lower to higher # abnormals elsewhere do higher to lower if($_ >= 88 || $_ ~~ [57..64]){ $y *= -1; } # move electrons $o[$p] += $y; $o[$p+1] -= $y; } # extract max number of electrons to fill shell with # >> 3 is equivalent to /8 for integers; $% is always an integer. $% = $a[$q] / 8, # do not overfill $% = $% > $_ ? $_ : $%, # add electrons to shell $o[ $a[$q++] & 7 ] += $% # reduce number of electrons left to fill shells with while($_ -= $%); # set list separator to space $, = $"; # print list representing shells say @o ``` Hex Dump: ``` 0000000: 4061 3d75 6e70 6163 6b27 432a 272c 2710 @a=unpack'C*','. 0000010: 4142 1352 3314 5334 1573 5435 1674 5536 AB.R3.S4.sT5.tU6 0000020: 273b 6966 2828 242d 3d3c 3e29 7e7e 5b75 ';if(($-=<>)~~[u 0000030: 6e70 6163 6b27 432a 272c 2718 1d29 2a2c npack'C*','..)*, 0000040: 2d2e 2f39 3a40 4e4f 595a 5b5c 5d60 6727 -./9:@NOYZ[\]`g' 0000050: 5d29 7b24 2e2b 3d28 242d 7e7e 5b34 362c ]){$.+=($-~~[46, 0000060: 3930 5d29 3b24 703d 322b 242d 2f33 333b 90]);$p=2+$-/33; 0000070: 242d 3e38 377c 242d 7e7e 5b35 372e 2e36 $->87|$-~~[57..6 0000080: 345d 2626 2824 2e2a 3d2d 3129 3b24 6f5b 4]&&($.*=-1);$o[ 0000090: 2470 5d2b 3d24 2e2c 246f 5b24 702b 315d $p]+=$.,$o[$p+1] 00000a0: 2d3d 242e 7d24 253d 2824 253d 2461 5b24 -=$.}$%=($%=$a[$ 00000b0: 715d 2f38 293e 242d 3f24 2d3a 2425 2c24 q]/8)>$-?$-:$%,$ 00000c0: 6f5b 2461 5b24 712b 2b5d 2637 5d2b 3d24 o[$a[$q++]&7]+=$ 00000d0: 2577 6869 6c65 2824 2d2d 3d24 2529 3b24 %while($--=$%);$ 00000e0: 2c3d 2422 3b73 6179 406f ,=$";say@o ``` [Answer] # CJam, ~~309~~ 289 bytes ``` 0000000: 22 cc b5 a3 1a f7 bd 07 1b 26 ce 73 16 55 87 08 "........&.s.U.. 0000010: 27 d2 65 54 66 ac c1 38 ff de 95 d8 8a 77 6d 4e '.eTf..8.....wmN 0000020: 0d 13 df bb b7 c6 8c ae 6b 32 4d b9 f1 7c b9 f1 ........k2M..|.. 0000030: bc 68 2d 8a 5c 22 e6 5c 22 e1 d7 c9 80 ba a5 5d .h-.\".\"......] 0000040: 64 24 47 0b aa 78 c9 13 a5 0a 65 41 08 f3 ee e3 d$G..x....eA.... 0000050: 2e 58 92 19 5f 1a 80 fc d9 30 3b 51 99 c7 1b 51 .X.._....0;Q...Q 0000060: ba 0c 8a 3c 7d f0 60 1e d5 1c e7 2f 33 16 c8 1f ...<}.`..../3... 0000070: e6 df 24 75 d1 51 e6 af 38 b4 f7 b1 63 77 14 8d ..$u.Q..8...cw.. 0000080: d3 69 bc 99 9e a5 98 56 53 e7 71 f7 48 76 7a 24 .i.....VS.q.Hvz$ 0000090: a7 dc 5c 22 fc a6 55 05 30 e2 03 d6 a8 ef 1a 9f ..\"..U.0....... 00000a0: e4 03 c6 a0 5e 60 be 01 2b ca 12 83 d4 64 69 3d ....^`..+....di= 00000b0: a7 2e cc 59 5e 0c bb 69 b0 19 1d e1 f2 53 e4 1b ...Y^..i.....S.. 00000c0: 6e 6d cc 45 d3 1f cc 3c b7 1b 5f ca c8 d0 94 fe nm.E...<.._..... 00000d0: 05 ea ae dc 98 9e 9a 47 a6 fa 3a 0e c3 45 ef 31 .......G..:..E.1 00000e0: 61 a0 7c 80 55 9a 5d 7a af 8e 51 e8 5c 79 c4 22 a.|.U.]z..Q.\y." 00000f0: 32 35 36 62 33 38 62 22 24 12 23 20 5c 22 12 21 256b38b"$.# \".! 0000100: 08 00 02 22 3a 69 32 2f 7b 5f 30 3d 5f 29 33 33 ...":i2/{_0=_)33 0000110: 3f 61 40 5c 2f 5c 2a 7d 2f 30 61 2f 6c 69 28 3d ?a@\/\*}/0a/li(= 0000120: 60 < ``` Works by replacing common runs (e.g., `2 8 18 32`) with integers greater than 32 and considering the array of all configurations a base 38 number, which is encoded in binary. ### Example run ``` $ base64 -d > electrons.cjam <<< Isy1oxr3vQcbJs5zFlWHCCfSZVRmrME4/96V2Ip3bU4NE9+7t8aMrmsyTbnxfLnxvGgtilwi5lwi4dfJgLqlXWQkRwuqeMkTpQplQQjz7uMuWJIZXxqA/NkwO1GZxxtRugyKPH3wYB7VHOcvMxbIH+bfJHXRUeavOLT3sWN3FI3TabyZnqWYVlPncfdIdnokp9xcIvymVQUw4gPWqO8an+QDxqBeYL4BK8oSg9RkaT2nLsxZXgy7abAZHeHyU+Qbbm3MRdMfzDy3G1/KyNCU/gXqrtyYnppHpvo6DsNF7zFhoHyAVZpdeq+OUehcecQiMjU2YjM4YiIkEiMgXCISIQgAAiI6aTIve18wPV8pMzM/YUBcL1wqfS8wYS9saSg9YA== $ cksum electrons.cjam 3109698089 289 electrons.cjam $ LANG=en_US cjam electrons.cjam <<< 42; echo [2 8 18 13 1] $ for i in {1..118}; do LANG=en_US cjam electrons.cjam <<< $i; echo; done | md5sum d09cb34c282ee52c2466a6b80aa30d22 - ``` ]
[Question] [ There is a 1x1x1 cube placed on a infinite grid of 1x1 squares. The cube is painted on every side, so it leaves a mark on the grid when it moves. [![enter image description here](https://i.stack.imgur.com/ZT7cr.jpg)](https://i.stack.imgur.com/ZT7cr.jpg) The sides of the cube are colored 6 distinct colors, re-presentable with any 6 distinct values. A 7th value represents a blank space. The cube can roll around the grid. Every step it rotates precisely 90 degrees around one edge that touches the ground. Then the side facing down will leave a mark in that spot. Given the path of the cube, output the pattern it leaves on the grid. You may assume every spot is hit at most once. 0 bonus points if you use proper paint mixing rules in this case, but this is not necessary. ## Test Cases ``` Path: Pattern EEE YMBG ESE YM RB SEN YY RM NNNN Y R B C Y ``` ## IO You can use any 4 distinct values to represent the directions, except complete or partial functions. Output as a 2d array, a string, or a image. Any 6 values can be used to represent the colors of the cube sides. Extra respect for those who output as a image though. You may leave extra blank spaces around the edges. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 28 bytes ``` 6ɾ£⟑½4ʁ=⁺…*9+⟑¥Ṗi£;¥h;1pṅ2ø∧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI2yb7Co+KfkcK9NMqBPeKBuuKApio5K+KfkcKl4bmWacKjO8KlaDsxcOG5hTLDuOKIpyIsIiIsIls2LDIsMCw0LDQsMCwyLDJdIl0=) Expects a list of numbers 0, 2, 4, 6 for `NESW` respectively. Outputs a string with numbers 1 to 6 for each of the colors. It represents cube rotations as permutations of sides of the cube. The lexicographically 9th permutation represents rotating 90 degrees around the vertical axis and the lexicographically 325th permutation represents rotating 90 degrees around the vertical axis and then rolling west. Rolling in direction \$n\$ can be represented as rotating \$90(n/2+1)\$ degrees around the vertical axis, rolling west and then rotating rotating \$90(3-n/2)\$ degrees around the vertical axis. This corresponds to sequences of three 9th permutations and one 325th permutation. ``` 6ɾ£ # save [1,2,3,4,5,6] to the register ⟑ # map input: ½ # halve 4ʁ # push [0,1,2,3] = # equals? ⁺…* # times 316 9+ # plus 9 # Now we have a list with three nines and one 325 ⟑ # for each: ¥ # push register Ṗi # index into permutations £ # save register ; # end for ¥h # first item of register ; # end map ``` Now we have the sequence of bottom side colors after rolling the cube along the path. ``` 1p # prepend 1 ṅ # join by nothing 2 # push 2 ø∧ # canvas draw ``` [Answer] # JavaScript (ES6), 154 bytes *-7 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects a list of directions in \$0..3\$ for `NWSE` and returns a matrix filled with \$-3..3\$ for `MRB.YCG`. A rather naive implementation. ``` a=>a.map(d=>m[[A,B,C]=[[-B,A,C],[A,C,-B],[B,-A,C],[A,-C,B]][d],y+=--d%2][x+=~-d%2]=B,m=(b=[...a+0,C=3]).map(_=>b.map(_=>0)),m[x=y=a.length][x]=B=1,A=2)&&m ``` [Try it online!](https://tio.run/##NY/NasMwEITvfgphaCJhSaTpMawhMqanutAcSlFFUfyTONiysUNJKO2ru2u12Ys@ZrSzuyf7acd8qPuzcF1RThVMFmIrW9vTAuJW6y1XPDGgtVB8i8RRSbhQCIqLmyISrozRheHXCIQo7tZGXyL48QSKt0D3oKWUNlrxBB4M8yM@IN7fYMUYb/UFrmBlU7rD@YgR2Av3fAtrtli000YHhIRpmobcw@4fdmn2BxlWGJhAVt2Q2vxIRwIx@UKrKc@kJ0DmHUbjZ@azF2avmCJrV5SX54rmuAT@nmsosZlUtGcbVPLOjV1TyqY7UHR8wDAHDB6dz3p6UfIteQy1IxGZbzx1taPLJbvRu1sytPy7Cb7Z9As "JavaScript (Node.js) – Try It Online") ### How? The sides of the cube are arranged in such a way that the sum of two opposite faces is always \$0\$, which is similar to how 6-sided dice are designed (except the sum is \$7\$ in that case). We only need to keep track of \$3\$ orthogonal faces \$A\$, \$B\$, \$C\$. By convention, we define \$B\$ as the face currently touching (and painting) the ground. When rotating the cube, the value of a 'hidden' face is given by \$-X\$ where \$X\$ is the value of its 'visible' counterpart. ### Commented ``` a => // a[] = input array a.map(d => // for each direction d in a[]: m[ // [A, B, C] = [ // apply the cube rotation ... [-B, A, C], // 0: North [ A, C, -B], // 1: West [ B, -A, C], // 2: South [ A, -C, B] // 3: East ][d], // ... according to d y += --d % 2 // add dy to y ][x += ~-d % 2] // add dx to x = B, // set m[y][x] = B // initialization: m = ( // set up a square matrix m[] b = [ ...a + 0, // using an array b[] twice as large as a[] C = 3 ] // with an additional (dummy) element ) // .map(_ => // fill all cells ... b.map(_ => 0) // ... with 0's ), // m[ // initialize (x, y) to the center square x = y = a.length // ][x] = B = 1, // and set this square to 1 (yellow) A = 2 // we start with (A,B,C) = (2,1,3) ) && m // end of map(); return m[] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~39~~ 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 6LIĆv¤ˆā•R∊j% uWQöñ•4ô₂S£y;δè`‡<è}2¯IΛ ``` Uses `0,2,4,6` for `N,E,S,W` respectively, and uses `1,2,3,4,5,6` for the colors `B,R,M,C,G,Y` of the challenge description respectively. [Try it online](https://tio.run/##AU4Asf9vc2FiaWX//zZMScSGdsKky4bEgeKAolLiiIpqJSB1V1HDtsOx4oCiNMO04oKCU8KjeTvOtMOoYOKAoTzDqH0ywq9Jzpv//1syLDQsMl0) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GpRRQlFpSUqlbUJSZV5KaopCZV1BaYqWgZK/DpeSYXFKamIMQUvJzDQ5XMj4899D2Rw0Lgw@vtw39b@YTcaSt7NCS021HGh81LAp61NGVpapQGh54eNvhjUABk8NbHjU1BR9aXGl9bsvhFTEJQJ02h1fUGh1aH6F3bvZ/mCX5pSUQW3RsMdyEkDPzUXIK8nV2j1QCGqNzaJs9F8gPXOUZmTmpCkWpiSD3c6Xkcyko6OcXlOhDvAql0Hxvo6ACVpuX@t/V1ZXLNdiVK9jVj8sPCLgA). **Explanation:** *General explanation:* 1. `6LIĆv¤ˆā•R∊j% uWQöñ•4ô₂S£y;δè`‡<è}` is to generate the output values in the correct order based on the 'rolling' cube. 2. `2¯IΛ` is to output it in the correct output-format. For step 1, I start with a list `[1,2,3,4,5,6]` as this starting position: ``` 1 U 2345 FRBL 6 D ``` (The diagram next to it indicates `U`p; `F`ront; `R`ight; `B`ack; `L`eft; and `D`own respectively.) For the four directions, the following changes take place: | Direction | Cube 'roll' change | Changes pattern | Actual changes | | --- | --- | --- | --- | | `N`orth | `123456`→`263154` | `xx.x.x` | `1246`→`2614` | | `E`east | `123456`→`521463` | `x.x.xx` | `1356`→`5163` | | `S`outh | `123456`→`413652` | `xx.x.x` | `1246`→`4162` | | `W`est | `123456`→`326415` | `x.x.xx` | `1356`→`3615` | These are basically the changes I do in my code as well with a transliterate on `123456`, after which I use this to index into the current state of the cube. For step 2: I use the Canvas builtin `Λ` ([see this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin](https://codegolf.stackexchange.com/a/175520/52210)) to draw the characters from step 1 in the directions of the given input. *Code explanation:* ``` 6L # Push list [1,2,3,4,5,6] I # Push the input-list Ć # Enclose; append its own head (to have an extra iteration) v # Pop and for-each `y` over these input-directions: ¤ # Push the last item of the list (without popping) ˆ # Pop and add this last digit to the global array ā # Push a list in the range [1,length] (without popping the list); # a.k.a. push list [1,2,3,4,5,6] again •R∊j% uWQöñ• # Push compressed integer 124613562614516341623615 4ô # Split it into parts of size 4: [1246,1356,2614,5163,4162,3615] ₂S£ # Split it into parts [2,6]: [[1246,1356],[2614,5163,4162,3615]] y # Push the current direction `y` ; # Halve it δ # Map over each inner list with halve the direction as argument: è # Modular 0-based index halve the direction into the inner list ` # Pop and push both integers to the stack ‡ # Transliterate the digits of the first to the second in list # [1,2,3,4,5,6] < # Decrease each by 1 to a 0-based index è # Index it into the current list }2 # After the loop: Push 2 ¯ # Push the global array I # Push the input-list Λ # Use the Canvas builtin with these three options, # and output immediately afterwards implicitly ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•R∊j% uWQöñ•` is `124613562614516341623615`. [Answer] # [Python](https://www.python.org) NumPy, 165 bytes ``` def f(p): s=r_[:4];y=x=len(p);o=pad([[s]],y)[...,y+1:-y] for c in p:s=s[2*c];_,j,k,l=c;y+=j+k-3;x+=(k+l)%4-1;o[y,x]=s[argmin(s):][1:4] return o from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NZHBbqMwEIa1Vz-FhVTJDhOESQ9bkI855JILh7SyRlEUYJdCbGSIhPMqe-ml-07t06wN2tPM_DOafz77z9_BTb-N_vj4vE_N9ufXZ1U3tGEDzwkdpT2r_BkLJ2fZ19qrhZHDpWJKjYjguEqSBFws8q1DQhtj6ZW2mg75KEeVba5YnOEdOujltXCxfI-77a6YY8m6uOdPz1tRGOVgRj99sb9urWYjz1EJb0qorae71dSQxpob1ffb4Gh7G4ydNuux3z9eqtaOVNKqvU6slCqDHQhIEY5S7SCDFATCKehp6CDspRI-SyFDTg4yKvfH4-lUluV-77OQL9VSr8oxIgfvoIKTqnCBrALkAYn1jYYdONEPaRNt9KO2hnHikeAsL4FHP0Bw8gavi3CZVyEWJOzpwx6rXP4Gc_6K-WBbPbGNUir1J3oMf6xHWqLH8TFbMXwUix4gxRL9JGLS6qqeWceNjZIoWHTBok8m07fjxDjCWA8yivj6gv-__R8) Takes a list of lists as input S=[2,3,1,0],N=[3,2,0,1],W=[2,0,3,1],E=[1,3,0,2] and returns an NxNx3 array of RGB values. ### How? Represents cube orientations (and 90 degree rotations) as permutations of its four long diagonals. Each diagonal connects two opposite corners of the cube: ``` 3----------2 /|\ /| / | \ / | 0----------1 | | | \ | | | 1----\--|--0 | / \ | / |/ \|/ 2----------3 ``` This wireframe shows the outline of a cube and one of the diagonals (diagonal 3). All eight corners are labelled by the diagonal (0,1,2,3) they belong to. As the rotations we are interested in are fully characterised by the permutation they induce on the corners and as they preserve oppositeness of corners it may look like a good idea to encode such rotations as permutations of the four diagonals. And it is. Now, we can see that the (orthogonal) orientations of the cube map 1:1 to permutations of 0,1,2,3. Let us against normal convention write permutation abcd as ``` ba cd ``` and think of corners of the bottom face like in the picture (in the picture a,b,c,d = 0,1,2,3) Now for example rolling the cube repeatedly over the (bottom) back edge will map: ``` 10 -> 32 -> 01 -> 23 -> 10 23 10 32 01 32 ``` (Always the bottom face is shown.) For the (bottom) right edge it would be ``` 10 -> 02 -> 23 -> 31 -> 10 23 31 10 02 23 ``` Note that every orientation maps to a unique permutation and, conversely, each permutation actually represents an orientation (not in the examples but over all possible orientations) Further note that by singling out a "null" orientation O\_n `0123` each orientation o doubles as a rotation r, viz. the r that takes O\_n to o. Also, te effect of two consecutive rotations is the product of the corresponding permutations. Finally, note the identity of the bottom face and therefore the colour applied is easily read off the permutation representation of the orientation: the total of 24 orientations / permutations splits into six groups of four which differ by quarter turns: ``` 10 ~~ 03 ~~ 32 ~~ 21 23 12 01 30 ``` In practical terms, we can given an orientation; find the position of zero and then read ccw. This yields one of the six permutations of 1,2,3; a different one depending on which of the six faces of the cube is facing down. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes ``` ≔YMCRGBηFS«✳ι§η⁰≔⭆§⪪”)⊟Z➙.κ⊗φαμ”⁶⌕RULι§ηIκη»§η⁰ ``` [Try it online!](https://tio.run/##XY7BC4IwGMXP@VeMnb6BwZyuSydTCiEhFA8dh5qOZIquCKK/fU2sQ93e9/jee7@yFWPZi86YcJpkowCf0yg77LCLWrJ1Lv2IIFHDTed6lKoBQtDTWZ2s1hDLsS617BVI4qJQJ6qqH9C6iBIbXX0Kl2AqBvh@5EMnNWCPM58GzOM08APKfO75HuUBs9Mb27eXqgKcFUd7S/I7EIlJw5XM7kz5chagPwRj4qww63v3Bg "Charcoal – Try It Online") Link is to verbose version of code. Uses `ULDR` instead of `NWSE`. Explanation: ``` ≔YMCRGBη ``` Start with the six colours. ``` FS« ``` Loop over the path. ``` ✳ι§η⁰ ``` Draw the square just being exited. ``` ≔⭆§⪪”)⊟Z➙.κ⊗φαμ”⁶⌕RULι§ηIκη ``` Permute the colours according to the direction. ``` »§η⁰ ``` Draw the final square. [Answer] # Python3, 580 bytes: ``` m=['abcd','afce','fbed'] E=enumerate def f(d): v,s,c,x,y,U,P=[[m[0][0]]],0,0,0,0,0,0 v[0][0]=m[0][0] for i in d: X,Y={'N':(-1,0),'S':(1,0),'E':(0,1),'W':(0,-1)}[i] if(0,0)!=(U,P)and((not U and X)or(not P and Y)):[(s,c)]=[(j,a.index(m[s][c]))for j,a in E(m)if m[s][c]in a and j!=s] U,P=X,Y c+=[-1,1][::[1,-1][s%2]][::[-1,1][i in['N','W']]][i in['E','N']];x+=X;y+=Y c%=4 if y==len(v[0]):y=len(v[0]);v=[I+['']for I in v] if y<0:y=0;v=[['']+I for I in v] if x==len(v):x=len(v);v=v+[[''for _ in v[0]]] if x<0:x=0;v=[[''for _ in v[0]]]+v v[x][y]=m[s][c] return v ``` [Try it online!](https://tio.run/##ZVHRaoMwFH33K9KHkgTTodsehl0e89AXKZSylksYViOzTC1qRRn79u4mlZVuKuSce48n5yansfuoq6eXU3O5lBJockgzKmiSpwaX/GAyqj0lTXUuTZN0xstMTnKW8cgjvWhFKgYxiq1YS4ASAo2f1iK4vSi7luXU9kheN6QgRUUyNCE7sZdfNKYRW4Qi4IJuEF6RQhSIENGbQ4uQf0OBDqTIkQZ8JhluzZMqY6yqO7IlCMmO142ja0f3nEfAMCrXEthRJA9FlZmBldBqSDXnNg@WbSLFSl7kZGphIXEWx5ls7bZ2TsyLKPUlYN5QQxRBiMk0tPNH7ei1bicEnMuGxzOZuEIeI18OvtwtR186s7l8dkORUcpPUzF7ZDwab3jZS1j5QKm2YVc2aq@nX14DVAZWYfv@ivyTDJMrj4YJoLr3rd5q353W3dykR8vh1/KPxO9R1MOgYbR36g7KI43pzg1KLqemqDqWM6qUopx7N7655xsV3/EYHyxcfgA) [Answer] # HTML + Javascript graphical output, ~~269~~ 254 bytes Building on Arnaulds answer, this draws the colored fields to a `<svg>`. -15 bytes by switching from `<canvas>` to `<svg>`. Directions are entered as 0..3 for `NWSE`. Colors are mapped from 1..6 as ``` 1: hsl(60,90%,50%) = #f2f20d 2: hsl(120,90%,50%) = #0df20d 3: hsl(180,90%,50%) = #0df2f2 4: hsl(240,90%,50%) = #0d0df2 5: hsl(300,90%,50%) = #f20df2 6: hsl(360,90%,50%) = #f20d0d ``` ``` w=a=>{A=1,B=2,C=3,x=y=a.length,c=`<svg viewBox=${[0,0,3*x,3*y]}>`;(f=()=>(c+=`<rect x=${x} y=${y} width=1 height=1 fill=hsl(${B*60},90%,50%) />`))();for(d of a){[A,B,C]=[[7-B,A,C],[A,C,7-B],[B,7-A,C],[A,7-C,B]][d],y+=--d%2,x+=~-d%2,f()}document.write(c)} w([3,2,3]) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~126 124 122~~ 119 bytes 2 bytes saved by changing colours from `ABCEFG` to `123456`, 2 bytes saved by deleting `[]` from `[1,2,3]`, 3 bytes saved by changing directions from `0,1,2,3` to `-2,-1,0,1`. ``` ->n{a=($/+?.*w=n.size*4)*w a[q=w*w/2]=?2 c=1,2,3 n.map{|i|c[j=i&1,2]=c[j+1]*s=i|1,-c[j]*s a[q+=s+j*w*s]="#{c[1]%7}"} a} ``` [Try it online!](https://tio.run/##Tc3bCsIwDAbg@z6FeELTdrNT8CruQUou6nDQgWNaR9Ftz147ETaSwJ8PQp7t9R1KDPJSdwZ365TnCXisE2c/NzjtwTOjH@jBpxlhnrEClcjEkdXJ3TRdb/tCV2i3EQlj5IrAoe2VkHGLeTzn6HgFHhzhctUVWtHmPCwHZobQtC@3KLU@iH8RscmU@M3MRpFqBjJ@mpoofAE "Ruby – Try It Online") Takes an array of numbers `-2,-1,0,1` corresponding to `W,N,E,S` or equivalently `x-=1,z-=1, x+=1,z+=1`. Outputs the path of the cube traced on a string of `w*w` periods, where `w` is four times the length of the input. The cube is represented as a vector `c=[x,y,z]` starting at `[1,2,3]` which rolls in the `xz` plane. The colour is determined by the current `y` coordinate. If the cube is rotated 180 degrees, the y coordinate becomes negative, so the possible values are `-3,-2,-1,1,2,3` with opposite faces adding to zero. To display, the number is taken mod 7 and this is converted to a character, so the possible displayed colours are `1,2,3,4,5,6` with opposite faces adding to 7. The vector is rotated by 90 degrees by swapping two coordinates and changing the sign of one of them, similar to Arnauld's answer, but where he uses an array, I use the formula `c[j,2]=c[j+1]*s,-c[j]*s` where `c[j,2]` is a block of 2 array elements starting at `j`=0 or 1 and `s` is the sign of the rotation, +1 or -1. `s` is also the sign of the direction of movement and is calculated as `i|1`. `s` equals -1 for `-2|1` and `-1|1`, and 1 for `0|1` and `1|1`. `j` is calculated as `i&1` and equals 0 for even numbers `-2` and `0` (travel in `x` direction) and 1 for odd numbers `-1` and `1` (travel in `z` direction.) **Commented code** ``` ->n{a=($/+?.*w=n.size*4)*w #make a string of w*w periods separated in lines by /n a[q=w*w/2]=?2 #set q to the centre of the field (padding by the /n characters ensures w*w/2 is central horizontally as well as vertically) c=1,2,3 #put a 2 at position q. Set up a vector c for colours x,y,z n.map{|i| #iterate through array of directions. j=1 for vertical, 0 for horizontal. s=1 for increase, -1 for decrease c[j=i&1,2]=c[j+1]*s=i|1,-c[j]*s #in accordance with value of j, swap c[0]&c[1] or c[1]&c[2] and change the sign of one in accordance with s a[q+=s+j*w*s]="#{c[1]%7}"} #modify the value of q by s (horizontal) or (1+w)s (vertical) and save colour%7 at a[q] a} #return the final string a. ``` ]
[Question] [ A [binary relation](https://en.wikipedia.org/wiki/Binary_relation) on a set \$X\$ is simply a subset \$S \subseteq X \times X\$; in other words, a relation is a collection of pairs \$(x,y)\$ such that both \$x\$ and \$y\$ are in \$X\$. The number of different relations grows quickly with the size of the set: if \$X\$ contains \$n\$ elements, there are \$2^{n^2}\$ binary relations on \$X\$. This challenge will have you computing the number of binary relations subject to certain constraints, listed here: * A binary relation is called "reflexive" if \$(x,x) \in S\$ for all \$x \in X\$. * A binary relation is called "irreflexive" if \$(x,x) \not\in S\$ for all \$x \in X\$. * A binary relation is called "symmetric" if whenever \$(x,y) \in S\$, then \$(y,x) \in S\$. * A binary relation is called "asymmetric" if whenever \$(x,y) \in S\$, then \$(y,x) \not\in S\$. * A binary relation is called "transitive" if whenever \$(x,y) \in S\$ and \$(y,z) \in S\$ then \$(x,z) \in S\$. * A binary relation is called "antitransitive" if whenever \$(x,y) \in S\$ and \$(y,z) \in S\$ then \$(x,z) \not\in S\$. # Challenge The goal of this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge is to write a function that takes in a nonnegative integer \$n\$, and some subset of the six conditions above in any reasonable format\*, and returns the number of binary relations on the set \$\{1,2,\dots,n\}\$ satisfying all of the conditions in the aforementioned subset. Brute-force strategies are okay, but your code should be able to handle all \$n \leq 4\$ on TIO. # Test Data ``` n | conditions | number of binary relations --+------------------------------------+------------------------- 0 | {reflexive, antitransitive} | 1 3 | {reflexive, antitransitive} | 0 3 | {} | 512 3 | {antitransitive} | 39 4 | {antitransitive} | 921 4 | {reflexive, irreflexive} | 0 4 | {symmetric, asymmetric} | 1 4 | {transitive, antitransitive} | 87 4 | {reflexive, symmetric, transitive} | 15 4 | {symmetric, transitive} | 52 4 | {asymmetric, antitransitive} | 317 ``` # Example For \$n = 3\$, there are \$39\$ antitransitive relations, as shown by the illustration below. (Strictly speaking, the illustration shows *unlabeled* relations.) 0. There is \$1\$ empty relation. 1. There are \$6\$ relations consisting of just one pair. 2. There are \$3 + 3 + 6 + 3\$ relations consisting of two pairs. 3. There are \$6 + 6 + 2\$ relations consisting of three pairs. 4. There are \$3\$ relations consisting of four pairs. [![The 39 antitransitive relations when n = 3](https://i.stack.imgur.com/PD0lq.png)](https://i.stack.imgur.com/PD0lq.png) --- \* For example, you could take the conditions as a list like `[False, False, True, False, False, True]`, with each position referring to the particular condition. As another example, you could take a set of strings like `{"transitive", "asymmetric"}`. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~99~~ 93 bytes ``` r←0∊0 0⍉⊢ R←r~ s←⊢≢⍉ S←1∊⊢∧⍉ t←0∊⊢≥∨.∧⍨ T←1∊⊢∧∨.∧⍨ {×⍵:+/∧⌿~(⍺,'0'){(⍎⍺)⊣⍵}\⍵-⍛↑∘⊤¨,⍳⍵⍴2*⍵⋄1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/4tA5KOOLgMFg0e9nY@6FnEFAUWK6riKgRSQ@6hzEVCcKxjIMwQqA4l0LAeJlEA1gtUsfdSxQg8ssYIrBFUpQqL68PRHvVuttPVB/J79dRqPenfpqBuoa1YDWX1AjuajrsVAFbUxQEL3Ue/sR20TH3XMeNS15NAKnUe9m4Gij3q3GGmB6O4Ww9r/aSAnAnV2NR9abwxS3Dc1OMgZSIZ4eAb/Vy8qLlFXSFMw4VKHUsEhYAYA "APL (Dyalog Extended) – Try It Online") -5 bytes thanks to @ovs for spotting `R←r~`, and -1 by taking the boolean negation of the intermediate results. Takes the condition as a string, using the abbreviation as follows: ``` r: reflexive R: irreflexive s: symmetric S: asymmetric t: transitive T: antitransitive ``` For example, reflexive + symmetric + transitive is given as `'rst'` and "no condition" is given as `''`. ### How it works (before golfing) ``` ⍝ Each of rRsStT takes an adjacency matrix and determines if the condition is met ⍝ reflexive: the diagonal is all ones r←∧/0 0⍉⊢ ⍝ irreflexive: the diagonal is all zeros R←∧/0 0⍉~ ⍝ symmetric: transpose is equal to self s←⊢≡⍉ ⍝ antisymmetric: each position in self and transpose cannot be both ones S←~1∊⊢∧⍉ ⍝ transitive: self includes the transitive square of self t←~0∊⊢≥∨.∧⍨ ⍝ antitransitive: each position in self and transitive square cannot be both ones T←~1∊⊢∧∨.∧⍨ ⍝ main function {×⍵:+/∧⌿(⍺,'≡'){(⍎⍺)⍵}\⍵-⍛↑∘⊤¨,⍳⍵⍴2*⍵⋄1} ⍝ ⍵: n, ⍺: conditions {×⍵: ... ⋄1} ⍝ Take 0 as a special case, always returning 1 ,⍳⍵⍴2*⍵ ⍝ Generate all length-n vectors of 0..2^n-1 ⍵-⍛↑∘⊤¨ ⍝ Convert them to n×n binary matrices (⍺,'≡') ⍝ Add a default function that always returns 1 to the list of conditions {...}\ ⍝ Take outer product of conditions and matrices... (⍎⍺)⍵ ⍝ Eval the condition function and apply it to the matrix +/∧⌿ ⍝ Count the matrices which satisfy all the conditions ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 182 bytes A slower but significantly shorter version suggested by @tsh. Expects `(n)(m)`, where **n** is a BigInt and **m** is a list of constraints among: ``` IRREFLEXIVE = 0, REFLEXIVE = 1, ANTISYMMETRIC = 2, SYMMETRIC = 3, ANTITRANSITIVE = 4, TRANSITIVE = 5 ``` ``` n=>m=>eval("g=(c,x=n)=>x?c(--x)&g(c,x):1;h=(x,y)=>!(k>>x+n*y&1n);for(t=0,k=1n<<n*n;k--;)t+=m.every(q=>g(x=>g(y=>g(z=>[h(x,x)^q,h(x,y)|h(y,x)^q%2,h(x,y)|h(y,z)|h(x,z)^q%2][q>>1]))))") ``` [Try it online!](https://tio.run/##lZFfa8IwEMDf/RSZMEk01abqg6vJkNFBYfpQy9gQB9LVdlPTqaWksu/eJToklvrgPdxxf353udz3Ilvsg93XT2rw5DMslrTglG0oC7PFGtYjCgMsKEeUiccAGoZAjUiF0AOxYwoFzmXqDq4YEy3ezBuEI3uZ7GBKTbyihA@HvMntlWHYKG3RTTvMwl0Ot5RFUCiVK3WgbBbLXgJ9bHF8bPobw/zo31t65KCMkEYl5rMtY2SOpNRRESR8nwLX85znF@fNfXUABSYGukswGE18d/o@Hju@5z7JkIWB7nZPFb43mkxd/0T1MLjw@3atpoYl67C9TiK4hCZHcHYeVG4hHwj@pdMBpMR2b2DNKlYruSqS7ROrir467pLuDkCJ7t1ADyxSRWtba2e77FKx9ZE9H610Up1Wv138AQ "JavaScript (Node.js) – Try It Online") (part 1) [Try it online!](https://tio.run/##dZBta8IwEMff@ykyYZJoqsYHHKuXIaNCYfqilrEhDkrXh601nVoklX33LlHY6tB7ccf/cr//Hfn09t7O33585YbI3oMyhFIAXwMP9l6K6xFgn0oQBLh88LFhSNKIdIvcMzMGLGmhnm5wwrlsiWbRYIKYYbbFOXRpAkyMx6IpzMQwTJK3YN0O9sG2wBvgEZY6FTodgC9j5SXJ24bGR9PvGBdHfdurdg66SFX0w2q54ZytiIo6Kf1M7HJkO441fbJe7GcLAepSVJWMosnctRevs5nlOvajavUoqsr@acJ1JvOF7Z6oAUVnemjWanpZlgbtNItwiAeC4OXfzH8PdSE6RaeD7kaX4N8rK@dU12oLBbPhJfgqUQkFD3uX4LMPuXK5gvtsVP4A "JavaScript (Node.js) – Try It Online") (part 2) --- # [JavaScript (Node.js)](https://nodejs.org), 215 bytes Expects `(n)(m)`, where **n** is a BigInt and **m** is a bit-mask describing which constraints are enabled, using a combination of: ``` IRREFLEXIVE = 1 REFLEXIVE = 2 ANTISYMMETRIC = 4 SYMMETRIC = 8 ANTITRANSITIVE = 16 TRANSITIVE = 32 ``` ``` n=>m=>{g=(c,x=n)=>x?c(--x)&g(c,x):1;h=(x,y)=>!(k>>x+n*y&1n);for(t=0,k=1n<<n*n;k--;)t+=![x=>h(x,x)^q,0,x=>g(y=>h(x,y)|h(y,x)^q),0,x=>g(y=>g(z=>h(x,y)|h(y,z)|h(x,z)^q)),0].some((c,j)=>m>>j&!g((q=j&1)?C:C=c));return t} ``` [Try it online!](https://tio.run/##lZFdT8IwFIbv@RXlhrSywTpAPkZLCJnJEuECFqMxmpAJwwGdwDQb4m@frWjo5hZCb5qec573nJ7Xm35Md8729S1Qmf8yi@ckZoSuCf10CXSUkDBEaNhzoKqGqOSKEOpgY0FgqEQ8VYRLSsMyu4pKmCFj7m9hQDRlSTDrdtkVM5aqaqCgTIqPIaELToXoeaNoXJm6MDqGInRYwOgng6SUC/eJ/F5cIb94Ga97quz89QzykTw@yJpSr1R0IdwQr4RRb9AZEAchYzsL3rcMBF@x47NdAKzx2Ly5Ne@tOxMQgBUgP3UF9Ee2NXkYDk17bA14qK4A@dk6Vtjj/mhi2b8i1wpIBGq6USiIdv5qVln5LpxDjSF46nRIiSAE/k61CnCKrV3AahmsJpXkHs42sJ5B53ZL0bU2SNH1C@i2jjNo@deScUmZjF8L9uTaIWmqTGdsW7CSm/nr5myreWZoeYiEhmjcODN17t6EV3rOstPf/icirMLN@Bs "JavaScript (Node.js) – Try It Online") Notes: * To get a much faster version, replace the first bitwise `&` with `&&`. * Using BigInts is slower and slightly longer, but allows this code to work for any **n** in theory. ### Formatted and commented ``` n => m => { // helper function to test whether c(x) is true for all x in [0 .. n - 1] g = (c, x = n) => x ? c(--x) & g(c, x) : 1; // helper function to test if (x, y) is *not* in S h = (x, y) => !(k >> x + n * y & 1n); // we use k = 2 ** n² - 1 to k = 0 to describe all possible binary relations // (k is essentially a flatten binary matrix of size n x n) for(t = 0, k = 1n << n * n; k--;) // increment t if ... t += // ... the following tests are all falsy ![ // irreflexive (q = 0) / reflexive (q = 1) x => h(x, x) ^ q, 0, // antisymmetric (q = 0) / symmetric (q = 1) x => g(y => h(x, y) | h(y, x) ^ q), 0, // antitransitive (q = 0) / transitive (q = 1) x => g(y => g(z => h(x, y) | h(y, z) | h(x, z) ^ q)), 0 ] .some((c, j) => // return true if the constraint is set ... m >> j & // ... and the test fails !g((q = j & 1) ? C : C = c) ); return t } ``` [Answer] # [Python 3](https://docs.python.org/3/), 319 bytes Expects to be called as `f(n, m)`, where m is a bitmask of which conditions are required, in the same order as the question. ``` r=lambda x:x and r(x[1:])+[x[:1]+a for a in r(x[1:])]or[[]] f=lambda n,c:(lambda z:n==0 or sum(1for a in map(set,r([(x,y)for x in z for y in z]))if not(lambda g,h,i:(g<=a)+(a-g==a)*2+(h==a)*4+(a-h==a)*8+(i|a==a)*16+(a-i==a)*32)(set(zip(z,z)),{(q,b)for(b,q)in a},{(d,c)for(d,b)in a for(l,c)in a if l==b})&c^c))(range(n)) ``` [Try it online!](https://tio.run/##fZHLboMwEEX3fMWsqnHtShhIQlD8JYhK5hkkYhKgEqHNt1PbSVAXJawu95552D5fh2Or/HnuRCNPaS5hjEaQKocOx5hHCaHxGEc8oRLKtgMJtVqipO3iOEmc8lmrWBbhQ0@REsIFXdN/nZAvxSd5xr4YWIcxjuxKTDCaYLIDrlYmhNQlqHZ4dqvYkdURVgchCUX5UQkt3j2KRysC491lSLH@kVbyrbFrq32PmLE41Wec2EQI@8YLS814TNmF6Knypr2cZdbLdWY8sxQ22rQ/eqlGiPRG3rLPjBDspKoKVITMXdHIoW5VDwJKx8mLEoaiH5BEDuhP9n3RDbBQ6DLgVC8FQgD/H/H/IO4q4tp8w71V4tHC3/9PBAux9/g68moNnQc0fHUW0@FwCCwS7lYZTgPKt/dGmxezHszGW2XC5835fOc496eYfwE "Python 3 – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 188 bytes ``` lambda n,Q:sum(all([m[x*n+x]^q,(b:=m[x*n+y])+m[y*n+x]^q-1,b*m[y*n+z]<=m[x*n+z]^q%2][q//2]for q in Q for x,y,z in p(*3*[range(n)]))for m in p(*n*n*[[0,1]])) from itertools import*;p=product ``` [Try it online!](https://tio.run/##jVNLbtswEN3rFAMDBUVFTfSJkcStDpE1wwKyQ7UEJEomGcNy5FN00U1P14u4Q0uR5QQGQm70PjOcGZFNa3/VKr1v9KHIng5lXi2fc1Dh48K8VH5elj6r2DZQV1v@Yx36y0XWw5bTq4q1g/A1DpdBD3f8@2DZofAl4Wx9c5PwotawBqngEdznNmzDnYONH6QB07n6KXxFOaVOrQZF4WYsCmOOglfoGgUrtK3r0oCsmlrb4FuTNbp@flnZgwu1wthVboTLMJvNvAg6eNWiKMVWbkQIubLS4nFGWsR7GFYHsZd@1hr11pG5uDqYx0lvvpDszJw@gHf7WfNDEvfmScVSj2B/Zo56q2mrSlgtV31zI9zDdA5H6@n4S4Po4P7uQwWTE6YRmHb@oYQLHeLQktMY3pX8LgZnFt95@J@vDXoan16bppTWJ0@K0IUHYCAbr8Sb1hGKikJFKusbFnGHLWL26rmsZGyILCAKe24yW2TjgR3LQy4ZuLOykU8H/lQ7krcT85kwd8KebfjxnWzcPTYs5kODBK8dGbsMgVCQBWw4xoixoeTYkEZc@Arn7FCjnUb@/f1NXASKGUaIEl8Kkn8wlaaH/w "Python 3.8 (pre-release) – Try It Online") Function receives two arguments. The first one is the size of set \$X\$. The second one is a list describe properties all relations should fit. while use 0~5 for reflexive, irreflexive, symmetric, antisymmetric, transitive, antitransitive. For example, `f(4, [0, 2, 4])` find the number of relations on set with 4 elements which is reflexive, symmetric, and transitive. ``` for matrix in itertools.product([0,1], repeat=n*n) # all possible relations for arguments in itertools.product(range(n), repeat=3) # all x, y, z combinations for q in Q # all properties need to follow ``` --- # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 205 bytes ``` lambda n,Q:sum(all([x:=k%n,m[x*n+x]^q,y:=k//n%n,(b:=m[x*n+y])+m[y*n+x]^q-1,z:=k//n//n,b*m[y*n+z]<=m[x*n+z]^q%2][q|1]for q in Q for k in R(n**3))for m in[[i>>j&1for j in R(n*n)]for i in R(2**n**2)]) R=range ``` [Try it online!](https://tio.run/##jZPPTuMwEMbveYpRJXAcspA/VEBEeAe4Gq@UssmuITFp7K2akj7FHvbC0/EiZVyHNAVVwsrB832/cWYmTt3qP88yvqybTZHeb8qsmv3KQPq3ifpbuVlZumyZpE9H0q/Y0pMnS/5z7reonJ1JFN1Zklqj5fSkYm2P/Aj9lYXw8WeedVb8uqdXyBxFnM27kBfPDcxBSLgFs30y2ztXel5MqREqFBgTNzePx6GJHz8ASbe5wsaR52FORDl17tImk7/zjXF1rvRDpnIDTSYTJ4AOXpq8KPOlWOQ@ZFILjbgSGuM19KuD0Im/iwYWHZSDq4NpGFn4wGF7cHwFzvl34asotPCoYtEMwXoPDiyq2qrKdSMebHNDuIbxHLbo7vWHBtHB5cWXCkZvGGfgsdMvJRzoEIcW7cbwqeRPOTiz8MLB73yqkKldeqrqUmiX3EtCEwdAQTpciQ@vIxQdiY6Q2lUs4CbWGLMXx5xKhoZIAoFvtdFsUQ17dSgPtajX9spGPe71Xe0ono/gPWNqjDVb8O3fsTD3WLGQ9w0SvHZk6NIHQkEUsOCYkw8NRduGGowLV@KcTVQ3xiNvr/@IyUAzxYy8xD8Fxf94VEM37w "Python 3.8 (pre-release) – Try It Online") Here is another version without `import itertools`. Save 2 bytes, thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 121 bytes ``` ILΦEX²×θθ⎇θ⪪﹪÷ιX²…⁰×θθ²θυ∧∨§η⁰⬤ι§λμ∧∨§η¹¬⊙ι§λμ∧∨§η²⬤ι⬤λ⁼ν§§ιξμ∧∨§η³¬⊙ι⊙λ∧ν§§ιξμ∧∨§η⁴⬤ι⬤⌕Aλ¹⬤⌕A§ιν¹§λπ∨§η⁵¬⊙ι⊙λ∧ν⊙§ιξ∧π§λρ ``` [Try it online!](https://tio.run/##hY/fa8MgEMf/FR9PcJBk3dOewrZCYd3KtrfSB6nSCPZMjOnav94pS9caZFXk7ns/PnduG263hmvvV1ahgyfeO3iVuHMNzJV20sKSt7Ay38GrGPlSe9lDx0hHaVDSIrenqD9brRwsjRi0gQW6Z3VQQoJi5K/3g@NOQpFCIqai0WVkiKJGAe8WardAIY/QMFLEqNaRdY5qRvY0X12G6JtxUOMp05Ftqa4GBBNKX7qB6x7w0n@2oeZIR1YWdj@ZH4z@rbtFy@Jm6W5zhWLcsaRp6IqJdExfPt@OE1L6w7/LBjVZNGbahGvp9Dx6v56xdcniLeLbbPzdQf8A "Charcoal – Try It Online") Link is to verbose version of code, which contains 17 consecutive `)`s, which might be a record for me in Charcoal. Takes input as `n` and an array of six integers where `0` means that the constraint is to be enforced. This is technically a 1-liner, but at 121 bytes it's too wide for me to format the explanation that way, so I'll pretend it isn't. Explanation: ``` ILΦ ``` Print the length of matching values... ``` EX²×θθ⎇θ⪪﹪÷ιX²…⁰×θθ²θυ ``` ... generated by iterating over all \$ 2^{n^2} \$ relations and turning them into an \$ n \$ by \$ n \$ binary matrix (except when \$ n \$ is 0, in which case just iterate the predefined empty array), where... ``` ∧∨§η⁰⬤ι§λμ ``` ... if the first constraint is to be enforced then check that the main diagonal only contains `1`s; and... ``` ∧∨§η¹¬⊙ι§λμ ``` ... if the second constraint is to be enforced then check that the main diagonal does not contain a `1`; and... ``` ∧∨§η²⬤ι⬤λ⁼ν§§ιξμ ``` ... if the third constraint is to be enforced then check that the matrix equals its transpose; and... ``` ∧∨§η³¬⊙ι⊙λ∧ν§§ιξμ ``` ... if the fourth constraint is to be enforced then check that the matrix does not contain a `1` where its transpose does; and... ``` ∧∨§η⁴⬤ι⬤⌕Aλ¹⬤⌕A§ιν¹§λπ ``` ... if the fifth constraint is to be enforced then check that wherever the matrix contains a `1` and the row of that `1`s column contains a `1` then the original row also contains a `1` in the second `1`'s column, and... ``` ∨§η⁵¬⊙ι⊙λ∧ν⊙§ιξ∧π§λρ ``` ... if the sixth constraint is to be enforced then check that that the matrix does not contain three `1`s where two are in the same row, two are in the same column and the other row and column index are the same. ]
[Question] [ > > In [atomic physics](https://en.wikipedia.org/wiki/Atomic_physic) and [quantum chemistry](https://en.wikipedia.org/wiki/Quantum_chemistry), the **electron configuration** is the distribution of [electrons](https://en.wikipedia.org/wiki/Electron) of an [atom](https://en.wikipedia.org/wiki/Atom) in [atomic orbitals](https://en.wikipedia.org/wiki/Atomic_orbital). For example, the electron configuration of the neon atom is *1s2 2s2 2p6* (From [Wikipedia](https://en.wikipedia.org/wiki/Electron_configuration)) > > > ## Challenge Your challenge is to take a number representing the [atomic number](https://en.wikipedia.org/wiki/Atomic_number) of an element and output the electron configuration of that element as defined by the [Aufbau principle](https://en.wikipedia.org/wiki/Aufbau_principle). Iron (26) has the electron configuration `1s2 2s2 2p6 3s2 3p6 3d6 4s2`. However, superscripts are unnecessary; the output for Iron (26) should be along the lines of `1s2 2s2 2p6 3s2 3p6 3d6 4s2`. ## Specification * You do not have to handle any inputs outside of the range `1 <= n <= 118`. * Your output should look something like the test cases, but you may use any non-digit character/characters (aside from `s`, `p`, `d`, and `f`) to delimit the different orbitals. * You must return/print a string containing the orbital names/values/delimiters; you cannot simply return/print an array. * You do not need to handle any exceptions to the Aufbau principle; where there are exceptions, printing the "incorrect" configuration is fine. Examples: ``` Input -> Valid output -> Invalid output 16 -> 1s2 2s2 2p6 3s2 3p4 -> 1s22s22p63s23p4 16 -> 1s2, 2s2, 2p6, 3s2, 3p4 -> [[1, 2], [2, 2], [2, 6], [3, 2], [3, 4]] 17 -> 1s2+2s2+2p6+3s2+3p5 -> 1s2s2s2s2p6p3s2s3p5 ``` Here is a list of all the electronic orbitals. The maximum values they can contain are below the name: ``` name: 1s 2s 2p 3s 3p 3d 4s 4p 4d 5s 5p 4f 5d 6s 6p 5f 6d 7s 7p max: 2 2 6 2 6 10 2 6 10 2 6 14 10 2 6 14 10 2 6 ``` ## Test Cases ``` Input -> Output 1 -> 1s1 2 -> 1s2 16 -> 1s2 2s2 2p6 3s2 3p4 50 -> 1s2 2s2 2p6 3s2 3p6 3d10 4s2 4p6 4d10 5s2 5p2 115 -> 1s2 2s2 2p6 3s2 3p6 3d10 4s2 4p6 4d10 5s2 5p6 4f14 5d10 6s2 6p6 5f14 6d10 7s2 7p3 ``` Here is a [complete list](https://pastebin.com/raw/yGJ1cFSC) and a [reference implementation](https://github.com/aaronryank/minproj/blob/master/chemistry/electron-config.c) of sorts ([Try it online!](https://tio.run/##hVPbboMwDH3PV1hMW8MGE/S2C233IWs1MQKtJQodpN2kil8fi8OldOrFqlL7OPGxc0JgL4OgLG8wCeKtCGGSS4Hp42rGDtDalytC2I0II0xC@Nqi5GkmMPFja@fHJswZnDSRwv5skgwj4BcrNLbJMJERN27zWwGG1WX3rjKEcbiGyRQc80o7mmkrg5Wf8d486V2pTZaFcpsll/cVZ7MFfK8wDoE7JmNqQkizT5R@zMm/p74tIHft/5hsr4twDZtgTwn12KGJOgUTGvQNuEqDDf5nXh8x4bU6UjC2S1FAkCYRLjWX3lAztFc2A9d9Ntm/URk7EkTMpT1TkugKdbIzyYdiDPP3BUxh37dA/cbN6jonvOG5qPD@l87f3Rdd16lzpBvcN8S5zCpaw80Ny@jrZaOWAXkD7Qm1DCkcUjikcEThSIcReYSNCRsTNiJsTNgTYU8bo@jMjFUfUZoBR0XteIBKDvdF/T88qNfX3mU7AlKLjep3WvHjm8OF6bXH6k/vMCAurE6pemdBClfPBhNOUrfSnmjS1U1Ooe84VZstW/M@VNmiLH@DKPaXeWnH6z8)) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins! [Answer] # [Python 2](https://docs.python.org/2/), ~~129~~ 128 bytes -1 byte thanks to notjagan ``` n=input() d='spdf'.find s='sspspdspdspfdspfdsp' i=0 while n>0:c=s[i];t=d(c)*4+2;print`s[:i].count(c)-~d(c)`+c,min(t,n);n-=t;i+=1 ``` [Try it online!](https://tio.run/##LYlBCoMwEEX3OYW7JI2KSunCML2ICELS4EA7hmakdNOrp2kR3l@8/@Kb142GnAmQ4s5KCw8yRR9kG5C8SMVSLMefcEwKhE68VrzfKrp2o4M04WwZvHL6dDaDjU8kXtI04ty6bScuofn88mJc/UBSXJO21ABbNNDn3F@@ "Python 2 – Try It Online") [Answer] # [Imperative Tampio](http://github.com/fergusq/tampio), 930 bytes ``` Yöllä on ilot.Olkoon oma ilo uusi yö, jonka iloja ovat ilo"1s",ilo"2s",ilo"2p",ilo"3s",ilo"3p",ilo"3d",ilo"4s",ilo"4p",ilo"4d",ilo"5s",ilo"5p",ilo"4f",ilo"5d",ilo"6s",ilo"6p",ilo"5f",ilo"6d",ilo"7s"ja ilo"7p".Olkoon iso yö uusi yö, jonka iloja ovat 2,2,6,2,6,10,2,6,10,2,6,14,10,2,6,14,10,2 ja 6.Kun iso luku juo ison ilon,iso ilo näyttää oman yön,missä oma yö on oman ilon ensimmäinen ilo ja ujo ilo on ison yön ensimmäinen ilo,jos iso luku on suurempi kuin ujo ilo,niin iso ilo näyttää ujon ilon,iso ilo näyttää ilon" ",oman ilon iloiksi asetetaan oman ilon ilot toisesta alkaen,ison yön iloiksi asetetaan ison yön ilot toisesta alkaen ja iso luku vähennettynä ujolla ilolla juo ison ilon ja,jos iso luku on pienempi tai yhtä suuri kuin ujo ilo,niin iso ilo näyttää ison luvun.Olkoon oma muuttuja uusi muuttuja.Kun iso sivu avautuu,omaan muuttujaan luetaan luku ja oman muuttujan arvo juo ison sivun. ``` > > Yöllä **on** ilot.**Olkoon** oma ilo **uusi** yö, **jonka** iloja **ovat** **ilo**`"1s"`,**ilo**`"2s"`,**ilo**`"2p"`,**ilo**`"3s"`,**ilo**`"3p"`,**ilo**`"3d"`,**ilo**`"4s"`,**ilo**`"4p"`,**ilo**`"4d"`,**ilo**`"5s"`,**ilo**`"5p"`,**ilo**`"4f"`,**ilo**`"5d"`,**ilo**`"6s"`,**ilo**`"6p"`,**ilo**`"5f"`,**ilo**`"6d"`,**ilo**`"7s"`**ja** **ilo**`"7p"`.**Olkoon** iso yö **uusi** yö, **jonka** iloja **ovat** `2`,`2`,`6`,`2`,`6`,`10`,`2`,`6`,`10`,`2`,`6`,`14`,`10`,`2`,`6`,`14`,`10`,`2` **ja** `6`.**Kun** iso luku *juo* ison ilon,iso ilo *näyttää* oman yön,**missä** oma yö **on** oman ilon `ensimmäinen` ilo **ja** ujo ilo **on** ison yön `ensimmäinen` ilo,**jos** iso luku **on** **suurempi** **kuin** ujo ilo,**niin** iso ilo *näyttää* ujon ilon,iso ilo *näyttää* **ilon**`" "`,oman ilon iloiksi *asetetaan* oman ilon ilot `toisesta` **alkaen**,ison yön iloiksi *asetetaan* ison yön ilot `toisesta` **alkaen** **ja** iso luku **vähennettynä** ujolla ilolla *juo* ison ilon **ja**,**jos** iso luku **on** **pienempi** **tai** **yhtä** **suuri** **kuin** ujo ilo,**niin** iso ilo *näyttää* ison luvun.**Olkoon** oma muuttuja **uusi** muuttuja.**Kun** iso sivu *avautuu*,omaan muuttujaan *luetaan* *luku* **ja** oman muuttujan arvo *juo* ison sivun. > > > [Online version](http://iikka.kapsi.fi/tampio/elektronit-golf.html) It is a very straightforward implementation. In the golfed version I simply replaced the words with short words like `ilo`, `yö`, `iso`, `oma`, etc. Ungolfed: > > Listalla **on** alkiot. > > > **Olkoon** lyhyt orbitaalilista **uusi** lista, **jonka** alkioita **ovat** > **orbitaali** `"1s"`, > **orbitaali** `"2s"`, > **orbitaali** `"2p"`, > **orbitaali** `"3s"`, > **orbitaali** `"3p"`, > **orbitaali** `"3d"`, > **orbitaali** `"4s"`, > **orbitaali** `"4p"`, > **orbitaali** `"4d"`, > **orbitaali** `"5s"`, > **orbitaali** `"5p"`, > **orbitaali** `"4f"`, > **orbitaali** `"5d"`, > **orbitaali** `"6s"`, > **orbitaali** `"6p"`, > **orbitaali** `"5f"`, > **orbitaali** `"6d"`, > **orbitaali** `"7s"` **ja** > **orbitaali** `"7p"`. > > > **Olkoon** lyhyt maksimilista **uusi** lista, **jonka** alkioita **ovat** > `2`, > `2`, > `6`, > `2`, > `6`, > `10`, > `2`, > `6`, > `10`, > `2`, > `6`, > `14`, > `10`, > `2`, > `6`, > `14`, > `10`, > `2` **ja** > `6`. > > > **Kun** *jaetaan* *orbitaaleille* pienehkö elektronimäärä nykyisellä sivulla, > > > * nykyinen sivu *näyttää* nykyisen orbitaalin, **missä** > nykyinen orbitaali **on** lyhyen orbitaalilistan `ensimmäinen` alkio **ja** > nykyinen maksimi **on** lyhyen maksimilistan `ensimmäinen` alkio, > * **jos** pienehkö elektronimäärä **on** **suurempi** **kuin** nykyinen maksimi, > **niin** > > > + nykyinen sivu *näyttää* nykyisen maksimin, > + nykyinen sivu *näyttää* **välin** `" "`, > + lyhyen orbitaalilistan alkioiksi *asetetaan* lyhyen orbitaalilistan alkiot `toisesta` **alkaen**, > + lyhyen maksimilistan alkioiksi *asetetaan* lyhyen maksimilistan alkiot `toisesta` **alkaen** > + **ja** *jaetaan* *orbitaaleille* pienehkö elektronimäärä **vähennettynä** nykyisellä maksimilla nykyisellä sivulla, > * **ja**, **jos** pienehkö elektronimäärä **on** **pienempi** **tai** **yhtä** **suuri** **kuin** nykyinen maksimi, > + **niin** > nykyinen sivu *näyttää* pienehkön elektronimäärän. > > > **Olkoon** mukava muuttuja **uusi** muuttuja. > > > **Kun** nykyinen sivu *avautuu*, > > > * mukavaan muuttujaan *luetaan* *luku* > * **ja** *jaetaan* *orbitaaleille* mukavan muuttujan arvo nykyisellä sivulla. > > > [Online version](http://iikka.kapsi.fi/tampio/elektronit.html) Translation: > > A list **has** items. > > > **Let** the short orbital list **be** a new list, its items **are** > the orbital `"1s"`, > the orbital `"2s"`, > the orbital `"2p"`, > the orbital `"3s"`, > the orbital `"3p"`, > the orbital `"3d"`, > the orbital `"4s"`, > the orbital `"4p"`, > the orbital `"4d"`, > the orbital `"5s"`, > the orbital `"5p"`, > the orbital `"4f"`, > the orbital `"5d"`, > the orbital `"6s"`, > the orbital `"6p"`, > the orbital `"5f"`, > the orbital `"6d"`, > the orbital `"7s"` **and** > the orbital `"7p"`. > > > **Let** the short maximum list **be** a new list, its items **are** > 2, > 2, > 6, > 2, > 6, > 10, > 2, > 6, > 10, > 2, > 6, > 14, > 10, > 2, > 6, > 14, > 10, > 2 and > 6. > > > **When** a small number of electrons *is divided to the orbitals* at the current page, > > > * the current page *shows* the current orbital, **where** the current orbital **is** the first item in the short orbital list **and** the current maximum **is** the first element in the short maximum list, > * **if** the small number of electrons **is greater than** the current maximum, > + the current page *shows* the current maximum, > + the current page *shows* the space `" "`, > + the elements of the short orbital list *are set to be* the elements of the short orbital list **beginning from** the second, > + the elements of the short maximum list *are set to be* the elements of the short maximum list **beginning from** the second > + **and** the small number of electrons **subtracted by** one *is divided to the orbitals* at the current page, > * **and**, **if** the small number of electrons **is less than or equal to** the current maximum, > + the current page *shows* the small number or electrons. > > > **Let** the nice variable **be** a new variable. > > > **When** the current page *opens*, > > > * *a number is read to* the nice variable > * **and** the value of the nice variable *is divided to the orbitals* at the current page. > > > The translation is approximate, I had to change the word order to make the English more natural. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 72 bytes ``` Nθ≔”{⊞″I⌀⁼C$Pπ3”α≔⁰ιW›θ⁰«§”o⧴∨c▷⎇_'l|”ι§αι≔⁺×⁴⌕spdf§αι²εI⌊⟦εθ⟧→≔⊕ιι≔⁻θεθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nnXndjzqnPKoYW71o655jxo2ez7qaXjUuMdZJeB8gzFQ@NxGkHTjhnM73@/Z/qhhF1B544ZDqw8tB8rlP1q@5VHHiuRH07Y/6muPV8@pAWnYeWj5uY3ndoK17To8/VHjlkc9U4sLUtIg4oc2ndv6fs/KRz1dj@YvO7cVaN785Y/aJoGUd009txOqcfe5HSC5//8NDU0B "Charcoal – Try It Online") Here you have [the verbose version](https://tio.run/##XVDNasMwDL73KUxOMtWgSewU1lMpbPTQUcZuYwe3URtB4iax0w3Gnt1z127rBtJB0vcjaVuZfnswdQhL2w7@YWg21EMnZ6O5c7y3kDjXurb8it0lExTmFzFBwbF6rbgmAfc9GX@SwImU4n0kxLpn62Hul7akN0jSLMvzXCmltdJFoYvpNEGWUeE/1Hy3L0brenDwxA05UHjHtozLteUubvOHITGTKOhKcGGchxVbboYGngm7F3kWXh2OBLePvK/8tdF4DCzPV/30Ij26d0hxcHrPRwhpqsPN8RM). [Answer] # JavaScript (ES6), 102 bytes ``` n=>'0010120120132013201'.replace(/./g,k=>n?++p[m=k*4+2,n-=e=m>n?n:m,k]+'spdf'[k]+e+' ':'',p=[0,1,2,3]) ``` ### Test cases ``` let f = n=>'0010120120132013201'.replace(/./g,k=>n?++p[m=k*4+2,n-=e=m>n?n:m,k]+'spdf'[k]+e+' ':'',p=[0,1,2,3]) console.log(f( 1)) // -> 1s1 console.log(f( 2)) // -> 1s2 console.log(f( 16)) // -> 1s2 2s2 2p6 3s2 3p4 console.log(f( 50)) // -> 1s2 2s2 2p6 3s2 3p6 3d10 4s2 4p6 4d10 5s2 5p2 console.log(f(115)) // -> 1s2 2s2 2p6 3s2 3p6 3d10 4s2 4p6 4d10 5s2 5p6 4f14 5d10 6s2 6p6 5f14 6d10 7s2 7p3 ``` ### Formatted and commented ``` n => // given the atomic number n '0010120120132013201' // list of azimuthal quantum numbers .replace(/./g, k => // replace each character k in the above string with: n ? // if n does not equal 0: ++p[ // ++p[k] = updated principal quantum number m = k * 4 + 2, // m = maximum number of electrons n -= // subtract from n: e = m > n ? n : m, // e = min(m, n) = number of electrons k // index actually used to access the p[] array ] + // followed by: 'spdf'[k] + // the label e + ' ' // and the number of electrons : // else: '', // an empty string p = [0, 1, 2, 3] // initial list of principal quantum numbers ) // end of replace() ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~63 62 56~~ 55 bytes ``` ḊFµi@€QḤ’Ḥ “ŒµḊuÆẓƙỊ’D,“çƥ÷£ḟ’ṃ“spdf”¤µxÇZ ¢ḣŒg'µQ€żL€K ``` [Try it online!](https://tio.run/##y0rNyan8///hji63Q1szHR41rQl8uGPJo4aZQJLrUcOco5MObQVKlh5ue7hr8rGZD3d3AeVcdIAyh5cfW3p4@6HFD3fMBynf2QwUKy5ISXvUMPfQkkNbKw63R3EdWvRwx@Kjk9LVD20NBBp9dI8PkPT@//@/oRkA "Jelly – Try It Online") Thanks to user202729 for saving 6 bytes with base decompression! **Explanation** First I construct the list `[[1,2,2,3,3,3,4,4,4,5,5,4,5,6,6,5,6,7,7],'sspspdspdspfdspfdsp']` with the code `“ŒµḊuÆẓƙỊ’D,“çƥ÷£ḟ’ṃ“spdf”¤` in the second link. * `“ŒµḊuÆẓƙỊ’` is the number `1223334445545665677` compressed into base 250. `D` gives turns this into a list of digits. * `“çƥ÷£ḟ’ṃ“spdf”` changes the base 250 number `“çƥ÷£ḟ’` into base 4 and indexes it into the string `“spdf”` yielding `'sspspdspdspfdspfdsp'`. This was contributed by user202729. The list is then take to the fist link by `Ç`. The first link does the following: ``` ḊFµQiЀµḤ’Ḥ ḊF Dequeue then flatten yields 'sspspd...'. Ṫ doesn't work because it modifies the input. µ New monadic link Q Unique elements → 'spdf' iЀ The index of each of 'sspspd...' into the string 'spdf' → [1,1,2,1,2,3...] µ New monadic link. This prevents Ḥ from acting on the right argument of iЀ. Ḥ’Ḥ Takes [1,1,2,1...] and computes 2(2l+1) → [2,2,6,2,6,10...] ``` Now back to the second link. With `xÇ` we repeat each of the elements in each sublist of `[[1,2,2,3...7],['sspspd...p']]` by the numbers in our new list `[2,2,6...]`. This yields `[[1,1,2,2,2,2...],['sssspp...']]`. `Z` zips the two sublist which yields `[[1,'s'],[1,'s'],[2,'s']...]`. Now to the main link. `¢` calls the second link which yields the final list of tuples described above. Assume the input to the program is 5 as an example. ``` ¢ḣŒg'µQ€żL€K ¢ Calls the second link as a nilad which yields the final list of tuples described above ḣ Takes the first 5 tuples → [[1,'s'],[1,'s'],[2,'s'],[2,'s'],[2,'p']] Œg' Group together runs of equal elements → [[[1,'s'],[1,'s']],[[2,'s'],[2,'s']],[[2,'p']]] µ New monadic link Q€ Unique elements of each of these runs L€ Length of each of these runs ż Zip these together → [[[1,'s'],2],[[2,'s'],2],[[2,'p'],1]] K Join this list with spaces → 1s2 2s2 2p1 ``` [Answer] # [Swift](https://swift.org), ~~177~~ ~~175~~ 156 bytes Loosly based on @Arnauld's Javascript answer ``` func f(n:Int){var i=n,a=0,b=[0,1,2,3];[0,0,1,0,1,2,0,1,2,0,1,3,2,0,1,3,2,0,1].map{a=$0*4+2;b[$0]+=1;i>0 ?print(b[$0],"spdf".map{$0}[$0],min(a,i)):();i-=a}} ``` [Try it online!](https://tio.run/##Ky7PTCsx@f8/rTQvWSFNI8/KM69Es7ossUgh0zZPJ9HWQCfJNtpAx1DHSMc41hrIArEhfARpjErH6uUmFlQn2qoYaJloG1knRasYxGrbGlpn2hko2BcUZeaVaIDFdJSKC1LSlMCqVQxqwUK5mXkaiTqZmppWGprWmbq2ibW1XP9B7jI00/wPAA "Swift 4 – Try It Online") ## Without the spaces in the electron groups, ~~190~~ ~~187~~ 169 bytes: ``` func f(n:Int){var i=n,a=0,b=[0,1,2,3];[0,0,1,0,1,2,0,1,2,0,1,3,2,0,1,3,2,0,1].map{a=$0*4+2;b[$0]+=1;i>0 ?print(b[$0],"spdf".map{$0}[$0],min(a,i),separator:""):();i-=a}} ``` [Try it online!](https://tio.run/##VY69DoIwFIVfhTQMrVxN@QkDTXX2GQjDRW1yB2pTqg6kz14FB@Nyfr6c4cwvMqFJyTzsJTPcdmcbxPJEn5G2gFrCqHsJJVRQD@qT1vztP63/fThM6BbUudw1RaXGPpdDoUtFR5mdnCcb@MaAze5q2LbOZdzQRJYjkID55tBjuPuOMdFxoWivMca0fixbkd4 "Swift 4 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), ~~43~~ 42 bytes ``` #~ElementData~"FullElectronConfiguration"& ``` -1 byte thanks to ovs. This does not work with [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6ZgqxDz3zUnNTc1r8QlsSQxWllHya00JwcolFxSlJ/nnJ@XlpleWgRUnp@nFKv2P6AoM68kOi3aUMdIx9BMx9DQNDb2PwA), so I've provided a screenshot instead. Note that this correctly shows the exceptions, such as `4s1 3d5` for chromium (Z=24), which occurs because half-filled and fully-filled orbitals are energetically favorable (thus slightly advantaging `4s1 3d5` over `4s2 3d4`); and `5s1 4d7` for ruthenium (Z=44): [![enter image description here](https://i.stack.imgur.com/A2nvi.png)](https://i.stack.imgur.com/A2nvi.png) In order to get the full electron configuration, it is necessary to use the "FullElectronConfiguration" option; the "ElectronConfigurationString" option will instead provide the electron configuration using "core notation" shorthand. E.g., for Z = 16, core notation is: [![enter image description here](https://i.stack.imgur.com/Y94aF.png)](https://i.stack.imgur.com/Y94aF.png) where `[Ne]` means "the electron configuration for Ne", i.e., `1s2 2s2 2p6` [Answer] # C (gcc), ~~260~~ ~~187~~ ~~167~~ ~~156~~ ~~152~~ ~~147~~ ~~143~~ 138 bytes ``` i,*m;f(e){for(m=L"...",i=0;e>0;printf("%.2s%d ","1s2s2p3s3p3d4s4p4d5s5p4f5d6s6p5f6d7s7p"+i++*2,(e-=*m)<0?*m+e:*m++));} ``` [Try it online!](https://tio.run/##TU7LboMwEJQ45MCh32C5imLziHiniiH9gX5CLsjGYSUMFia9RPx6qdNEpCvt7OzsQ8PDC@fLO/S8u4oGlWYSMOzbk/uSVD21Vlkg8BSTpKE3OYxEVV/YcTbO5tw/8m0FHEAVseYUMT1CP0mCt/vEbAXCAY5NYhKdmlSnIjOZzkRucp3JXBSm0LksxMEcNPbB970kIE1YeYqW0aen/OZowaeUzYv9ilQNPfkeQFD35iIbdxHYH7UGEQFUoZghQKWt8Ydl9ho9du@xmkvF0VoDytaRJP87fZ14W49kd@53T3l25@WHy66@mCXs1C8) Golfed from the reference implementation. StackExchange removes unprintables, so the value of `m` is replaced with `"..."`. Here is a reversible hexdump of the program, since it uses unprintables in a string, which replaces the integer array `{2,2,6,2,6,10,2,6,10,2,6,14,10,2,6,14,10,2,6}` with the literal byte values of the integers. ``` 00000000: 692c 2a6d 3b66 2865 297b 666f 7228 6d3d i,*m;f(e){for(m= 00000010: 4c22 0202 0602 065c 6e02 065c 6e02 060e L".....\n..\n... 00000020: 5c6e 0206 0e5c 6e02 0622 2c69 3d30 3b65 \n...\n..",i=0;e 00000030: 3e30 3b70 7269 6e74 6628 2225 2e32 7325 >0;printf("%.2s% 00000040: 6420 222c 2231 7332 7332 7033 7333 7033 d ","1s2s2p3s3p3 00000050: 6434 7334 7034 6435 7335 7034 6635 6436 d4s4p4d5s5p4f5d6 00000060: 7336 7035 6636 6437 7337 7022 2b69 2b2b s6p5f6d7s7p"+i++ 00000070: 2a32 2c28 652d 3d2a 6d29 3c30 3f2a 6d2b *2,(e-=*m)<0?*m+ 00000080: 653a 2a6d 2b2b 2929 3b7d e:*m++));} ``` Alternatively, you could just copy the code from the TIO link. [Answer] # Clarion, 388 bytes ``` PROGRAM Map End o CString('sspspdspdspfdspfdsp') n CString('1223334445545665677') m CString('2 2 6 2 6 102 6 102 6 14102 6 14102 6 ') r CString(129) Code e#=Command('ATOM'); Loop i#=1 To 19 If e#>m[(i#*2)-1:(i#*2)] Then r=r&n[i#]&o[i#]&Clip(m[(i#*2)-1:(i#*2)])&' ' e#-=m[(i#*2)-1:(i#*2)]; Cycle.;If e# < m[(i#*2)-1:(i#*2)] Then r=r&n[i#]&o[i#]&e#;Break.;End;Message(r) ``` Loosely based on @Rod's Python answer [Answer] # [Scala](http://www.scala-lang.org/), 173 bytes A port of [@Endenite's Swift answer](https://codegolf.stackexchange.com/a/150476/110802) in Scala. 173 bytes. It can be golfed much more. --- Golfed version. [Try it online!](https://tio.run/##VY8xb4MwEIV3fsUp011xESRVBpCROnbIFHWqOhwJThyBQ40VESH/dmo3Q9Qb7u49fcN744E7Xq7NpT042LE2MCcJ3LgDVQJ@GCfrT6MdgVyMrOcbW9SCRUMSjcjFu7V8x1wUYi02RNW@/Qkq6of33Jv/l7Keh3mSNcvp5S1dVw1OlMqi0gp1ndM8WG1cZzD6mbvuXdCndDUOR7WKaM/unPXaIAv9BMhX@lWy9wvAsVXQcyTsaSzhL@rXA/umEmItkKEuhFFYbCl8PvHLLw) ``` n=>{var(i,a,b)=(n,0,Array(0,1,2,3));Seq(0,0,1,0,1,2,0,1,2,0,1,3,2,0,1,3,2,0,1).map{x=>a=x*4+2;b(x)+=1;if(i>0){println(b(x).toString+"spdf"(x)+math.min(a,i).toString)};i-=a}} ``` Ungolfed version. [Try it online!](https://tio.run/##bZAxa8MwEIV3/4pHJqlxjZ2UDAYHOhaaKXQqHc5JlF6JFSOL4BD8211ZVlwI1XTfu7t34jU7OlHfn8ufw85iQ6xxi4D9QUEJneNNW5njQ7NF4TvAhQzYkZ6IHKUTlY5ejaGrSGNkMRYxltJ337mxgzjqU/ehWP5by6SiGje0KNbwbvB3WzzhBXMsglaKVmJeIAvMCoKxRirD94dXG9b2pMUwnNjz1jo@OpNZU@/VzDugIvudVKwFxeC/KRlMurs/ngtQdJe6KKRX0bBqjk0@hvE5rn89pqlEtpJ@sev7Xw) ``` object Main { def f(n: Int): Unit = { var i = n var a = 0 var b = Array(0, 1, 2, 3) List(0, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1).map { x => a = x * 4 + 2 b(x) += 1 if (i > 0) { println(b(x).toString + "spdf"(x) + math.min(a, i).toString) } i -= a } } def main(args: Array[String]): Unit = { f(16) } } ``` ]
[Question] [ There are many magic squares, but there is just *one* non-trivial magic hexagon, as [Dr. James Grime explained](https://www.youtube.com/watch?v=ZkVSRwFWjy0), which is the following: ``` 18 17 3 11 1 7 19 9 6 5 2 16 14 8 4 12 15 13 10 ``` As it is done in [Hexagony](https://esolangs.org/wiki/Hexagony) this is easiest written as just one line, by just reading it row by row: ``` 18 17 3 11 1 7 19 9 6 5 2 16 14 8 4 12 15 13 10 ``` Of course there are twelve such list representations of this magic hexagon in total, if you count rotations and reflections. For instance a clockwise 1/6 rotation of the above hexagon would result in ``` 9 11 18 14 6 1 17 15 8 5 7 3 13 4 2 19 10 12 16 ``` @Okx asked to list the remaining variants. The remaining lists are: ``` 15 14 9 13 8 6 11 10 4 5 1 18 12 2 7 17 16 19 3 3 17 18 19 7 1 11 16 2 5 6 9 12 4 8 14 10 13 15 18 11 9 17 1 6 14 3 7 5 8 15 19 2 4 13 16 12 10 9 14 15 11 6 8 13 18 1 5 4 10 17 7 2 12 3 19 16 ``` plus all the mentioned lists reversed. ### Challenge Write a program that outputs the magic hexagon as a list. You can choose *any* of the 12 reflections/rotations of the hexagon. Please add a few words on how your solution works. [Answer] # Octave, 24 bytes ``` 'IKRNFAQOHEGCMDBSJLP'-64 ``` [Try it online!](https://tio.run/##y08uSSxL/f9f3dM7yM/NMdDfw9Xd2dfFKdjLJ0Bd18zk/38A "Octave – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “JɼQⱮȦ>Ȯ’Œ? ``` A niladic link returning the list of the given orientation reflected left-right. **[Try it online!](https://tio.run/##AR8A4P9qZWxsef//4oCcSsm8UeKxrsimPsiu4oCZxZI///// "Jelly – Try It Online")** ### How? Just the kind of thing for which I made `Œ?` ``` “JɼQⱮȦ>Ȯ’Œ? - Niladic link: no arguments “JɼQⱮȦ>Ȯ’ - base 250 number, 18473955480703453 Œ? - shortest permutation of some set of natural numbers one through to some N - inclusive which would lie at that index in a list of all permutations of - those same natural numbers when sorted lexicographically. - - - for example 7Œ?: - - since 7 is greater than 3! and less than 4!+1, it references four items - - the sorted order of permutations of 4 items is: - - [[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[1,4,3,2],[2,1,3,4], ...] - - so 7Œ? yields [2,1,3,4] ``` [Answer] # Pyth, 15 bytes ``` .PC"A¡öò\x06\x11Ý"S19 ``` (Control characters replaced with `\x06` and `\x11` for your viewing convenience.) [Try it online](https://pyth.herokuapp.com/?code=.PC%22A%C2%A1%C3%B6%C3%B2%06%11%C3%9D%22S19&input=18473955480703453) ### How it works ``` "A¡öò\x06\x11Ý" magic string C convert to number n using codepoints as base-256 digits .P S19 nth lexicographic permutation of [1, …, 19] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes Both solutions generate the list `[3,17,18,19,7,1,11,16,2,5,6,9,12,4,8,14,10,13,15]` ``` 19Lœ•δn2мׄÁ•è ``` Generates a list of all (sorted) permutations of the range `[1...19]` and indexes into that list with a base 255 compressed base 10 number. Or 15 bytes runnable online ``` •áRвºñ*$vn+•20в ``` Decompresses a base 255 string to a base 10 number and converts to a list of base 20 digits. [Try it online!](https://tio.run/##MzBNTDJM/f//UcOiwwuDLmw6tOvwRi2VMk9HoICRwYVN//8DAA "05AB1E – Try It Online") [Answer] # [SOGL](https://github.com/dzaima/SOGL), 15 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ³←@uΙΒQH√y׀“L«─ ``` Explanation: ``` ...“ push the number 4121998669867569415662783 L« push 20 ─ convert 4121998669867569415662783 from base 10 to a base 20 number aka base 10 array ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` 18473955480703453œ?19 ``` I really want to compress that big number, but I'm not sure how. [Try it online!](https://tio.run/##y0rNyan8/9/QwsTc2NLU1MTCwNzA2MTU@Ohke0PL//8B "Jelly – Try It Online") [Answer] # APL, 24 bytes ``` ⎕A⍳'RQCKAGSIFEBPNHDLOMJ' ``` [Try it online!](http://tryapl.org/?a=%u2395A%u2373%27RQCKAGSIFEBPNHDLOMJ%27&run) **How?** ``` ⎕A ⍝ 'ABC... ⍳ ⍝ indices of 'RQCKAGSIFEBPNHDLOMJ' ⍝ ← this vector ``` [Answer] # JavaScript (ES6), 49 bytes ``` [...'ih3b17j9652ge84cfda'].map(n=>parseInt(n,26)) ``` ``` console.log( [...'ih3b17j9652ge84cfda'].map(n=>parseInt(n,26)) ) ``` [Answer] ## Mathematica, 37 bytes ``` 36^^md1o3apsqxqkfhq6~IntegerDigits~20 ``` Explanation (that may be already obvious as Mathematica is not a codegolf language, but according to the OP requirement): ``` 36 : Number base ^^ : Input a number in arbitrary base. See BaseForm documentation md1o3apsqxqkfhq6 : the number in base 36 ~IntegerDigits~20 : convert to base 20 as list of digits ``` Output: ``` {18,17,3,11,1,7,19,9,6,5,2,16,14,8,4,12,15,13,10} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 27 bytes Inspired by rahnema1's solution. ``` `ikrnfaqogcmdbsjlp`¬®c -96 ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.5&code=YGlrcm5mYXFvlGdjbWRic2pscGCsrmMgLTk2&input=) ]
[Question] [ **A [strictly non-palindromic number](https://en.wikipedia.org/wiki/Strictly_non-palindromic_number) N is a number that isn't a palindrome in *any* base (in bases 2 to N-2).** These numbers are listed on [OEIS](https://oeis.org/A016038) For example, the number `19` in base 2,3,4,5,6,...17 is: `10011`,`201`,`103`,`34`,`31`,...`12`. None of these representations is palindromic, so the number is strictly non-palindromic. For this challenge, you need to **return a truthy value if the number is non-palindromic, otherwise a falsy value**. * You may assume the number passed to you is greater than or equal to 0. * Your program should work for values up to your languages' integer size. # Test cases: Truthy: ``` 0 1 2 3 4 6 11 19 47 53 79 103 389 997 1459 ``` Falsy: ``` 5 7 8 9 10 13 16 43 48 61 62 101 113 211 1361 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your answers as short as possible! [Answer] # C, 82 bytes ``` p(n,a,b,c,r){c=0;for(b=1;++b<n-2;c+=r==n)for(a=n,r=0;a>0;a/=b)r=r*b+a%b;return!c;} ``` [Ideone it!](http://ideone.com/QDQDhS) ## Explanation This code reverses `n` in base `b` and stores in `r`: ``` for(a=n,r=0;a>0;a/=b)r=r*b+a%b; ``` The outer loop counts the number of bases from `2` to `n-1` in which `n` is a palindrome. If `n` is non-palindromic, the count would be `1` (`n` must be a palindrome in base `n-1`). [Answer] # Python 2, 71 bytes ``` n=input();b=1 while b<n-2: m=n;r=0;b+=1 while m/(r!=n):r=r*b+m%b;m/=b ``` Output is via [exit code](http://meta.codegolf.stackexchange.com/a/5330/12012), where **0** is truthy and **1** is falsy. Test it on [Ideone](http://ideone.com/ETyqKZ). [Answer] # [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 206 bytes ``` GOTO e lbld c - 1 GOTO c lble readIO n = i i - 3 b = i b + 1 GOTO f lbla a = n r = 0 lblb m = a m % b r * b r + m a / b if a b r - n r | if r d lblc c + 1 i - 1 b - 1 lblf if i a c / c c - 1 c | printInt c ``` [Try it online!](http://silos.tryitonline.net/#code=R09UTyBlCmxibGQKYyAtIDEKR09UTyBjCmxibGUKcmVhZElPIApuID0gaQppIC0gMwpiID0gaQpiICsgMQpHT1RPIGYKbGJsYQphID0gbgpyID0gMApsYmxiCm0gPSBhCm0gJSBiCnIgKiBiCnIgKyBtCmEgLyBiCmlmIGEgYgpyIC0gbgpyIHwKaWYgciBkCmxibGMKYyArIDEKaSAtIDEKYiAtIDEKbGJsZgppZiBpIGEKYyAvIGMKYyAtIDEKYyB8CnByaW50SW50IGM&input=&args=MTk) Port of [my answer in C](https://codegolf.stackexchange.com/a/91152/48934). [Answer] # Haskell, ~~75~~ 68 bytes ``` (a!c)b|a<1=c|x<-c*b+mod a b=div a b!x$b f n=all((/=n).(n!0))[2..n-2] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` bRµ⁼"US<3 ``` [Try it online!](http://jelly.tryitonline.net/#code=YlLCteKBvCJVUzwz&input=&args=MTQ1OQ) or [verify all test cases](http://jelly.tryitonline.net/#code=YlLCteKBvCJVUzwzCsOH4oKs4oKsRw&input=&args=WzAsIDEsIDIsIDMsIDQsIDYsIDExLCAxOSwgNDcsIDUzLCA3OSwgMTAzLCAzODksIDk5NywgMTQ1OV0sIFs1LCA3LCA4LCA5LCAxMCwgMTMsIDE2LCA0MywgNDgsIDYxLCA2MiwgMTAxLCAxMTMsIDIxMSwgMTM2MV0). ### How it works ``` bRµ⁼"US<3 Main link. Argument: n R Range; yield [1, ..., n]. b Convert n to all bases between 1 and n, yielding a 2D array A> µ Begin a new, monadic chain. Argument: A U Upend; reverse the 1D arrays in A. ⁼" Zipwith equal; yield 1 for each array that matches its inverse. S Sum; add the resulting Booleans. If n > 1, the sum will be 2 if n is strictly non-palindromic (it is only a palindrome in bases 1 and n - 1), and greater than 2 otherwise. For 0 and 1, the sum will be 0 (sum of the empty array) and 1 (only a palindrome in base 1); both are less than 2. <3 Compare the sum with 3, yielding the desired Boolean. ``` [Answer] # Mathematica, ~~58~~ 43 bytes ``` !Or@@Table[#==#~IntegerReverse~i,{i,2,#-2}]& ``` TIL that `#~IntegerReverse~i` reverses the digits of the input when written in base i. [Answer] # Pyth, ~~12~~ 10 bytes Saved two bytes with Dennis' trick. ``` >3sm_IjQdS ``` [Try it online!](http://pyth.herokuapp.com/?code=%3E3sm_IjQdS&input=0&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A10%0A997%0A998&debug=0) Explanation: ``` S (Q) Get all the bases we need by building a list from 1 to Q m For all bases d in the bases list: jQd cast Q to base d as a list _I and check to see if the list is palindromic (invariant on reversal) Compile all the results back into a list s Sum the results (a shorter form of any), gives 3 or more for palindromics (2 is the usual because of bases 1 and Q-1) >3 And verify that the sum is greater than three to get non-palindromics ``` [Answer] ## JavaScript (ES6), 83 bytes ``` f=(n,i=n-2,g=n=>n<i?[n]:[...g(n/i|0),n%i])=>i<2||`${a=g(n)}`!=a.reverse()&&f(n,i-1) ``` ``` <input type=number oninput=o.textContent=f(this.value);><pre id=o> ``` [Answer] ## Perl6, ~~110~~ ~~72~~ 65 ``` my &f={?all(map {{.reverse ne$_}(@(.polymod: $^a xx*))},2..$_-2)} ``` Couldn't use base since that's broken for any base above 36. ### Previous attempts ``` my &a={$^a??flat($a%$^b,a($a div$b,$b))!!()};my &f=-> $n {?all(map {.reverse ne$_ given @(a($n,$_))},2..$n-2)} my &f=->\n {?all(map {.reverse ne$_ given @(n.polymod: $_ xx*)},2..n-2)} ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes ``` ¬{⟦₆bk∋;?ḃ₍.↔} ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXaciU9BaWHuzprH26d8P/QmupH85c9ampLyn7U0W1t/3BH86OmXr1HbVNq//@PNtBRMNVRMNRRMNdRMNJRsNBRMNZRsNRRMAEKAuXMgBRQwBCowBDEBskA@SZA1SZAtaZAthlIM1DczAikBaTYAChibGEJ0gYyzBJkNNgEE1OQoLGZYSwA "Brachylog – Try It Online") Outputs through predicate success or failure, which prints `true.` or `false.` if run as a program. ``` ¬{ } It cannot be shown that ? the input ; ḃ₍ in a base ∋ which is an element of ⟦₆ the range from 1 to the input - 1 b without its first element k or its last element . can be unified with both the output variable ↔ and its reverse. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `GRr`, 58 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7.25 bytes ``` ⇩Ḣƛ?τḂ⁼;a ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJHUnJBPSIsIiIsIuKHqeG4osabP8+E4biC4oG8O2EiLCIiLCIwXG4xXG4yXG4zXG40XG42XG4xMVxuMTlcbjQ3XG41M1xuNzlcbjEwM1xuMzg5XG45OTdcbjE0NTlcbjVcbjdcbjhcbjlcbjEwXG4xM1xuMTZcbjQzXG40OFxuNjFcbjYyXG4xMDFcbjExM1xuMjExXG4xMzYxIl0=) Bitstring: ``` 1101010001101111001011011000000100110010001101101010011011 ``` [Answer] **C, 77 bytes** ``` h(n,b,k,z){for(z=0,k=n;z+=k%b,k/=b;z*=b);return b+3>n?1:z==n?0:h(n,++b,0,0);} ``` recursive exercise...i change (b+2>=n) with (b+3>n) whithout debugging... ``` main() {int v[]={0,1,2,3, 4, 6,11,19,47,53,79,103,389,997,1459}, n[]={5,7,8,9,10,13,16,43,48,61,62,101,113,211,1361}, m; // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 for(m=0; m<15; ++m) printf("%u=%u\n", v[m], h(v[m],2,0,0)); for(m=0; m<15; ++m) printf("%u=%u\n", n[m], h(n[m],2,0,0)); } /* 77 0=1 1=1 2=1 3=1 4=1 6=1 11=1 19=1 47=1 53=1 79=1 103=1 389=1 997=1 1459=1 5=0 7=0 8=0 9=0 10=0 13=0 16=0 43=0 48=0 61=0 62=0 101=0 113=0 211=0 1361=0 */ ``` [Answer] # C, 129 bytes ``` f(n,b,k,j){int a[99];for(b=2;b+2<n;++b){for(j=0,k=n;a[j]=k%b,k/=b;++j);for(;k<j&&a[k]==a[j];++k,--j);if(k>=j)return 0;}return 1;} ``` [Answer] # PHP, 68 bytes ``` for($b=$argn;--$b;)strrev($c=base_convert($argn,10,$b))!=$c?:die(1); ``` takes input from STDIN, exits with `1` for falsy, `0` for truthy. Run with `-R`. [Answer] # APL(NARS), chars 47, bytes 94 ``` {⍵≤4:1⋄∼∨/{⍵≡⌽⍵}¨{⍵{(⍺⍴⍨⌊1+⍺⍟⍵)⊤⍵}w}¨2..¯2+w←⍵} ``` where `{(⍺⍴⍨⌊1+⍺⍟⍵)⊤⍵}` would be the function conversion one positive omega in digits number base alpha, and `{⍵≡⌽⍵}` would be the function check palindrome... test: ``` f←{⍵≤4:1⋄∼∨/{⍵≡⌽⍵}¨{⍵{(⍺⍴⍨⌊1+⍺⍟⍵)⊤⍵}w}¨2..¯2+w←⍵} f¨0 1 2 3 4 6 11 19 47 53 79 103 389 997 1459 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 f¨5 7 8 9 10 13 16 43 48 61 62 101 113 211 1361 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` ]
[Question] [ What general tips do you have for golfing in Tcl? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Tcl (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] Use [`lmap`](http://www.tcl.tk/man/tcl8.6/TclCmd/lmap.htm) instead [`foreach`](http://www.tcl.tk/man/tcl8.6/TclCmd/foreach.htm). This requires Tcl 8.6. The syntax is the same, but `lmap` returns a list with the result of each loop. [Answer] Subcommands and options can (usually) be abbreviated. This can save quite a bit, but you *must* test as not everything can be shortened this way (`regsub`'s options can't, for example). You can then use this with the magic of `namespace` to do some truly evil things. Consider this: ``` namespace exp *;namespace en cr -c ? ``` After that, `?` is now a magical command that lets you abbreviate any global Tcl command, and all without the nasty uncertainty of messing around with `unknown`. [Answer] On my answer <https://codegolf.stackexchange.com/a/107557/29325> I can demonstrate: 1. Usually `set j 0;while \$j<$n;{...;incr j}` is shorter than the equivalent `for {set j 0} {$j<$n} {incr j} {...}` 2. When the looping variable begins at 1, we can do the increment as part of the `while` test condition, avoiding to write before `set i 1` unnecessarily: `while {[incr i]<=$n} {...}` instead of `set i 1;while \$i<=$n;{...;incr i}` **ATTENTION**: One can only do 2. in the case of an outer loop! I could not apply it to my `j` variable as it needs to be reset to 1 in the outside of its own inner loop! And `incr j` would acquire the value that was set on the last step of the inner loop, instead of grabbing an **undefined** variable `j` to assume `0` and increment it to `1`! [Answer] Sometimes it is worth to use `time {script} n` where `n` is the number of iterations instead of a normal `while` or `for` loop. Although `time`'s purpose is not looping, the achieved effect is the same. I made changes recently to my own answers following this direction. **UPDATE:** I've just discovered an easy to fall pitfall: You can not replace a `for` or a `while` by a `time` block, if it contains a `break` or a `continue`. [Answer] Use the interactive shell. This allows you to abbreviate the command names as long as only 1 command starts with the remaining letters. Example: * `gets` -> `ge` * `lassign` -> `las` * `expr` -> `exp` * `puts` -> `pu` And interactive solutions are free :P **Background**: When `tclsh` runs with a terminal as input device, it sets the variable `tcl_interactive` to `1`. This causes `unknown` (default procedure that will be called if a command can not be found) to search for commands that starts with that name. Downside: it will print the result of every line, use `;` instead of newlines. Ohh, and it might invoke external commands like `w`, which is a good abbreviation of `while`. [Answer] # else is optional As it is said on [if manual page](https://www.tcl.tk/man/tcl/TclCmd/if.htm), `else` is implicit on `if` block constructs. So what is `if ... {} else {}` can become `if ... {} {}` as you can see on some of my answers. [Answer] I'm using Tcl 8.0.5, but I believe the following are applicable to all recent versions. 1. Use `rename` to rename `rename`: ``` rename rename & ``` The `&` can be any identifier; `&` just reminds me of "references" in C. 2. Use the renamed `rename` to rename `set`: ``` & set = ``` Again, the `=` can be any identifier; `=` is just intuitive to me. 3. Now, rename other commands that are worth renaming, *e.g.* ``` & regsub R & string S & while W ``` A command is worth renaming if, given its length *n*, and occurrences *k*, *k(n-1)-(n+4) > 0*. Solving for *k*, the formula becomes `k > (n+4)/(n-1)`. Here's a reference table that makes it easy: ``` length of minimum example(s) command occurrences ------------------------------------------------ 2 6 if (consider renaming to "?") 3 4 for, set (consider renaming to "=") 4 3 eval, expr, incr (consider renaming to "+"), info, join, proc, puts, scan 5 3 break, catch, lsort, split, subst, trace, unset, while 6 3 format, lindex, lrange, regexp, regsub, rename, return, string, switch 7 2 foreach, lappend, linsert, llength, lsearch, unknown . 2 lreplace . 2 continue . 2 ``` 4. Next, compact frequently used subcommands like ``` = I index = L length ``` so you can do things like ``` S $I $x 7 S $L $x ``` 5. Some obvious miscellanea: 1. `lappend` can set the first element of a list if it doesn't yet exist (no need to initialize). 2. You can set arrays without using `array`, *e.g.* `set doesNotExist(7) 43`. 3. You can use strings (`"a b c"`) instead of `[list a b c]`. 4. You can interpolate in strings like so: `foo${a}bar`. 5. You can use `two\ words` rather than `"two words"`. (Remember in general that for contiguous strings without spaces, double quotes can be omitted!) 6. You can almost always rewrite `for`s as `while`s to save a character or two, since a `while` can simultaneously check and increment while a `for` uses separate blocks. 6. For larger programs, here's a trick I thought of but haven't yet applied: ``` proc unknown {c args} {eval [info commands $c*] $args} ``` This emulates interactive command abbreviations! It costs 54 characters, but now you can use `j` for `join`, `sp` for `split`, `st` for `string`, `w` for `while`, and so on. [Answer] May be it should be integrated on another answer, but here it goes: When a `proc` has only one parameter it could be written as ``` proc p a {DO THINGS} ``` instead of ``` proc p {a} {DO THINGS} ``` --- The same applies to a two parameters `proc` using a backslash; it can be written as ``` proc p a\ b {DO THINGS} ``` instead of ``` proc p {a b} {DO THINGS} ``` --- For an higher number of parameters the `{}` render shorter code. [Answer] Sometimes it is worth to replace the two `set` statements to concatenate strings by only one `lappend` statement. On a construction like, one can substitute ``` set s "" loop { # ... set s $s\X } ``` by ``` loop { # ... append s X } ``` The `append` command has an `incr` like behaviour, which initializes a not yet defined variable. Take care to not mistake `append` by `lappend` [Answer] If you are handling a list with an operation that syntactically is interleaving between each element, sometimes you can `join` elements to do a specific operation, instead of traversing it. On <https://codegolf.stackexchange.com/a/127042/29325> there is an example: ``` puts \n[expr [join [split [read stdin]] +]] ``` It `read stdin` gives `23 214 52` then split will give the list `{23 214 52}`. **After, `[join {23 214 52} +]` will return the string `23+214+52`.** Finally `expr 23+214+52` does the job of summing [Answer] If you have large codes, it's possible to avoid multiple usages of `expr` using `namespace pat tcl::mathop` at the beginning. It provides prefix-syntax operation as a regular Tcl fonction. For example: ``` namespace pat tcl::mathop set sum [+ 1 2 3] set prod [* {*}{1 2 3 4}] puts $sum\ $prod ``` [See official mathop doc page](https://www.tcl.tk/man/tcl8.6/TclCmd/mathop.htm) [Answer] When you have several variables that are been `set` on subsequent lines you can use one `lassign` instead of several `set` instructions to achieve the same effect. One example is my own answer <https://codegolf.stackexchange.com/a/105789/29325> To decide, one just needs to weight the number of variables (assuming 1 letter variables, as it is expected when golfing): * <5, `set` is golfier * =5, `set` and `lassign` generate the same byte count * >5, `lassign` is golfier ]
[Question] [ Chaim Goodman-Strauss, Craig Kaplan, Joseph Myers and David Smith [found](https://cs.uwaterloo.ca/%7Ecsk/hat) the following simple (both [objectively](https://en.wikipedia.org/wiki/Simple_polygon) and subjectively) polygon that tiles the plane, but only aperiodically: ![](https://i.stack.imgur.com/y926j.png) Indeed they found a one-parameter family of such aperiodic monotiles or "einsteins". The edges of all tiles in this family meet at 90° or 120° and are made out of two distinct lengths: ![](https://i.stack.imgur.com/hsp4K.png) Let \$a\$ and \$b\$ be nonnegative real numbers and define the following turtle graphics commands: * \$A,B\$: move forwards by \$a\$ or \$b\$ respectively (blue and purple edges in the image above) * \$L,R\$: turn left or right by 90° respectively * \$S,T\$: turn left or right by 60° respectively Then the aperiodic tile \$T(a,b)\$ associated with \$a\$ and \$b\$ is traced by the command sequence $$ASAR\ BSBR\ ATAL\ BTBR\ ATAL\ BTBBTBR$$ It is clear that \$T(a,b)\$ is similar to \$T(ka,kb)\$ for any scaling constant \$k\$, so we can reduce the number of parameters to one by defining $$T(p)=T(p,1-p)\qquad0\le p\le1$$ The tile in this challenge's first picture – the "hat" of the GKMS paper – is \$T\left(\frac{\sqrt3}{\sqrt3+1}\right)\$. \$T(0)\$, \$T(1)\$ and \$T(1/2)\$ admit periodic tilings, but the first two of these exceptions are polyiamonds and play a central role in the proof that \$T(p)\$ for all other \$p\in[0,1]\$ is aperiodic. ## Task Given a real number \$p\$ satisfying \$0\le p\le1\$, draw \$T(p)\$ as defined above. * The image can be saved to a file or piped raw to stdout in any common image file format, or it can be displayed in a window. * The polygon may be drawn in any orientation and may be flipped from the schematic above (though of course the aspect ratio must not be changed). It may be filled with any colour or pattern and may optionally be outlined with any colour, but the polygon's boundary must be clear. * Raster images must be at least 400 pixels wide, and an error of 2 pixels/1% is allowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins. ## Test cases | \$p\$ | \$T(p)\$ | | --- | --- | | 0 | | | 0.2 | | | \$\frac1{\sqrt3+1}=\$0.36602540378443865 | | | 0.5 | | | \$\frac{\sqrt3}{\sqrt3+1}=\$0.6339745962155613 | | | 0.8 | | | 1 | | [Answer] # JavaScript (ES6), 150 bytes *-10 thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)* Generates a SVG. ``` with(Math)f=p=>`<svg viewBox="-1 -1 9 9"><path d="M0 0${"0354105723572".replace(/./g,v=>`l${(d=v&4?p:1-p)*cos(a+=PI/=v%4*5%9-3)} ${d*sin(a)}`,a=0)}">` ``` [Try it online!](https://tio.run/##DYzbCoMgAEB/RaSGtixbxdbIBnvbw2CfkJhdhqRk2CD69hac83Y4X@64FdNgZjLqRu77Msw9evO5xy0zrKpL6zrgBrk89Y9BkoCDAhSwKs0RgYbBNwXUWyFN8yyh@fWSHsJokkZxIVEcxV3ojpHyVtQwd8oe5p4QgwOhLeJn9nnFzPlZkPsFSfEGvLUJ7DAijrc65IziDVb1LvRotZKR0h1qEY1uGO9/ "JavaScript (Node.js) – Try It Online") ### Move encoding Each move is encoded with a 3-bit value \$v\$ stored as a single decimal digit. ``` Bit: 2 1 0 | \_/ | | | +--> rotation angle **a** (00: **-π/3**, 01: **π/2**, 10: **-π/2**, 11: **π/3**) +-----> distance **d** (**p** if set, **1-p** otherwise) ``` We use the expression \$\big(((v\bmod 4)\times 5)\bmod 9\big)-3\$ to convert \$v\$ into the divisor of \$\pi\$: ``` v mod 4 | *5 | mod 9 | -3 ---------+----+-------+---- 0 | 0 | 0 | -3 1 | 5 | 5 | 2 2 | 10 | 1 | -2 3 | 15 | 6 | 3 ``` This is implemented as `Math.PI/=v%4*5%9-3`. Although `Math.PI` is read-only, this is a valid syntax which (fortunately!) doesn't modify the value of \$\pi\$ and is one byte shorter than using parentheses. ### Drawing Once we have \$d\$ and \$a\$, we compute \$(dx,dy)\$ with: $$dx=d\times\cos(a)\\dy=d\times\sin(a)$$ and append a statement `l dx dy` to the SVG path. ### Animated output ``` with(Math)f=p=>`<svg viewBox="-1 -1 9 9"><path d="M0 0${"0354105723572".replace(/./g,v=>`l${(d=v&4?p:1-p)*cos(a+=PI/=v%4*5%9-3)} ${d*sin(a)}`,a=0)}">` k = 0; setInterval(_ => { p = 0.5 + 0.5 * Math.cos(k += 0.04); document.body.innerHTML = `<p style="margin-bottom:-40px">p = ${p.toFixed(2)}</p>` + f(p); }, 20) ``` [Answer] ## Logo, 133 bytes ``` to s:a:n:m fw:a*150 rt:n*60-60 fw:a*150 rt:m*90-90 end to t:a s 1-:a 2 2 s:a 0 2 s 1-:a 0 2 s:a 2 0 s 1-:a 2 2 s:a 2 0 s 1-:a 2 1 end ``` Unfortunately the online logo resource I used to use is no longer available, but you can paste the code into the textbox on <https://rmmh.github.io/papert/static/> and run it. (Also paste the following code to actually get anything to run.) ``` clear t 0.5 ``` (Substitute your desired value for `0.5`.) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 112 bytes ``` (q=1-#;r=Pi/2;t=Pi/3;AnglePath@MapThread[List,{{#,#,q,q,#,#,q,q,#,#,q,2 q,q},{0,-t,r,-t,r,t,-r,t,r,t,-r,t,t}}])& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n65g@1@j0NZQV9m6yDYgU9/IugREGVs75qXnpAYAVTr4JhaEZBSlJqZE@2QWl@hUVyvrKOsUAiEqbaQAZNfqVBvo6JboFEGIEh1dEAFnlNTWxmqq/Q8oyswrcUh3MNCz@A8A "Wolfram Language (Mathematica) – Try It Online") With TIO output is a list of vertices. With Mathematica desktop: ``` data = {0.0, 0.2, 0.366, 0.444, 0.5, 0.634, 0.8, 1.0}; Multicolumn[ Row@{#, Graphics[{Blue, Polygon@g@#}]} & /@ data, 4] ``` [![enter image description here](https://i.stack.imgur.com/xIFfj.jpg)](https://i.stack.imgur.com/xIFfj.jpg) [Answer] # Python, ~~123~~ 118 bytes ``` from turtle import* def t(a): m=13609645555;reset() while m:fd([1-a,a][m>>2&1]*150);rt((m%4*5%9-3)*30);m>>=3 home() ``` The magic number stores every combination of turtle forward and turn command in three bits: * the highest bit says whether to use `fd(a)` or `fd(1-a)` * the lower two select a right turn by a computation similar to that of Arnauld The double forward motion would break that rhythm. To avoid that, the drawing is started at the point immediately after, and as the final move it is implemented with `home()`. [![enter image description here](https://i.stack.imgur.com/OQiuB.png)](https://i.stack.imgur.com/OQiuB.png) [Answer] # [R](https://www.r-project.org/), ~~111~~ ~~100~~ 97 bytes ``` function(p,t=utf8ToInt("GEUSKMYSKMDYSG"),u=t%%4-2,`?`=cumsum)plot(?((u>0)-u*p)*1i^?t%%7/3-1,,"l") ``` [Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=gkms%3D%0Afunction(p%2Ct%3Dutf8ToInt(%22GEUSKMYSKMDYSG%22)%2Cu%3Dt%25%254-2)plot(cumsum(1i%5Ecumsum(t%25%257%2F3-1)*((u%3E0)-u*p))%2C%2C%22l%22)%0A%0Agkms(0.4)) 'Roll-your-own' turtle-graphics-like approach using complex numbers: less than half the length of the `TurtleGraphics`-package approach below. **How?** We use the code `M`=LA, `E`=RA, `S`=RB, `U`=SA, `Y`=TA, `G`=SB, `K`=TB, `D`=TAA. The Utf8 codepoints (`t`) modulo-3 minus 1 (`%%4-2`) then give `-1`, `-2` or `1` to indicate step-lengths of `p`,`2p` or `1-p`, decoded using `(u>0)-u*p`. The Utf8 codepoints modulo-7, divided by 3, minus 1 give `-1`, `-2/3`, `2/3` and `1` corresponding to the powers of `i` to turn the correct number of degrees. We then just take the cumulative sum and plot lines joining all the points on the complex plane. --- # [R](https://www.r-project.org/) + `TurtleGraphics`, ~~256~~ 254 bytes ``` function(p,f="forward(x",g="left(x",`+`=function(i,j)sub("x",j*10,i))eval(parse(t=paste("turtle",c("init(",c(f+p,f+(1-p),g+9,g+27,g+6,g+30)[c(1,5,1,4,2,5,2,4,1,6,1,3,w<-c(2,6,2),4,1,6,1,3,w,w,4)],"hide()"),sep="_",collapse=");"))) library(TurtleGraphics) ``` [Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=gkms%3D%0Afunction(p%2Cf%3D%22forward(x)%22%2Cg%3D%22left(x)%22%2C%60%2B%60%3Dfunction(i%2Cj)sub(%22x%22%2Cj*10%2Ci))eval(parse(t%3Dpaste(%22turtle%22%2Cc(%22init()%22%2C%22hide()%22%2Cc(f%2Bp%2Cf%2B(1-p)%2Cg%2B9%2Cg%2B27%2Cg%2B6%2Cg%2B30)%5Bc(1%2C5%2C1%2C4%2C2%2C5%2C2%2C4%2C1%2C6%2C1%2C3%2Cw%3C-c(2%2C6%2C2)%2C4%2C1%2C6%2C1%2C3%2Cw%2Cw%2C4)%5D)%2Csep%3D%22_%22%2Ccollapse%3D%22%3B%22)))%0Alibrary(TurtleGraphics)%0A%0Agkms(0.7))\* \*The rdrr.io output isn't perfect, but you can scroll to the bottom to see the image of the tile. On my local installation, the output of `gkms(0.6)` is this: [![enter image description here](https://i.stack.imgur.com/RCggx.png)](https://i.stack.imgur.com/RCggx.png) [Answer] # LOGO, ~~74 73~~ 72 bytes Answering 3 months after the original post, but the shortest answer so far. online interpreter at <https://www.calormen.com/jslogo/> ``` TO h :p repeat 14[fd(:p-(#%4%3>0))*200rt(3-#%2)*30*-1^(1149/2^#%2>1)]end ``` clear screen and call the function by adding the following below the function declaration: ``` cs h 0.634 ``` use `ht` and `st` to hide and show the turtle. LOGO is an obvious choice for this challenge, but has some issues. Firstly, the iteration number (available in `#`) is 1-indexed. Secondly, arithmetic is done in real numbers - hence of use of the `>` to truncate an expression to `0` or `1`, as the `int` and logic operators are rather verbose. An interesting feature is use of sidelength expressions `p` and `p-1`. The negative sidelength `p-1` instead of `1-p` means that these sides get drawn with the turtle moving backwards. As each change of sidelength occurs at a 90 degree rotation, this can be compensated for by performing the 90 degree rotations in the opposite direction. The shape is condidered to have 14 sides with one 0 deg vertex, seven 60 deg vertices and six 90 deg vertices. We start at the 0 deg vertex facing in a northward direction, so the shape is rotated 60 degrees anticlockwise from the orientation in the question. The rotations alternate between 60 deg and 90 deg at each turn, and the length expressions alternate between p-1 and p at every second turn. We start with the turtle facing north and go south (backwards) `-(p-1)` then southwest `-(p-1)` leaving the turtle facing northeast after moving backwards in a generally clockwise direction. To continue moving in a clockwise sense we now turn the turtle 90 degrees LEFT (northwest) and continue in a forward direction by distance `p`. We follow the pattern in the question (shifted so that the 0 deg rotation occurs at the beginning/end) with the following substitution to encode the direction of rotation: ``` S=1 T=0 L=0 R=1 BTBR ASAR BSBR ATAL BTBR ATAL BTB 0 1 1 1 1 1 0 0 0 1 0 0 0 ``` This in reverse gives the constant `1000111110` to which we append an extra digit 1 giving `10001111101`=1149, as the fact that `#` is 1-indexed means we start by dividing by 2 on the first iteration. The expression `1149/2^#` always gives a noninteger when taken mod 2 because the real arithmetic does not discard fractional digits. Hence we can test for a 1 bit using `>1` (strictly greater than 1.) **Commented code** ``` TO h :p repeat 14[ ;iterate through sides #=1 through #=14 fd(:p-(#%4%3>0))*200 ;forward p if #%4 = 0 or 3, back 1-p if #%4 = 1 or 2. Scale factor 200 rt(3-#%2)*30*-1^(1149/2^#%2>1) ;turn 90 if # even, 60 if # odd. direction given by -1^(0 or 1) ] ;decode the direction in binary from constant 1149 by dividing by 2^# and taking mod 2 end ``` [Answer] # [Desmos](https://www.desmos.com/calculator), 168 bytes ``` n=[1...14] m=\cos(1.6n)+2 s(x)=\sum^n_{i=1}x[i] a=s(\frac\pi{[.5,2,-2,3,2,3,-2,3,2,-3,2,-3,2,3]}) f(p)=\operatorname{polygon}(s([1-p,p][m]\cos(a)),s([1-p,p][m]\sin(a))) ``` [Try it online!](https://www.desmos.com/calculator/rkjgqyn9va) ]
[Question] [ As input you will be given a ragged list of positive integers containing at least one integer at some level. For example: ``` [[],[[1,2,[3]]],[]] ``` You should output the depth of the least deep integer. For example if the input is just a list of integers, then the every integer is 1 level deep so the answer is 1. There may be a tie for the crown of least deep but it doesn't matter since we only need to output the depth not the least deep integer itself. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being the goal. ## Test cases ``` [1] -> 1 [[[[1]]],[]] -> 4 [[[[1]]],[[]]] -> 4 [[[[1]]],[1]] -> 2 [[[6],1,2,3,[4,5]]] -> 2 [[],[[1,2,[3]]],[]] -> 3 [[[[]]],[2]] -> 2 ``` [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` f=lambda a:min(a)<[]or-~f(sum(a,a)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY1NCsIwFIT3PUWomwRSIW0VKcYLeIQQNGJDA2kS2tTixou46UY8U29jfxQ7q8c382aeb3f3hTVx170aL6Ndv5JUi_JyFUBkpTJQoD3jtooeEtZNCQUWCH2jx7ZQOgckC8AghS2goBLtSRnXeIjWtdPKwxBEBxCiKeMqZTyUML8JDRVClE6X_VV2_ZkRPj6QgA0inHPM-ETSBSEzike05ZjgGCeYpXjD_8YQY6PBkkVJEsxDHw) #### Old [Python 2](https://docs.python.org/2/), 36 bytes ``` f=lambda a:min(a)<[]or-~f(sum(a,[])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY1BDoIwFET3nKIhLtqkmBTQGGK9gEdoGq0RQpPSNlAkbryIGzbGM3EbC2hkVj9v5s883_buSqPjvn-1roh2w6qgSlSXqwAiq6SGAu0ZN3X0KGDTVlBgxhH6Zo9dKVUOSBYAL4kNoKAW3Ulq2zqI1o1V0sEQRAcQoilja6kdLGB-EwpKhCidLvOr7IczI3x8IAHzIpxzvziRdEHIjOIRbTkmOMYJZine8L_hY2w0WLIoSYJ56AM) ## [Python](https://www.python.org), 45 bytes ``` f=lambda a:int in map(type,a)or-~f(sum(a,[])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY1BDoIwFET3nKJx9ZsUkwIaQ1K3HqJpYo00NCm0gaJh40XcsNE7cRsLaGRWP2_-zDzfrvelrYfh1XkVH8ZYMSOry1UimevaI12jSjrwvSuIxLaJHwrargJJuMD4GzrdS20KRPMIBWliEQtB13nA29YZ7WGD4iPa4Nl3TSgGBcVNGtAYMzZf9lc3jGdOxRSgEQ-iQoiwNpNsReiCkgntBaEkISnhGdmJvxHe-GTwdFWSRsvQBw) #### Old [Python](https://www.python.org), 46 bytes ``` f=lambda a:int in map(type,a)or 1+f(sum(a,[])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY1BCoMwFET3nuLjKqFRiNpShHTbQ4RAU2owoCZobPEs3bhp7-RtGrWlzurz5s_M820HV5pmHF-9U9FxihWrZH29SZC5bhzoBmppkRtsQSQ2LdCdQl1fI0m4wPibOj9KXRVA8wC8NDHAfNL2DuG4s5V2KIToBCFefNv6ZqRQcZcV0hgztlzmVzdOF07FHKAB96JCCL-2kGxD6IqSGR0EoSQhKeEZ2Yu_4d_4bPB0U5IG69AH) Outputs True for 1. Does a bfs for integers. ### Details: The bfs, or breadth first search, is implemented as follows: If there is an int at level 1 return 1. If not there are only lists; we can sum (concatenate) them; this eliminates depth 1 nodes, combines all former depth 2 nodes into the new depth 1 tier and pulls each level below up one tier. We can now recursively repeat until we find the first integer. Shortcuts in Python 2: Python 2 but not Python 3 has a total ordering on all objects, in particular, every list is greater than every integer. The type check can therefore be cheaply done using min. And one dirty trick: The `sum` function is meant for numbers. If you apply it to lists you explicitly have to set the starting value from `0` to `[]`. But, technically, any list will do, so to save a byte we use `a` itself instead. While this is rather dirty one can check that it leaves the `min` unchanged. [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 4 bytes ``` ŒJẈṂ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLFkkrhuojhuYIiLCIiLCIiLFsiW1tbMV0sMixbWzMsNF1dXV0iXV0=) -1 byte thanks to Razetime ``` ŒJẈṂ Main Link ŒJ Get the multidimensional index of each scalar value Ẉ Length of each coordinate = depth of each value Ṃ Minimum ``` [Answer] # [R](https://www.r-project.org/), ~~66~~ ~~60~~ 57 bytes ``` f=function(l)"if"(all(Map(is.list,l)),1+f(unlist(l,F)),1) ``` [Try it online!](https://tio.run/##jc5BCsIwEAXQvacodTMfByFJdefWnYcowkBgiGLb86dNoiKtRTdh/uTB/EeMcpIhXHt/C6SovdTUqtKlvZPv9uq7nhVgsxMaQoqkfE4LRKGcDVBtK7N5xtkz/YLzhOyan@6F/9OmQLuEx6kkW3bFNXzAN/p5NPE8uFlpt1Ljzexqi3J8AeMI "R – Try It Online") -3 bytes thanks to pajonk. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes ``` Min[1+#0/@-1^#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983My/aUFvZQN9B1zBOOVbtf0BRZl5JtLKCrp1CWrRybKyCmoK@g0J1tWGtDpAE0bUgVi0q1xDKNwNShjoKRjoKxkC@iY6CKUS@GkxAZKqNYUbU/gcA "Wolfram Language (Mathematica) – Try It Online") Abuses the fact that `f/@a = a` for any atomic `a`. [Answer] # JavaScript, 35 bytes ``` f=x=>x.at?Math.min(...x.map(f))+1:0 ``` `x.at` is a method (truthy) if `x` is an Array (requires a newish browser) and is `undefined` (falsy) if `x` is a Number. The rest is straightforward. ``` f=x=>x.at?Math.min(...x.map(f))+1:0 testcases = [[1], [[[[1]]],[]], [[[[1]]],[1]], [[[6],1,2,3,[4,5]]], [[],[[1,2,[3]]],[]]] console.log(testcases.map(f)) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ⁽LÞZfg ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigb1Mw55aZmciLCIiLCJbW10sW1sxLDIsWzNdXV0sW11dIl0=) Can’t be bothered trying to add an explanation on mobile, feel free to edit one in. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 27 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⌊/(⍵∊⎕d)/+\1 ¯1 0['[]'⍳⍵]} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37U06Wv8ah366OOrkd9U1M09bVjDBUOrTdUMIhWj45Vf9S7GSgZWwsA&f=S1NQjzaMVVd41DtXQddOwZArDSgABIaxsbE60bEIGRNUGUMkKSOolFmsjqGOkY6xTrSJjmkspgKgtmiQgmhjdMONuQA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ ~~14~~ 13 bytes ``` ≬ƛƛ;⁼;A⁽ÞfŀL› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiazGm8abO+KBvDtB4oG9w55mxYBM4oC6IiwiIiwiW1tdLFtbMSwyLFszXV1dLFtdXSJd) Feels too long. Vyxal parsing isn't janky at all why would you even think that? ## Explained ``` ≬ƛƛ;⁼;A⁽ÞfŀL› ≬......⁽..ŀ # call function ≬ on the input until the result of function ⁽ is falsey ≬ # a function that: (this is the predicate for ŀ) ƛƛ;⁼; # checks whether each item is a list - an empty map over a list equals itself A # and returns whether all items are truthy under that # ---------------------------------------------------- # N.B. The ≬ modifier (next 3 elements as a lambda) is used here because of the way map lambdas are parsed: # Rather than treating them as their own structure type internally, # they are converted to a lambda structure # followed immediately by a token representing the `M` (map) element. # This means that map lambdas are considered to be 2 elements # ‡ doesn't work because it doesn't catch the extra `M` # token generated while parsing. # ------------------------------------------------------ ⁽Þf # a function that flattens its argument by 1 depth L› # the length of the list collected by ŀ + 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` d[¼D1å#€`}¾ ``` [Try it online](https://tio.run/##yy9OTMpM/f8/JfrQHhfDw0uVHzWtSag9tO///@joWJ3oaEMdI51o49hYIDs2FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/lOhDe1wMDy9VftS0JqH20L7/OnqHtv6PjjaM1VGIjgbRsbE60bEoPEMo1yxWx1DHSMdYJ9pExzQWIgiUjgYJRhtDNcYCAA). **Explanation:** ``` d # Transform all integers to 1s in the (implicit) input (with >=0 check) [ # Loop indefinitely: ¼ # Increase the counter variable (implicitly starts at 0) D # Duplicate the current list 1å # Check if it contains a 1 # # If it does: stop the infinite loop €` # Flatten the list one level down }¾ # After the loop, push the counter variable # (after which it is output implicitly as result) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 32 bytes ``` \d+ $'¶ 1A` +`[^][¶]|\[] O` \G] ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tF/dA2LkPHBC7thOi42OhD22JrYqJjubj8E7hi3GP//482jOWKBgLD2NhYnehYZA6Qh8w1hPDMYnUMdYx0jHWiTXRMISpAakFi0cZQQwA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $'¶ 1A` ``` Get all the suffixes of the integers. ``` +`[^][¶]|\[] ``` Delete everything except unbalanced `]`s. ``` O` \G] ``` Output the smallest depth. [Answer] # [Ruby](https://www.ruby-lang.org/), 43 bytes ``` g=->l{l.any?{|x|x*0==0}?1:1+g[l.flatten 1]} ``` [Try it online!](https://tio.run/##bc1BCsIwEAXQvacIdGN1DJ0kuhBiDxJmEUWzCaVIhZa2Z49pFmqws/zv8@f5ug4hOH24@NFz2wz1OPVTv6u0ruYaz7h3xvOHt113bxjSHDYtc/xmvd8aJFayAn@SeEhEYCiRWqNoEdcNE4mMTgQIAiQYBUf6LyyTS8HIz@dC5uMJBFGZx@qbhzc "Ruby – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~36~~ 30 bytes ``` !l::Int=0 !l=1+min(Inf,.!l...) ``` [Try it online!](https://tio.run/##ZczBCsIwDIDh@54i3anFWOymHgbbfQefoBQprINKrGOr4tvP1R0cmFP4fpLbk7xV73lmVFVtiPUhY1Sr3d0H3oYeJSMppZj7xwjkgwMfYHS2S/vERQbLWLxCDdNAPvLkCDnsG8jXSktzL0v84qKVgx0nx61Y2zD6EClwC3UDjETmQjdrZdK5yvQyyhiD2nzluJGF/kytVCQ6G1RYYIn6iCfzC@k0BV1uHpcf "Julia 1.0 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ;.≜∋ⁱ⁾İ∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w31rvUeecRx3djxo3Pmrcd2TDo47l//9HRxvG6kRHg6hYICMWmRMdi8I1hPDMYnUMdYx0jHWiTXRMoeqAGCQWbYxsCJhtBCQB "Brachylog – Try It Online") Cannot be golfed to `∋ⁱ↖.İ∧≜`, as failing to pre-label the output variable causes it to hang--perhaps because it gets stuck exploring the elements (digits) of the integers themselves ad infinitum? [Answer] # [Whython](https://github.com/pxeger/whython), 26 bytes ``` f=lambda l:1+f(sum(l,l))?1 ``` Idea taken from [loopy walt's Python 2 answer](https://codegolf.stackexchange.com/a/241037/16766), which you should upvote. [Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8GCpaUlaboWu9JscxJzk1ISFXKsDLXTNIpLczVydHI0Ne0NIQpu9qblFynkKGTmKURzKUQbxuoASSAwjI2N1YmOReVGx6IJGML4ZrE6hjpGOsY60SY6pjBVIB0g0WhjVMPAPCMwN9aKS0GhoCgzr0QjTQPoLIijYK4HAA) ### Explanation ``` f=lambda l:1+f(sum(l,l))?1 f= # Define f as lambda l: # a function of one argument, l, a list: sum(l ) # Add (concatenate) each element of l ,l # to l # If all elements of l are lists, this succeeds, # essentially flattening l by one level and concatenating # that to the original l f( ) # Call f recursively on that list 1+ # and add 1 to the result # If there are any integers in l, sum raises an exception ?1 # Catch that exception and return 1 ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 17 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {0∊≡¨⍵:1⋄1+∇⊃,/⍵} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=qzZ41NH1qHPhoRWPerdaGT7qbjHUftTR/qirWUcfKFILAA&f=S1N41DfVK9jfTz3aMFZd4VHvXF07BUOuNIQwEBjGxsbqRMfC5U2wyhsiFBihKjCL1THUMdIx1ok20TGNxaUMaEQ0SFm0MZp1xgA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) A dfn submission which takes a ragged array on the right. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` ≔¹ηW⬤θ⁼κ⁺υκ«≦⊕ηFθFκ⊞υλ≔υθ≔⟦⟧υ»Iη ``` [Try it online!](https://tio.run/##TYw/D4IwEEdn@RQ3XpNzwH8LEzEODibshKHBaglnsS3VwfjZa1EG33J5@eVdq6VrB8kxlt53V4M5gRZF9tQdK8CSGS3BwQbJHnuCioPHQNCLBLyyxUne5/JoWqduyozq/PuxuAwO0Ar43l5AFbyeYp7GuUpq/7RuCELyd1a5zoy4l35ELUQRY53YNZTTitZUb2jbJOLywR8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔¹η ``` Start off with a depth of `1`. ``` W⬤θ⁼κ⁺υκ« ``` While all of the elements of the input are arrays, then: ``` ≦⊕η ``` Increment the depth. ``` FθFκ⊞υλ≔υθ≔⟦⟧υ ``` Flatten the array by one level. (This is only four bytes in trunk Charcoal but unfortunately that's not available on TIO.) ``` »Iη ``` Output the final depth. [Answer] # Python3, 57 bytes: ``` f=lambda x:min(isinstance(i,int)or 1+f(i)for i in x if i) ``` [Try it online!](https://tio.run/##bYy9DsIwDIR3nsJjLLyEAEJIPInlIfxEWKJulGZonz6EpUPFTXf36S4v9T1auOTSWrp94nB/Rpivg5rTSW2q0R4vp6RWcSzg98kppu4U1GAGTaDYcuncJcdeEHdr6vIiQiz/a7/tz0KeDhSIj3SSDe0D/lEO62f7Ag) [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 68 bytes ``` [ 1 swap [ dup [ real? ] ∃ ] [ [ 1 + ] dip flatten1 ] until drop ] ``` Flatten the input by one depth until a number is an element at the surface, keeping track of the number of iterations. This is shorter than the recursive solutions I tried, especially because Factor has no terse way of handling the minimum value of a sequence when it can be empty. (And because recursion is verbose in Factor.) Since `flatten1` postdates build 1525, the one TIO uses, here's a screenshot of running the above code in Factor's REPL: [![enter image description here](https://i.stack.imgur.com/dlPFf.png)](https://i.stack.imgur.com/dlPFf.png) [Answer] # [Perl 5](https://www.perl.org/) List::Util, 43 bytes ``` $_=min map/\d/?$d:9e9+($d+=/,/?0:92-ord),@F ``` [Try it online!](https://tio.run/##Fcy7CoAgFADQX2lwKLpib1CImppqbDKJwAZBU8rv70bnA044b9sikr135krcEdim2UC04CfPU6LzngEbCsEr6m@dwTghSik7BSVUUINsoFVKvT5E468H6TKbJwqxRmP/EumE9Aj2Aw "Perl 5 – Try It Online") Runs through the input as a list of chars. Increases depth `$d` for each `[`, decreases for each `]` since `92-ord` becomes 92 - 91 = +1 for `[` and 92 - 93 = -1 for `]`. Nothing changes for `,` and yield current depths for which the minimum is printed for digits. To run all tests `$d` needs to be reset between each: [Try all test cases online!](https://tio.run/##K0gtyjH9/z@3UiXFWiXeNjczTyE3sUA/JkXfXiXFyjLVUltDJUXbVl9H397AytJIN78oRVPHwe3//2jDWK5oIDCMjY3ViY5F5hhCeGaxOoY6RjrGOtEmOqaxYDGgZDRILNoYqutffkFJZn5e8X9dX5/M4hIrq9CSzByQK/7ruv3XTSzIAQA "Perl 5 – Try It Online") A more sane algorithm would be [this one](https://tio.run/##ZZBNT8JAEIbP9ldMyJK2uljLV0KbFQ7c/OCip7IhqNtmI203u22iKeWnW6eASnAu@77zzL6TjBJ6M2oaU75AXKUyg3StQIt4GjtkRf0rsop87nreREyCo6OzCt8bXtdNaQTcS1MEwXMhN2BjgB1abXe@LtZBMC9TJXRotfFGVwfrqFy5bGe860u2XZpt6HmJrq04144VAeAGOC92Cz4Ap3uO5XPOacT5CR/@5/7vAPL@CR9z6tM@HdBoSEc4esbxa9TyaPCzBvlgz93KavPST4dISoTLZmQVHlskYXg06R680jIr4k63NzYA4kOJ10K8BUAEsiQvUCWoZKZK1F2zzDrUuiCCMexPwc7fbQjAflw8weLOpkYfkuvmK1eFzDPT9B7@Ls/w8N8 "Perl 5 – Try It Online"), but 11 bytes longer. ]
[Question] [ (This challenge is related to the challenge "[Generate the Abacaba sequence](https://codegolf.stackexchange.com/q/68978/53884).") [Zimin words](https://en.wikipedia.org/wiki/Sesquipower) (also called "sesquipowers") are an important idea in the subject of "combinatorics on words". This is because every Zimin word is "unavoidable", meaning that every sufficiently long word over a finite alphabet has a substring that is an "instance" (defined below) of the Zimin word. Remarkably, [*every* binary word of length 29 has a substring that is an instance of the pattern \$ABACABA\$](https://arxiv.org/pdf/1509.04372.pdf#page=94). ### Definitions Zimin words are recursively defined: * \$Z\_1 = A\$ * \$Z\_2 = ABA\$ * \$Z\_3 = ABACABA\$ * \$Z\_4 = ABACABADABACABA\$ * \$\vdots\$ * \$Z\_{n+1} = Z\_n X Z\_n\$ It's a little tricky to formally define what it means to be an "instance" for a word without talking about free monoids and homomorphisms, but it's easy enough to see from some examples. At a hand-wave-y level, a word \$w\$ is said to be an "instance" of a pattern if there's a way to assign a (non-empty) string to each letter of the pattern and recover \$w\$. ### Examples Consider the word `"11211212211221"` on two letters. * It has \$105\$ substrings that are instances of the Zimin word \$Z\_1 = A\$ because every substring is an instance of \$A\$. * It has \$54\$ substrings that are instances of the Zimin word \$Z\_2 = ABA\$—for example, the substring `"212211221"`: $$ 11211\underbrace{21}\_A\underbrace{22112}\_B\underbrace{21}\_A. $$ * It has \$1\$ substring that is an instance of the Zimin word \$Z\_3 = ABACABA\$: $$ 11 \underbrace{2}\_A \underbrace{11}\_B \underbrace{2}\_A \underbrace{12}\_C \underbrace{2}\_A \underbrace{11}\_B \underbrace{2}\_A 21. $$ * It has \$0\$ substrings that are instances of the Zimin word \$Z\_4 = ABACABADABACABA\$. Thus if you are given `"11211212211221"`, you should return `[105, 54, 1]`. ### Challenge This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge will give you a word as an an input, and asks you to output a list of the number of substrings that are instances \$Z\_1, Z\_2, \cdots, Z\_n\$ until there are not any substrings that are instances. That is, your program should never output `0`. You can take the word in any reasonable way: as a string, as a list of strings, as a list of appropriately coded integers, as a pair of integers \$(b,i)\$ where \$i\$ is base-\$b\$ encoded integer, etc. ### Test Data ``` word | zimin_counts(word) -------------------------------+------------------- "" | [] "P" | [1] "MOM" | [6,1] "alfalfa" | [28, 8] "aha aha!" | [36, 9, 1] "xxOOOxxxxxOOOxxx" | [136, 64, 9] "3123213332331112232" | [190, 55, 1] "2122222111111121221" | [190, 80, 3] "13121311213121311212" | [210, 114, 25, 2] "344112222321431121114" | [231, 48] "141324331112324224341" | [231, 49] "344342224124222122433" | [231, 61, 1] "331123321122132312321" | [231, 74] "11221112211212122222122" | [276, 149, 4] "2222222112211121112212121" | [325, 166, 6] "AAAaaAAAAAAAaAaAAaAaAAAAA" | [325, 198, 30] "1100000010010011011011111100" | [406, 204] "1111221211122111111221211121" | [406, 261, 56, 2] ``` [Answer] # [J](http://jsoftware.com/), 63 58 53 52 51 47 bytes ``` _1}.1#.a:~:[:([#~[e.&,(],,)&.>/)^:a:~@;<@(<\)\. ``` [Try it online!](https://tio.run/##PYzRCoIwFIbvfYpTgnMwl2ea2LIQgq4So1utGKFIBN16k6@@pq7G/rOd7zvbUy85aWEngQCDEKRJwOFwOR31HT8cXa7kICvpV@5QNdxj/pUx6vH9it6kUfk2y/2spjXX1Gke3RtaIEVZEGfuCIFAjozMvc8kUovOliWAlkwPJyZSSC1Ur3bcVkQJbP7zqlNgsrAOjUxi42fb92VZ9uOaz9/XGAJiDGINwk5ihMJkKvYiiP4C "J – Try It Online") -2 bytes thanks to Bubbler -3 bytes thanks to FrownyFrog for golfier way to create all substrings of a string. ## how We'll use `MOM` as our example: * `[:...;<@(<\)\.` All substrings of the input, boxed. ``` ┌─┬─┬─┬──┬──┬───┐ │M│O│M│MO│OM│MOM│ └─┴─┴─┴──┴──┴───┘ ``` * `(...)^:a:~` Using the substrings as both the left and right args `~`, apply the verb in parens until a fixed point, keeping track of each iteration's results `^:a:`. * `(...(],,)&.>/)` To create the next "level" of candidates, create all possible combinations that look like `<level_n><orig substring><level_n>` where `level_n` is any element from the current level, and `<orig substring>` is one of the original input substrings (level 0). Then the 1st level looks like: ``` ┌─────┬─────┬─────┬───────┬───────┬─────────┐ │MMM │OMO │MMM │MOMMO │OMMOM │MOMMMOM │ ├─────┼─────┼─────┼───────┼───────┼─────────┤ │MOM │OOO │MOM │MOOMO │OMOOM │MOMOMOM │ ├─────┼─────┼─────┼───────┼───────┼─────────┤ │MMM │OMO │MMM │MOMMO │OMMOM │MOMMMOM │ ├─────┼─────┼─────┼───────┼───────┼─────────┤ │MMOM │OMOO │MMOM │MOMOMO │OMMOOM │MOMMOMOM │ ├─────┼─────┼─────┼───────┼───────┼─────────┤ │MOMM │OOMO │MOMM │MOOMMO │OMOMOM │MOMOMMOM │ ├─────┼─────┼─────┼───────┼───────┼─────────┤ │MMOMM│OMOMO│MMOMM│MOMOMMO│OMMOMOM│MOMMOMMOM│ └─────┴─────┴─────┴───────┴───────┴─────────┘ ``` * `[#~[e.&,...` Check if each original substring is an element of this candidate list `[e.&,`, and use that to filter the original substrings `[#~`. In the above example, only `MOM` passes. * After the above process iterates to its fixed point (no more matches), the result is: ``` ┌───┬─┬─┬──┬──┬───┐ │M │O│M│MO│OM│MOM│ ├───┼─┼─┼──┼──┼───┤ │MOM│ │ │ │ │ │ ├───┼─┼─┼──┼──┼───┤ │ │ │ │ │ │ │ └───┴─┴─┴──┴──┴───┘ ``` * `a:~:` Since we don't want to count empty boxes, we perform an elementwise test for "not equal to the empty box `a:`", giving us a 0-1 matrix: ``` 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 ``` * `1#.` Sum rows: ``` 6 1 0 ``` * `_1}.` And kill the last element: ``` 6 1 ``` [Answer] # JavaScript (ES6), ~~148 142~~ 141 bytes *Saved 6 bytes thanks to @user81655* Expects an array of characters. ``` f=(a,o=[],s='')=>a.map(c=>{for(s+=c,i=p='';s.match(`^${p+='(.+)'+p.replace(/\(.../g,_=>"\\"+n++)}$`);n=1)o[+i]=-~o[i++]})+a?f(a.slice(1),o):o ``` [Try it online!](https://tio.run/##jZJvT8MgEMbf@ymQmAwCdh6wfxrmJzDzfVcdqeusqaNZjVli9KvPY50zUTa9FAohv4fn7nhyr67JV2X9cr70D/PNprDMSW/TTDa20@F27JJnV7Pcjt8Kv2KNsLksbY1nVw2evOSPbHZ39lYL22GJ4B1RJ6t5Xbl8zrpTliRJdyHv7ZhOp1QsheDvZzN@tbTAfSrKzJ5/@LQUInvnwl0XzCVNVSIKXHp@6Te5Xza@mieVX7CCpShHKTkSGeek2yVpdhIhb@k/SIiiN5Mb@ifal3HYVUX46FFYDSUZxvFHR3Cc0mO47ksykiRuYL2eTCbrEO2fRhMPEn2DMlENDUor0ForrQFA4Y7@1hhdSNLrHfKhEMOANsIODmgMceioBqARHNtpt/g2si8mIA@AySg0o@IJGQNbP5iW2eogQH8KaZDExPsCBrQybTVwoXBtIC4wOuRAI6YMBDqUA9WiAn04VNJwPXZEhVTQTtulqMbAxLOAbUPCpOCrQWpX0r3AAN8GGHxgJtt8Ag "JavaScript (Node.js) – Try It Online") ### How? For each substring in the input string, we apply the following patterns while they match: ``` P₀ ^(.+)$ P₁ ^(.+)(.+)\1$ P₂ ^(.+)(.+)\1(.+)\1\2\1$ P₃ ^(.+)(.+)\1(.+)\1\2\1(.+)\1\2\1\3\1\2\1$ ... ``` Apart from the delimiters `^` and `$` which are ignored below, these patterns are built recursively as follows: * \$P\_0\$ is `(.+)` * \$P\_{k+1}\$ is \$P\_{k}\$, followed by `(.+)`, followed by \$P\_k\$ with each \$n\$-th group `(.+)` replaced with the back reference `\{n}` (1-indexed) e.g. for \$P\_2 \rightarrow P\_3\$: ``` (.+)(.+)\1(.+)\1\2\1 -> (.+)(.+)\1(.+)\1\2\1 (.+) ~~(.+)(.+)~~\1~~(.+)~~\1\2\1 \1 \2 \3 ``` It's worth noting that: * if a substring matches some \$P\_i\$, it also matches all \$P\_j,\:j<i\$ * if a substring doesn't match some \$P\_i\$, it also won't match any \$P\_j,\:j>i\$ We keep track of the results in the array `o[]`, which is eventually returned. Whenever \$P\_i\$ matches a substring, we increment `o[i]`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 30 bytes ``` {s{h∧1|~cṪ↺₁hʰb=h↰ᶠ⌉+₁}ᵘ}ᶠcọtᵐ ``` [Try it online!](https://tio.run/##TU69SgNBEH6VcwsbFW5mtlW4BwiXXiw2B7pFQFAhJ2cCXhEMKFha2glWaRSMb@Bb3L7IOT8r@O3s7Px88@3MrkITb@eXFzh2C1ccnRRusZ/W29T3w26zHD6ex@66i@nhDe5WzfD1nta71N/Hn@3sODJv@HxNj5sDLjH3ZclpM3w/3cjceOrcYeGm4ib1RJ4wPxfTMIaC757EbVvXdSuwV2oESAhEhEQAgJxJGTligEEykDIwna@6HCidvAedYC2vZQCvAx4IvUlzgBx7yBPEKXqQqnzALG3IOK8jejxr@6kU6D7iEP72Q9sW87bGMJYcaVZVFUJlCHzMMUy0VIAZmAnK0vpZK2v/S8Gd/QI "Brachylog – Try It Online") * `{s … }ᶠ` for every substring: * `{h∧1| …}` on every non-empty string, return 1. Also try … * `~c` input split into groups, so that … * `Ṫ↺₁…b=` it unifies with `[A,B,A]` (this works, too, but is sadly longer). * `hʰ` B is non-empty * `h↰ᶠ` take `A` and call the predicate recursively, finding all results * `⌉+₁` get the highest number and add 1 * `ᵘ` Find all unique values. So for `aha aha` we get `[1,2,3]` from `[aha aha, aha, a]`. * `cọtᵐ` join the results from all the substrings, count the occurrences of each number, and return them [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 77 bytes ``` K`(.+) /\(/{G` %"$+"~`^ w` "¶0"(Am`^0 K` $+2 (.*?\))+(.*)$ $&¶$&(.+)$2\$#1$2 ``` [Try it online!](https://tio.run/##K0otycxLNPz/3ztBQ09bk0s/RkO/2j2BS1VJRVupLiGOqzyBS@nQNgMlDcfchDgDLu8ELi4VbSMuDT0t@xhNTW0granCpaJ2aJuKGsgAFaMYFWVDFaP//w2NDY2AGExAGUYA "Retina – Try It Online") No test suite because of the advanced use of result history. Explanation: ``` K`(.+) ``` Start by considering matches of Z₁. ``` /\(/{` ``` Repeat while the working area contains a `(`. ``` G` ``` Do nothing. This is here solely to record the value at the start of each pass of the loop in the stage history, so that it can be referred to later on. ``` %"$+"~`^ w` ``` Processing each line of regex separately, evaluate it as an overlapped count command on the original input, thereby returning a list of counts. ``` "¶0"(` ``` If the list contains a `0` (strictly speaking this can only happen on the second pass, as I use a newline to check that it's a leading 0)... ``` Am`^0 ``` ... then delete all `0` values (including the first if the input string was empty), otherwise: ``` K` $+2 ``` Retrieve the value saved in step 2. (Because Retina numbers stages in post-order traversal, this is the `G` command.) Unfortunately `$` doesn't work directly in a `K` command, so the easiest way to do this is to delete the result and then substitute the empty string with the saved value. ``` (.*?\))+(.*)$ $&¶$&(.+)$2\$#1$2 ``` Append an additional regex that matches the next Zimin word. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` āεo<VŒε.œYùεĆ4ô€¨yªεÂQ}P}1å]O0Ü ``` [Try it online](https://tio.run/##yy9OTMpM/f//SOO5rfk2YUcnnduqd3Ry5OGd57YeaTM5vOVR05pDKyoPrTq39XBTYG1AreHhpbH@Bofn/P9vaGgEQkYg0sgQAA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlS5K/480ntuabxN2aN3RSee26h2dHHl457mtR9pMDm951LTm0IrKQ6vObT3cFFgbUGt4eGmsv8HhOf@V9MJ0/kcrKekoKAWACF9/XxCVmJMGQmBmRqICECuC2IaGRiBkBCKNDEEiFRX@/v4VIAChlWIB) (pretty slow, so the larger test cases are omitted in the test suite). **Explanation:** Step 1: Loop over the possible sizes \$n\$ of the \$Z\_n\$ based on the input-length.*†* We can calculate the valid \$n\$ to check with the following formula: \$m = \left\lceil\log\_2(L)\right\rceil\$, where \$L\$ is the input-length, and the result \$m\$ indicates the range \$[1,m]\$ to check for Zimin 'words': \$Z\_{n=1}^m\$. In 05AB1E code, this would have resulted in `g.²îLεo<VŒε.œYùεĆ4ô€¨yªεÂQ}P}1å]O0Ü` (**35 bytes**): [try it online](https://tio.run/##yy9OTMpM/f8/Xe/QpsPrfM5tzbcJOzrp3Fa9o5MjD@88t/VIm8nhLY@a1hxaUXlo1bmth5sCawNqDQ8vjfU3ODzn/39DQyMQMgKRRoYA). *†* Since we have to strip trailing 0s at the end in case no \$Z\$ were found for them anyway, we simply don't calculate this maximum. Instead, we'll just check in the range \$[1,L]\$ for Zimin words. Less efficient in terms of performance, but 4 bytes shorter, which is all we care about with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). :) We can also calculate the amount of parts in the resulting Zimin 'word' (\$Z\_n\$), which is the oeis sequence [A000225](https://oeis.org/A000225): \$2^n-1\$. ``` ā # Push a list in the range [1, (implicit) input-length] ε # Map over each of these integers: o # Take 2 to the power this integer < # Decrease it by 1 V # Pop and store this in variable `Y` ``` Step 2: For each of these amount of parts \$Y\$, we check how many substrings of the input are valid Zimin 'words' (\$Z\_Y\$). Step 2a: We do this by first generating all substrings of the input, and mapping over them: ``` Œ # Get all substrings of the (implicit) input-list ε # Inner map over each substring: ``` Step 2b: Then we'll get all partitions of the current substring of exactly \$Y\$ amount of parts: ``` .œ # Get all partitions of this subtring Yù # Only leave the partitions of `Y` amount of parts ``` Step 2c: We then check for each of these (correctly sized) partitions of this substring if it's a valid Zimin 'word'. We do this by checking two things: 1. Is the current list of parts in this partition a palindrome? 2. Is every \$ABA\$ part within the current partition a palindrome? As for step 2c2, we do so by first adding a dummy trailing item to the partition; then splitting the partition-list into sublists of size 4; then we remove the trailing item from each of these sublists; after which we can check for each \$[A,B,A]\$ sublist whether it's a palindrome. ``` ε # Inner map over each remaining partition: Ć # Enclose the partition; append its own first part at the end 4ô # Split the partition into parts of size 4 €¨ # Remove the final part of each quartet yª # Append the full partition to this list of triplets as well ε # Inner map over this list of lists: # Check if the current list is a palindrome by:  # Bifurcating: short for Duplicate & Reverse copy Q # Check if the list and reversed copied list are the same } # After this inner-most map: P # Check if all were truthy by taking the product ``` Alternatively for step 2c2, `Ć4ô€¨` could have been `4ô3δ∍` instead: Split the partition-list into sublists of size 4 (with 3 in the trailing sublist); shorten each sublist to size 3 by removing trailing item(s); same as above. [Try it online.](https://tio.run/##yy9OTMpM/f//SOO5rfk2YUcnnduqd3Ry5OGd57aaHN5ifG7Lo47eykOrzm093BRYG1BreHhprL/B4Tn//xsaGoGQEYg0MgQA) Step 2d: And we then check if there is at least one valid Zimin 'word' (\$Z\_Y\$) among the mapped partitions for this substring: ``` } # After the map over the partitions of the current substring: 1å # Check if any were truthy by checking if it contains a 1 # (NOTE: we can't use the max builtin `à` here like we usually do when # we want to mimic an `any` builtin, because lists could be empty here, # resulting in an empty string) ``` Step 3: Now we sum the amount of truthy results per size \$Y\$: ``` ] # Close all remaining nested maps O # Sum the inner-most lists together ``` Step 4: And finally we clean-up all trailing 0s (both the \$\geq m\$ sizes we've checked in our golfed approach, as well as any trailing \$Z\$ within the \$[1,m]\$ range that simply resulted in \$0\$), before outputting the result: ``` 0Ü # Remove any trailing 0s from this list # (after which the resulting list is output implicitly) ``` [Answer] # [Python 3](https://docs.python.org/3/), 205 bytes ``` def f(w): R=range(len(w));s=[w[i:j+1]for i in R for j in R[i:]];v=[*s];n=len(s);r=[] while n:r+=[n];s={i+j+i for i in s for j in v if i+j+i in w};n=sum(len({w.find(a,b)for b in R})-1for a in s) return r ``` [Try it online!](https://tio.run/##TVPbkppAEH3nKzq8CHE2Rc@M9yJVfsCWqX1leWB1iBjDWoCrieW3m@4eXNPM5Zy@nGlwPPzptu@1ud02roQyOsXzAF7Spqh/umjvanLEizbNTlk13w0xL98bqKCq4QUY7gRSLM8XH2n2tc0Xdcplbbxo0iwP4LSt9g7qeTNMszonqUs13A0r@BRqH0IfUJXgw8ROV9Jqj7@ljcvpW1nVm6hQbzHnv8nB1/gJmRUiFAfQuO7Y1NDcOtd2LaQQhaGC8Acvz6tn3op9yUPgtgCaXxifz6vV6szmd/YZ1EajMUYbg4iaGLs1ITL0xgzZjZROU5YeSLqxFqWCtKy4Ea0UWDTaemkCmrDFvsIQ1RbZywdQlgS4nNphPar1/YkUSj@8aLz3p323uu/WZ/gsfji4XC6LYumtoMcvZF40EUM/0A@2JPHxXqvX/o9iGAfufHDrzm34V8hyBRnyMlay6amCKQMzVjBTIE5kMrbkEDZLFIxG9xizKU0j5UiIPqMCTQlaXAYV2OkDzj7hGHsRYRMrcEJnoaWjhRrWwTGf/6AzatIkzG1CEZ3YB2bNEYM8iIP11q1/uYbfdPB61BO7HigQhGYQB3xFO@X4kv6tDpHcTQX378P/ODK@rWXUxUIOTVV3UTkIL901hKfvcGmvcOmPyVyatvl1EN/@AQ "Python 3 – Try It Online") *Quite* verbose. Inputs a string and returns a list of the number of substrings that are instances \$Z\_1, Z\_2, \dots, Z\_n\$. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 66 bytes ``` Counts@Level[z@@@Subsequences@#,-3]& z[Longest@a___,__,a___]:=z@a! ``` [Try it online!](https://tio.run/##hU5Na4NAEL37KxoDOSXg7G4vhZSVXBMM5CgiU1ljIDHUjyKW5q/bmR0LpZc@Z@f7PeeGXeVu2F0KnMrttLv3ddfavftw13S01p76t9a9964uXGuX643OVsGY7u/12bWdxTzP12Qcs5ftaHExHZtL3aXLzWtpdxU2WHSuIWq2epwKrB@fQRiug/DI7pAcOOC1ZPNphU/0FpwPQ5IkA0Mi9zQorUBrrbQGAEUVtxVlBBBwBdwGWqfn3Zz4dW0MeAZpGd8GMJ5gQCsj0pQoyg3MDE2lMsBd/gFt@QHT6RzWI67c56XA38NOwc99Sq5V87WyIVv88TCOY8RYgPSJI4ho5AFiIMaIIpnPWrP2r9KLE0vR03M0f@rnf@Zh8DV9Aw "Wolfram Language (Mathematica) – Try It Online") Returns an `Association` with corresponding values. Prepend `List@@` for list output. ]
[Question] [ ## Challenge For each character of the string except for the last one, do the following: * Output the current character. * Followed by randomly outputting from the following list a random number of times between 1 - 5 (inclusive): + The current character + The next character of the string + The switchcase version of the character that you are currently on + The switchcase version of the next character of the string. ## Test Cases `String` --> `SSSTSStrTrIiinIIngn` `, . , . , . Hello world!` --> `,,, .. , ,, .... , , .. .. . HHH HHEeelLlLllooO wwOworOOrrrRllDd!!D` `Programming Puzzles and Code Golf` --> `PrPPrRrOooooogggRgGraAraaaMMMmmmimMIiininGGgG PPPPuZzZZzZzzZzllLLEEeEsEsssS a aANnNddD C COCoooOOdeDe E GGGoOllFFf` ## Notes * You only need to apply the switchcase version of a character if the character is part of the alphabet (A-Z and a-z). * Your random function does not need to be uniform but it still needs to have a chance of returning any element in the list given. * You are allowed to use any standard I/O format. * You may assume that the length of the input is greater than or equal to two. * You may assume that the input only consists of ASCII characters. * The title is not a test case (it is unintentional if it is a valid test case). * Switchcase means to turn the char to lowercase if it is uppercase and to turn it to uppercase if it is lowercase. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 25 bytes ``` ṇ\+†ṅ\⟨)₌¤:~+4ṛ⟨ṛ₌¤⟩ₓ\⟩¦$ ``` [Try it online!](https://tio.run/##S0/MTPz//@HO9hjtRw0LHu5sjXk0f4Xmo6aeQ0us6rRNHu6cDeSDSJDIo/krHzVNBqpYeWiZyv//wSVFmXnpAA "Gaia – Try It Online") *Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for pointing out 2 bugs!* ``` ṇ\ | delete the last character from the input +† | push the input again and concatenate together, so for instance | 'abc' 'bc' becomes ['ab' 'bc' 'c'] ṅ\ | delete the last element ⟨ ⟩¦ | for each of the elements, do: )₌ | take the first character and push again ¤ | swap : | dup ~ | swap case + | concatenate strings 4ṛ | select a random integer from [1..5] ⟨ ⟩ₓ | and repeat that many times ṛ₌¤ | select a random character from the string \ | clean up stack $ | convert to string ``` Note that `4ṛ` is because `ṛ` is implemented for an integer `z` as python's `random.randint(1,z+1)`, which returns an integer `N` such that `1<=N<=z+1`. [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), 23 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") Anonymous tacit prefix function. ``` ∊2(⊣,{?4⍴⍨?5}⊇,,-⍤,)/ ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R24RHHV1GGo@6FutU25s86t3yqHeFvWnto652HR3dR71LdDT1/z/qmwpUl6YeXFKUmZeuzgXj6yjoKcCwR2pOTr5CeX5RTooiQkVAUX56UWJuLlCbQkBpVVVOarFCYl6KgnN@SqqCe35Omvp/AA "APL (dzaima/APL) – Try It Online") `2(`…`)/` apply the following infix tacit function between each character pair:  `-` the switchcase  `⍤` of  `,` the concatenation of the pair  `,,` prepend the concatenation of the pair to that  `{`…`}⊇` pick the following elements from that:   `?5` random number in range 1…5   `4⍴⍨` that many fours   `?` random indices for those `∊` **ϵ**nlist (flatten) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 60 bytes ``` {S:g{.)>(.)}=$/~[~] roll ^5 .roll+1,$/.lc,$/.uc,$0.lc,$0.uc} ``` [Try it online!](https://tio.run/##RYvBCoJAGITvPcUkEi7JWoc6JHbpUEehYxRIrhL8uvJvEir66ptG0WE@PoaZSjFtbdFgkSGC7c67vJNi70nRR24wXIYrWBPhtoGcZLn23UDSfWI9cvXx1ei9NUmDzHPMkx9l7ohw9i18SPxyUkQaL82Uzv8TQzVXIrQx65yTohj/iOu2JWWQlCkOOlU4asre "Perl 6 – Try It Online") The lowercase/uppercase part is kinda annoying. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ;Œsṗ5X¤XṭṖµƝ ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//O8WSc@G5lzVYwqRY4bmt4bmWwrXGnf///1N0cmluZw "Jelly – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 121 bytes *-20 bytes thanks to Nahuel* *-9 bytes thanks to roblogic* ``` for((i=0;i<${#1};i++)){ s=${1:i:1} m=${1:i:2} m=${m,,}${m^^} for((t=0;t++<RANDOM%6;)){ s+=${m:RANDOM%4:1} } printf "$s" } ``` [Try it online!](https://tio.run/##S0oszvifpqFZ/T8tv0hDI9PWwDrTRqVa2bDWOlNbW1OzmqvYVqXa0CrTyrCWKxfKNIIwc3V0aoFkXFwtF1hzCVBziba2TZCjn4u/r6qZNVi7NkilFVTMBGRMLVdBUWZeSZqCkkqxElft/1ourjQF9cS8/JKM1CKFktTiEgU9HYXC8tSikkr1/wA "Bash – Try It Online") ## Original answer # [Bash](https://www.gnu.org/software/bash/), 150 bytes Have done very little golf bashing and trying to improve my bash, so any comments welcome. ``` for((i=0;i<${#1}-1;i++));do c=${1:$i:1} n=${1:$((i+1)):1} a=($n ${c,} ${c^} ${n,} ${n^}) shuf -e ${a[@]} -n "$(shuf -i 1-5 -n 1)"|xargs printf %s done ``` [Try it online!](https://tio.run/##JYpBCsIwEEX3OcWgETLUgLNw01rwDi7FQmybNpupNBWEmLPHxm4e7z/@0/gxWYUh2WlWytWnyl1k2FPUVLmiQKy6SbS1DFRKV1IUvPn6LQgxF1MrySBDe4yZTSb/nZuIwo9vC7pfp7lfHxE0w06qrTogfc6FcPf9mHnw8JodLxYOXnQT9ykKYeG2rHFIPw "Bash – Try It Online") Code is straightforward loop through chars setting current `c` and next `n` character, then creating an array of the 4 possibilities, repeating one of them so there's exactly 5. Next we shuffle that array, and then choose n elements from it, where n itself is random between 1 and 5. [Answer] # [Python 2](https://docs.python.org/2/), 107 bytes ``` f=lambda s:s and s[0]+''.join(sample((s[:2]+s[:2].swapcase())*5,randint(1,5)))+f(s[1:]) from random import* ``` [Try it online!](https://tio.run/##HYs7CsMwEET7nEKddi1jYoMbQU6R0qhYx1aiYH3QCkJOr8hpZgbem/QtrximWu3tIL9uJFizoLAJXq5GSTm8owvA5NOxA/CiJ6P@OfCH0oN4B8Ru7nP7uFBg7GdEVLapozZ4sTl6ccJWzqeYS1dTbqawIO@lrafE@gM "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ü)vyн5LΩFyD.š«Ω]J ``` Inspired by [*@Giuseppe*'s Gaia answer](https://codegolf.stackexchange.com/a/182566/52210). -1 byte thanks to *@Shaggy*. [Try it online 10 times](https://tio.run/##ASsA1P9vc2FiaWX/VEb/w7wpdnnQvTVMzqlGeUQuxaHCq86pfX1K/yz/U3RyaW5n) or [verify all test cases 10 times](https://tio.run/##yy9OTMpM/V9WGWpo4Bbx//AezbLKC3tNfc6tdKt00Tu68NDqcytra73@6/yPVgouKcrMS1fSUQAiPQUY9kjNyclXKM8vyklRBMkFFOWnFyXm5gKVKgSUVlXlpBYrJOalKDjnp6QquOfnpIEUgTUpxQIA). **Explanation:** ``` ü) # Create all pairs of the (implicit) input # i.e. "Hello" → [["H","e"],["e","l"],["l","l"],["l","o"]] v # Loop over each these pairs `y`: yн # Push the first character of pair `y` 5LΩ # Get a random integer in the range [1,5] F # Inner loop that many times: y # Push pair `y` D.š« # Duplicate it, swap the cases of the letters, and merge it with `y` Ω # Then pop and push a random character from this list of four ]J # After both loops: join the entire stack together to a single string # (which is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` FLθ«F∧ι⊕‽⁵‽⭆✂θ⊖ι⊕ι¹⁺↥λ↧λ§θι ``` [Try it online!](https://tio.run/##VY3LCsIwEEXX7VdkOYG6cOHKVcFNoUJp8QNCMraBdNKm8QHit8fEouKFWZwDc68chJNWmBDO1jGokXo/wMw5e@TZW5WkQBesIulwRPKooBWk7Ag7HsMap8l/VOcj9UcxQWe0RJgLdsDfo@b/RYm38RpzWeA0TeikWBBMVLW9fSlln2frUukrUnhP1TrpZwjrathczQs "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FLθ« ``` Loop over all of the indices of the input string. ``` F∧ι⊕‽⁵ ``` Except for the first index, loop over a random number from 1 to 5 inclusive... ``` ‽⭆✂θ⊖ι⊕ι¹⁺↥λ↧λ ``` ... extract the previous and next characters from the string, take the upper and lower case versions, and pick a random character of the four. ``` §θι ``` Print the character at the current index. [Answer] # perl 5 (`-p`), 77 bytes ``` s/(.)(?=(.))/$x=$1;'$x.=substr"\U$1$2\L$1$2",4*rand,1;'x(1+5*rand)/gee;s/.$// ``` [TIO](https://tio.run/##K0gtyjH9/79YX0NPU8PeFkhq6qtU2KoYWqurVOjZFpcmFZcUKcWEqhiqGMX4gEglHROtosS8FB2gkgoNQ21TME9TPz011bpYX09FX////@CSosy8dC58VEBRfnpRYm4ukK0QUFpVlZNarAA0R8E5PyVVwT0/J22wqPiXX1CSmZ9X/F@3AAA) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 14 bytes ``` äÈ+Zu pv ö5ö Ä ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=5MgrWnUgcHYg9jX2IMQ&input=IlN0cmluZyI) ``` äÈ+Zu pv ö5ö Ä :Implicit input of string ä :Take each consectutive pair of characters È :Pass them through the following function as Z + : Append to the first character of the pair Zu : Uppercase Z p : Append v : Lowercase ö : Get X random characters, where X is 5ö : Random number in the range [0,5) Ä : Plus 1 :Implicitly join and output ``` [Answer] # [Python 3](https://docs.python.org/3/), 167 bytes ``` from random import*;c=choice def f(s): i=0;r="" for i in range(len(s)-1): r+=s[i] for j in range(randrange(5)):r+=c([str.upper,str.lower])(c(s[i:i+2])) return r ``` [Try it online!](https://tio.run/##RY2xbsMwDER3fwXhSYrbIE3RxYGnDl2zGx4MmbJZ2KJAyyiSn3coBEgnHu4e7@ItTRw@990LLyB9GPTQElnS4eIaNzE5LAb04M1q6wKoOV2kKcsCPAsQUMhfI5oZgxLvHxkCqZq1pU5Vpn7/qbzwVF/W1oo5065JjluMKG9ZzfyH0lnjjDbUVJ07awsQTJtoyR6FQjLelMpSGEsNX9ZVeJR@WdSH63a/z7iC7sE3Dwg/PHul9wc "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ;;;Œs$Xɗ¥5X¤¡Ɲ ``` [Try it online!](https://tio.run/##AT8AwP9qZWxsef//Ozs7xZJzJFjJl8KlNVjCpMKhxp3///9Qcm9ncmFtbWluZyBQdXp6bGVzIGFuZCBDb2RlIEdvbGY "Jelly – Try It Online") ### Explanation ``` Ɲ | For each overlapping pair of letters ; | Join the first letter to... 5X¤¡ | Between 1 and 5 repetitions of... Xɗ¥ | A randomly selected character from... ;;Œs$ | A list of the two letters and the swapped case versions of both ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~154~~ ~~105~~ ~~103~~ ~~95~~ 87 bytes -67 bytes thanks to mazzy who can't be stopped ``` -join(($x=$args)|%{$_;$x[$i,++$i]*5|%{"$_"|% *wer;"$_"|% *per}|random -c(1..5|random)}) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V83Kz8zT0NDpcJWJbEovVizRrVaJd5apSJaJVNHW1slM1bLFCikpBKvVKOqoAXUaw1jF6QW1dYUJeal5Ocq6CZrGOrpmUK5mrWa/2u5uFSKS4oy89IVbBWUgiGs4vy8dCUuNZU0BQeIHJe6OrIyRydnBRdXNxQl/wE "PowerShell – Try It Online") ~~Not a fantastic method but it works.~~ Now it's pretty good. Takes input via splatting [Answer] # C(GCC) ~~175~~ ~~162~~ 150 bytes -12 bytes from LambdaBeta -12 bytes from ceilingcat ``` f(s,S,i,r,a)char*s,*S,*i;{srand(time(0));for(i=S;s[1];++s)for(r=rand(*i++=*s)%5+1;r--;*i++=rand()&1&&a>96&a<123|a>64&a<91?a^32:a)a=s[~rand()&1];*i=0;} ``` [Try it online!](https://tio.run/##PY7BToQwFEX3fkVDAulrS0JhnKRTO34ES8TkDdKZLqimxdWIv44Fo7ubc@5N7lBeh2FdLY2iFU4EgTDcMLAoWCuY0/cY0L/R2U0jrQC0fQ/UmVbHTvaa8wgbCGYvMce5YRHyRy51KEu9g11BIYsCz@pY4JOsmy88Hw8pKvmMr019QkATu@@/ap@WptLL6vxMJnSeArk/ELI9I5dPa8fQKaV6nZilWTsH56@Z@DWw0Y9E5qTy@OIzQf7Nsv4A "C (gcc) – Try It Online") [Answer] # [Scala](https://scala-lang.org) 2.12.8, 214 bytes Golfed version: ``` val r=scala.util.Random;println(readLine.toList.sliding(2).flatMap{case a :: b :: Nil=>(a +: (0 to r.nextInt(5)).map{_=>((c: Char)=>if(r.nextBoolean)c.toUpper else c.toLower)(if(r.nextBoolean)a else b)})}.mkString) ``` Golfed with newlines and indents: ``` val r=scala.util.Random println(readLine.toList.sliding(2).flatMap{ case a :: b :: Nil=> (a +: (0 to r.nextInt(5)).map{_=> ((c: Char)=>if(r.nextBoolean)c.toUpper else c.toLower)(if(r.nextBoolean)a else b) }) }.mkString) ``` Ungolfed: ``` import scala.io.StdIn import scala.util.Random def gobble(input: String): String = { input.toList.sliding(2).flatMap { case thisChar :: nextChar :: Nil => val numberOfAdditions = Random.nextInt(5) (thisChar +: (0 to numberOfAdditions).map { _ => val char = if(Random.nextBoolean) thisChar else nextChar val cc = if(Random.nextBoolean) char.toUpper else char.ToLower cc }) }.mkString } println(gobble(StdIn.readLine())) ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, 61 bytes ``` s/.(?=(.))/print$&,map{(map{lc,uc}$&,$1)[rand 4]}0..rand 5/ge ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX0/D3lZDT1NTv6AoM69ERU0nN7GgWgNE5CTrlCbXAkVUDDWjixLzUhRMYmsN9PTATFP99NT/1mA9CkoxeUr/g0u4gkuA3HQuHQU9BRj2SM3JyVcozy/KSVHkCijKTy9KzM0FKlIIKK2qykktVgCZ5Zyfkqrgnp@T9i@/oCQzP6/4v24eAA "Perl 5 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~236~~ ~~213~~ 209 bytes ``` a=>{int i=0,j;var m=new Random();var s="";var c = a.Select(x=>Char.IsLetter(x)?(char)(x^32):x).ToArray();for(;i<a.Length-1;i++)for(j=m.Next(1,5);j-->0;)s+=new[]{a[i],c[i],a[i+1],c[i+1]}[m.Next(0,3)];return s;} ``` [Try it online!](https://tio.run/##LY5RS8MwFIXf9ytCn3JpG1qHL2apiCAIwwcVfCgdhCxdU9oEbjIXGfvtta2@3PPxwTlc5XPlzfRytmrnAxp7yv6iIq2YpKiuxgZiRJH1/FsiGYXVF/Iu7dGNFFblRZKsoIggkn3oQatAo6ieO4ns1e91CBpphEeqZgM0HrZ38BCBfbonRPkz77QOKTc7yfbankKXl9ykKSy2FyN70zHQMrsH3ud5VXDw6fJG3VxlbZpMLWemtFx5jlv9XyqyLTQcdTijJZ7fJr7ZfKEJmrY06fQwOHJxOBwTAD79Ag "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # T-SQL query, 286 bytes ``` DECLARE @ char(999)='String' SELECT @=stuff(@,n+2,0,s)FROM(SELECT top 999*,substring(lower(c)+upper(c),abs(v%4)+1,1)s FROM(SELECT*,number n,substring(@,number+1,2)c,cast(newid()as varbinary)v FROM(values(1),(2),(3),(4),(5))F(h),spt_values)D WHERE'P'=type and n<len(@)-1and h>v%3+2ORDER BY-n)E PRINT LEFT(@,len(@)-1) ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1023387/ssttssttrrriininnnnnnniiinngg)** unfortunately the online version always show the same result for the same varchar, unlike MS SQL Server Management Studio [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 156 bytes ``` n=>{var k=new Random();int i=0;foreach(var j in n.Skip(1).Zip(n,(a,b)=>a+b))for(Write(j[1]),i=0;i++<k.Next(5);)Write(k.Next()%2<1?j.ToUpper():j.ToLower());} ``` [Try it online!](https://tio.run/##LY5BS8UwEITv/opQEHZpDVbwYpqIBw@CePApguIhjVvd9r1NSaNPEH97bXmeZphvGCZMJ2Hi@SpkjtLcXMvnjpJvt9RMObG8O9fZWaz7@fJJDVZor@69vMUdoGHJiu2p6WIiHz5grfSKRYneDDxCjfp5EanAVy1a58sWcSnDU@JM0L/Ur1itA1yWzaDv6DvDORo84P8Aj8@a@rLXD/FxHCkBXqz@Nu5Xj@Z3NkcdFIezhd7QlkKGYF0oi2Lh8x8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), ~~43~~ 16 bytes ``` äÈ+(Zv +Zu)ö5ö Ä ``` Shortened by a lot now! [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=5MgrKFp2ICtadSn2NfYgxA&input=IlN0cmluZyI) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~110~~ 109 bytes ``` i,p;g(char*_){for(i=rand(putchar(*_))%1024;p=_[i%2],putchar(i&2&&p>64&~-p%32<26?p^32:p),i/=4;);_[2]&&g(_+1);} ``` [Try it online!](https://tio.run/##TZA9b8IwEIZ3fsU1UqIEAi0BMTSEDh3aoUOljoRGrm3Sk@zYtR0qgehfd00qpA433HPvvfdBpy2l3mOuyzaln8SMm@y0VybFypCOpbp3F5oGnMXzu2JZ6qrZYlzs8msJkyJJ9Ga1TH6mOl4U62L1oN8Xxb3OcrytlmVWNttilyRt2kzmWXn2kmCXYueA5sPI8SE7jQCGsYFiNS9xTUucTAYOoE3g@zSqo9jWEVQbqKMoP2xxl5WDoE3/JWExe9HWXTSQ8@js/ZsLHq3PYQbXeOZCKPhWRrAb/2pUa4iUQQSv/fEouIXwAHhUjMOTEnv/ogyXgNr2EpgSyoBFB0RylwNVneXUcdcbIAw1Wnox4gJD0XIWGoBjb6Vi4LjUoRk7igxZHw7uHQjyEeyBuz9rDpK0HQEi8Ksns18 "C (gcc) – Try It Online") -1 thanks to [ceilingcat](https://codegolf.stackexchange.com/questions/182559/ssttssttrrriininnnnnnniiinngg/182755?noredirect=1#comment439899_182755) ``` i,p;g(char*_){ for(i=rand(putchar(*_)) //print current char %1024; // and get 10 random bits p=_[i%2], //1st bit => current/next char putchar(i&2&& //2nd bit => toggle case p>64&~-p%32<26 // if char-to-print is alphabetic ?p^32:p), i/=4;); //discard two bits _[2]&&g(_+1); //if next isn't last char, repeat with next char } ``` --- The number of characters printed (per input character) is not uniformly random: ``` 1 if i< 4 ( 4/1024 = 1/256) 2 if 4<=i< 16 ( 12/1024 = 3/256) 3 if 16<=i< 64 ( 48/1024 = 3/ 64) 4 if 64<=i< 256 (192/1024 = 3/ 16) 5 if 256<=i<1024 (768/1024 = 3/ 4) ``` [Answer] # Zsh, ~~113~~ 107 bytes With a lot of help from `man zshexpn` and `man zshparam`. [Try it Online!](https://tio.run/##qyrO@P8/Lb9IQUPDOtNG2dA6U1tbU7M611al2tBKJdPKqNYayM61ygHiUi6owhKbIEc/F39fVVPrEpDyCm2g8txoqKBJbC1XanJGvgLQiOjM2FqVipiYZOsSW@sKW@va////68bb1mp7pObk5Cu4JhaVZORk5qUXK6oqWGkCAA) * ***-6*** by me, tweaking ``` for ((;i<#1;i++)){m=${1:$i:2};m=$m:l$m:u for ((;t<RANDOM%5;t++))x+=${m[RANDOM%4]} echo ${1[i]}$x\\c;t=;x=;} ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 74 bytes ``` gsub(/.(?=(.))/){([$&,$1,$&.swapcase,$1.swapcase]*5).sample(rand 1..5)*""} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6BUuyCpaUlaboWN73Si0uTNPT1NOxtNfQ0NfU1qzWiVdR0VAx1VNT0issTC5ITi1OBXDg7VstUU684MbcgJ1WjKDEvRcFQT89UU0tJqRZiItTgBcuCS4oy89IhPAA) [Answer] # [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` êß~Φ~a[├x◙w↓┬┬►{⌂ ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=88e17ee87e615bc3780a7719c2c2107b7f&i=,+.+,+.+,+.+Hello+world%21%0AProgramming+Puzzles+and+Code+Golf&m=2) ### Unpacked (20 bytes) and explanation: ``` 2BFch]pc:~+5R|':$|'p 2B all size-2 subarrays F for each: ch]p print its first element c copy it on the stack :~ case-swap the copy + concatenate 5R|' random integer 1-5, inclusive :$ Cartesian power |' random choice p print ``` ]
[Question] [ **Input:** An integer. **Output:** 1. First convert the integer to it's equivalent Roman Numeral. 2. Then convert each capital letter of that Roman Numeral to their ASCII/UNICODE decimal value. 3. And output the sum of those. **Example:** ``` 1991 -> MCMXCI -> 77+67+77+88+67+73 -> 449 ^ input ^ output ``` ***Roman Numerals:*** [![enter image description here](https://i.stack.imgur.com/pVmmz.png)](https://i.stack.imgur.com/pVmmz.png) [Here is a perhaps useful Roman Numeral Converter.](http://www.sorenwinslow.com/RomanNumerals.asp) **Challenge rules:** * Standard Roman Numeral rules are applied, so no alternative forms like `IIII` or `VIIII` instead of `IV` and `IX`.\* * The Macron lines above the Roman Numerals past 1,000 are `¯` (UNICODE nr. 175). So one line counts as `+175` and two as `+350`. * You are allowed to use any kind of input and output type, as long as it represents the integers. * The test cases will be in the range of `1 - 2,147,483,647`. \* Roman Numeral rules (quote from Wikipedia): > > Numbers are formed by combining symbols and adding the values, so `II` is two (two ones) and `XIII` is thirteen (a ten and three ones). Because each numeral has a fixed value rather than representing multiples of ten, one hundred and so on, according to position, there is no need for "place keeping" zeros, as in numbers like 207 or 1066; those numbers are written as `CCVII` (two hundreds, a five and two ones) and `MLXVI` (a thousand, a fifty, a ten, a five and a one). > > > Symbols are placed from left to right in order of value, starting with the largest. However, in a few specific cases, to avoid four characters being repeated in succession (such as `IIII` or `XXXX`), subtractive notation is often used as follows: > > > * `I` placed before `V` or `X` indicates one less, so four is `IV` (one less than five) and nine is `IX` (one less than ten) > * `X` placed before `L` or `C` indicates ten less, so forty is `XL` (ten less than fifty) and ninety is `XC` (ten less than a hundred) > * `C` placed before `D` or `M` indicates a hundred less, so four hundred is `CD` (a hundred less than five hundred) and nine hundred is `CM` (a hundred less than a thousand) > > For example, `MCMIV` is one thousand nine hundred and four, 1904 (`M` is a thousand, `CM` is nine hundred and `IV` is four). > > > Some examples of the modern use of Roman numerals include: > > 1954 as `MCMLIV`; 1990 as `MCMXC`; 2014 as `MMXIV` > > [SOURCE](https://en.wikipedia.org/wiki/Roman_numerals#Roman_numeric_system) > > > **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](http://meta.codegolf.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](http://meta.codegolf.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:** ``` 100 -> 67 1 -> 73 4 -> 159 22 -> 322 5000 -> 261 2016 -> 401 1000000000 -> 427 1991 -> 449 9999 -> 800 1111111111 -> 2344 2147483647 -> 5362 ``` [Answer] # Python 3, ~~281~~ ~~278~~ ~~273~~ 269 bytes My first attempt at codegolf, here we go. Tried to do it without looking at the linked question, so it's probably terrible :) ``` def f(n):d=len(str(n))-1;l=10**d;return 0if n<1else(n<l*4and[73,88,67,77,263,242,252,438,417,427][d]+f(n-l))or(l<=n//9and[161,155,144,340,505,494,690,855,844][d]+f(n-9*l))or(n<l*5and[159,164,135,338,514,485,688,864,835][d]+f(n-4*l))or[86,76,68][d%3]+(d//3*175)+f(n-5*l) ``` 8 bytes smaller, thanks to Gábor Fekete Ungolfed: ``` def f(n): d = len(str(n)) - 1 # number of digits minus one l = 10 ** d # largest power of 10 that is not larger than parameter if n == 0: return 0 elif n < 4 * l: # starts with X, C, M, ... return [ ord('I'), ord('X'), ord('C'), ord('M'), ord('X') + 175, ord('C') + 175, ord('M') + 175, ord('X') + 350, ord('C') + 350, ord('M') + 350 ][d] + f(n - l) elif n // 9 * 10 >= 10 * l: # starts with IX, XC, ... return [ ord('I') + ord('X'), ord('X') + ord('C'), ord('C') + ord('M'), ord('M') + ord('X') + 175, ord('X') + ord('C') + 350, ord('C') + ord('M') + 350, ord('M') + ord('X') + 525, ord('X') + ord('C') + 700, ord('C') + ord('M') + 700 ][d] + f(n - 9*l) elif n < 5 * l: # starts with IV, XL, CD, ... return [ ord('I') + ord('V'), ord('X') + ord('L'), ord('C') + ord('D'), ord('M') + ord('V') + 175, ord('X') + ord('L') + 350, ord('C') + ord('D') + 350, ord('M') + ord('V') + 525, ord('X') + ord('L') + 700, ord('C') + ord('D') + 700 ][d] + f(n - 4 * l) else: # starts with V, L, D, ... return [ ord('V'), ord('L'), ord('D'), ord('V') + 175, ord('L') + 175, ord('D') + 175, ord('V') + 350, ord('L') + 350, ord('D') + 350 ][d] + f(n - 5 * l) ``` [Answer] # Mathematica, 181 173 166 151 bytes ## Golfed ``` (q=Select[ToCharacterCode@#,64<#<99&]&/@StringSplit[RomanNumeral[#],"_"];p=PadLeft;l=Length;Total[p[q,4]+p[{350,350*Mod[l@q,2],175,0}[[-l@q;;]],4],2])& ``` ## Ungolfed ``` ( q = Select[ ToCharacterCode@#, 64<#<99& ]&/@StringSplit[RomanNumeral@#,"_"]; p=PadLeft; l=Length; Total[ p[q,4]+ p[{350,350*Mod[l@q,2],175,0}[[-l@q;;]],4] ,2] )& ``` Mathematica's `RomanNumeral` implementation gives (IX)CMXCIX for 9999, and so the program returns 971 for that number. As written, a roman numeral of the type ((...))(...)... returns a nested list of the ASCII codes for the roman numerals of length 4, ((...))... returns a list of length 3, (...)... returns a list of length 2, and ... returns a list of length 1. The final line converts those rules into the appropriate number of macrons for each section of the list, adds those macrons in, and then sums the entire nested list to return the output. [Answer] # Ruby, 188 bytes An adaptation based on [my old Ruby answer for Roman numeral conversion](https://codegolf.stackexchange.com/a/78000/52194). [Try it online!](https://repl.it/CiIG) ``` f=->x,i=0{k=0;(x<t=1e3)?"CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1".gsub(/(\D+)(\d+)/){v=$2.to_i;s=x/v;x%=v;($1*s).bytes.map{|c|k+=c==73&&i>0?77+175*~-i:c+175*i}}:k=f[x/t,i+1]+f[x%t,i];k} ``` [Answer] # Mathematica, 198 bytes ``` Tr[Tr@Flatten[ToCharacterCode/@#]+Length@#*Tr@#2&@@#&/@Partition[Join[SplitBy[Select[Characters@#/."\&"->1,MemberQ[Join["A"~CharacterRange~"Z",{1}],#]&],LetterQ]/. 1->175,{{0}}],2]]&@RomanNumeral@#& ``` Unfortunately, the builtin doesn't help here much, though I'm sure this can be golfed far more. Note: Evaluates `9999 -> 971` as per [here](http://romannumerals.babuo.com/9999-in-roman-numerals). [Answer] ## Batch, 373 bytes ``` @echo off set/an=%1,t=0,p=1 call:l 73 159 86 161 call:l 88 164 76 155 call:l 67 135 68 144 call:l 77 338 261 340 call:l 263 514 251 505 call:l 242 485 243 494 call:l 252 688 436 690 call:l 438 864 426 855 call:l 417 835 418 844 call:l 427 0 0 0 echo %t% exit/b :l set/ad=n/p%%10,p*=10,c=d+7^>^>4,d-=9*c,t+=%4*c,c=d+3^>^>3,d-=5*c,t+=%3*c+%2*(d^>^>2)+%1*(d^&3) ``` Works by translating each digit of the number according to a lookup table for the values 1, 4, 5 and 9. Uses `M(V)`, `M(X)`, `(M(V))` and `(M(X))`. If you prefer `(IV)`, `(IX)`, `((IV))` and `((IX))` then use `call:l 77 509 261 511` and `call:l 252 859 436 861` respectively. [Answer] # R, 115 bytes So... I'm posting my solution because I find the question pretty interesting. I did my best with **R**'s capacities to deal with roman numbers without packages : you can only input numbers between `1` and `3899`, as the `as.roman`'s [documentation](https://stat.ethz.ch/R-manual/R-devel/library/utils/html/roman.html) explains. That's why I cheated a bit by giving range between `1` to ~~`11`~~ `14` in the `for` loop : ~~it's the lenght of `as.roman(3899)`'s output (`MMMDCCCXCIX`)~~. In fact, according to [this website](http://www.web40571.clarahost.co.uk/roman/quiza.htm), the longest roman number is `MMDCCCLXXXVIII` (14 characters), which corresponds to `2888`. Furthermore, you can't compute the `length` of the output of this function. ``` a=scan();v=0;for(i in 1:14){v=c(v,as.numeric(charToRaw(substring(as.character(as.roman(a)),1:14,1:14)[i])))};sum(v) ``` If anyone sees a solution to deal with the above problems, please feel free to comment. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` RƵêS£í.XÇεNĀi73¬Ć:Ny73Q-Ƶм*+]˜O ``` [Try it online](https://tio.run/##AT8AwP9vc2FiaWX//1LGtcOqU8Kjw60uWMOHzrVOxIBpNzPCrMSGOk55NzNRLca10LwqK13LnE///zIxNDc0ODM2NDc) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/6BjWw@vCj60@PBavYjD7ee2@h1pyDQ3PrTmSJuVX6W5caDusa0X9mhpx56e4/9fSS9MRzPmf7ShgYGOoY6JjpGRjqkBkG1kYGimAxSEAh1DS0tDHUsg0DGEAx0jQxNzEwtjMxPzWAA). **Explanation:** 05AB1E does have a builtin to convert from/to Roman numbers. Unfortunately, \$M=1000\$ is the highest supported Roman digit, so it would convert something like `9999` to `MMMMMMMMMCMXCIX`. Because of this we'll split the input into parts at the 1000 separators, and convert each part separately. This results in the following code: ``` R # Reverse the (implicit) input-integer Ƶê # Push compressed integer 334 S # Convert it to a list of digits: [3,3,4] £ # Split the reversed input into parts of that size í # Reverse each individual part back .X # Convert it from an integer to a Roman number string Ç # Convert each string to a list of codepoint integer ε # Map over each list of codepoints: NĀi # If the (0-based) map-index is NOT 0: 73 # Push 73 ¬ # Push its first digit (without popping): 7 Ć # Append its own head: 77 : # Replace all 73 with 77 (replaces all "I" with "M") y # Push the list of codepoints again 73Q # Check for each if it's equal to 73 ("I") N - # Subtract those checks from the (0-based) map-index Ƶм* # Multiply each by the compressed integer 175 + # Add those to the list of codepoints (with 73 as 77) ]˜ # After the if-statement and map: flatten the list O # And sum this list of integers # (after which it is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶм` is `175`. [Answer] ## JavaScript (ES6), 183 bytes ``` f=(n,a=0)=>n<4e3?[256077,230544,128068,102535,25667,23195,12876,10404,2648,2465,1366,1183,329].map((e,i)=>(d=e>>8,c=n/d|0,n-=c*d,r+=c*(e%256+a*-~(i&1))),r=0)|r:f(n/1e3,a+175)+f(n%1e3) ``` Note: not only prefers `(IV)` to `M(V)`, but also prefers `(VI)` to `(V)M`; in fact it will only use M at the very start of the number. [Answer] # Python, 263 bytes ``` def g(m):x=0;r=[73,86,88,76,67,68,77,261,263,251,242,243,252,436,438,426,417,418,427,0,0];return sum([b%5%4*r[i+(i*1)]+((b==9)*(r[i+(i*1)]+r[(i+1)*2]))+((b==4)*(r[i+(i*1)]+r[i+1+(i*1)]))+((b in [5,6,7,8])*r[i+1+(i*1)])for i,b in enumerate(map(int,str(m)[::-1]))]) ``` [Answer] # Python 3, 315 bytes ``` def p(n=int(input()),r=range):return sum([f*g for f,g in zip([abs(((n-4)%5)-1)]+[t for T in zip([((n+10**g)//(10**g*5))%2for g in r(10)],[(n%(10**g*5))//(10**g*4)+max((n%(10**g*5)%(10**g*4)+10**(g-1))//(10**g),0)for g in r(1,10)])for t in T],[73,86,88,76,67,68,77,261,263,251,242,243,252,436,438,426,417,418,427])]) ``` **Ungolfed version:** ``` def p(n=int(input()),r=range): return sum([f*g for f,g in zip( [abs(((n-4)%5)-1)]+ [t for T in zip( [((n+10**g)//(10**g*5))%2for g in r(10)], [(n%(10**g*5))//(10**g*4)+max((n%(10**g*5)%(10**g*4)+10**(g-1))//(10**g),0)for g in r(1,10)] )for t in T], [73,86,88,76,67,68,77,261,263,251,242,243,252,436,438,426,417,418,427])]) ``` **Explanation:** This version uses a different approach, it counts occurrences of roman numerals in the number. `[abs(((n-4)%5)-1)]` is the number of **`I`**s in the roman numeral. `[((n+10**g)//(10**g*5))%2for g in r(10)]` is the number of **`V,L,D,(V),(L),(D),((V)),((L)),((D))`**s in the number. `[(n%(10**g*5))//(10**g*4)+max((n%(10**g*5)%(10**g*4)+10**(g-1))//(10**g),0)for g in r(1,10)]` is the number of the **`X,C,M,(X),(C),(M),((X)),((C)),((M))`**s in the number. It then multiplies the occurrences with the value of the character and returns the sum of it. [Answer] I don't know if I understood the challenge correctly but I leave here a first contribution. First I did a good research on Roman numerals on this [site](https://numerosromanos.pro/numeros-romanos-del-1-al-100/) in Spanish and this other very interesting [site](https://romannumerals.pro/4-in-roman-numerals/) in English And then I dedicated myself to preparing the following code: ``` get_ascii_sum = functools.partial(lambda f, n: sum([ord(c) for c in f(n)]), lambda n: functools.reduce(lambda r, vg: (r[0] + vg[1] * vg[2], r[1] - vg[1] * vg[2]), zip((lambda v, s: (v, [s[i] * ((n + 10 ** i) // (10 ** i * 5)) % 2 for i in range(len(s))], [((n % (10 ** i * 5)) // (10 ** i * 4)) + max(((n % (10 ** i * 5) % (10 ** i * 4)) + 10 ** (i - 1)) // (10 ** i), 0) for i in range(1, len(s))]))(values, symbols)), (0, num))) ``` ]
[Question] [ A [field](https://en.wikipedia.org/wiki/Field_(mathematics)) in mathematics is a set of numbers, with addition and multiplication operations defined on it, such that they satisfy certain axioms (described in Wikipedia; see also below). A finite field can have pn elements, where `p` is a prime number, and `n` is a natural number. In this challenge, let's take `p = 2` and `n = 8`, so let's make a field with 256 elements. The elements of the field should be consecutive integers in a range that contains `0` and `1`: * -128 ... 127 * 0 ... 255 * or any other such range Define *two* functions (or programs, if that is easier), `a(x,y)` for abstract "addition", and `m(x,y)` for abstract "multiplication", such that they satisfy the field axioms: * Consistency: `a(x,y)` and `m(x,y)` produce the same result when called with same arguments * Closedness: The result of `a` and `m` is an integer in the relevant range * Associativity: for any `x`, `y` and `z` in the range, `a(a(x,y),z)` is equal to `a(x,a(y,z))`; the same for `m` * Commutativity: for any `x` and `y` in the range, `a(x,y)` is equal to `a(y,x)`; the same for `m` * Distributivity: for any `x`, `y` and `z` in the range, `m(x,a(y,z))` is equal to `a(m(x,y),m(x,z))` * Neutral elements: for any `x` in the range, `a(0,x)` is equal to `x`, and `m(1,x)` is equal to `x` * Negation: for any `x` in the range, there exists such `y` that `a(x,y)` is `0` * Inverse: for any `x≠0` in the range, there exists such `y` that `m(x,y)` is `1` The names `a` and `m` are just examples; you can use other names, or unnamed functions. The score of your answer is the sum of byte-lengths for `a` and `m`. If you use a built-in function, please also describe in words which result it produces (e.g. provide a multiplication table). [Answer] ## Python 2, 11 + 45 = 56 bytes **Addition** (11 bytes): ``` int.__xor__ ``` **Multiplication** (45 bytes): ``` m=lambda x,y:y and m(x*2^x/128*283,y/2)^y%2*x ``` Takes input numbers in the range `[0 ... 255]`. Addition is just bitwise XOR, multiplication is multiplication of polynomials with coefficients in GF2 with [Russian peasant](https://en.wikipedia.org/wiki/Finite_field_arithmetic). And for checking: ``` a=int.__xor__ m=lambda x,y:y and m(x*2^x/128*283,y/2)^y%2*x for x in range(256): assert a(0,x) == a(x,0) == x assert m(1,x) == m(x,1) == x assert any(a(x,y) == 0 for y in range(256)) if x != 0: assert any(m(x,y) == 1 for y in range(256)) for y in range(256): assert 0 <= a(x,y) < 256 assert 0 <= m(x,y) < 256 assert a(x,y) == a(y,x) assert m(x,y) == m(y,x) for z in range(256): assert a(a(x,y),z) == a(x,a(y,z)) assert m(m(x,y),z) == m(x,m(y,z)) assert m(x,a(y,z)) == a(m(x,y), m(x,z)) ``` [Answer] # Intel x86-64 + AVX-512 + GFNI, 11 bytes ``` add: C5 F0 57 C0 # vxorps xmm0, xmm1, xmm0 C3 # ret mul: C4 E2 79 CF C1 # vgf2p8mulb xmm0, xmm0, xmm1 C3 # ret ``` Uses the new `GF2P8MULB` instruction on Ice Lake CPUs. > > The instruction multiplies elements in the finite field GF(28), operating on a byte (field element) in the first source operand and the corresponding byte in a second source operand. The field GF(28) is represented in polynomial representation with the reduction polynomial x8 + x4 + x3 + x + 1. > > > [Answer] ## JavaScript (ES6), 10 + 49 = 59 bytes ``` a=(x,y)=>x^y m=(x,y,p=0)=>x?m(x>>1,2*y^283*(y>>7),p^y*(x&1)):p ``` Domain is 0 ... 255. [Source](https://en.wikipedia.org/wiki/Finite_field_arithmetic#Program_examples). [Answer] ## [Hoon](https://github.com/urbit/urbit), 22 bytes ``` [dif pro]:(ga 8 283 3) ``` Hoon already has a function `++ga` that creates Galois Fields, for use in the AES implementation. This returns a tuple of two functions, instead of using two programs. Operates in the domain `[0...255]` Testsuite: ``` =+ f=(ga 8 283 3) =+ n=(gulf 0 255) =+ a=dif:f =+ m=pro:f =+ %+ turn n |= x/@ ?> =((a 0 x) x) ?> =((m 1 x) x) ~& outer+x %+ turn n |= y/@ ?> =((a x y) (a y x)) ?> &((lte 0 (a x y)) (lte (a x y) 255)) ?> &((lte 0 (m x y)) (lte (m x y) 255)) %+ turn n |= z/@ ?> =((a (a x y) z) (a x (a y z))) ?> =((m x (a y z)) (a (m x y) (m x z))) ~ "ok" ``` Posting a multiplication table would be gigantic, so here are some random testcases: ``` 20x148=229 61x189=143 111x239=181 163x36=29 193x40=1 ``` [Answer] # IA-32 machine code, 22 bytes "Multiplication", 18 bytes: ``` 33 c0 92 d1 e9 73 02 33 d0 d0 e0 73 02 34 1b 41 e2 f1 ``` "Addition", 4 bytes: ``` 92 33 c1 c3 ``` This stretches rules a bit: the "multiplication" code lacks function exit code; it relies on the "addition" code being in memory right afterwards, so it can "fall-through". I did it to decrease code size by 1 byte. Source code (can be assembled by `ml` of MS Visual Studio): ``` TITLE x PUBLIC @m@8 PUBLIC @a@8 _TEXT SEGMENT USE32 @m@8 PROC xor eax, eax; xchg eax, edx; myloop: shr ecx, 1 jnc sk1 xor edx, eax sk1: shl al, 1 jnc sk2 xor al, 1bh sk2: inc ecx loop myloop @m@8 endp @a@8 proc xchg eax, edx; xor eax, ecx ret @a@8 ENDP _text ENDS END ``` The algorithm is the standard one, involving the usual polynomial `x^8 + x^4 + x^3 + x + 1`, represented by the hexadecimal number `1b`. The "multiplication" code accumulates the result in `edx`. When done, it falls through to the addition code, which moves it to `eax` (conventional register to hold return value); the `xor` with `ecx` is a no-op, because at that point `ecx` is cleared. One peculiar feature is the loop. Instead of checking for zero ``` cmp ecx, 0 jne myloop ``` it uses the dedicated `loop` instruction. But this instruction decreases the loop "counter" before comparing it to 0. To compensate for this, the code increases it before using the `loop` instruction. [Answer] # Mathematica 155 bytes ``` f[y_]:=Total[x^Reverse@Range[0,Log[2,y]]*RealDigits[y,2][[1]]];o[q_,c_,d_]:=FromDigits[Reverse@Mod[CoefficientList[PolynomialMod[q[f@c,f@d],f@283],x],2],2] ``` *Implementation* ``` (* in: o[Times, 202, 83] out: 1 in: o[Plus, 202, 83] out: 153 *) ``` addition check: ``` (* in: BitXor[202, 83] out: 153 *) ``` More: ``` (* in: o[Times, #, #2] & @@@ {{20, 148}, {61, 189}, {111, 239}, {163, 36}, {193, 40}} out: {229, 143, 181, 29, 1} *) ``` NB Should be able to use any of `{283, 285, 299, 301, 313, 319, 333, 351, 355, 357, 361, 369, 375, 379, 391, 395, 397, 415, 419, 425, 433, 445, 451, 463, 471, 477, 487, 499, 501, 505}` in place of `283`. ]
[Question] [ This challenge is about reading random lines from a potentially huge file without reading the whole file into memory. **Input** An integer `n` and the name of a text file. **Output** `n` lines of the text file chosen uniformly at random without replacement. You can assume that `n` is in the range 1 to the number of lines in the file. Be careful when sampling `n` numbers at random from the range that the answer you get is uniform. `rand()%n` in C is not uniform for example. Every outcome must be equally likely. **Rules and restrictions** Each line of the text file will have the same number of characters and that will be no more than 80. Your code must not read any of the contents of text file except: * Those lines it outputs. * The first line to work out how many characters per line there are in the text file. We can assume each character in the text file takes exactly one byte. Line separators are assumed to be 1 byte long. Solutions may use 2 bytes long line separators only if they specify this need. You may also assume the last line is terminated by a line separator. Your answer should be a complete program but you can specify the input in any way that is convenient. **Languages and libraries** You can use any language or library you like. **Notes** There was a concern about calculating the number of lines in the file. As nimi points out in the comments, you can infer this from the file size and the number of chars per line. **Motivation** In chat some people asked if this is really a "Do X without Y" question. I interpret this to ask if the restrictions are unusually artificial. The task of randomly sampling lines from huge files is not uncommon and is in fact one I sometimes have to do. One way to do this is in bash: `shuf -n <num-lines>` This is however very slow for large files as it reads in the whole file. [Answer] # Ruby, ~~104~~ ~~94~~ ~~92~~ 90 bytes File name and number of lines are passed into the command line. For example, if the program is `shuffle.rb` and the file name is `a.txt`, run `ruby shuffle.rb a.txt 3` for three random lines. -4 bytes from discovering the `open` syntax in Ruby instead of `File.new` ``` f=open$*[0] puts [*0..f.size/n=f.gets.size+1].sample($*[1].to_i).map{|e|f.seek n*e;f.gets} ``` Also, here's a 85-byte anonymous function solution that takes a string and a number as its arguments. ``` ->f,l{f=open f;puts [*0..f.size/n=f.gets.size+1].sample(l).map{|e|f.seek n*e;f.gets}} ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 63 bytes ``` ⎕NREAD¨t 82l∘,¨lׯ1+⎕?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍞⎕NTIE 0 ``` Prompts for file name, then for how many random lines are desired. ### Explanation `⍞` Prompt for text input (file name) `⎕NTIE 0` Tie the file using next available tie number (-1 on a clean system) `t←` Store the chosen tie number as `t` `83 80,⍨` Append [83,80] yielding [-1,83,80] `⎕NREAD` Read the first 80 bytes of file -1 as 8-bit integers (conversion code 83) `10⍳⍨` Find the index of the first number 10 (LF) `l←` Store the line length as `l` `(⎕NSIZE t)÷` Divide the size of file -1 with the line length `⎕` Prompt for numeric input (desired number of lines) `?` X random selections (without replacement) out the first Y natural numbers `¯1+` Add -1 to get 0-origin line numbers\* `l×` Multiply by the line length to get the start bytes `t 82l∘,¨` Prepend [-1,82,LineLength] to each start byte (creates list of arguments for `⎕NREAD`) `⎕NREAD¨` Read each line as 8-bit character (conversion code 82) ### Practical example File /tmp/records.txt contains: ``` Hello Think 12345 Klaus Nilad ``` Make the program RandLines contain the above code verbatim by entering the following into the APL session: ``` ∇RandLines ⎕NREAD¨t 82l∘,¨lׯ1+⎕?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍞⎕NTIE 0 ∇ ``` In the APL session type `RandLines` and press Enter. The system moves the cursor to the next line, which is a 0-length prompt for character data; enter `/tmp/records.txt`. The system now outputs `⎕:` and awaits numeric input; enter `4`. The system outputs four random lines. ### Real life In reality, you may want to give filename and count as arguments and receive the result as a table. This can be done by entering: ``` RandLs←{↑⎕NREAD¨t 82l∘,¨lׯ1+⍺?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍵⎕NTIE 0} ``` Now you make MyLines contain three random lines with: ``` MyLines←3 RandLs'/tmp/records.txt' ``` How about returning just a single random line if count is not specified: ``` RandL←{⍺←1 ⋄ ↑⎕NREAD¨t 82l∘,¨lׯ1+⍺?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍵⎕NTIE 0} ``` Now you can do both: ``` MyLines←2 RandL'/tmp/records.txt' ``` and (notice absence of left argument): ``` MyLine←RandL'/tmp/records.txt' ``` ### Making code readable Golfed APL one-liners are a bad idea. Here is how I would write in a production system: ``` RandL←{ ⍝ Read X random lines from file Y without reading entire file ⍺←1 ⍝ default count tie←⍵⎕NTIE 0 ⍝ tie file length←10⍳⍨⎕NREAD 83 80,⍨tie ⍝ find first NL size←⎕NSIZE tie ⍝ total file length starts←lengthׯ1+⍺?size÷length ⍝ beginning of each line ↑⎕NREAD¨tie 82length∘,¨starts ⍝ read each line as character and convert list to table } ``` --- \*I could save a byte by running in 0-origin mode, which is standard on some APL systems: remove `¯1+` and insert `1+` before `10`. [Answer] ## Haskell, ~~240~~ ~~224~~ 236 bytes ``` import Test.QuickCheck import System.IO g=hGetLine main=do;f<-getLine;n<-readLn;h<-openFile f ReadMode;l<-(\x->1+sum[1|_<-x])<$>g h;s<-hFileSize h;generate(shuffle[0..div s l-1])>>=mapM(\p->hSeek h(toEnum 0)(l*p)>>g h>>=putStrLn).take n ``` Reads filename and n from stdin. How it works: ``` main=do f<-getLine -- read file name from stdin n<-readLn -- read n from stdin h<-openFile f ReadMode -- open the file l<-(\x->1+sum[1|_<-x])<$>g h -- read first line and bind l to it's length +1 -- sum[1|_<-x] is a custom length function -- because of type restrictions, otherwise I'd have -- to use "toInteger.length" s<-hFileSize h -- get file size generate(shuffle[0..div s l-1])>>= -- shuffle all possible line numbers mapM (\->p ... ).take n -- for each of the first n shuffled line numbers hSeek h(toEnum 0).(l*p)>> -- jump to that line ("toEnum 0" is short for "AbsoluteSeek") g h>>= -- read a line from current position putStrLn -- and print ``` It takes a lot of time and memory to run this program for files with many lines, because of a horrible inefficient `shuffle` function. Edit: I missed the "random without replacement" part (thanks @feersum for noticing!). [Answer] ## PowerShell v2+, 209 bytes ``` param($a,$n) $f=New-Object System.IO.FileStream $a,"Open" for(;$f.ReadByte()-ne10){$l++} $t=$f.Length/++$l-1 [byte[]]$z=,0*$l 0..$t|Get-Random -c $n|%{$a=$f.Seek($l*$_,0);$a=$f.Read($z,0,$l-1);-join[char[]]$z} ``` Takes input `$a` as the filename and `$n` as the number of lines. Note that `$a` must be a full-path filename, and assumed to be ANSI encoding. We then construct a new [`FileStream` object](https://msdn.microsoft.com/en-us/library/system.io.filestream(v=vs.110).aspx), and tell it to access the file `$a` with `Open` privilege. The `for` loop [`.Read()`](https://msdn.microsoft.com/en-us/library/system.io.filestream.read(v=vs.110).aspx)s through the first line until we hit a `\n` character, incrementing our line-length counter each character. We then set `$t` equal to the size of the file (i.e., how long the stream is) divided by how many characters per line (plus one so it counts the terminator), minus one (since we're zero-indexed). We then construct our buffer `$z` to also be line length. The final line constructs a dynamic array with the `..` range operator.1 We pipe that array to `Get-Random` with a `-C`ount of `$n` to randomly select `$n` line numbers without repetition. The lucky numbers are piped into a loop with `|%{...}`. Each iteration we [`.Seek`](https://msdn.microsoft.com/en-us/library/system.io.filestream.seek(v=vs.110).aspx) to the particular location, and then `.Read` in a line's worth of characters, stored into `$z`. We re-cast `$z` as a char-array and `-join` it together, leaving the resultant string on the pipeline and output is implicit at the end of the program. *Technically* we should end with a `$f.Close()` call to close out the file, but that costs bytes! :p ### Example ``` a.txt: a0000000000000000000000000000000000000000000000001 a0000000000000000000000000000000000000000000000002 a0000000000000000000000000000000000000000000000003 a0000000000000000000000000000000000000000000000004 a0000000000000000000000000000000000000000000000005 a0000000000000000000000000000000000000000000000006 a0000000000000000000000000000000000000000000000007 a0000000000000000000000000000000000000000000000008 a0000000000000000000000000000000000000000000000009 a0000000000000000000000000000000000000000000000010 PS C:\Tools\Scripts\golfing> .\read-n-random-lines.ps1 "c:\tools\scripts\golfing\a.txt" 5 a0000000000000000000000000000000000000000000000002 a0000000000000000000000000000000000000000000000001 a0000000000000000000000000000000000000000000000004 a0000000000000000000000000000000000000000000000010 a0000000000000000000000000000000000000000000000006 ``` --- 1 Technically, this means we can only support a maximum of 50,000 lines, as that's the largest range that can be dynamically created in this manner. :-/ But, we can't just loop a `Get-Random` command `$n` times, discarding duplicates each loop, since that's not deterministic ... [Answer] # Python 3, ~~146~~ 139 bytes ``` from random import* i=input f=open(i()) l=len(f.readline()) [(f.seek(v*l),print(f.read(l)))for v in sample(range(f.seek(0,2)//l),int(i()))] #print is here^ ``` Input: [filename]\n[lines]\n This solution heavily stole from @pppery but ~~is python3.5 only and~~ is a complete program. Edit: Thanks to @Mego for the inline range and python3.x compatibility. Edit2: Clarification where the print is because i got two comments about it. (Comment is obviously not part of the code or the byte count.) [Answer] # Lua, ~~126~~ 122 ``` r=io.read;f=io.open(r())c=2+f:read():len()for i=1,r()do f:seek("set",c*math.random(0,f:seek("end")/c-1))print(f:read())end ``` Uses 2 bytes for line breaks. Change the 2 to a 1 for 1. I only have it as 2 because that's what my test file had. Got myself under the PHP entry, but still 2nd place (currently). Curse you, Ruby entry! [Answer] ## Bash (well, coreutils), 100 bytes ``` n=`head -1 $2|wc -c`;shuf -i0-$[`stat -c%s $2`/$n] -n$1|xargs -i dd if=$2 bs=$n skip={} count=1 2>&- ``` ### Explanation This avoids reading the whole file using `dd` to extract the portions of the file we need without reading the file entirely, unfortunately it ends up quite large with all the options we have to specify: `if` is the input file `bs` is the block size (here we set it to `$n` which is the length of the first line `skip` is set to the random integers extracted from `shuf` and equates to the `ibs` value skipping `skip`\*`ibs` bytes `count` the number of `ibs` length sections to return `status=none` is needed to strip out the information normally output by `dd` We get the line length using `head -1 $2|wc -c` and the filesize with `stat -c%s $2`. ### Usage Save above as `file.sh` and run using `file.sh n filename`. ### Timings ``` time ~/randlines.sh 4 test.txt 9412647 4124435 7401105 1132619 real 0m0.125s user 0m0.035s sys 0m0.061s ``` vs. ``` time shuf -n4 test.txt 1204350 3496441 3472713 3985479 real 0m1.280s user 0m0.287s sys 0m0.272s ``` Times above for a 68MiB file generated using `seq 1000000 9999999 > test.txt`. Thanks to [@PeterCordes](https://codegolf.stackexchange.com/users/30206/peter-cordes) for his -1 tip! [Answer] # Python 3 - ~~161 160~~ 149 bytes ``` from random import*; def f(n,g):f=open(g);l=len(f.readline());r=list(range(f.seek(0,2)/l));shuffle(r);[(f.seek(v*l),print(f.read(l)))for v in r[:k]] ``` This code defines a function which is called like `f(10,'input.txt')` [Answer] # C# 259 bytes without duplicates ``` class Program{static void Main(string[]a){int c=Convert.ToInt32(a[1]);var h=File.ReadLines(a[0]);HashSet<int>n=new HashSet<int>();while(n.Count<c)n.Add(new Random().Next(0,h.Count()));for(;c>0;c--)Console.WriteLine(h.Skip(n.ElementAt(c-1)).Take(1).First());}} ``` Ungolfed ``` class Program{static void Main(string[] a) { int c = Convert.ToInt32(a[1]); var h = File.ReadLines(a[0]); HashSet<int> n = new HashSet<int>(); while (n.Count < c) n.Add(new Random().Next(0, h.Count())); for (; c > 0; c--) Console.WriteLine(h.Skip(n.ElementAt(c-1)).Take(1).First()); } } ``` File.ReadLines is Lazy. This has the additional benefit that all lines can have different length. Running it would be: ``` sample.exe a.txt 10000 ``` # C# 206 bytes with duplicates ``` class Program{static void Main(string[]a){var n=new Random();int c=Convert.ToInt32(a[1]);var h=File.ReadLines(a[0]);for(;c>0;c--)Console.WriteLine(h.Skip((int)(n.NextDouble()*h.Count())).Take(1).First());}} ``` Ungolfed ``` class Program { static void Main(string[] a) { Random n = new Random(); int c = Convert.ToInt32(a[1]); var h = File.ReadLines(a[0]); for (; c > 0; c--) Console.WriteLine(h.Skip((int)(n.NextDouble()*h.Count())).Take(1).First()); } } ``` [Answer] # Python (141 bytes) Keeps each line with equal probability, use with pipes too. It doesn't answer the skip ahead limitation of the question though... Usage `cat largefile | python randxlines.py 100` or `python randxlines 100 < largefile` (as @petercordes pointed out) ``` import random,sys N=int(sys.argv[1]) x=['']*N for c,L in enumerate(sys.stdin): t=random.randrange(c+1) if(t<N):x[t] = L print("".join(x)) ``` ]
[Question] [ You can determine the volume of objects based on a given set of dimensions: * The volume of a sphere can be determined using a single number, the radius (`r`) * The volume of a cylinder can be determined using two numbers, the radius (`r`) and the height (`h`) * The volume of a box can be determined using three numbers, the length (`l`), width (`w`) and the height (`h`) * The volume of an irregular triangular pyramid can be determined using four numbers, the side lengths (`a, b, c`) and the height (`h`). The challenge is to determine the volume of an object given one of the following inputs: * A single number `(r)` or `(r, 0, 0, 0)` => `V = 4/3*pi*r^3` * Two numbers `(r, h)` or `(r, h, 0, 0)` => `V = pi*r^2*h` * Three numbers `(l, w, h)` or `(l, w, h, 0)` => `V = l*w*h` * Four numbers `(a, b, c, h)` => `V = (1/3)*A*h`, where `A` is given by [Heron's formula](https://en.wikipedia.org/wiki/Heron%27s_formula): `A = 1/4*sqrt((a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c))` **Rules and clarifications:** * The input can be both integers and/or decimals * You can assume all input dimensions will be positive * If Pi is hard coded it must be accurate up to: `3.14159`. * The output must have at least 6 significant digits, except for numbers that can be accurately represented with fewer digits. You can output `3/4` as `0.75`, but `4/3` must be `1.33333` (more digits are OK) + How to round inaccurate values is optional * Behaviour for invalid input is undefined * Standard rules for I/O. The input can be list or separate arguments This is code golf, so the shortest solution in bytes win. **Test cases:** ``` calc_vol(4) ans = 268.082573106329 calc_vol(5.5, 2.23) ans = 211.923986429533 calc_vol(3.5, 4, 5) ans = 70 calc_vol(4, 13, 15, 3) ans = 24 ``` --- [Related, but different](https://codegolf.stackexchange.com/questions/67027/how-much-present-did-you-get-for-christmas). [Answer] # Vitsy, 49 bytes I thought you handed this one to me on a plate, but I found an unresolved bug to work around. Didn't hurt me, though. ``` lmN 3^43/*P* 2^*P* ** v:++2/uV3\[V}-]V3\*12/^v*3/ ``` Basically, with the input being a certain length for different functions, you spoon feed me my method syntax for doing this stuff. So, yay, success! Explanation, one line at a time: ``` lmN l Get the length of the stack. m Go to the line index specified by the top item of the stack (the length). N Output as a number. 3^43/*P* 3^ Put to the power of 3. 43/* Multiply by 4/3. P* Multiply by π 2^*P* 2^ Put to the second power. * Multiply the top two items. P* Multiply by π ** ** Multiply the top three items of the stack. v:++2/uV3\[V}-]V3\*12/^v*3/ v Save the top item as a temp variable. : Duplicate the stack. ++ Sum the top three values. 2/ Divide by two. u Flatten the top stack to the second to top. V Capture the top item of the stack (semiperimeter) as a permanent variable. 3\[ ] Do the stuff in the brackets 3 times. V}- Subtract the semiperimeter by each item. V Push the global var again. 3\* Multiply the top 4 items. 12/^ Square root. v* Multiply by the temp var (the depth) 3/ Divide by three. ``` Input is accepted as command line arguments in the exact reverse as they appear in the question, with no trailing zeroes. [Try it online!](http://vitsy.tryitonline.net/#code=bG1OCjNeNDMvKlAqCjJeKlAqCioqCnY6KysyL3VWM1xbVn0tXVYzXCoxMi9ediozLw&input=&args=NA+MTM+MTU+Mw) As an aside, here's something that's currently in development. ### Java w/ Vitsy Package Note that this package is work in progress; this is just to show how this will work in the future (documentation for this is not yet uploaded) and it is *not* golfed, and is a literal translation: ``` import com.VTC.vitsy; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; public class Volume { public static void main(String[] args) { Vitsy vitsyObj = new Vitsy(false, true); vitsyObj.addMethod(new Vitsy.Method() { public void execute() { vitsyObj.pushStackLength(); vitsyObj.callMethod(); vitsyObj.outputTopAsNum(); } }); vitsyObj.addMethod(new Vitsy.Method() { public void execute() { vitsyObj.push(new BigDecimal(3)); vitsyObj.powerTopTwo(); vitsyObj.push(new BigDecimal(4)); vitsyObj.push(new BigDecimal(3)); vitsyObj.divideTopTwo(); vitsyObj.multiplyTopTwo(); vitsyObj.pushpi(); vitsyObj.multiplyTopTwo(); } }); vitsyObj.addMethod(new Vitsy.Method() { public void execute() { vitsyObj.push(new BigDecimal(2)); vitsyObj.powerTopTwo(); vitsyObj.multiplyTopTwo(); vitsyObj.pushpi(); vitsyObj.multiplyTopTwo(); } }); vitsyObj.addMethod(new Vitsy.Method() { public void execute() { vitsyObj.multiplyTopTwo(); vitsyObj.multiplyTopTwo(); } }); vitsyObj.addMethod(new Vitsy.Method() { public void execute() { vitsyObj.tempVar(); vitsyObj.cloneStack(); vitsyObj.addTopTwo(); vitsyObj.addTopTwo(); vitsyObj.push(new BigDecimal(2)); vitsyObj.divideTopTwo(); vitsyObj.flatten(); vitsyObj.globalVar(); vitsyObj.push(new BigDecimal(3)); vitsyObj.repeat(new Vitsy.Block() { public void execute() { vitsyObj.globalVar(); vitsyObj.rotateRight(); vitsyObj.subtract(); } }); vitsyObj.globalVar(); vitsyObj.push(new BigDecimal(3)); vitsyObj.repeat(new Vitsy.Block() { public void execute() { vitsyObj.multiplyTopTwo(); } }); vitsyObj.push(new BigDecimal(1)); vitsyObj.push(new BigDecimal(2)); vitsyObj.divideTopTwo(); vitsyObj.powerTopTwo(); vitsyObj.tempVar(); vitsyObj.multiplyTopTwo(); vitsyObj.push(new BigDecimal(3)); vitsyObj.divideTopTwo(); } }); vitsyObj.run(new ArrayList(Arrays.asList(args))); } } ``` [Answer] # C, ~~100~~ 97 bytes ``` #define z(a,b,c,d) d?d*sqrt(4*a*a*b*b-pow(a*a+b*b-c*c,2))/12:c?a*b*c:3.14159*(b?a*a*b:4/3.*a*a*a) ``` edit 1: remove unnecessary decimal `.`, thanks Immibis! [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~57~~ ~~53~~ ~~51~~ 44 bytes ``` 3^4*3/YP*GpG1)*YP*GpG0H#)ts2/tb-p*X^3/*XhGn) ``` Input is an array with 1, 2, 3 or 4 numbers. [**Try it online!**](http://matl.tryitonline.net/#code=M140KjMvWVAqR3BHMSkqWVAqR3BHMEgjKXRzMi90Yi1wKlheMy8qWGhHbik&input=WzUuNSAyLjIzXQ) ### Explanation Instead of using nested `if` loops, which is expensive in terms of bytes, this computes four possible results for any input, and then picks the appropriate result depending on input length. When computing the results, even though only one of them needs to be valid, the others cannot give errors. This means for example that indexing the fourth element of the input is not allowed, because the input may have less than four elements. ``` % take input implicitly 3^4*3/YP* % compute a result which is valid for length-1 input: % each entry is raised to 3 and multiplied by 4/3*pi G % push input pG1)*YP* % compute a result which is valid for length-2 input: % product of all entries, times first entry, times pi G % push input p % compute a result which is valid for length-3 input: % product of all entries G % push input 0H#)ts2/tb-p*X^3/* % compute a result which is valid for length-4 input: % shorter version of Heron's formula applied on all % entries except the last, times last entry, divided by 3 Xh % collect all results in a cell array G % push input n) % pick appropriate result depending on input length % display implicitly ``` [Answer] # JavaScript ES6, ~~129~~ ~~126~~ ~~125~~ ~~116~~ ~~114~~ 90 bytes Saved lots of bytes (9) with a wonderful formula, thanks to Stewie Griffin! Since input must be nonzero, `variable?` will suffice for a defining-check. ``` with(Math){(a,b,c,h,Z=a*a)=>h?sqrt(4*Z*b*b-(D=Z+b*b-c*c)*D)/4:c?a*b*c:b?PI*Z*b:4/3*PI*Z*a} ``` ## Test it out! ``` with(Math){Q = (a,b,c,h,Z=a*a)=>h?sqrt(4*Z*b*b-(D=Z+b*b-c*c)*D)/4:c?a*b*c:b?PI*Z*b:4/3*PI*Z*a} console.log = x => o.innerHTML += x + "<br>"; testCases = [[4], [5.5, 2.23], [3.5, 4, 5], [4, 13, 15, 3]]; redo = _ => (o.innerHTML = "", testCases.forEach(A => console.log(`<tr><td>[${A.join(", ")}]` + "</td><td> => </td><td>" + Q.apply(window, A) + "</td></tr>"))); redo(); b.onclick = _ => {testCases.push(i.value.split(",").map(Number)); redo();} ``` ``` *{font-family:Consolas,monospace;}td{padding:0 10px;} ``` ``` <input id=i><button id=b>Add testcase</button><hr><table id=o></table> ``` [Answer] **Haskell, ~~114~~ ~~109~~ ~~107~~ ~~101~~ 99 bytes** ``` v[r]=4/3*pi*r^3 v[r,h]=pi*r^2*h v[x,y,z]=x*y*z v[a,b,c,h]=h/12*sqrt(4*a^2*b^2-(a^2+b^2-c^2)^2) ``` Takes a list of numbers and returns a volume. Call it like ``` v[7] ``` for a sphere, etc. The function is polymorphic for any type that implements `sqrt` (so, basically `Float` or `Double`). It's not going to win any contests for brevity. But note how *readable* it is. Even if you don't really know Haskell, you can tell what it does quite easily. Haskell's pattern matching syntax makes it really easy to define strange functions that do something totally different depending on the shape of the input. [Answer] ## PowerShell, ~~165~~ 161 bytes ``` param($a,$b,$c,$h)((($h/12)*[math]::Sqrt(($a+$b+$c)*(-$a+$b+$c)*($a-$b+$c)*($a+$b-$c))),(($a*$b*$c),((($p=[math]::PI)*$b*$a*$a),($p*$a*$a*$a*4/3))[!$b])[!$c])[!$h] ``` So ... Many ... Dollars ... (31 of the 161 characters are `$`, for 19.25% of the code) ... but, saved 4 bytes thanks to Stewie Griffin! We take in four inputs, and then progressively index into pseudo-ternary statements based on them in reverse order. E.g., the outside `(..., ...)[!$h]` tests whether the fourth input is present. If so, the `!$h` will equal `0` and the first half is executed (the volume of an irregular triagonal pyramid). Otherwise, `!$h` with `$h = $null` (as it's uninitialized) will equal `1`, so it goes to the second half, which itself is a pseudo-ternary based on `[!$c]` and so on. This is likely close to optimal, since the supposedly-shorter formula that (e.g.) [Cᴏɴᴏʀ O'Bʀɪᴇɴ](https://codegolf.stackexchange.com/a/75137/42963) is using is actually 2 bytes longer in PowerShell thanks to the lack of a `^` operator ... The only real savings comes from `(1/3)*(1/4)*A*$h` golfing to `A*$h/12`, and setting `$p` later to save a couple bytes instead of the lengthy `[math]::PI` call. [Answer] ## CJam, ~~67~~ 66 bytes ``` q~0-_,([{~3#4*P*3/}{~\_**P*}{:*}{)\a4*(a\[1W1]e!..*+::+:*mq*C/}]=~ ``` I will work on shortening it soon. [Try it online](http://cjam.aditsu.net/#code=q~0-_%2C(%5B%7B~3%234*P*3%2F%7D%7B~%5C_**P*%7D%7B%3A*%7D%7B)%5Ca4*(a%5C%5B1W1%5De!..*%2B%3A%3A%2B%3A*mq*C%2F%7D%5D%3D~&input=%5B4%2013%2015%203%5D)! Explanation to come. [Answer] ## Seriously, ~~65~~ ~~59~~ 55 bytes ``` `kd@;Σ½╗"╜-"£Mπ╜*√*3@/``kπ``ª*╦*``3;(^/4*╦*`k,;lD(E@i(ƒ ``` [Try it online!](http://seriously.tryitonline.net/#code=YGtkQDvOo8K94pWXIuKVnC0iwqNNz4DilZwq4oiaKjNAL2Bga8-AYGDCqirilaYqYGAzOyheLzQq4pWmKmBrLDtsRChFQGkoxpI&input=NCwgMTMsIDE1LCAz) ### Explanation This one is a doozy. I'm going to break the explanation into multiple parts. Main body: ``` `...``...``...``...`k,;lD(E@i(ƒ `...``...``...``...`k push 4 functions to a list ,;lD push input, len(input)-1 (E get the function at index len(input)-1 @i( flatten the input list ƒ execute the function ``` Function 0: ``` 3;(^/4*╦* 3;(^ push 3, r^3 / divide (r^3/3) 4* multiply by 4 (4/3*r^3) ╦* multiply by pi (4/3*pi*r^3) ``` Function 1: ``` ª*╦* ª r^2 * multiply by h (r^2*h) ╦* multiply by pi (pi*r^2*h) ``` Function 2: ``` kπ listify, product (l*w*h) ``` Function 3 (21 bytes; nearly half the program length!) ``` kd@;Σ½╗"╜-"£Mπ╜*√*3@/ kd@ listify, dequeue h, bring [a,b,c] back on top ;Σ½ dupe, sum, half (semiperimeter) ╗ push to register 0 "╜-"£M map: push s, subtract (s-x for x in (a,b,c)) π product ╜*√ multiply by s, sqrt (Heron's formula for area of the base) *3@/ multiply by h, divide by 3 (1/3*A*h) ``` [Answer] # Matlab, 78 bytes ``` @(a,b,c,d)pi*a^2*(4/3*a*~b+b*~c)+a*b*c*~d+d/12*(4*a^2*b^2-(a^2+b^2-c^2)^2)^.5; ``` Quite sure it can't get any shorter than this. `~b`, `~c` and `~d`, are `0` if each of the dimensions are non-zero. A formula with a zero dimension will just give zero. That way, each of the formulas can simply be summed. No `if` and `else` required. Call it like this (or [try it online here](http://ideone.com/6VZF9z)): ``` g=@(a,b,c,d)pi*a^2*(4/3*a*~b+b*~c)+a*b*c*~d+d/12*(4*a^2*b^2-(a^2+b^2-c^2)^2)^.5; g(4,0,0,0) ans = 268.082573106329 g(5.5,2.23,0,0) ans = 211.923986429533 g(3.5,4,5,0) ans = 70 g(4,13,15,3) ans = 24 ``` [Answer] # Python ~~3~~ 2, ~~127~~ ~~119~~ 116 bytes Credit to [somebody](https://codegolf.stackexchange.com/users/39244/somebody) and [Mego](https://codegolf.stackexchange.com/users/45941/mego) for all their help with golfing. Credit also to [Cᴏɴᴏʀ O'Bʀɪᴇɴ](https://codegolf.stackexchange.com/a/75137/47581) and [Josh](https://codegolf.stackexchange.com/a/75142/47581) as I borrowed parts of their answers for this one. ``` def v(a,b,c,d):z=a*a;P=3.14159;print filter(int,[max(0,(4*z*b*b-(z+b*b-c*c)**2))**.5*d/12,a*b*c,P*z*b,P*z*a*4/3])[0] ``` **Ungolfed:** ``` def v(a, b, c, d): z = a*a p = 3.14159 s = filter(int,[max(0,(4*z*b*b-(z+b*b-c*c)**2))**.5*d/12,a*b*c,P*z*b,P*z*a*4/3]) print s[0] ``` [Answer] ## Mathematica, 114 (103) **Pure function: 114** ``` Which[(l=Length@{##})<2,4.Pi/3#1^3,l<3,#1^2.Pi#2,l<4,#1#2#3,l<5,(4#1^2#2^2-(#1^2+#2^2-#3^2)^2)^.5#4/12]~Quiet~All& ``` Ungolfed: ``` fun = Which[ (l = Length@{##}) < 2, 4. Pi/3 #1^3, l < 3, #1^2 Pi #2, l < 4, #1 #2 #3, l < 5, (4 #1^2 #2^2 - (#1^2 + #2^2 - #3^2)^2)^.5 #4/12 ]~Quiet~All & ``` Usage: ``` fun[4] 268.083 fun[5.5, 2.23] 211.924 fun[3.5, 4, 5] 70. fun[4, 13, 15, 3] 24. ``` **If named functions are allowed: 103** ``` f[r_]:=4.Pi/3r^3 f[r_,h_]:=r^2.Pi h f[l_,w_,h_]:=l w h f[a_,b_,c_,h_]:=(4a^2b^2-(a^2+b^2-c^2)^2)^.5h/12 ``` Usage: ``` f[4] 268.083 f[5.5, 2.23] 211.924 f[3.5, 4, 5] 70. f[4, 13, 15, 3] 24. ``` [Answer] # Factor, 783 bytes Well, this took forever. ``` USING: arrays combinators io kernel locals math math.constants math.functions quotations.private sequences sequences.generalizations prettyprint ; : 1explode ( a -- x y ) dup first swap 1 tail ; : 3explode ( a -- b c d ) 1explode 1explode 1explode drop ; : spr ( r -- i ) first 3 ^ 4 3 / pi * swap * ; : cyl ( r -- i ) 1explode 1explode drop 2 ^ pi swap * * ; : cub ( v -- i ) 1 [ * ] reduce ; : A ( x a -- b d ) reverse dup dup dup 0 [ + ] reduce -rot 3explode neg + + -rot 3explode - + 3array swap 3explode + - 1array append 1 [ * ] reduce sqrt .25 swap * ; : ilt ( a -- b c ) V{ } clone-like dup pop swap A 1 3 / swap pick * * ; : volume ( v -- e ) dup length { { [ 1 = ] [ spr ] } { [ 2 = ] [ cyl ] } { [ 3 = ] [ cub ] } { [ 4 = ] [ ilt ] } [ "bad length" throw ] } cond print ; ``` Call `{ array of numbers } volume` . ]
[Question] [ # The Task In this challenge, your task is to draw an ASCII art representation of several stacks of boxes of increasing height. You are given as input the number of stacks, which is a positive integer. The first stack contains one box of size `2x2`. The second stack contains 2 boxes of size `3x3`. In general, the `k`th stack contains `k` boxes of size `(k+1)x(k+1)`. The borders of each box are drawn using the characters `-|+`, and their interior consists of whitespace. Adjacent boxes share their borders, and corners should always be drawn with `+`, even when they are part of a border of another box. # Examples Output for `1`: ``` ++ ++ ``` Output for `2`: ``` +-+ | | +-+ ++ | ++-+ ``` Output for `3`: ``` +--+ | | | | +--+ | | +-+ | | +--+ +-+ | ++ | | ++-+--+ ``` Output for `5`: ``` +----+ | | | | | | | | +----+ | | | | | | +---+ | | +----+ | | | | | | +---+ | | | | | +----+ +--+ | | | +---+ | | | | | +--+ | | | | +----+ +-+ +---+ | | +--+ | | +-+ | | | ++ | | | | ++-+--+---+----+ ``` # Rules and Scoring The input can be received from STDIN, as a command line argument, or as a function argument. Output **must** go to STDOUT or closest equivalent. Any finite amount of trailing whitespace is allowed, as are preceding and trailing newlines, but there cannot be any extra preceding spaces. This is code-golf, so the lowest byte count wins. Standard loopholes are disallowed. [Answer] # CJam, ~~64 60~~ 58 bytes ``` ]ri:X{'|'}{I))*\I**XX*)Se[s}:L~:M.e>S'-LaI*~M}fI]zN*'}/'+* ``` Constructing each column at a time. [Try it online here](http://cjam.aditsu.net/#code=%5Dri%3AX%7B'%7C'%7D%7BI))*%5CI**XX*)Se%5Bs%7D%3AL~%3AM.e%3ES'-LaI*~M%7DfI%5DzN*'%7D%2F'%2B*&input=5) [Answer] # Java (~~407~~ 349 chars) *A few chars thanks to @Zgarb and @Geobits* **Code** ``` void s(int q){int d,h,y,i,j,x,z,t=q*q+1;char b;for(i=0;i<t;i++){z=x=0;d=t-i;for(j=0;j<(q*q+q)/2+1;j++){b=' ';h=x*x+1;if(x==z){y=x+1;if((d<=h&d%(x==0?1:x)==(x==1?0:1))|(y<=q&d<=y*y+1&d%(y==0?1:y)==(y==1?0:1)))b='+';else if(d<=h|y<=q&d<=y*y+1)b='|';x++;z=1;}else{if(d<=h&d%(x==0?1:x)==(x==1?0:1))b='-';z++;}System.out.print(b);}System.out.println();}} ``` Not sure if this is optimal, but it's my first attempt, I will probably try to put it in a better golfing language later. Any suggestions are welcome! **Expanded** ``` class StackingBlocks{ public static void main(String[]a){ int d,h,y,i,j,x,z,t,q=10; t=q*q+1; char b; for(i=0;i<t;i++){ z=x=0; d=t-i; for(j=0;j<(q*q+q)/2+1;j++){ b=' '; h=x*x+1; if(x==z){ y=x+1; if((d<=h&d%(x==0?1:x)==(x==1?0:1))|(y<=q&d<=y*y+1&d%(y==0?1:y)==(y==1?0:1))) b='+'; else if(d<=h|y<=q&d<=y*y+1) b='|'; x++; z=1; }else{ if(d<=h&d%(x==0?1:x)==(x==1?0:1)) b='-'; z++; } System.out.print(b); } System.out.println(); } } } ``` [Check it out here.](http://ideone.com/3xDr4j) [Answer] # Python 2, ~~144~~ 128 bytes ``` n=input() i=n*n while-~i:j=x=1;l="";exec'y=i%j<1;z=i>j*j;l+=j*z*" "or"|+"[x|y]+" -"[y]*~-j;x=y^z>z;j+=1;'*n;print l+"|+"[x];i-=1 ``` Bit twiddling. Bit twiddling everywhere. [Answer] # Python, 188 bytes Mathematically calculates the character at each `x,y` position. It was tricky making the `+`s print on both sides of each box as well as stopping the rightmost `+`s of what would be `n+1`th boxes. ``` n=input();l=1;c=0 for y in range(n*n,-1,-1): s="" for x in range((n*n+n)/2+1):k=((8*x+1)**.5+1)/2;i=int(k);b=y<=i**2;s+=" |-+"[((k==i)+2*((y%l+c)*(y%i+(k==n+1))<1))*b];l=i;c=b^1 print s ``` [Answer] ## C# - 304 bytes (function) ``` void b(int s){int h=s*s,w=h+s>>1,x,y,j;var c=new int[w+1,h+1];for(;s>0;s--){for(y=s*s-s;y>=0;y-=s){x=s*s-s>>1;for(j=0;j<s;){c[x+j,y]=c[x+j,y+s]=13;c[x,y+j]=c[x+s,y+j++]=92;}c[x,y]=c[x+s,y]=c[x+s,y+s]=c[x,y+s]=11;}}for(y=h;y>=0;y--){for(x=0;x<=w;x++)Console.Write((char)(32+c[x,y]));Console.WriteLine();}} ``` or 363 bytes (full code) ``` namespace System{class C{static void Main(string[]a){int s=int.Parse(a[0]),h=s*s,w=h+s>>1,x,y,j;var c=new int[w+1,h+1];for(;s>0;s--){for(y=s*s-s;y>=0;y-=s){x=s*s-s>>1;for(j=0;j<s;){c[x+j,y]=c[x+j,y+s]=13;c[x,y+j]=c[x+s,y+j++]=92;}c[x,y]=c[x+s,y]=c[x+s,y+s]=c[x,y+s]=11;}}for(y=h;y>=0;y--){for(x=0;x<=w;x++)Console.Write((char)(32+c[x,y]));Console.WriteLine();}}}} ``` I tried to avoid if statements. Ungolfed: ``` namespace N { public class Explained { static void boxes(string[] args) { int size = int.Parse(args[0]); int height = size * size + 1; int width = size * (size + 1) / 2 + 1; var canvas = new int[width, height]; for (; size > 0; size--) drawboxes(size, canvas); for (int y = height - 1; y >= 0; y--) { for (int x = 0; x < width; x++) Console.Write((char)(32 + canvas[x, y])); Console.WriteLine(); } } static void drawboxes(int size, int[,] canvas) { int x = size * (size - 1) / 2; for (int i = size - 1; i >= 0; i--) { drawbox(x, i * size, size, canvas); } } static void drawbox(int x, int y, int size, int[,] canvas) { for (int i = 0; i < size; i++) { canvas[x + i, y] = 13; // +32 = '-' canvas[x + i, y + size] = 13; canvas[x, y + i] = 92; // +32 = '|' canvas[x + size, y + i] = 92; } canvas[x, y] = 11; // +32 = '+' canvas[x + size, y] = 11; canvas[x + size, y + size] = 11; canvas[x, y + size] = 11; } } } ``` [Answer] # Ruby (205 bytes) Takes the number as a command line arguments. It starts with a fail leading newlines, but that's allowed. ``` n=$*[0].to_i m=n+1 f=m.times.inject(:+)+1 c=((" "*f+p=?+)*n*m).split p y=0 1.upto(n){|b|(b*b+1).times{|x|d=x%b==0;r=c[x] d&&b.times{|g|r[y+g]=?-} r[y]=d||r[y]==p ?p:?| r[y+b]=d ?p:?|} y+=b} puts c.reverse ``` [Answer] # JavaScript (ES6), 293 bytes ``` (n,o='',r,f,t,u,b,c,e=n*n+1,i)=>{for(t=0;e>t;t++){for(c=b=0,d=e-t,u=0;(n*n+n)/2+1>u;u++)i=" ",r=b*b+1,b==c?(f=b+1,d<=r&d%(0==b?1:b)==(1==b?0:1)|n>=f&d<=f*f+1&d%(0==f?1:f)==(1==f?0:1)?i="+":d<=r|n>=f&d<=f*f+1&&(i="|"),b++,c=1):(d<=r&d%(0==b?1:b)==(1==b?0:1)&&(i="-"),c++),o+=i;o+="\n"}return o} ``` I ran this in Firefox. Ignore the `"` the console adds between the strings. This is mostly ES5 stuff but I'll try to golf this more. Ungolfed / ES5 ``` function box(n, o, r, f, t, u, b, c, e, i) { if (o === undefined) o = ""; if (e === undefined) e = n * n + 1; return (function() { for (t = 0; e > t; t++) { for (c = b = 0, d = e - t, u = 0; (n * n + n) / 2 + 1 > u; u++) i = " ", r = b * b + 1, b == c ? (f = b + 1, d <= r & d % (0 == b ? 1 : b) == (1 == b ? 0 : 1) | n >= f & d <= f * f + 1 & d % (0 == f ? 1 : f) == (1 == f ? 0 : 1) ? i = "+" : d <= r | n >= f & d <= f * f + 1 && (i = "|"), b++, c = 1) : (d <= r & d % (0 == b ? 1 : b) == (1 == b ? 0 : 1) && (i = "-"), c++), o += i; o += "\n"; } return o; })(); } document.getElementById('g').onclick = function(){ document.getElementById('o').innerHTML = box(+document.getElementById('v').value) }; ``` ``` <input id="v"><button id="g">Run</button><pre id="o"></pre> ``` [Answer] # Python 2, ~~294~~ 290 I got it working, but I still need to golf it more. I'm so happy, though, that was tough (for me, at least)! I'll probably add an explanation later, unless it's immediately clear to someone...? I kind of doubt it. [**Try it here**](http://ideone.com/opaUt4) ``` n=input() w=n*n+n+2>>1 a=eval(`[[' ']*w]*-~n**2`) r=range j=[i*i+i>>1for i in r(n+1)] p=0 for i in r(w): if i in j: p+=p<n for k in r(p*p+1):a[~k][i]='+'if k%p<1or' '<a[~k][i-1]<'.'else'|' else: for k in r(p*p+1):a[~k][i]=' 'if k%p else'-' print'\n'.join(''.join(i)for i in a) ``` [Answer] # Python - 243 bytes Generates all the columns, replacing the overlaps on columns except the first one. Then it pads with spaces, transposes, and prints. ``` Q=input() Y=[] for i in range(Q): f="+"+i*"-"+"+";x=map(list,zip(*([f]+["|"+" "*i+"|"]*i)*(i+1)+[f])) if i:y=Y.pop();x[0][-len(y):]=y Y+=x print"\n".join("".join(i)for i in zip(*["".join(j[::-1]).ljust(Q*Q+1," ")for j in Y])[::-1]) ``` I am considering translating to Pyth, but I will need a replacement for the pad function. ]
[Question] [ *This is a [repost](https://codegolf.meta.stackexchange.com/questions/24851/repost-word-stays-a-word-after-taking-away-a-letter) of [this](https://codegolf.stackexchange.com/questions/145222/word-stays-a-word-after-taking-away-a-letter-repeat) challenge* --- # Challenge There is an old, popular riddle: > > Find an English word with 8 letters that, taken away one letter, creates a new valid word. Repeat that until there are no letters left. > > > Example solution: ``` starting staring string sting sing sin in I ``` Your task is to write a program, which takes a dictionary and outputs the longest word, that still occurs in the dictionary after repeatedly taking away a letter. # Rules * All words will be lower case and contain only ASCII-letters * If multiple valid words have the same length you can output any one of those * The dictionary will never be empty * If there isn't any solution in the dictionary, then you have to output nothing/return an empty list/a falsey value * You're allowed to output a list representing the process of removing each letter (eg.`['this', 'his', 'is', 'i']`) * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins! # Examples ``` In: ['this', 'hat', 'his', 'hi', 'is', 'i', 'a', 'at'] Out: this In: ['pings', 'aid', 'ping', 'ad', 'i', 'in', 'a'] Out: aid In: ['a', 'ab', 'bac'] Out: ab In: ['a', 'aa', 'aaaa'] Out: aa In: ['as', 'i', 'his', 'that', 'ping', 'pin', 'in', 'was', 'at', 'this', 'what', 'is', 'it', 'and', 'a', 'in', 'can', 'if', 'an', 'hand', 'land', 'act', 'ask', 'any', 'part', 'man', 'mean', 'many', 'has', 'stand', 'farm', 'eat', 'main', 'wind', 'boat', 'ran', 'heat', 'east', 'warm', 'fact', 'fast', 'rain', 'art', 'heart', 'am', 'arm', 'sit', 'train', 'sat', 'gas', 'least', 'fit', 'flat', 'cat', 'bit', 'coast', 'sand', 'beat', 'hit', 'party', 'wing', 'wash', 'bat', 'meat', 'suit', 'fat', 'meant', 'coat', 'band', 'win', 'seat', 'hat', 'salt'] Possible outputs: 1. stand (stand -> sand -> and -> an -> a) 2. heart (heart -> heat -> eat -> at -> a) 3. train (train -> rain -> ran -> an -> a) 4. least (least -> east -> eat -> at -> a) 5. coast (coast -> coat -> cat -> at -> a) 6. party (party -> part -> art -> at -> a) 7. meant (meant -> meat -> eat -> at -> a) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḊÐḟ¹-Ƥf¥Ƈ@Ƭ⁸ẎṪ ``` A monadic Link that accepts a list of lists of characters and returns a list of characters or zero (falsey) if no solution is possible. **[Try it online!](https://tio.run/##RVExTsQwEPwKXRr4A/9AFJsQxz6cHIqNopRUSBSIH9AczekekKO8k/KP3EcM2RlD47F3Z2Znk03t/ZjSMr2dP5bp83S8mXfm9DW/3s6Hy8u0fL8vx31K6a6QUFxfFW49rNN7tBJXfHJdQ1SKngP4YEQqBirwcnqX7kHhX1oJfAzaOpEsn9kVtOERnFHnS6/VFpq2JrJtkShEehjp2xVroYrBHdrlFvWeCUirJUTsB7VhFMN6Txtm@ZXhIi2qCgGrx0wO8G6Q0OcZBjTj0a4AJarVlqzAfUomtOivX2PkQg3/iFUe9yU9PHPKX7nL/hhH@4FR8xSqxcfi/gc "Jelly – Try It Online")** ### How? ``` ḊÐḟ¹-Ƥf¥Ƈ@Ƭ⁸ẎṪ - Link: list of lists of characters (words), W Ðḟ - filter out those for which: Ḋ - dequeue (i.e. remove words of length > 1) (let's call this list of single-character words S) ⁸ - with W as the right argument... Ƭ - collect up input, I (initially S), while distinct applying: @ - with swapped arguments - f(W, I): Ƈ - filter keep those (w in W) for which: ¥ - last two links as a dyad - f(w, I): Ƥ - for overlapping outfixes (of w)... - - ...of size: -1 (i.e. outfixes of length one less) ¹ - ...do: nothing (i.e. get all potential sub-words of w) f - filter keep -> sub-words which are in I (an empty list is falsey) -> words in W which can be shorted to any of those in I -> reachable word lists ordered by word-length plus an empty list Ẏ - tighten -> list of all words reached Ṫ - tail -> (one of) the longest one(s) or 0 if empty ``` ...that's some pretty serious Jelly right there I reckon. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 45 bytes ``` N^$` $.& +Gml`.|(.*).(.*)(?=(?s).+^\1\2$) 0G` ``` [Try it online!](https://tio.run/##JU/baoNAEH2f75CiDSxN30se89YvCMHRuu7S1YTdKRLIv5tztqAjc65jniyuetz372vTS@Pe5HBeUu@erXvvHEd7@mpPpXOH6@V4@Ww6@Tj3@65FooRYxIKa3OM6cwieDRQgI7mRxDea6PojSn5UyDx2CcRSJUYIyi/Ah9w1myygl4mDUEBkMQq95kUmpYBVEdBww5oZR3zSYjgBKs9QzzVTy1QoMHUR8gVHWaUKfDMqUjV74D4BGvEOWMYb4cL6gRUBGI98sH/m/wYZeBLJ8kf7/7ZWL0Jo3VhU7VRpshc "Retina – Try It Online") Explanation: ``` N^$` $.& ``` Sort the list of words in descending order of length. ``` +Gml`.|(.*).(.*)(?=(?s).+^\1\2$) ``` Repeatedly delete words of two or more letters that cannot be reduced to another word in the list by the deletion of a letter. ``` 0G` ``` Keep only the first (i.e. longest) (if any) word. [Answer] # JavaScript (ES6), 91 bytes ``` f=(a,p=o='',n)=>p[n]||a.map(w=>w!=p&p.match([...w,,].join`?`)==p&&f(a,w,-~n),o[n]?0:o=p)&&o ``` [Try it online!](https://tio.run/##bVLLasMwELz3K9qLH6CYngtKPiQEsrEtW6ktCUupCYT@umtrVimUXrTa3ZnZWVtX@iJfT9qFnbFNuyxKFiSctDLPhSnl3h3N6fGgaiRXzHI/v0mXuTULdV8cq6qahThVV6vN@XAu5drM1Cowi923KYVdyYf3DytdmWV2qa3xdmirwXaFKo556LXPxWveU4iBM72duMcrxSPkp7J8@SvhtOkiknSzhS2PafOkawOR/@j0O4WnBzaThBzoOGfggUjuZ2aw43gn0zydg1oTdBTaWBuoIaFrcP0nMPc4n6ZYHcEZW47c7uHIB9ZQNI1bbIlZbFyjfbGoT@yAYS35gP3AVmxFcX1iGfay0nChEdUYPFYPCeyh3cHhkGYowNSAdo1wQbW2jPK8z6VNbyOkr3HnhTr@I33E8b4M9zee8iybpI9xLD@z1TSF2TTE17b8AA "JavaScript (Node.js) – Try It Online") ### How? We start from the empty string and try to build the longest possible word from there. This is more efficient than taking each word and trying to reach the empty string because we'd need to keep track of the original word, or at least its length. When looking for a word \$w\$ of \$n+1\$ characters which is a valid successor of a previous word \$p\$ of \$n\$ characters, it would be easier to do something like: ``` [...w].some((_,i)=>p==w.slice(0,i)+w.slice(i+1)) ``` But this is quite verbose. Instead, we look for a word \$w\$ which contains all the letters of \$p\$ in order but is not equal to \$p\$: ``` w!=p&p.match([...w,,].join`?`)==p ``` The problem is that \$w\$ may contain more than just one additional letter. For instance, we can go directly from `man` to `meant`. So we have to check its length afterwards, but we keep track of the current expected length in \$n\$ anyway to avoid the use of `.length` and this is still overall shorter. ### Commented ``` f = ( // f is a recursive function taking: a, // a[] = input dictionary p = // p = previous word in the chain, initially empty o = '', // o = output n // n = expected length of the previous word ) => // p[n] || // abort if p is too long a.map(w => // otherwise, for each word w in a[]: w != p & // force the test to fail if w is equal to p p.match( // build a pattern consisting of: [...w,,].join`?` // each letter of w followed by a '?' ) // if this regular expression applied to p == p // is matching p (which means that p can be obtained && // by taking some letters of w in order): f(a, w, -~n), // do a recursive call with p = w and n + 1 // before the loop starts: o[n] ? 0 // do nothing if the length of o is greater than n : o = p // otherwise, update o to p ) // end of map() && o // return the final output ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~96~~ 95 bytes Thanks to [movatica](https://codegolf.stackexchange.com/users/86751/movatica) for a byte saved! ``` f=lambda d,w='':max([f(d,c)for c in d if{w}&{c[:i]+c[i+1:]for i in range(len(c))}]+[w],key=len) ``` [Try it online!](https://tio.run/##RVJBjoMwDLz3FTktoHJZ7Q2JlyAOJiQQFQIiqVhU9e0syTjdS@zYM@MxZD38uNif89T1RHPXk@jLvc6yaqbfvNF5X8pCL5uQwljRC6Nf@/vrJZvKtHfZmPt31Ya2Ce2N7KDySdlcFsW7vTd7Wz7UUV@V4vTKeSdq0WR@NC4rRTaSj4FvJpzIY0rx8FlbXpzV2CG2yPQhhHu89h@8sWBFPP3rsL7ncYm5Ao9zBx6I5G9nBnuKOdn@4w1USdDRaGMxoKaEluC6BzBHnE9brM7gzIojt0c4cp41NG1ziIqYxcYN2t2C@sYOGKbIeewHtmYrmusby7CXi4aEZlRjcFjdJ7CD9gCHU5qhAdMT2hKhQ1UujHK8T6fS3/fpaxy80MB/ZIw43pfh7slTPmWb9DGO5Xe2mqYwm6brPd1u4cX68GLjo6xuQqybsT7XuS@K8w8 "Python 3 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` ~₃≬£⁰'ẏ⋎¥↔;İft ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ+4oKD4omswqPigbAn4bqP4ouOwqXihpQ7xLBmdCIsIiIsIlsnYXMnLCAnaScsICdoaXMnLCAndGhhdCcsICdwaW5nJywgJ3BpbicsICdpbicsICd3YXMnLCAnYXQnLCAndGhpcycsICd3aGF0JywgJ2lzJywgJ2l0JywgJ2FuZCcsICdhJywgJ2luJywgJ2NhbicsICdpZicsICdhbicsICdoYW5kJywgJ2xhbmQnLCAnYWN0JywgJ2FzaycsICdhbnknLCAncGFydCcsICdtYW4nLCAnbWVhbicsICdtYW55JywgJ2hhcycsICdzdGFuZCcsICdmYXJtJywgJ2VhdCcsICdtYWluJywgJ3dpbmQnLCAnYm9hdCcsICdyYW4nLCAnaGVhdCcsICdlYXN0JywgJ3dhcm0nLCAnZmFjdCcsICdmYXN0JywgJ3JhaW4nLCAnYXJ0JywgJ2hlYXJ0JywgJ2FtJywgJ2FybScsICdzaXQnLCAndHJhaW4nLCAnc2F0JywgJ2dhcycsICdsZWFzdCcsICdmaXQnLCAnZmxhdCcsICdjYXQnLCAnYml0JywgJ2NvYXN0JywgJ3NhbmQnLCAnYmVhdCcsICdoaXQnLCAncGFydHknLCAnd2luZycsICd3YXNoJywgJ2JhdCcsICdtZWF0JywgJ3N1aXQnLCAnZmF0JywgJ21lYW50JywgJ2NvYXQnLCAnYmFuZCcsICd3aW4nLCAnc2VhdCcsICdoYXQnLCAnc2FsdCddIl0=) [Answer] # [Zsh](https://www.zsh.org/), 98 bytes ``` A=($@) f()for ((i=0;i++<$#w;))(w[i]=;((!#w||A[(I)$w]))&&f)&&break for w;(($#w>$#a))&&f&&a=$w <<<$a ``` [Try it online!](https://tio.run/##NZHLboMwEEX3fEWqILCVTfeBqln2G6IsBoKDVR4RdmSlyr9TfK@zYDyeOXce@M/1q1Farada5d8623wzLzulbP15tIdDle/DUWsVzvZSH5X62IfX63RWPzoPF62Lwmxfs3Tym0Vd2JBN8ZXvBcmikDoPWVVVuaw6y8yu9L115a7sxUdL324GXnQkfr6M7N1OtxgWey15i5drAu0EOoLyFrOgZ/UkuAOECQCRTHMEouwePZmuaQgoWoHYIIO5kR8S1kLifpF@xmayxNAIeOx4MNWjufOUGlnG7eiEOMezSDUzggsbkujEeSwAlWFjw@BCNTtvPE4ZEYrWYTGfMId6NwwzpLIGhBmQamEbhNqZgOPQTZeezadVn5z6xn/bR4QLEXQPFn7HplQTDVgycKhUmCoZ@P7THG/z8PB2nsr1Hw "Zsh – Try It Online") ``` A=($@) # save the arguments so we don't have to pass them in the recursive calls f() # { <- implicit for ((i=0;i++<$#w;)) ( # enter a subshell, so changes to $w here # and $i in the recursive call won't affect their values here w[i]= ((!#w||A[(I)$w])) && # if $w is empty or is found in $A, f # recurse. If f exited truthy, ) && break # then the subshell exits truthy, and we break # } <- implicit for w # for each word (($#w > $#a)) && f && # if it is the longest word found so far, a=$w # set it as our answer <<<$a # output our answer ``` [Answer] # Python3, 130 bytes: ``` lambda d:max([i for i in d if f(i,d)],key=len) f=lambda x,d:len(x)==1 or any(f(T,d)for i in range(len(x))if(T:=x[:i]+x[i+1:])in d) ``` [Try it online!](https://tio.run/##VVKxboQwDN37FdlIdCynLhUS631BN8pgCAHrIKAk1cHXU4gdTl1ix37v@RmybGGY7efX4vZH@bOPMDUahC4mWGWFwsxOoEArtEAjjMRcqzp/dls5dlZ9mJIJa66LoyJXVZZ3cZDAbtLI7wN@STiwfScJpfBoFuVaFVjf1gpv96JW5xi1Lw5tkA9ZZWFAn@UiGyDEwDc8T8pjCvEIWa3Ux5u8oO0jBlCf4bzHq76IaIn@nwhvZZ4Y2ECSWIhI54vwhEiOX8xglzEHqy@3RG2BdAy1aVVCjQndEtc/CbPF@eBidSLO1HHk9kCOfGANA246YwfMYuNI7WamumMHDOvAB9qP2IatGK47lmEvB40SmKgag6fVQwJ70u7J4ZhmGIKZkdothYaq7cwoz/s0XXoPIX2NjRfq@Y8MEcf7Mtz/8pSrbJM@jWP5F1tNU5gNY3xh@x8) [Answer] # [J](http://jsoftware.com/), 43 bytes ``` 0{](#~1*@#.(1=#&>)+]e."1(1<\.])&>)^:_@\:#&> ``` [Try it online!](https://tio.run/##XVDLTsJAFN3zFTc0sQV0pNtRDNHElXHhFtBMS4dW20I6Ywgh6a/Xc4YNcTHT3vO87fcwVrGVhZZYbmUuGudOycvH2@swP2@SqE@ny0gl6SK6eZrMNoUap0n6uFabCeZP/bVcazDDZPT@rCSBJepX@qzH6UrP1L2oKTT94r/x4hoVebkXKw869mXlpDRewrMS3JUYMT6@Eh2qdufEVFvhm5gtNFUr5lpjaGSIZ1rQ4aLsCApQaDqSZIcX025RBD43kFnM2ANYHYgcAvcD8CQH03lpQDcFL0IlIp2n0JqukcJQwKoKULbH2DGOeGGcxwpQWYZajh21TIUCt2mEvMNSPlAOvh0q6mC2wG0NKMfJMOR7wo71WRF@nQ9Lnti/4/eWknElku6X9svUBi9CaD2yKNipMrWPhz8 "J – Try It Online") *-4 bytes thanks to [Neil's clever idea](https://codegolf.stackexchange.com/a/249426/15469)* My original approach was to construct an adjacency matrix and self multiply it to a fixed a point, and then use the final column as a mask on the sorted input. But it turned that Neil's idea was slightly shorter. In both approaches, we get to use `1<\.]` J's outfix adverb to produce all the possible strings with 1 character deleted. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` ⊞υωFθ≔⁺υΦθ‹№υκ⊙κ№υΦκ⁻μξυ⊟υ ``` [Try it online!](https://tio.run/##RVJBboMwELz3Fb5hJPcFOUWVemol7lEOhmJsxZjEa4fyegreIeXAmNmZ3Vmgszp2k/br2mSyMisx16c3M0UhH7U4E7khyMZn2kufzqc@yocSXz2R/JhySDt/q5U4h0XelHhx0G7UtwubfVTit@ZLibzNaKLblM10l7muT@t6uVSaKiUqt9@sK@dkddrx7sIALJJyn1nPigTHDAc/uXLW4afAv7XT3MdwuUyEyh/qjr10Y81S5utY2JE9Yw9E2XIiSuhhdBx37DVcCO643E7MRySArNeUeD92G0Qx4CPaIMtm44MemS1AvHo6xMS9B07ojxmGZcZzuWNomd1@DFYR9mmR0HJ9fxsLFhrwRWzRYV/IKWPKiw5Hfx6H9jOiHlPg1j5V1@v6/vR/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υω ``` Start with a list of just the empty string. ``` Fθ ``` Loop enough times. ``` ≔⁺υΦθ‹№υκ⊙κ№υΦκ⁻μξυ ``` Append all words that don't yet exist in the list but which do when one of their letters is removed to the list. ``` ⊟υ ``` Output the last word from the list. If the input was in ascending order of length then it would be only 20 bytes: ``` ⊞υωFθF⊙ι№υΦι⁻λν⊞υι⊟υ ``` [Try it online!](https://tio.run/##RVC7boQwEOzzFe4AiXzBVVGkdJHoT1cYgrEVY4gfh/h6gj1D4sKznp3dnfWgpR8WaY@jS0HXqRVbc3tRixf1TyMKvrm9Nq14X5KLWfBhbBx9pj6NS6G2rXBNPuJqYc4WnTenvFvWOjXN7Tju98pUrahkuUK@jStxLDGY@M8bVbLQzPnWEK3Ib2gi3VeGgcIhov83cnuGGTmNghEDPQs8CnyZEGAgQDKhQIEcQPZ4aUAPUgE2w0HlFYmn3wlv@N/Ia1q3xJVe5hHWZtpXNDdLLm6g7xf24UajDHBBveJnKPKe9cpKbsk@45/7iR@r6QO6xA/gvJ514cpLC4xMnIawSbxG2svb2QNBXna/to3V43G8Pu0v "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` éæéʒ€gāQ}ʒü.LP}θ ``` Pretty slow for big input-lists. Outputs the sequence of the longest word instead of just the longest word (e.g. `["a","ad","aid"]` instead of `aid`). [Try it online](https://tio.run/##yy9OTMpM/f//8MrDyw6vPDXpUdOa9CONgbWnJh3eo@cTUHtux///0UoFmXnpxUo6SomZKUASxANxQOxMEM4D8ZRiAQ) or [verify the first two test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/wysPLzu88tSkR01r0o80BtaemnR4j55PQO25Hf91/kdHK5VkZBYr6ShlJJaASAg7E0iAWSBGIgiXKMXqRCsVZOalg4QTM1OAJIgH4qRAFWbmgVWDFGakgo0rLkksKoGqAukrKUoEKwITxRCJYjAHqKGoBGoOTC9UHmgG1AiIMJQHNaoE5PDYWAA). **Explanation:** ``` é # Sort the (implicit) input-list on length (smallest to largest) æ # Pop and push the powerset of this list é # Sort that by length as well ʒ # Filter this list of lists by: €g # Get the length of each word in the list ā # Push a list in the range [1,list-length] (without popping the list itself) Q # Check if both lists are the same }ʒ # After the first filter: filter again: ü # For each overlapping pair of words: .L # Calculate the Levenshtein distance P # Product: check if all Levenshtein distances are 1 }θ # After the filter: pop and leave the last/longest list # (which is output implicitly as result) ``` [Answer] # [Haskell](https://www.haskell.org), 118 bytes ``` d#w=any(\y->y==[]||y`elem`d&&d#y)[take i w++drop(i+1)w|(i,c)<-zip[0..]w] f d=snd$maximum$[(length x,x)|x<-filter(d#)d] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVNBjtswDAR6zCuEJFjYSLJobz2s-4k9ugaWtqRYiOQYlrKOi_ykl70UfVP7h_6htobKFvWBpEgOOZSp7z9b8idl7dvbj0vQh8-_XuVmLKibsq_T4ctUFGV1u00vyir3Ih8e5GbKy0AnJYwYdzs5nPvM7D7l4y0z-yZ_Onwzffnx8bEaq5UWsvCd3Dq6Gndx2zKzqjuGVlz31_x2fTpoY4MaMrnJZYXuvz_8kV4UolyJ-SvXoTV-vRfrlkJUfDKLhB1NiiKsqz3jetMdY5iMXNRyjkd5x5gOyDsGRepF1tT872dJ_wLeCTCxwDxTux5NIEfkIyMNNjKCh4k2dfI-FKANoY5GGDeCLJuyG2D9CTlT7E9D9DpgnGLN4RaMfOAamga3aEWMYuIG4foM_8AMOE2RD5gPaM1UNPsHLsNcZhgMcvBG5TF6SMketY9gaFMPjTRtEW6ganibM2d5nqdWaW1Cuo2JBzryH2nxuwNfD-AX7nJ3d6k-2nH5kammLowmOy9iXJFqtVrucN7n_hKewyC2wrfncVaOejE_D4-tT2_vLw) ]
[Question] [ ## Incremental Game Time Format ### Goal Incremental games often have a countdown timer expressing the days, hours, minutes and seconds until a task is complete. Depending on the space available, they can be formatted as: ``` 2d 13h 23h 59m 48s 14m 3h 0m 0s ``` The goal of this code golf is to write a function or program that performs this formatting. ### Inputs * The total number of seconds. * The maximum number of segments to output. ### Output * Segments include: + **0w** weeks + **0d** days + **0h** hours + **0m** minutes + **0s** seconds * Each segment is separated by a single space. * Displayed segments must be contiguous. For example, you will not show hours and seconds without showing minutes, even if there are zero minutes. * Single-digit values do not have leading zeros, though a value of zero must be shown as `0`. * Values are rounded down. * The first segment displayed is the first non-zero value. ### Test Cases ``` seconds segments output 0 1 0s 123 1 2m 123 2 2m 3s 123 3 2m 3s 82815 3 23h 0m 15s 307891 2 3d 13h 307891 4 3d 13h 31m 31s 604800 1 1w 604800 6 1w 0d 0h 0m 0s ``` ### Winning The lowest byte-count solution in one week will win "acceptance". ### Edits * Clarified which segment is first, as shown in examples. * Added test case 4 as per request. [Answer] # CJam (snapshot), ~~41~~ 38 bytes ``` q~"<<^X^G"{imd\}%W%"wdhms":s.+_{0=}#><S* ``` The above uses caret notation, since two of the characters are unprintable. *Thanks to @Sp3000 for golfing off 2 bytes.* ### Testing The latest stable release (0.6.5) has a [bug](https://sourceforge.net/p/cjam/tickets/72/ "CJam / Tickets / #72 {}# can return an Integer") that can cause `{}#` to return Integers instead of Longs. Quite paradoxically, this can be circumvented by casting to integer (`i`). To run this with code with the online interpreter, click [this permalink](http://cjam.aditsu.net/#code=q~%22%3C%3C%18%07%22%7Bimd%5C%7D%25W%25%22wdhms%22%3As.%2B_%7B0%3D%7D%23i%3E%3CS*&input=2%20307891) or copy the code from [this paste](http://pastebin.com/x5hQRGhD). Alternatively, you can download and build the latest snapshot by executing the following commands: ``` hg clone http://hg.code.sf.net/p/cjam/code cjam-code cd cjam-code/ ant ``` You can create the CJam file like this: ``` base64 -d > game-time.cjam <<< cX4iPDwYByJ7aW1kXH0lVyUid2RobXMiOnMuK197MD19Iz48Uyo= ``` ### How it works ``` q~ e# Read an evaluate the input. "<<^X^G" e# Push the string corresponding to the array [60 60 24 7 { e# For each character: i e# Replace it by its code point. md e# Push divisor and residue of the division by that code point. \ e# Swap their order. }% W% e# Reverse the resulting array. "wdhms":s e# Push ["w" "d" "h" "m" "s"]. .+ e# Perform vectorized concatenation. _ e# Push a copy. {0=}# e# Find the index of the first pair with positive integer. > e# Remove the preceding pairs. < e# Truncate to the number of pairs specified in the input. S* e# Join, separating by spaces. ``` [Answer] # Java, ~~197~~ 191 bytes ``` String p(int s,int m){String a[]={s%60+"s",(s/=60)%60+"m",(s/=60)%24+"h",(s/=24)%7+"d",(s/7)+"w"},b="",z="";for(s=5;s>0&&a[--s].charAt(0)=='0';);for(;s>=0&&--m>=0;z=" ")b+=z+a[s--];return b;} ``` I just noticed that Java supports declaration like `String a[]`. This allowed me to pull the declaration of `b` and `z` into the same line, which saved me from writing `String` again. [Answer] # C, 134 127 110 104 103 bytes New Version: ``` a,e=5;f(n,x){for(;e;n%=a)a=(int[]){1,60,3600,86400,604800}[--e],x>e?printf("%u%c ",n/a,"smhdw"[e]):0;} ``` Previous Version: ``` #define p(a) x>--e?printf("%u%c ",n/a,"smhdw"[e]):0;n%=a; e=5;f(n,x){p(604800)p(86400)p(3600)p(60)p(1)} ``` [Answer] # Pyth, ~~39~~ 43 bytes ``` jd_>vz+V?u?GeGPG+m%~/QddCM"<<"Q)Q]0"smhdw ``` edit: +4 chars, because I forgot the `0s` test case. This includes 2 unprintable chars. Get the actual code and try it online: [Demonstration](http://pyth.herokuapp.com/?code=jd_%3Evz%2BV%3Fu%3FGeGPG%2Bm%25~%2FQddCM%22%3C%3C%18%07%22Q%29Q]0%22smhdw&input=2%0A0&debug=0) ### Explanation: ``` z = 1st input line (segments, as string) Q = 2nd input line (time, as int) "<<.." string with 4 chars CM convert to ASCCI-values => [60,60,24,7] m map each d of ^ to: /Qd Q / d ~ update Q, but use the old value for % Q d Q mod d this gives [sec, min, hour, day] + Q add Q (week) u ) apply the following expression to G, starting with G = [s,m,h,d,w], until G stops changing: ? eG if eG != 0: G update G with G (stop changing) else: PG update G with G[-1] this gets rid of trailing zeros +V "smhdw vectorized add with "smhdw" >vz only use the last eval(z) items _ reverse order jd join by spaces and print ``` [Answer] ## Python 2.7 - ~~181~~ ~~178~~ 174 bytes My first attempt to golf something. ``` def I(s,M): z=[0]*5;j=0 for i in [604800,86400,3600,60,1]:z[j],s=s/i,s%i;j+=1 l=[z.index(n)for n in z if n][0] return" ".join([str(i)+n for n,i in zip('wdhms',z)][l:l+M]) ``` [Answer] # Julia, 158 bytes I'm sure this could be shorter with a more clever approach, but this is what I have for now. ``` (s,g)->(j=0;p=cell(5,1);for i=[604800,86400,3600,60,1] p[j+=1],s=s÷i,s%i end;z=findfirst(p);z>0?join([string(p[i],"wdhms"[i])for i=z:min(z+g-1,5)]," "):"0s") ``` This creates an unnamed function that accepts two integers as input and returns a string. To call it, give it a name, e.g. `f=(s,g)->...`. Ungolfed + explanation: ``` function f(s, g) # Initialize an array and an index p = cell(5, 1) j = 0 # Loop over the number of seconds in a week, day, hour, # minute, and second for i in [604800, 86400, 3600, 60, 1] # Set the jth element in p to be the quotient and s # to be the remainder of i into s p[j+=1], s = s ÷ i, s % i end # Get the index of the first nonzero value in p z = findfirst(p) if z > 0 # We start the string at the first nonzero value # and continue until we hit the desired number of # units (z+g-1) or the maximum number of units (5), # whichever comes first. The appropriate unit is # appended to each value and the values are then # joined with a space. join([string(p[i], "wdhms"[i]) for i in z:min(z+g-1,5)], " ") else # If there are no nonzero values in p, we just # have 0 seconds "0s" end end ``` Examples: ``` julia> f(82815, 6) "23h 0m 15s" julia> f(604800, 4) "1w 0d 0h 0m" ``` [Answer] ## Scala, 147 bytes ``` def p(s:Int,i:Int)=List(s/604800+"w",s/86400%7+"d",s/3600%24+"h",s/60%60+"m",s%60+"s").dropWhile(k=>k.head=='0'&&k.tail!="s").take(i).mkString(" ") ``` [Answer] # [rs](https://github.com/kirbyfan64/rs), 367 bytes ``` ^(\d+)/(_)^^(\1) (_*) (\d)/\1!\2 _{60}/# #{60}/@ @{24}/: :{7}/; (_+)/(^^\1)s (#+)/(^^\1)m (@+)/(^^\1)h (:+)/(^^\1)d (;+)/(^^\1)w ([a-z])/\1 w ((\d+[^\dd])|!)/w 0d \1 d ((\d+[^\dh])|!)/d 0h \1 h ((\d+[^\dm])|!)/h 0m \1 (m|^) ?!/\1 0s! !(\d+)/!(_)^^(\1) # +#(\d+)([a-z]) ?(.*)!(_*)/\1\2 #\3!\4@ #/ (@+)/ (_)^^((^^\1)) !(_+) \1(_*)/!\2 _+ _+/ +\d+[a-z] ?!_/! *!/ ^$/0s ``` [Live demo and all test cases.](http://kirbyfan64.github.io/rs/index.html?script=%5E(%5Cd%2B)%2F(_)%5E%5E(%5C1)%0A(_*)%20(%5Cd)%2F%5C1!%5C2%0A_%7B60%7D%2F%23%0A%23%7B60%7D%2F%40%0A%40%7B24%7D%2F%3A%0A%3A%7B7%7D%2F%3B%0A(_%2B)%2F(%5E%5E%5C1)s%0A(%23%2B)%2F(%5E%5E%5C1)m%0A(%40%2B)%2F(%5E%5E%5C1)h%0A(%3A%2B)%2F(%5E%5E%5C1)d%0A(%3B%2B)%2F(%5E%5E%5C1)w%0A(%5Ba-z%5D)%2F%5C1%20%0Aw%20((%5Cd%2B%5B%5E%5Cdd%5D)%7C!)%2Fw%200d%20%5C1%0Ad%20((%5Cd%2B%5B%5E%5Cdh%5D)%7C!)%2Fd%200h%20%5C1%0Ah%20((%5Cd%2B%5B%5E%5Cdm%5D)%7C!)%2Fh%200m%20%5C1%0A(m%7C%5E)%20%3F!%2F%5C1%200s!%0A!(%5Cd%2B)%2F!(_)%5E%5E(%5C1)%0A%23%0A%2B%23(%5Cd%2B)(%5Ba-z%5D)%20%3F(.*)!(_*)%2F%5C1%5C2%20%23%5C3!%5C4%40%0A%23%2F%0A(%40%2B)%2F%20(_)%5E%5E((%5E%5E%5C1))%0A!(_%2B)%20%5C1(_*)%2F!%5C2%0A_%2B%20_%2B%2F%0A%2B%5Cd%2B%5Ba-z%5D%20%3F!_%2F!%0A%20*!%2F%0A%5E%24%2F0s&input=0%201%0A123%201%0A123%202%0A123%203%0A82815%203%0A307891%202%0A307891%204%0A604800%201%0A604800%206) Messy, messy, messy... Takes about 3-7 seconds to execute the test cases on Chrome for Android. Do *not* use debug mode, which can freeze your browser in this case because of all the output that would be printed. [Answer] ## C#, 239 237 170 164 bytes This is no where near as compact as other solutions, but I can't pose this challenge without having a stab at it myself. This latest iteration was inspired by [ESC's answer](https://codegolf.stackexchange.com/a/52796/4934). Indented for clarity: ``` string G(int s,int n){ int[]x={s%60,(s/=60)%60,(s/=60)%24,(s/=24)%7,s/7}; for(s=5;x[--s]==0&s>0;); var o=""; while(n-->0&s>=0) o+=" "+x[s]+"smhdw"[s--]; return o.Trim(); } ``` ]
[Question] [ > > Inspired by [this](https://chat.stackexchange.com/transcript/message/61670136#61670136) > > > Your task today: given two strings, find the string with the lowest maximum [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) to the input strings. For example, using `Steffan` and `Seggan`, the average string will be `Steggan`. It is distance 2 from `Steffan` (replace the `gg` with `ff`), and 1 from `Seggan` (add a `t`). That gives it a maximum distance of 2. Other constraints: * If there are multiple possibilities, output any of them or all of them (duplicates are OK) * The inputs are distinct * The input will be given in uppercase or lowercase ASCII, you choose * There will always be common letters in the inputs * The outputs will only have letters from the inputs * There will always be a solution satisfying the above constraints As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins. ## Testcases ``` seggan, steffan -> ['seffan', 'sefgan', 'segfan', 'stefgan', 'stegfan', 'steggan'] (2) hello, ho -> ['hllo', 'hlo', 'helo', 'heo'] (2) string, ring -> ['tring', 'sring'] (1), aaa, aaaa -> ['aaa', 'aaaa'] (1) abc, abcd -> ['abc', 'abcd', 'abd', 'abca', 'abcb', 'abcc'] (1) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` Þ∪Þx:ƛ□꘍GN;ÞMİ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnuKIqsOeeDrGm+KWoeqYjUdOO8OeTcSwIiwiIiwic3RyaW5nXG5yaW5nIl0=) I think `Þ∪` can be `J`, but that makes it so slow that it's practically impossible to run. This is already really, really, really slow. ``` Þ∪Þx:ƛ□꘍GN;ÞMİ Þ∪ # Get the multiset union of the two strings Þx # Get all combinations without replacement of all lengths and of all orders : # Duplicate (call this X) ƛ # Over each: □꘍ # For each of the inputs, get the Levenshthein distance between that input and this string G # Get the maximum of that N # Negate that ; # Close map ÞM # Get the indices of maximal elements. (If Vyxal had an "indices of minimal elements" builtin, then negate could be removed.) İ # Index this into X ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` JæΣ.L{R}н ``` Outputs one possible result. [Try it online](https://tio.run/##yy9OTMpM/f/f6/Cyc4v1fKqDai/s/f8/Wim4JDUtLTFPSUcpODU9HciIBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@9Di87t/jQOj2f6qDaC3v/6/yPjlYKLklNS0vMU9JRCk5NTwcyYnUUopUyUnNy8oFiGfkQfnFJUWZeOlAATIGFEhMTgfxEEAXhJyWD@EnJKUqxsQA). **Explanation:** ``` J # Join the (implicit) input-pair together to a single string æ # Pop and get the powerset of this string Σ # Sort it by: .L # Get the Levenshtein distance of the two strings with the (implicit) input { # Sort the pair from lowest to highest R # Reverse it from highest to lowest }н # After the sort-by: leave the first result # (which is output implicitly as result) ``` Note: if we'd use `à` (max) instead of `{R`, it would also give results where the Levensthein distance is `[2,2]` even if `[1,2]` are available. If we'd use just `{`, it would give results where the Levensthein distance is `[0,3]` over `[1,2]`. So using the `{R` ensures the minimum pair while prioritizing the maximum of the pair. --- Although it works for the test cases, I'm not 100% sure if `Jæ` is *always* correct. Using [an additional group-by (and uniquify) to get all results](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@9Di87t/jQOj2f6qBavUMLoawLew/P/K/zPzpaKbgkNS0tMU9JRyk4NT0dyIjVUYhWykjNyckHimXkQ/jFJUWZeelAATAFFkpMTATyE0EUhJ@UDOInJacoxcYCAA) shows that `Stegfan` and `Segfan` aren't among them for example, since the powerset builtin uses characters of the joined string in order. This could be fixed by changing it to `Jœ€æ˜` [+3 bytes] (powerset of each permutation of the joined string), but it becomes extremely slow and [it'll timeout](https://tio.run/##yy9OTMpM/f/f6@jkR01rDi87PefcYj2f6qBavUMLwfSFvYdn/v8frRRckpqWlpinpKMUnJqeDmTEAgA). [Answer] # [Factor](https://factorcode.org) + `lcs math.combinatorics`, ~~123~~ ~~120~~ 78 bytes ``` [ 2dup append all-subsets [ tuck [ levenshtein ] 2bi@ max ] 2with infimum-by ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZCxTsMwEIb3PMW9QDp0QiAhNsTSBTFVHS7OObbq2I7vTKiqPglLFth4Gba-DQ5BUCz9_q3vP_3S-fVdo5KQpvPn0-PD5v4akDkoBqYhk1fE0KOYlQp9Yz2WSVvCPSVPDpz6SUNqKUFMJHKIyXqBYYSbqjpWUM4wHktd16EHFtK6-Ok3MORcABMuEEup6OD7-qOIOAsvUaNmtf8RAaqWCju9ZdH11XmzhXWbI2CM5FtA52rODZMwbEGy2hdz9EyejZD1sIN1Y-_KZi_zc7RiwHpt-9zXzQF2S-uHXn7qtscIq4VN0-Jf) -42 bytes(!) using the idea behind @KevinCruijssen's [05AB1E answer](https://codegolf.stackexchange.com/a/250701/97916). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ∑ṗµ?꘍sṘ;h ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiJHhuZfCtT/qmI1z4bmYO2giLCIiLCJbXCJTdGVmZmFuXCIsXCJTZWdnYW5cIl0iXQ==) Port of Kevin Cruijssen's answer, go upvote that! [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~95~~ 93 bytes ``` J._+k._KwFGUz=ZJ=J]+_._<zhGkVlK aJh.mlb[+<zhG@ZhN+eJ<KhN+m+d@zG@ZN?q@zG@KNY]+e@ZN@KN;@eJ/leJ2 ``` [Try it online!](https://tio.run/##FYhPC0YwGMDvPoX7U1OuyE7Us9qNeklr8rAyIurNvvzM6ffneG7jPTIFK1PiX9WNKzoscADFVO5MvbZWxBoN2@zYw3d4ZyQQ5iJgg4m7cGR5fhTyNwCFDJZxwsQSpt5ftCx6j66b5lnvLw) I know what you're thinking: "That seems long." In my defense, it's been a while since I've touched Pyth. Furthermore, this runs in Ο(m·n·max(m,n)) time, where m, n are the lengths of the two input strings. This is wicked fast and can handle pretty long strings with ease. I used [this](https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows) algorithm from Wikipedia, but instead of keeping track of the distance, I keep track of the optimal path throughout. Then at the end we can simply output the middle element of the optimal path. This must satisfy the requirements, as if there were some string with a lower max distance, there would then exist a shorter path. [Answer] # [Python](https://www.python.org), 150 bytes ``` n=lambda A,B:{a[:x]+y+a[z:]for a in A for x in range(len(a)+1)for z in[x,x+1]for b in B for y in[*b,""]} f=lambda A,B:(N:=n(A,B))&(M:=n(B,A))or f(N,M) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVM9T8MwEJUY8ytOQaI2dRHdUKQitTtsTJGHc3A-pOBUsUENiL_BwsIC_wl-DT47aQsefM_vvTv7HOf9azu4ujMfH5-Prlxcfb-ZVYsP6h5hLTbZC-bZTs6HOebPmSy7HhAaA2sguCPYo6k0a7VhyOdLTvyz5_Od2M2XIUORbRMyBlLOlUhT-ZqUxxux22xlmEecn7Ebwhux5tznlOxW3PB4up-TO6ets7CCNE0Tq6sKjQDrdFmigcU15DMb8EwAoWpC1cS5A-mOWao0k0mt27YTUHexWO1XZKjHoKfYea91fWMqATRHeyBCwQBkgogC_IRR94BUIkhUhRdVcT-KqgiiJ2IcQ4FjVGMsfC61n9CVto3RdMHhXi7stm0cUZbxLAE_mjJY4oLG1h_NMeL4ngtFViHEEixdXKcH3TehRj2_lBfU-JbxySrgyNrTx9FP2IYt8qXkyV4bSCtZjlJAriT_d6bBHhhqrQ_vyx6OHqxo7R_idMzu-V8fkcB6Ecsc1w4dWat7N2nxdU3_wC8) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~92~~ 88 bytes ``` (c=Characters/@#;""<>#&/@MinimalBy[Subsets@*Join@@c,Max[EditDistance[x,#]&/@c]/.x->#&])& ``` [Try it online!](https://tio.run/##DcvNCgIhEADgd1FYKrZ8gNoY@rkEC0FH8TCZ6w6kgU5gRM9u3r7LF5BnF5DJYvVDXdjhOGNCyy5lBXIrxG4vOwUjRQr4PHz07X3PjjOsLi@KALYfsejzg/hEmTFap0svTSvWqE1Zt22WXb0migweviI77zGKXmR209T0q38 "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ We are to define the idea of a *fixed list* as follows: * A **fixed list** is a list of fixed lists. This definition is recursive so it's useful to look at some examples. * The empty list `[]` is a fixed list. * And list of empty lists is a fixed list. e.g. `[[],[],[]]` * Any list of the above two is also a fixed list. e.g. `[[],[],[[],[],[]]]` We can also think of these as "ragged lists" with no elements, just more lists. ## Task In this challenge you will implement a function \$g\$ which takes as input an fixed list and as output produces a fixed list. The only requirement is that there must be some fixed list \$e\$, such that you can produce every fixed list eventually by just applying \$g\$ enough times. For those more inclined to formulae, here's that expressed as symbols: \$ \exists e : \mathrm{Fixt}, \forall x : \mathrm{Fixt} , \exists n : \mathbb{N}, g^n(e) = x \$ You can implement any function you wish as long as it meets this requirement. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being the goal [Answer] # [Python 2](https://docs.python.org/2/), ~~168~~ 164 bytes -3 thanks to [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)! (In-place list addtion `r=...;r+=[]` to `r=...+[]` >.<) No doubt there is a far terser way, but this is quite a fun way... ``` j=''.join n=int(j(`ord(c)%3`for c in`input()`if','<c),2) while 1: try:n+=1;r=eval(j('[]'[i<'1']for i in bin(n)[2:]).replace('][','],['))+[] except:1 else:exit(r) ``` A full program that accepts a fixed list as input and prints the next fixed list in an order defined by a binary encoding where `[` is a `1` and `]` is a `0` (ignoring and `,`). The integer sequence of this ordering is listed on the OEIS under [A057547](https://oeis.org/A057547 " A014486-encodings of Catalan mountain ranges with no sea-level valleys, i.e., the rooted plane general trees with root degree = 1."). **[Try it online!](https://tio.run/##FcxBDoMgEADAu6/g0iwbjQn2RstLCImWYlxDVkJpq6@n9janSUdZNh5qXQ1Av27EDRviIlc5bvkpPV6u47xl4QXxSJzeReJIM3Rw99gN2HwXikEo3YiSD82tUbdswmeKZwHWgaU7KHD/g85DPIglox20wz6HFCcfJDh7hq6zgNha14iw@5CKVqfiK@iwU5EZa7XuBw "Python 2 – Try It Online")** ...or see [this slightly augmented code](https://tio.run/##HY/BbsMgEETvfAWXalnFjWpXvZDwJQTVGG8aHLpYxG2Tr3dx9rI70urNzPxYLpm7NeSRDACc1qmu/ZQjCzaRFzWpPpdRBXx578@5yCAj95Hnn0VhH8/QwDFg06H4u8REstVCLuWheWfaQzH061NFgHVg4xFacBsjVoYcIitG22mH@0Jz8oEUOFuBrrGAuLNOSLoHmhfd1ivdSHtTDkMhf11rVqtfWye8NLJ@PhOZ5L@H0WsvNpfPzaV4/iLVfbxhDVZnLlspj09Bdwpqq47rPw "Python 2 – Try It Online") to see the the ordering. ### How? First the input list is encoded as a binary number by reading left to right and treating encountered `[` as `1`s and `]` as `0`s. Then this number is incremented and we form the decoded pattern of `[` and `]` , place `,` between any `][` and try to evaluate this as Python code. If this evaluates as a list\* we exit and print that list representation to STDERR. If not, we increment our number and try again. \* There are also strings we form that are valid tuples, rather than lists, like `"[],[]" -> ([], [])` which we must ignore. This is handled by attempting to concatenate an empty list to the end inside the `try` block, which fails for tuples, and is a no-op for lists. [Answer] # [Python](https://www.python.org), 170 bytes ``` d=lambda X:(1-(","in str(X)))*len(str(X))//2 e=[[]] def f(X):L,*R=X or e;return X and(d(R)and(d(L)and(R and[d(L)*e]+(d(R)-2)*e or d(X)*e)or[f(L)]+~-d(R)*e)or[L]+f(R))or e ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NVAxbsMwDNz1CsKTaEtIGmQIHOgF1eTJgKDBhajGgCMHqjJ06Ue6ZGmH_ii_iWSnXMi7I48Ev38vn-k0h9vt55q8PNz_nJqG85sboG_5i-SVqMYAHynyHhHriQJ_gs1mx0gZYy1z5MFnrtWi7lQPcwQ6RkrXGKCHITjueIdr1kvuCmsKqsk2iyx3uS6jLjvVhHM0Puu2-ZJFXhltG58Blg3Pi1-1Mpb5zIyQT41DeCe-32LLIMcljiHxUWhBwakKQEqAChdNq7KArS37rdC4Wv4_4wE) #### Old [Python](https://www.python.org), 200 bytes ``` d=lambda X:1+max([*map(d,X),-1]) s=lambda X:1+sum(map(s,X)) e=[[]] def f(X):L,*R=X or e;return X and(~d(R)==-s(R)and(~d(L)==-s(L)and(R and[-~d(L)*e]+~-d(R)*e or-~d(X)*e)or[f(L)]+d(R)*e)or[L]+f(R))or e ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZAxbsMgGIV3TvErE78NUiJliFxxgjB5QkIMVEBiqcYWtqV2yUW6ZGnP0iv0NgU7lcIC33vvfwg-v8eP-TrE-_1rmQM__f448Wb7V2dBNYe6t-9UV70dqWMKGT8YJNNzYFp6Wuwp20i80NoY4nyAQBU2klWtUDAk8C_Jz0uKoMBGR2-OtigEn_L2YLmxXLktKc1XufKmvvEyUPlcVUSVjzgkHbJt6s0qLE0dMmC58PGesxTakJCVDroIycaLp8c9NgTyGlMXZ9oxyXx0YgfAOcAOV0-KUk-2yHHPJG6V_1_1Bw) This enumerates based on an order which sorts first by number of nodes and then by "breadth-over-depth", i.e. for example [[],[],[]] < [[[[]]]]. These are the first and last with 3 nodes (plus root). How does it look in between? We split into first element and of root list and root list minus first element and order first by number of nodes within either; the example has 0,2 ([[],[],[]] -> [], [[],[]]) and 2,0 ([[[[]]]] -> [[[]]], []). Whatever conceptual gaps may be still there are resolved recursively, with lexicographic order at each split. The implementation has to find the direct successor of its input. This is done using the same recursive splitting. To manage the "carry" in the lexicographic and outermost orderings we use helper functions d (depth) which returns the height of subtree under investigation but only if it is a pure tower and therefore has no successor, triggering carry to the next more significant subtree. Carry simply means the triggering subtree is reset to a flat list and the triggered subtree is incremented if possible. If not, the number of nodes is incrermented and the entire tree reset to flat. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 102 bytes ``` I=([h,...t])=>h?h[0]?[D(h),...I(t)]:[I(t)]:[[]] D=([h,...t])=>t[0]?[I(h),...D(t)]:h[0]?[[],...D(h)]:[] ``` [Try it online!](https://tio.run/##VYyxDoIwEEB3vuLGNmBTVxFZWOqgg2NzQ4NAawg1bWNijN9eKbA4vcu7d/dQL@VbZ55hN9l7F6OoiNQFYywgrU661pJjLRuiaZKCBIoHuUEiZs1fH5ZabHWzZOsHiavR6RBjbx0QBRXMHsxMXs44wp6nIc8LSEtBFKXwyQBaO3k7dmy0AznfrhfmgzPTYPp3SsrsG38 "JavaScript (Node.js) – Try It Online") `I` calculate succ, while `D` calculate prev. I hope it corrects... --- # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 94 bytes ``` I=([h,...t])=>h?h[0]?[D(h),...I(t)]:[I(t)]:[[]] D=(a,b=[],U=uneval)=>U(I(b))==U(a)?b:D(a,I(b)) ``` [Try it online!](https://tio.run/##LYuxDoIwFEV3vuKNrwEbXMHKwoKDDoap6VAQaBUpKZWEGL8di3E6N/fec5eznGqrR7ebRn1r7NMMj2ZZ14IhVxGl1AnCjipTPBYZz1GRrSzQEZHwP7gQQc5QRhXjIirZa2hm2XutxAIrQhgrUZKsSnL/@TVrayygBAZeAO0Zpx4H2MdbCMMItrHwGoF3AFCbYTJ9Q3vT4el6OdPJWT10ul22Sxp81i8 "JavaScript (SpiderMonkey) – Try It Online") [Answer] # JavaScript (ES6), 134 bytes Expects and returns a string. ``` f=(S,i=0)=>(F=(n=i++,o=r=[],s=[])=>n?n%2?F(n>>1,q=[],[...s,o],o.push(q)):s[0]?F(n>>1,s.pop(),s):F():JSON.stringify(r))()==S?F():f(S,i) ``` [Try it online!](https://tio.run/##NY2xjsIwEER7vsINYlfxWYEysEmX4gooXEYpEOBghLzBy52EEN8ebCSanaeZWc1l/7@XQ/Tj/Sfw8TRNjsBqTyVSDS1BIF8UmilS12tJJ/mhCfNV00Ko66W@5aAzxojmXrMZ/@QMN8RKurL/lsSMPAJqwaoFrH7tbmvkHn0YvHtARAQksk3OXJ7HyXEEq0gtun6hVUhUrpNs1LLMUBSonjOlDhyErydz5QEsrpOTn9yHX9Mb "JavaScript (Node.js) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 54 bytes ``` , (^|]\[)(\[)*(?<4-2>])*(]*)$ [$3$#4$*1] 1 [] ]\[ ],[ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX4eLSyOuJjYmWlMDiLU07G1MdI3sYoGsWC1NFa5oFWMVZRMVLcNYLkOu6FguoEKuWJ3o//@B7OjoWDChA6GBJIyrA5eBCkKEwCwQHculAFcJ14DQDFaDMAMqgqFGB2IUQgTMjwUA "Retina 0.8.2 – Try It Online") Link includes test cases. Directly calculates the next string of equal numbers of `[`s and `]`s that satisfy the conditions that every prefix contains more `[`s than `]`s, ordered by length and then lexicographically. Explanation: ``` , ``` Remove all commas from the input. ``` (^|]\[)(\[)*(?<4-2>])*(]*)$ ``` Match a run of `[`s followed by a run of `]`s at the end of the string. Capture starting either at the beginning of the string (for an input of that form) or just after a `][` pair. Subtract the count of `[`s from the count of `]`s. (This is done by matching a `]` for every `[` using a .NET balancing group, and then matching the leftover `]`s at the end.) ``` [$3$#4$*1] ``` Insert the leftover `]`s followed by a `[]` pair (marked with a `1` for now) for each `[`, the whole thing being wrapped in `[` and `]`, which make up for the `][` pair matched at the start, but also serve to extend the string if it was of the form `[` followed by `]`s. ``` 1 [] ``` Expand the `1`s into `[]`s. (This can be written more succinctly in Retina 1 using `[$3$#4*$([])]`.) ``` ]\[ ],[ ``` Restore all necessary commas. [Answer] # [Ruby](https://www.ruby-lang.org/), 156 bytes ``` f=->l,x=1,q=p{r=0;w=x.digits(2).map{|d|r+=d+d-1};w.pop==0&&w.max<0&&(k=eval x.digits(2).map{|x|"]["[x]}.reverse.join.gsub("][","],[");q)?k:f[l,x+1,q||l==k]} ``` [Try it online!](https://tio.run/##Zc69DoMgGIXhvVdhGIxGJNix9msvhDBoQEPViuAPjXjtls7dTvLkJK9Z6s95NpA/euygwBPo3QAtN3BEqFbNNrmmZKj07oU3GYhM5MVRbkSPGoDG8RbQ3cNIOpBr1Ud/P@cRZ4g5fhAjV2msJK9RvUlrlzr5EUYcM5SWU/rsbg0LIVkI8b4H6PhxGmD8UlBKyawGaXcdGWiYCfIF "Ruby – Try It Online") Work in progress. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes ``` ≔⁻S,θ≔…⮌θ⌕⮌⁺][θ[]η⪫⪪⪫⟦…θ⁻⁻LθLη²[×]⁻№η]№η[×[]№η[¦]⟧ω][¦],[ ``` [Try it online!](https://tio.run/##VY7LCsIwEEX3fkXJKoW4cduVFARFoVh3QxalhiYQk77Fr4@TNLYIYR6ZuedOLau@tpV27jgMqjH0psw00LNpp7Ece2UamrKEMIKxS7Nd3Mo/tRa5tC29i1n0g6AdLpyUea4fhUYO4UC80DOAE58lUgoEj/RilaFlq1UsYaN2LFkOWeJVmGaUwSOW0qMOCxcdHuolvBv56XI7oYPEMfenby3gEekqAK/4HwYJZ8k7VEBCYn6SOQcEABt8MXGOy24/6y8 "Charcoal – Try It Online") Link is to verbose version of code. Note that Charcoal's default input auto-converts a fixed list from JSON input format, so you actually have to wrap the string in JSON for Charcoal to read it as a string. Explanation: Port of my Retina 0.8.2 answer. ``` ≔⁻S,θ ``` Remove commas from the input. ``` ≔…⮌θ⌕⮌⁺][θ[]η ``` Get the suffix of the string after the last `][` (or the whole string if there is no `][`). ``` ⪫⪪⪫⟦…θ⁻⁻LθLη²[×]⁻№η]№η[×[]№η[¦]⟧ω][¦],[ ``` Concatenate the prefix of the string, a `[`, `]`s to make up the difference in numbers of `[`s and `]`s in the suffix, `[]`s for each `[` in the suffix, and a final `]`, then reinsert commas as necessary. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes ``` ¯[Dæ«DÙDÅΔIQ}>èDgĀ#\ ``` [Try it online!](https://tio.run/##ASwA0/9vc2FiaWX//8KvW0TDpsKrRMOZRMOFzpRJUX0@w6hEZ8SAI1z//1tbW11dXQ "05AB1E – Try It Online") [All values](https://tio.run/##ATMAzP9vc2FiaWX/wrjOu8Kp/8KvW0TDpsKrRMOZRMOFzpTCrlF9PsOoRGfEgCNc/112eSz/W10 "05AB1E – Try It Online") Uses the fact that the infinite list defined by repeatedly applying `x += powerset(x)` (+ is list concatenation) contains all fixed lists (it's easily proven with induction). It repeatedly does that, starting from the empty set, and each time looks at the element following the input in the current list uniquified. If the input isn't in the array it will look at the -1 + 1 element which is an empty set so it will continue. If the input is the last element due to modular indexing it'll also look at the first element and continue. Otherwise, there is a next element, and it will output it. ]
[Question] [ You are employed as Administrator in charge of Road Maintenance and Planning. The intelligence division of the Agency for Road Maintenance and Planning has come up with a brilliant and not at all inefficient way to take random sample pictures of the roads: missiles with cameras on them. In this genius and not at all wasteful technique, smart non-explosive missiles are sent hurtling down each road. Each missile moves in a straight line and captures images at equal spatial intervals. Eventually the Agency will get a good overall sample of the state of affairs for each road. On Masagaki Road, for example, images are captured at positions 1, 4, 5, 6, 8, 11, 12 and 14: `1 X X 4 5 6 X 8 X X 11 12 X 14` (X represents no image) Your job is to find the largest number of images that could have been captured by the camera on a single missile. A single camera could have captured the three images at positions 4, 5, 6 (having a spacing of 1); the three images at positions 4, 6, 8 (spacing 2); or the three images at 4, 8, 12 (spacing 4). However, here the answer is four: positions 5, 8, 11, 14 (spacing 3). **Input:** a sequence of \$1\leq n\leq1000\$ unique integers, each satisfying \$1\leq i\leq1000000\$, representing the positions of the images captured for a certain road. These will be given from smallest to largest. **Output:** a single integer representing the largest number of images that could have been captured by a single camera. ## Sample 1 Input: `1 4 5 6 8 11 12 14` Output: `4` ## Sample 2 Input: `5 8 9 10 12 15 16 17` Output: `3` --- * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the shortest code in bytes wins. * [The](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/) [linked](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) [rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * Please explain your code. * Please link to Try It Online! or another online demo. --- Inspired by ['Air Drop' (AIO 2007, Senior)](https://orac.amt.edu.au/cgi-bin/train/problem.pl?set=aio07sen&problemid=341) [Answer] # [Python 2](https://docs.python.org/2/), 74 bytes ``` lambda l:max(reduce(lambda i,x:i+(a+i*(b-a)==x),l,0)for a in l for b in l) ``` [Try it online!](https://tio.run/##LY1BbsMgFET3PsWIFdQ4CqmdtpbIRdoucG0rSBgjoJJzevfjZjf/zWMIj3xf/WWf9dfuzDKMBq5fzMbjNP7@TPzJrNx6W3NT2xc@NEZovQnp5FnMawTVHg4lDkcUu13CGjPSI1VV4c76qVQETimP1vcVkCSMT9BYTOApR2qiDfKQTyk4mzlrbkwIch1piSankRfb@iyRnpI4jP8pKjilAiKdM3clhkgcTqLsSUQKnww16EMetS4P6GLfbFdo0eGKdygFdYFq0dzQVh2RD6jzwTqoK9RbaV7/AA "Python 2 – Try It Online") Tries every possible sequence of the form `a,b,...` with `a` and `b` in the input `l`. To find the smallest index `i` of this arithmetic progression that's outside `l`, we do something a bit unusual. Instead of counting up the progression to find an element not in `l`, we iterate over `l`, taking advantage of it being sorted. For each successive element `x` of `l`, we move to the next index in the arithmetic progression if its current value matches `x`, and stay at the current index otherwise. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` æʒ¥Ë}€gà ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8LJTkw4tPdxd@6hpTfrhBf//RxvqKJjoKJjqKJjpKFjoKBgC@YZGQGwSCwA "05AB1E – Try It Online") ``` æ # power set ʒ } # filtered by: ¥ # deltas Ë # all equal €g # length of each à # maximum ``` [Answer] # [Python 2](https://docs.python.org/2/), 98 bytes ``` f=lambda l,i=1:i/l[-1]or max(f(l,i+1),*[g(a,l,i)for a in l]) g=lambda a,l,i:a in l and-~g(a+i,l,i) ``` [Try it online!](https://tio.run/##NY/BboMwEETvfMWIk11M2k0hTZHIjyAOrgipJWMs24fk0l@na9Ledmbe7Gr9I32v7rhtc2/18jVpWGV66syrHWoa14BF38Us2K1IqpfhJrRiIWeONIyDHWVx@y/vWff0od1U/zBfmb2xmcWvISE@YlHkujXumkk2DjFNxnUFEBX3Inq@60VMgZNgvNrhQ/TWJFHWl1JKZi1jkVdeJ5Fp45JC/IPkTjxXcSB4ykZgyd/k0Qf2@V3kfQqBh6FEBT4oQt/nAqtyLDdCgxYnnEEEOoIa1Bc0RcvOJ@ht91rQCfSRk/df "Python 2 – Try It Online") A function that takes in a list of integers and returns the max number of images **Approach**: Try for each element `a` in the list, and for each increment `i` in the range `1` to `max(l)`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` I⊟Φ⊕Lθ⊙θΦ⌈θ¬⁻⁺×…⁰ι⊕νλθ ``` [Try it online!](https://tio.run/##TYzBCsIwEER/ZY9bWMFKFcGTCIJgpYi30kOoSw0kW5umol8fV/TgwAwMM7z2ZkLbG5dSFaxE3JkxYtXfcW9d5IAHaQN7lshXPLJ08YZDlhFs5YUDwe9Vmqf1k9eJ4NRHLK1MI1ZO42I9j3g20jHOCaw@/pnygTm1Ur/apFTXOUFBsCRYEawJcu35Ql00TZo93Bs "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array L Length ⊕ Incremented Φ Filter over implicit range θ Input array ⊙ Any element where θ Input array ⌈ Maximum Φ Filter over implicit range where …⁰ι Range of length given by outer index × ⊕ν Multiplied by incremented inner index ⁺ λ Offset by selected element ⁻ θ Set difference with input array ¬ Is empty (i.e. this is a subset) ⊟ Take the last (i.e. highest) element I Cast to string for implicit print ``` The second `Φ` would be `⊙` except Charcoal doesn't support this. [Answer] # JavaScript (ES6), 89 bytes ``` A=>A.reduce((a,x)=>[...a,...a.map(y=>x-2*y[0]+y[1]?y:(b+=!!y[b],[x,...y]))],[[]],b=0)|b+1 ``` [Try it online!](https://tio.run/##XctNDoIwFATgvbdg18qj4RHAn6Q1nKPpooViNEgJqKGJd6/FpZvJJPPNXb/10s636ZmNrrOh56HhomGz7V6tJUTDSrmQjDENW7CHnojnYs2KvZe5Sr1EdfFnYlKeJF4aBXLdpFeUxi6VAsNz@jEphtaNixssG9yV9EQilFBBDUdABCwAy/jZ/aEqzifA/AcqwBrwEFn4Ag "JavaScript (Node.js) – Try It Online") ### Commented ``` A => // A[] = input array A.reduce((a, x) => // for each value x in A[], // using a[] as the previous list of lists: [ // build a new list of lists: ...a, // append all previous lists stored in a[] ...a.map(y => // for each list y[] in a[]: x - // if both y[0] and y[1] are defined 2 * y[0] + // and (x - y[0]) is not equal y[1] ? // to (y[0] - y[1]): y // leave y[] unchanged : // else: ( b += // increment b if: !!y[b], // y[b] is defined (i.e. the length of y[] is b+1) [x, ...y] // prepend x to y[] ) // ) // end of map() ], // end of the new list of lists [[]], // start with a[] containing a single empty list b = 0 // start with b = 0 ) // end of reduce() | b + 1 // return b + 1 ``` [Answer] # [Red](http://www.red-lang.org), 127 bytes ``` func[b][m: 0 repeat s t: last b[n: 1 forall b[d: s until[either find b b/1 + d[n: n + 1][m: max n m n: 1 d: t]t < d: d + s]]]m] ``` [Try it online!](https://tio.run/##PYwxDsIwFEP3nsI7A/2oLRBxCtboDwlJRKQ0VOmvxO1D2oHN9rNdvKtP7zR3QaGGLb@0ZT0r9Ch@8UawQhSSWQVWZwVC@BSTUnNONbhliUn7KG9fuhCzg4U9E05wez03QcfhbL7NzTg@2lRY8NiFa5WVmWeuS4lZEKAJA0ZMuIEIdAENjO5Px5bfQf1BRtAEunL9AQ "Red – Try It Online") Naive imperative solution. ## Explanation: ``` f: func [b][ m: 0 ; the max number of images so far repeat s t: last b [ ; s (for step) is a list 1..last n: 1 ; current max forall b [ ; iterate over the input d: s ; current step until [ ; and do the following : either find b b/1 + d [ ; if there is a number in the list that is equal ; to the current number + the current step n: n + 1 ; increase the current max ][ ; else m: max n m ; update max, n: 1 ; reset current max d: t ; and set the current step at the last number ] t < d: d + s ; until current step is beyond the last number ] ] ] m ; return max ] ``` [Answer] # [Perl 5](https://www.perl.org/), 111 bytes ``` $_=max(map{$j=$_;(grep{(reduce{$a.(' 'x(-1+$b-length$a)).'x'}@F)=~join'.'x$j,('x')x$_}1..$F[-1])[-1]}0..$F[-1]) ``` [Try it online!](https://tio.run/##Pc49C8IwFIXh3V9xhwtJ0BSvWD8qBScnHZ1EStRQW9I2tBEKpf50Y1VwOfCc6bW6NqH3mMSFanmhbId5jMmGp7W2Ha/17XHVHaqAM2AtlzTGizS6TN0dlRABa1m/3Yn4mVdZyQZiPuHDKVpMegoC3J0kncVn@umf3hPMIYQFrIAIaAY0H4UD1kDTL0OgBdDyVVmXVWXj5WGfNS6Kji4zn9TJr8xLZc0b "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒPIE$ƇṪL ``` A monadic Link accepting a list which yields an integer. **[Try it online!](https://tio.run/##y0rNyan8///opABPV5Vj7Q93rvL5//9/tKGOgomOgqmOgpmOgoWOgiGQb2gExCaxAA "Jelly – Try It Online")** ### How? We are looking for the longest sub-sequence which has equal incremental differences, this just filters all sub-sequences in length order and takes the length of the last one. ``` ŒPIE$ƇṪL - Link: list of numbers ŒP - powerset (all sub-sequences ordered by length) $ - last two links as a monad: I - incremental differences (e.g. [4, 7, 11] -> [7-4,11-7] = [3,4]) E - all equal? Ṫ - tail L - length ``` [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 102 bytes Port of xnor's Python 2 answer. ``` f(R)->lists:max([lists:foldl(fun(X,I)->I+(case A+I*(B-A)==X of true->1;_->0 end)end,0,R)||A<-R,B<-R]). ``` [Try it online!](https://tio.run/##ZctPC4JAEAXwu59ijzM1G05k/xP05tWTIBJiu7GwraFGHfzuttQlaOA93uE3qrO1u0rVN525D1MwachRxtb0Q7@/1S8ov1O39mJBPxwUlHmQzaGpeyWSeTaDVCZ4OhWi1WLoHkrGfDjLOBTKXdCHQspxHJOjzCn1VeFiutXGQVmhkHEg/Jl2/@zMoEBDybSiiNa0JWbiJfGqQiQvnAWkPx55uCMOPzQiXhNvfh4W0xs "Erlang (escript) – Try It Online") ]
[Question] [ A half cardinal cyclic quine is a cyclic quine with two states, one perpendicular to the other. ## Rules You can decide which rotation you want to implement, clockwise or counter-clockwise. Once rotated, any gaps in your code should be replaced with spaces to preserve the positioning. Your program must satisfy [the community definition of a quine](https://codegolf.meta.stackexchange.com/a/4878/9365). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest program in each language wins. Your *first* program is used for your byte count. [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/9365) are forbidden. ## Examples If your program is: ``` $_='print';eval ``` Then the next iteration must be either: ``` $ _ = ' p r i n t ' ; e v a l ``` or ``` l a v e ; ' t n i r p ' = _ $ ``` which must output the original program: ``` $_='print';eval ``` If your program is: ``` ;$_='; ;$_='; print ``` Then the next iteration must be either: ``` ;; ''t ==n __i $$r ;;p ``` or: ``` p;; r$$ i__ n== t'' ;; ``` which must output the original program: ``` ;$_='; ;$_='; print ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), ~~19~~ ~~17~~ 15 bytes ``` {s"_~"+N*""-}_~ ``` [Try it online!](https://tio.run/##S85KzP3/v7pYKb5OSdtPS0lJtza@7v9/AA "CJam – Try It Online") [Try the rotation.](https://tio.run/##S85KzP3/v5qrmEuJK56rDkhqc/lxaQFpJS5drlqQ2P//AA "CJam – Try It Online") ### Explanation ``` {s"_~"+ e# Standard quine framework. Puts a string representation of the entire e# program on the stack. N* e# Riffle linefeeds into the string, which is effectively a clockwise e# rotation by 90°. ""- e# Does nothing. }_~ ``` In the rotated code, we've got linefeeds everywhere: ``` { s " _ ~ " + N * " " - } _ ~ ``` As [Lynn noticed on Dom's earlier quine challenge](https://codegolf.stackexchange.com/a/156142/8478) inserting linefeeds actually still forms valid quine, because the linefeeds inside the block will just be retained verbatim anyway, and there will also be linefeeds in the `"_~"` string to make those two characters at the end show up on their own line. So `{s"_~"+...}_~` (with linefeeds) is still a valid quine framework (although there'll be an additional linefeed at the end of the string). `N*` now inserts even more linefeeds into that string, but we don't really care: because now `""-` has a linefeed inside that string so it actually removes all linefeeds from the program representation. So we end up with the horizontal form of the code again, undoing the rotation. [Answer] # [Stax](https://github.com/tomtheisen/stax), 28 bytes ``` "8H^Hs+2*A]/Mm"8H^Hs+2*A]/Mm ``` [Run and debug the first form](https://staxlang.xyz/#c=%228H%5EHs%2B2*A%5D%2FMm%228H%5EHs%2B2*A%5D%2FMm&i=&a=1) [Run and debug the second form](https://staxlang.xyz/#c=%22%0A8%0AH%0A%5E%0AH%0As%0A%2B%0A2%0A*%0AA%0A%5D%0A%2F%0AM%0Am%0A%22%0A8%0AH%0A%5E%0AH%0As%0A%2B%0A2%0A*%0AA%0A%5D%0A%2F%0AM%0Am&i=&a=1) [Answer] # [><>](https://esolangs.org/wiki/Fish), 22 bytes ``` "2+}>oao#ov*48}}*d3'v ``` [Try it online!](https://tio.run/##S8sszvj/X0HJSLvWLj8xXzm/TMvEorZWK8VYvez/fwA "><> – Try It Online") Rotated anti-clockwise: ``` v ' 3 d * } } 8 4 * v o # o a o > } + 2 " ``` [Try it online!](https://tio.run/##S8sszvj/v4xLncuYK4VLi6sWCC24TICsMq58LmUgTgRiO6CoNpcRlxLX//8A "><> – Try It Online") The first one prints the line in reverse with newlines interspersed, and the second prints it in reverse without the newlines. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~36~~ 34 bytes ``` 4"D6Ø·çýD¶åi¶KëS»"D6Ø·çýD¶åi¶KëS» ``` [Try first iteration](https://tio.run/##MzBNTDJM/f/fRMnF7PCMQ9sPLz@81@XQtsNLMw9t8z68OvjQbpwSXP//AwA "05AB1E – Try It Online") or [Try next iteration](https://tio.run/##MzBNTDJM/f/fhEuJy4XLjOvwDK5D27kOL@c6vBfIP7SN6/BSrkwQ7c11eDVXMNeh3cQr/P8fAA) ]
[Question] [ What is the shortest way we can express the function ``` f(a,b)(c,d)=(a+c,b+d) ``` in point-free notation? [pointfree.io](http://pointfree.io/) gives us ``` uncurry (flip flip snd . (ap .) . flip flip fst . ((.) .) . (. (+)) . flip . (((.) . (,)) .) . (+)) ``` which with a little bit of work can be shortened to ``` uncurry$(`flip`snd).((<*>).).(`flip`fst).((.).).(.(+)).flip.(((.).(,)).).(+) ``` for 76 bytes. But this still seems *really* long and complex for such a simple task. Is there any way we can express pairwise addition as a shorter point-free function? To be clear by what I mean by point-free, a point-free declaration of a function involves taking existing functions and operators and applying them to each other in such a way that the desired function is created. Backticks, parentheses and literal values (`[]`,`0`,`[1..3]`, etc.) are allowed but keywords like `where` and `let` are not. This means: * You may not assign any variables/functions * You may not use lambdas * You may not import [Here is the same question when it was a CMC](https://chat.stackexchange.com/transcript/message/41972114#41972114) [Answer] # 44 bytes Got this from `\x y -> (fst x + fst y, snd x + snd y)` ``` (<*>).((,).).(.fst).(+).fst<*>(.snd).(+).snd ``` [Try it online!](https://tio.run/##JYk5DoAgEAC/soXFriKJRym@xIagKBEJEd7virGaycyh07l5z1YtjFM9k0QUJAukTbmgoU/KQZnC@ocifGkXQEG8XchQgQXsRE@AgxiJH2O93hO3JsYX "Haskell – Try It Online") Or, 42 bytes using `do`: ``` do a<-fst;((,).(a+).fst<*>).(.snd).(+).snd ``` [Try it online!](https://tio.run/##DYg7DoAgDECv0sGhKJL42fycxKUBUSMiEc9v7fQ@O@VzDYH9tLC7gcba53dA1MogVcpIjeUsYXJ0AlkifNERYYL0HPGFAjxgo1sF2Ole8Wd9oC1zbVP6AQ "Haskell – Try It Online") [Answer] # 44 bytes *-8 bytes thanks to Ørjan Johansen. -3 bytes thanks to Bruce Forte.* ``` (.).flip(.)<*>(zipWith(+).)$mapM id[fst,snd] ``` [Try it online!](https://tio.run/##DcU9DsIwDAbQq3xDBxtCJH5Gyg2YGYAhajG1SCOLZOrha3jLm1L9vHJ26R9OkaNktf/nzYUWtZu2ibYcuZuTXaHjXWoLtYxPn5MW9LCvloYOAtoHHBh0DDixr4Pk9K6@G8x@ "Haskell – Try It Online") Translates to: ``` f t1 t2 = zipWith (+) (mapM id [fst, snd] $ t1) (mapM id [fst, snd] $ t2) ``` ## 67 bytes *-8 bytes thanks to Ørjan Johansen. -1 byte thanks to Bruce Forte.* If tuple output is required: ``` (((,).head<*>last).).((.).flip(.)<*>(zipWith(+).)$mapM id[fst,snd]) ``` [Try it online!](https://tio.run/##DYm7DsIwDAB/xUMHG0IkHiPlD5g7AIPVNMQijSycqR9PyHIn3SW2z5Jzi@OzIaIjnxYO190ts1Xy5BE7Yhbt7hk30Ulqwn2fw8p6BwmPaNVZCS9qK0uBEfQrpcIAEfDo4ESAZwcXar85Zn5bO8yqfw "Haskell – Try It Online") Yup, me manually doing it doesn't produce ripe fruit. But I am happy with the `[a] → (a, a)` conversion. ``` listToPair ∷ [a] → (a, a) listToPair = (,) . head <*> last -- listToPair [a, b] = (a, b) ``` Now if there was a *short* function with `m (a → b) → a → m b`. [Answer] # 54 bytes I honestly doubt that we'll beat @H.PWiz's 44 bytes solution, but nobody was using the fact that `(,)` implements the type class `Functor`, so here's another interesting one which isn't too bad: ``` ((<*>snd).((,).).(.fst).(+).fst<*>).flip(fmap.(+).snd) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfpmCrEPNfQ8NGy644L0VTT0NDR1MPSOmlFZcAKW1NEAMoCaRzMgs00nITC8CiIMX/cxMz84D6C4oy80oUVBTSFDQMdXSNNBU0jHV0TTT//0tOy0lML/6vG@EcEAAA "Haskell – Try It Online") ### Explanation The implementation of the type class `Functor` for *2*-Tuples are very similar to that of `Either` (from *base-4.10.1.0*): ``` instance Functor ((,) a) where fmap f (x,y) = (x, f y) instance Functor (Either a) where fmap _ (Left x) = Left x fmap f (Right y) = Right (f y) ``` What this means for this challenge, is that the following function adds the second elements while keeping the first element of the second argument: ``` λ f = fmap.(+).snd :: Num a => (a, a) -> (a, a) -> (a, a) λ f (1,-2) (3,-4) (3,-6) ``` So if only we got some little helper `helpPlz = \a b -> (fst a+fst b,snd b)` we could do `(helpPlz<*>).flip(fmap.(+).snd)` and would be done. Luckily we have the tool [`pointfree`](https://hackage.haskell.org/package/pointfree) which gives us: ``` helpPlz = (`ap` snd) . ((,) .) . (. fst) . (+) . fst ``` So by simply plugging that function back in we arrive at the above solution (note that `(<*>) = ap` which is in *base*). [Answer] # 60 bytes I'm not seeing any `uncurry` love here, so I figured I'd pop in and fix that. ``` uncurry$(uncurry.).flip(.)(flip(.).(+)).(flip(.).((,).).(+)) ``` I thought, with all of the `fst` and `snd`, that unpacking the arguments with `uncurry` might yield some results. Clearly, it was not as fruitful as I had hoped. ]
[Question] [ [Inspiration](https://codegolf.stackexchange.com/q/151176/43319). Posted with [permission](https://codegolf.stackexchange.com/questions/151176/how-many-calendar-facts-are-there-really#comment369485_151176). # Print one of the possible XKCD calendar "facts": [![XKCD Calendar Facts](https://i.stack.imgur.com/xN6zC.png)](https://xkcd.com/1930/ "While it may seem like trivia, it (causes huge headaches for software developers / is taken advantage of by high-speed traders / triggered the 2003 Northeast Blackout / has to be corrected for by GPS satellites / is now recognized as a major cause of World War I).") You can get the raw text and structure from [my APL reference implementation](https://tio.run/##pVjNcts2EL77KXDTxe74T27dS8a/qWecNBNlxtPeVuCa3AgEGACUTD9Ak2Of0S/iLihFomiIlF1dLFoLYH@@79sFoVB7SQXKpM/PTz@@26d//r0AdQ3S74jwMLikRFSmFBNtZsJn4MVgR/w@QoXSi3en/P0CHIqDHRE@djes8RkGq/BZWh4unpvWqxXXoNRySW1y2DYZFZZ0ujS60sl86@bBV99K0uahdrG5y1vduiPt0fY5VuZ5w6jl2JYnjYxyniT2nPWnqvKCpIudNl9y9P8ivgKrCJ3v8eMWfNPojTGX2pLD3vRqh35zwMfNgC@hUpRm/pVRj2DaxNYGR2oj143AL5TjCn7D5k@3CMUr/eJwepz6C8Fuzs3JGjnALcA8//HXPqQcdfr2B9hpP1BGZdEm0FHb5lwZk3Sn9YMxeuX5b2sZN5XxIL7YUk7EB6N9tjI8bRqOMrATcYc4qQ2ayWpEHJGzDIoCtXtlfrBmUp94KPC9@WHNDeWZWcMY9QuAbc4VTtFWoloAI6KDiaV774QpvTD3wlVaihlx2mIYGPYxuCe@n4XrCO9vkxDIdaPjldHSleb/2u6sdntvMTWWYHlq1LmGg1DFbI9itrelXrEt6uzKlj5lRuOacataK1vuuKgTaOFg@BIHJicppDKMdNLiwihjITFbNoP8DcKojRdz@PfUeWHkZ80eFoWnz8it0Nkwmf88Rgkln8DIbA4aw/igEcjwGPKsMCXHZCKGG@lXUvVGMwI1dEd4ZolPgm4sfy6dI9hYjzUagkhQWkQxrmrqFabA4Hv4fjDc33eDVhmX0Zx0RlNYlMhumL6aKRrbeca6g9Klj5gdR7aLmL1AMUqJ2luS5FvN7aRtasaKeKJr2EURxVCJSVd3loIw9Q4e3XnhWclng4ET8ECuOzf4rWT22u7M8IDLcOZZkgIcN6WmzdwePawnWF0XBpRIuN1sKYw5OKP3EnowejsVU6Rxuykth1QjT7vinlAlwoaO5UDFxyZWZ7Bj8ha4qzFjqEb2uHolx89Rf4Wc6XVtQU/Y1@7i3zjgnvQRZ970oOD68nMs6hfC9k6cFQVYxr6q1qTtJCpt5EUthIwuwYxOSHoYqyAQrBnBmkORLKIgJSW8qdt05wEfIDrLKjFD1vJp0EoeRB1Ko5MXGjNf5STxluR4SmCPuUB8PeP1xlrCZBCtKfs7Aye4lFrkhhfhg7fIeE7K@t4WY@hxd8V43nlEcZZiT6nkS6MXVbqw6EGiKXuIenB6uu82onjYGpkt1vTnApnCMIKFN4zpB0F@V4x5vCL/yphnxPdgHfiwaLvdofM1vaxLk8OEkcKtNVxQuE6uJ2fcgp3nlZjUOOLB0nLL6F4znx/GKErNC/i26su5qmx3/aAahyl6H@BQ@yhAJ0IbERp4eL9QwzQ6Ffwi7jIK6PccasXgxVwomqDgRjIl2F1kumdcWBAqK1NmAkICMuPHe2OFM/d@FqCecO4VN2K7gU@cOM@5Zk1KpqA9pPWkwmqUcXb2XIGcUZaqpLnB@pXcUpoycJKaEYf7@0fio@E@wpz24lyBnPBcHqdYxvxigHEFJDOR4@RNgvN8@vtPI@FY25UivpjHhZRdD@9weKFJNT3yYgjYzeEr77Ecuu6MZUm@Y2W5iVdisPP04/vz88@3RK2//wE "APL (Dyalog Unicode) – Try It Online") or from [Explain XKCD's transcript](http://www.explainxkcd.com/wiki/index.php/1930#Transcript) (including the title text just under the illustration). ### Rules At every decision node, there must be an equal (pseudo-)random chance of each choice. You may use all uppercase. You must generate three sentences; a question, a reason, and a title text. The three sentences should be ended by `?`, `.`, and `.` respectively, and separated from each other by a single space. The only extra white-space you may include is one trailing space and/or line break. ### Examples `Did you know that the Latest Sunset drifts out of sync with the Zodiac because of time zone legislation in Indiana? Apparently it's getting worse and no one knows why. While it may seem like trivia, it has to be corrected for by GPS satellites.` `Did you know that Leap Year happens later every year because of precession of the equator? Apparently scientists are really worried. While it may seem like trivia, it is taken advantage of by high-speed traders.` `Did you know that Easter drifts out of sync with the atomic clock in Colorado because of a decree by the pope in the 1500s? Apparently scientists are really worried. While it may seem like trivia, it causes huge headaches for software developers.` [Answer] # Befunge-93, ~~1959~~ 1930 bytes ``` "#~$}%|&{'zwy#x$-#w$v%u&tTs*-#r$q%p&oTn0m1l2kpj#-#i$h%gFf(e)-#d#c$bC-'a(`)_*E+"v v"#*_?F@%A$B#C3DYE,F+G*-TH&I%J$K#L$M#-'NCO$P#Q#RjSFT%U$V#-<W;-cX(Y'Z&[%\$]#^cF"< >">$=%<#;$:%9F$*8+-#7$6C5/4#3$-C23-#1$0C*#/$.C$:-#,$+C*#)$(C$A'#&$%C$J#"75*-0\:v $::"P"vv-*84:-*57$$_1-\1+::"P"%\v>+>\1-:v>-#1:#$>#\_:$#<$:#v_".",@v/"P"\%"P"::\_ >\#%4#<3g/7+g"!"-:!^!:\,g+7/"P"<<^1?<*2\_$\%1++64*g48*-^<<<>75*-0v>7+g84*-+\1-:^ #<<<*2\>#$$:0\`#$_\$55++:64*g48*-90^https://xkcd.com/1930/^<<<<<<>#\\:#< >#<>#<^ 3Did you know that %the %fall'spring) equinox'winter'summer" )solstice)Olympics! )earliest'latest(sunrise'sunset0daylight saving"s& time&leap $day%year'Easter(ha rvest&super&blood& moon3Toyota Truck Month+Shark Week)happens (earlier&later2at the wrong time, every year=drifts out of sync with the $sun%moon'zodiac*Gregoria n&Mayan&lunar'iPhone* calendar9atomic clock in Colorado'might +not happen-happen twice+ this year- because of :time zone legislation in (Indiana(Arizona'RussiaB a decree by the Pope in the 1500s+precession*libration)nutation)libation-eccentr icity*obliquity) of the -earth's axis(equator/Prime Meridian3International Date, Mason-Dixon& Line8magnetic field reversal:an arbitrary decision by 2Benjamin Fra nklin-Isaac Newton$FDR.? Apparently Rit causes a predictable increase in car acc idents@that's why we have leap seconds>scientists are really worriedEit was even more extreme during the +Bronze Age(Ice Age+Cretacious&1990sFthere's a proposal to fix it, but it 2will never happen;actually make things worse7is stalled in C ongress:might be unconstitutionalHit's getting worse and no one knows whyE. Whil e it may seem like trivia, it Ncauses huge headaches for software developersLis taken advantage of by high-speed tradersFtriggered the 2003 Northeast BlackoutJh as to be corrected for by GPS satellitesRis now recognized as a major cause of W orld War I" "# "$) (6DLTV`b$ "$&% "$&2# *B& "$&(*% *,PR& "$&2>% "$&( ``` [Try it online!](http://befunge.tryitonline.net/#code=IiN+JH0lfCZ7J3p3eSN4JC0jdyR2JXUmdFRzKi0jciRxJXAmb1RuMG0xbDJrcGojLSNpJGglZ0ZmKGUpLSNkI2MkYkMtJ2EoYClfKkUrInYKdiIjKl8/RkAlQSRCI0MzRFlFLEYrRyotVEgmSSVKJEsjTCRNIy0nTkNPJFAjUSNSalNGVCVVJFYjLTxXOy1jWChZJ1omWyVcJF0jXmNGIjwKPiI+JD0lPCM7JDolOUYkKjgrLSM3JDZDNS80IzMkLUMyMy0jMSQwQyojLyQuQyQ6LSMsJCtDKiMpJChDJEEnIyYkJUMkSiMiNzUqLTBcOnYKJDo6IlAidnYtKjg0Oi0qNTckJF8xLVwxKzo6IlAiJVx2Pis+XDEtOnY+LSMxOiMkPiNcXzokIzwkOiN2XyIuIixAdi8iUCJcJSJQIjo6XF8KPlwjJTQjPDNnLzcrZyIhIi06IV4hOlwsZys3LyJQIjw8XjE/PCoyXF8kXCUxKys2NCpnNDgqLV48PDw+NzUqLTB2PjcrZzg0Ki0rXDEtOl4KIzw8PCoyXD4jJCQ6MFxgIyRfXCQ1NSsrOjY0Kmc0OCotOTBeaHR0cHM6Ly94a2NkLmNvbS8xOTMwL148PDw8PDw+I1xcOiM8ID4jPD4jPF4KCjNEaWQgeW91IGtub3cgdGhhdCAldGhlICVmYWxsJ3NwcmluZykgZXF1aW5veCd3aW50ZXInc3VtbWVyIiApc29sc3RpY2UpT2x5bXBpY3MhCillYXJsaWVzdCdsYXRlc3Qoc3VucmlzZSdzdW5zZXQwZGF5bGlnaHQgc2F2aW5nInMmIHRpbWUmbGVhcCAkZGF5JXllYXInRWFzdGVyKGhhCnJ2ZXN0JnN1cGVyJmJsb29kJiBtb29uM1RveW90YSBUcnVjayBNb250aCtTaGFyayBXZWVrKWhhcHBlbnMgKGVhcmxpZXImbGF0ZXIyYXQKdGhlIHdyb25nIHRpbWUsIGV2ZXJ5IHllYXI9ZHJpZnRzIG91dCBvZiBzeW5jIHdpdGggdGhlICRzdW4lbW9vbid6b2RpYWMqR3JlZ29yaWEKbiZNYXlhbiZsdW5hcidpUGhvbmUqIGNhbGVuZGFyOWF0b21pYyBjbG9jayBpbiBDb2xvcmFkbydtaWdodCArbm90IGhhcHBlbi1oYXBwZW4KIHR3aWNlKyB0aGlzIHllYXItIGJlY2F1c2Ugb2YgOnRpbWUgem9uZSBsZWdpc2xhdGlvbiBpbiAoSW5kaWFuYShBcml6b25hJ1J1c3NpYUIKYSBkZWNyZWUgYnkgdGhlIFBvcGUgaW4gdGhlIDE1MDBzK3ByZWNlc3Npb24qbGlicmF0aW9uKW51dGF0aW9uKWxpYmF0aW9uLWVjY2VudHIKaWNpdHkqb2JsaXF1aXR5KSBvZiB0aGUgLWVhcnRoJ3MgYXhpcyhlcXVhdG9yL1ByaW1lIE1lcmlkaWFuM0ludGVybmF0aW9uYWwgRGF0ZSwKTWFzb24tRGl4b24mIExpbmU4bWFnbmV0aWMgZmllbGQgcmV2ZXJzYWw6YW4gYXJiaXRyYXJ5IGRlY2lzaW9uIGJ5IDJCZW5qYW1pbiBGcmEKbmtsaW4tSXNhYWMgTmV3dG9uJEZEUi4/IEFwcGFyZW50bHkgUml0IGNhdXNlcyBhIHByZWRpY3RhYmxlIGluY3JlYXNlIGluIGNhciBhY2MKaWRlbnRzQHRoYXQncyB3aHkgd2UgaGF2ZSBsZWFwIHNlY29uZHM+c2NpZW50aXN0cyBhcmUgcmVhbGx5IHdvcnJpZWRFaXQgd2FzIGV2ZW4KIG1vcmUgZXh0cmVtZSBkdXJpbmcgdGhlICtCcm9uemUgQWdlKEljZSBBZ2UrQ3JldGFjaW91cyYxOTkwc0Z0aGVyZSdzIGEgcHJvcG9zYWwKIHRvIGZpeCBpdCwgYnV0IGl0IDJ3aWxsIG5ldmVyIGhhcHBlbjthY3R1YWxseSBtYWtlIHRoaW5ncyB3b3JzZTdpcyBzdGFsbGVkIGluIEMKb25ncmVzczptaWdodCBiZSB1bmNvbnN0aXR1dGlvbmFsSGl0J3MgZ2V0dGluZyB3b3JzZSBhbmQgbm8gb25lIGtub3dzIHdoeUUuIFdoaWwKZSBpdCBtYXkgc2VlbSBsaWtlIHRyaXZpYSwgaXQgTmNhdXNlcyBodWdlIGhlYWRhY2hlcyBmb3Igc29mdHdhcmUgZGV2ZWxvcGVyc0xpcwp0YWtlbiBhZHZhbnRhZ2Ugb2YgYnkgaGlnaC1zcGVlZCB0cmFkZXJzRnRyaWdnZXJlZCB0aGUgMjAwMyBOb3J0aGVhc3QgQmxhY2tvdXRKaAphcyB0byBiZSBjb3JyZWN0ZWQgZm9yIGJ5IEdQUyBzYXRlbGxpdGVzUmlzIG5vdyByZWNvZ25pemVkIGFzIGEgbWFqb3IgY2F1c2Ugb2YgVwpvcmxkIFdhciBJIiAiIyAiJCkgKDZETFRWYGIkICIkJiUgIiQmMiMgKkImICIkJigqJSAqLFBSJiAiJCYyPiUgIiQmKA&input=) **Explanation** In the first three lines, we start by building up a kind of state table on the stack, representing the graph of all possible sentences. These stack entries are grouped into pairs, so there is first a string item, and then a jump or branch. Where necessary, the graph is padded with empty strings and zero-length jumps in order to meet this requirement. Our main loop then begins by popping a number, representing a string item, off the stack. This number is interpreted as an offset into the string table in the lower section of the source. The string table is essentially a kind of linked list, wrapped over multiple lines to fit into Befunge's constrained memory space. After outputting a string, the next item on the stack is either a jump or branch. If the number is less than 32, it's a jump, which we interpret by dropping that many pairs of items from the stack. If the number is 32 or more, it's a branch, and we use the value (minus 32) to lookup the branch details from the table on the last line of the source. The entries in the branch table each consist of a count, followed by a list of offsets. Once we know which branch to use, we simply generate a random number, modulo the branch count, to lookup the appropriate offset. This offset is then interpreted as a jump, dropping the required number of items from the stack. We repeat this process, outputting a string, then performing a jump or branch, until we run out of stack entries. At that point, we simply output a "." to mark the end of the final sentence, and then exit. [Answer] # Javascript (ES6), ~~1698~~ ~~1510~~ ~~1506~~ 1501 bytes *Thanks to 12Me21 for fixing a bug in the code, which added 2 bytes* `f=` and `document.write(f())` are not part of the byte count ``` f=_=>eval(`"Did you know that {the {Fall;Spring} Equinox;the {Wint;Summ}er {Solstice;Olympics};the {Earli;Lat}est Sun{rise;set};Daylight Saving{;s} Time;Leap {Day;Year};Easter;the {Harvest;Super;Blood} Moon;Toyota Truck Month;Shark Week} {happens {earlier;later;at the wrong time} every year;drifts out of sync with the {Sun;Moon;Zodiac;{Gregorian;Mayan;Lunar;iPhone} Calendar;atomic clock in Colorado};might {not happen;happen twice} this year} because of {time zone legislation in {Indian;Arizon;Russi}a;a decree by the pope in the 1500s;{{precession;eccentricity;obliquity};{lib;liber;nut}ation} of the {Moon;Sun;Earth's axis;equator;prime meridian;{international date;mason-dixon} line};magnetic field reversal;an arbitrary decision by {Benjamin Franklin;Isaac Newton;FDR}}? Apparently {it causes a predictable increase in car accidents;that's why we have leap seconds;scientists are really worried;it was even more extreme during the {{Bronz;Ic}e Age;{Cretaceou;1990}s};there's a proposal to fix it, but it {will never happen;actually makes things worse;is stalled in congress;might be unconstitutional};it's getting worse and no one knows why}. While it may seem like trivia, it {causes huge headaches for software developers;is taken advantage of by high-speed traders;triggered the 2003 Northeast Blackout;has to be corrected for by GPS satellites;is now recognized as a major cause of World War I}."`.split`{`.join`"+(a=>a[Math.random()*a.length|0])(["`.split`}`.join`"])+"`.split`;`.join`","`) document.write(f()) ``` [Answer] # [Python 2](https://docs.python.org/2/), 1297 bytes *-419 bytes thanks to ovs.* ``` exec'eJxNVcGO3DYMvecriLk4m2yCSYseUqAomgYpcgkW7WHPtMSxmZElR5Jnxvv1fZQns3sybZHi4+MjfchposzR46HTnHJ988r9EXjqPb/h392Y1Mlrvns1Z421+6ye1rTQMaYz1ZErdW/d666OshkHDqG774p5D93d247kx6IxXfDx5nTGTZLNbZkmGObWDkoKpSIfjlJYp1ld6e5eBArnoFIqzgNXM55Dl5i1SLs0FqkW53kNOoyVCp8MjvmZQ4uqOpl3EJ63G+CN9xU5LFa4bBhvyUfOpy13WeZ21IeUfLtsSimab1pTZap5cUd8i3U0bwQe6SxyfEY78jxLLC+rytei7AlaLe05pzhsQBuTJ8krNYCoLeuhFkpLpXSgskZHZ60j3eCCBrhdgT0lr+y6e3wfsgwpK7dTXtszLLFdqg9jilsyx0Gi5w1NmtSRCwlVaSSXQsrsk9E0NX5bwpgqbXUhZjOonq2bje5Ry4bd3npxvBQx6Jt+UCM9ITcFGbSAB03RcrVTjUAf2aBkhZdZeSlF2SAweXFZhPq1Vf+QZrFQsz/8tt+XVvacxQlCGh1B+5YBZlzqT/PFV3FOYs3qtJooUh8UMoZt4AH6xvKV30b2DtWh44X4omWHS34soM4YxDSgPkhdfSO+1YRWx5aPA3k0vvWjpPjO6wWXWqag1g37PkTBYNBBJXjKpoTCNmgciXOvNTOkAR7UKjQmGrpPEr/zBC6+YMKPuA0RXwuzo29yrg35l8//dnfI9Sf9Nc+cUXW4Bmul1iTUQ2DPq6vcB6MWbHNpHDvOxM6pRxx43tlGAAHncYXgoYaTNRQDVsSl6I2U4hS+WqBdZEMpWBhwTjmreJNgpTMX03rEBMFDLjUL2POLrZRn5nsMx5MQD0YcVHa1gK2y07QATvfh48e9bRDgkizdVkmaE7ijmsDmhbTeU48hQt7dtptCoGgEP4uZXV0azImPYkqOQzHIbd1A1qXiVLwR8jcmNkNn3c/R6IWWiOKx1+qyddsAqdE0SK1WU7uKsIMpJrIhsO3aWNyhM+/pcVTjvSL/CiplgjAMSNaT8r0dNEau3RqXAdQLe3YjXg8pU0mHeja6PQoLmI9cNuQVBUFB/sSxgj+TNrQzAvm7MgtKgrD85o1swwAWfWvBL/v9r/QNf4vRFiV9CuyO2EVt8otxi7odmiquIsIw4N5/Hv7DKq4SgmJ5bwjsPwKvNER9gidbjyb+joDbhnhMGaJ/hNS+2lS87/4H4KM8AA=='.decode('base64').decode('zip') ``` [Try it online!](https://tio.run/##PdI3sqNYAADA4/ydomrxLpgAJ4GE95DhPTx4CKPLz060accN7r1dZuLPn@qqip/qdZlh8bRIOTGOqtg6faAm4pa8BFbBKixTk4CiGSI2Uu3d8K4pVUaXfs3XceB16syQhHeeqh2FGH1dtGCBX5diVH9WXzzHbbwS96udoy3JEwlujNsxQzylCBxh7grffMfIki@eKlsZoSXDMBZsB1VenyxLAVrmyZKg2OFitCuu5Yue/aef6maeDtPTyiN5WN7A0@p@fCUAH0umoitR2Obloa3fxowNmpZHusM9HWKPdYhocjCt5Q4lwBn9MaUO9VktMJLKiyGfiGTyV0Drj4zKxfa4g9oCN05GVUrgWhXU@g69bspyHPhpBugiKLmODLD8dCrGu@5aSViuv3RdQrZ7rzpWGDO9wmjwbaEjfvwXN2xmIi169WkfA9BB7DVwSNWUwXqykiRxa8vGx8YNuZmKPGvYnODNln68w6@uP8q14ftuhPeFPTv6xM1p91zpHMPM82IHbnDgFcyM6fwEzZrHQZv21jKvRN5XtHtTeUnO4DpE52JeOxJIBq/5xeOZe4KIkW6xhX4fCDWRiUOblmnljQ/CE84qfqStveJhjTjp9nDgF@X2HYnDIysuZ5SeLS4idCKm43f1UfsRkg8rgeS6v5YlaLnAWNKdElTmOt4hieWEvEctRcXUMkWqR1JwMajkkr3GHtqy9iwET9zoojNbIAfsOKIe2L3FnFEcrVmDNyRrD76YmKL4ivs3WHzJnJqii63D9K1BcNng3TvTcwO2sqFfUWKQxHjbHwFz4/PzXQj@3hqSHjkULeda472aNwukCOKIEqfPiHd@4BCyvTJHITJGlKsmUOXDugwGuNdFkfv4FAR1LpK4WZLMN11HDqE3MhoRUK2HRKtYpooBIrE9/X7aqpfZAN@IMXJTROMh632gE7alb6k70zM0LtpwZCwpQjXDmzdxY6wj@EfdUlzF567cDN23DIcpU9iun6A8tblfBRTXOjtb7mCXlmej2NQnjUMs@2qTnQyr5XxVLS9xAV/jLtRPl@uLyRzMmSxQl9GiqLPeF46sd1lCYS0VzHvjUcB@3lAzwGvTWmiRWWTerYGgoPhb4vB0VOrA2PSC4ZmZz21YaSrZh3TXWCgdvSKTPm44EGCTWvUZYzuLPml8YX6cUAweIgq9q@kR39ycr3BMrNHs72aTOXrB4XkKUR0doo4e/IY6Zk0d7qMLeelzW4QS7tyyXx27lFO3fjSonZRJo@rByu@V8prp9Td6D@3zfZiKyzddmfd3jvSLnLdzazyzF9qaHkKMHseilEq9DU4Qfv/@@besiqWs/vnJM1gx1M@v/@HbgZ9ff/78Bw "Python 2 – Try It Online") The actual code: ``` from random import* c=lambda*a:choice(a) print'Did you know that '+c('the '+c('fall','spring')+' equinox','the '+c('winter','summer')+' '+c('solstice','olympics'),'the '+c('earliest','latest')+' '+c('sunrise','sunset'),'daylight saving'+c('','s')+' time','leap '+c('day','year'),'easter','the '+c('harvest','super','blood')+' moon','toyota truck month','shark week')+' '+c('happens '+c('earlier','later','at the wrong time')+' every year','drifts out of sync with the '+c('sun','moon','zodiac',c('gregorian','mayan','lunar','iPhone')+' calendar','atomic clock in colorado'),'might '+c('not happen','happen twice')+' this year')+' because of '+c('time zone legislation in '+c('indiana','arizona','russia'),'a decree by the Pope in the 1500s',c('precession','libation','nutation','libation','eccentricity','obliquity')+' of the '+c('moon','sun',"earth's axis",'equator','prime meridian',c('international date','mason-dixon')+' line'),'magnetic field reversal','an arbitrary decision by '+c('Benjamin Franklin','Isaac Newton','FDR'))+'? Apparently '+c('it causes a predictable increase in car accidents',"that's why we have leap seconds",'scientists are really worried','it was even more extreme during the '+c('bronze age','ice age','cretacious','1990s'),"there's a proposal to fix it, but it "+c('will never happen','actually make things worse','is stalled in Congress','might be unconstitutional'),"it's getting worse and no one knows why")+'. While it may seem like trivia, it '+c('causes huge headaches for software developers','is taken advantage of by high-speed traders','triggered the 2003 Northeast Blackout','has to be corrected for by GPS satellites','is now recognized as a major cause of World War I')+'.' ``` That was tiring. I haven't even done basic golfing. Somebody please write a script to golf this. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 806 bytes ``` ≔”}‽÷⌊&β¶&⁰5EYB∕¤ⅉ‖≧I2[y·↔m⁷b∕¶⎆w‹ta≔Þ…¤eN⌕⟦1H}⁷φb$≧xζ→j5⮌↗2Σ↶C$JiψT↧⊘ν;{Fκⅉ⊘V⁵)}LZ)←‴F9cCIj+FJ➙N¶℅Pφ⦄≧πΦjt/;⊗…→⎇↓y⁻OD¤HRw2◧eE≦⊗▶⁴Uμ4⁶⊟P}⁼Ruf→u≧″℅9ξ→W⊗7≧↨↥ω⎚,_-,*U∕$⊖τJb4%L'⪪*⎇⊕>Þ↨IQ.&XVSv⧴×↑N:εγC~f≔hI¶⊖⎇N6ydy"⁸?⁷∕Oυ⁻~Þ⁶πv″ZOgΦ✂⊘qV↓Y5U,fν¶⁼⟲Y⁺⪪“↓‹5Hψ.>⊕LS⁸◨›±3¤�[<⊟D´YυΣOR↓↓g⟧⎈″:;9≧¿×➙ρlZσ31‴8↖HXυ3@⁺�@δIΣ≔⁺@ⅉCX⎇",H²⁻↥uνu⎚⌊ÀW⊘∕U ψu]q➙⟲BoF⧴Qψ8)Zk⌕⊗ü;≡N±$⊞QU≕⁹↘NYFY?⊗↖\≦∧₂!Fd⌈B"η№⁻⎈O2jηQμfÞωσdJ↧Àκ«ⅈ∕+¤êE�№F´⟲τ₂Gξr1⦃:>Oa²O[)¬X⎚∧V⊖«⪫J⁼0✂⦄Blν≦&C₂?⁹κIWÞ⁶≕>u/EKπd4ζ¤h]≕D@;VWR$▷ω≔BU″″◧⁸|%↔φ;Φ?@R:↙!,⧴¹3H%⁸⧴↨⁵&⁼E¶N V⬤⌊←}⁸⁺aw⌈Vς2A§A⟦W3«;{aZKl⊞Lξd⌊2≦2?⎈OM↔ü?⎚_Q▶δMp>{✂Mx§+↔⎆}Cκ·W∧Sd⎇⁹_ςCüI.G↓x≕χ«]n⦄&➙{‽ι⦃⁺^⦃Jk⎈O+oκs◧¿#W↙QR[Lα±´@⁰¶◧⊗βυ⊕⁴…«✳τi"TWι&=l¦⦄Þ⪪Þ▷‴υγ±A↥2⭆⁴≕↖≔…L¦ê⊘↥Bwψ¦⊘⊕*YkxAyg-'≦sΦd4◨υÀ?⁶[)…WS×∧ηt\e↗⊕Xκ≕№q₂‽Az←ERT◨⟦◨<1↧Φ…⊗E›c*«R↥M6-±⌀↑F⟲#π'F5/±κ;↗~&ζTUI⁺U⦃⸿?^↙i⧴t”θFβ≔⁺⁺§⪪θι⁰‽✂⪪θι¹±¹¦¹⊟⪪θιθθ ``` [Try it online!](https://tio.run/##VVRNU@M4EL3vr@iay0AVTMFu7WFqDlsdqWP3RJa8kkwwtwABMoQEkvAx8@fZJ4fa2j1YtqVWv9evn3R1N9tcrWfL93febhe3q4NPv379/GnVUh86mvgwpVxzpkWuhWbc5a7xs9RG9dWM5O9OfTgf1i6n6rPEy9Q1DV50lYJLWY1cBdc3rZp0NcRdC0en147ztaRMqfPzqEnmSfJ8Ybl3WtWY5jMg3NykG8rayMIJt3SL5dse@28XwglgQ8K7muMZUt2lrpV4N3Ih2DtqQvCLHPqQmXLszAQzPteLhOgJTUUmC1rV3LbiE/0YOEn8AVYYUW5JPI3BVwP8D5IziT0V7JWNOs6JQpcpjCn13tBUcz1sWaKcZYFeXgSrbJb3VZQqRGV/33CP0XWe4722dfByT4adeMtxyTk0asi4AKbqyQQXItuwXDWDHg8@ZNrTfdi/KE8h7gNgNe2J0UgMd0kKrV2hTRcAISeVJhSmwZfMa/Vg5nnNUbHO69ilpLzeMVkxUYRG/VBLG1opG8r36Z8nJ2n32EYxmpDo0elI4pDz0Xd5/yHGiM9Rjeb@MYycwh34KnRKjk3RZQOBNiCb68@J@FzTBh5C8XEDS4ExrKOF3uZpcJMfMrMji8Y8NZyCP7Z6HvwTOfWy2TVceYHLaKziLMXSp8Rux544jjRHRtvsB@tS2XYk/js3qGsc2U@QZauJ2ZCXaQ5@O7Zxu/uLIDFHVON6etVMg64gTFDAqsk8ckUbyMVpEMlwJDZGLfak13JiUN@07uE0tO2sdAEGTmKCt@k1GUWcJtgIKGDNDkDTEKOKLXhTTsVyHqbFupznKBDHduXYDWI@j2DOCyGu5Bk2GN5gk9lI6NLz6devJ@kZPCTK5z3v0AYIQzlAqnPSfEQjOBhYL1N1DuVDuQ@HvbDJ3UCp4QnKhsV8lQq/JC9wW8pYFLv3qYfDU3rZ23Qk1HnM4eDnbt@6F9QDCpXkXMgPSYi9JR@o2LNcMYNUr18watE1A7eHWNKgyxPB@dUz5aOy8PbRibqrIKywZVPjdxwipTDO0yKnRSkO5o3pDWQzSoAZ7Bn7DJWKG2GDGnSPUyuoAh6xJRYoVQW97CDw7ycnf4AijFquGho5NhMc@bcanYGGKNSgXWIy4gs6clYtpIFPndMsA3a5PRETKq8XiOPSiYa/I/zfgwo94FvwJn378ono6fDbbzfrDR1cHtLHjdwun7f7gXe6up6/HaTH5WJ38HREi8MjOsETZ6vr9cNBWi6u5v9fPT0iP7@d7eYHp@Xv8BBju378b1CZKrDtZrHC1OG39/f345flPw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ”....” Compressed string ≔ θ Assign to `q` β Lowercase letters F Loop over each letter ⪪θι ⪪θι ⪪θι Split `q` at that letter § ⁰ First string in split (i.e. prefix) ✂ ¹±¹¦¹ Slice split excluding prefix and suffix ‽ Select random element ⊟ Pop last string (i.e. suffix) ⁺⁺ Concatenate ≔ θ Assign to `q` θ Print `q` ``` [Answer] # [R](https://www.r-project.org/), ~~1903~~ ~~1751~~ 1743 bytes A simple brute-force solution. Might be some way to golf it down some more. ``` p=paste P=paste0 s=function(...)sample(c(...),1) C='calendar' T='the' P(p('Did you know that',s(p(T,s('Fall','Spring'),'Equinox'),p(T,s('Winter','Summer'),s('Solstice','Olympics')),p(T,s('Earliest','Latest'),s('Sunrise','Sunset')),P('Daylight Saving',s('s',''),' Time'),p('Leap',s('Day','Year')),'Easter',p(T,s('Harvest','Super','Blood'),'Moon'),'Toyota Truck Month','Shark Week'),s(p('happens',s('earlier','later','at the wrong time'),'every year'),p('drifts out of sync with the',s('Sun','Moon','Zodiac',p('Gregorian',C),p('Mayan',C),p('Lunar',C),p('iPhone'),'atomic clock in Colorado')),p('might',s('not happen','happen twice'),'this year')),'because of',s(p('time zone legislation in',s('Indiana','Arizona','Russia')),'a decree by the pope in the 1500s',p(s('precession','libration','nutation','libation','eccentricity','obliquity'),'of the',s('Moon','Sun',"Earth's axis",'equator','prime meridian','international date line','mason-dixon line')),'magnetic field reversal',p('an arbitrary decision by',s('Benjamin Franklin','Isaac Newton','FDR')))),'? Apparently ',s('it causes a predictable increase in car accidents',"that's why we have leap seconds",'scientists are really worried',p('it was even more extreme during the',s('Bronze Age','Ice Age','Cretaceous','1990s')),p("there's a proposal to fix it, but it",s('will never happen','actually makes things worse','is stalled in congress','might be unconstitutional')),"it's getting worse and no one knows why"),'. While it may seem like trivia, it ',s('causes huge headaches for software developers','is taken advantage of by high-speed traders','triggered the 2003 Northeast Blackout','has to be corrected for by GPS satellites','is now recognized as a major cause of World War I'),'.') ``` [Try it online!](https://tio.run/##RVXBbts4EL3nKwa@MAbcwNnFHnoIFknadAMk3aAJEOzextRYYk2RKknZUX4@fUM57SWmpOHMe2/eTNLb23AxcC5y8jD/rk/yxXYMtrgYTs/OzpaZ@8HLqa0Pq/PlyfWFsewlNJzMydOFKZ2Yk4fT4dR8cg1NcaRdiAcqHRezynj/hL/mhr03K/M4JBdas1yZzz9GF@ILjseIZxeKJI0Z@x6Hpb58jD4XZwWv//VTPzibzfLXlc@cvJOMOuaOix7mS2NILktNFbIUvfEAeDx513aFHnmvIDQ0I0jR0JPrpWIxd8JD/YZ4fP1PwHOpgFUe4DvW/ofTfi79OA4V95WPsdFk9zEG/X2KUyxMT2m0O7qPoXQa3XHa0bPIroJFwY6HQUKuNaUy0myeZzW4QEqhQ4qhpTKjNLKXNNFUoSnmJrltyRTHQnFLeQqWDq50etMcFTFHXCvzf2wcWyViviRpY3KM19c10T1Pvx/uxoACxwf30MVQi3OJvbNkfQQtF@g6@pi4iXNjTK8a16ohFprJoep8oHLQbiJL6Vw@MsDTRiyPWYB@9oxRpvSKiuSldRlqwJCoVhPfBjAIjKyXySFIT9/GnB3XZEyN2CRCm6lqN8RBFKiez/9ar7NyR5ohiRXcqqp4t0m1CM5hLO9HvH4/irUSSnLWFTVG3HgHD@OMklD9XeujylXyBRyKrmfiF5cXSPFjhHraVswBCMLnrqnym@r@UGuxpwbdJ@@CmrjnHMOHxr1AgPpKOfbcBsFk0NaJbyipIzL72lUOxGnjSmKYBFI4pQgxKrwrCd@5hxo3icPOq6LmNjNb@iqHUqHffPqGGlrlb7ocBk6g7Seq112h2ilQIujXOFt441VeKM656mw5EVvrGtyD1ou6CjIduokOAkfstak8UBYbQ6O6ZOsQ6zI8jGpgg22B4JiSk6ZyQt0DZwLNQH1EjLyUJJCwGXWj/FL/CnPyKnTZqnK39v10naSwlTjqwJ9//Lg@rhFgkyRmZhOHCAmpRIj6Qq6saIOBcmWhiQ/Oewoq829Psy1jRdrzDorA0qHNCrsuH/g7F3yWpoqC@U1wmza0bqGNEPZsDNhvZZzbrpgWTrVqpRSlVXMRh4ZCJJ0G3a1VygXac0bPnVPxCxBM0FN6OGQnBJfuHa/0Q1Xl2LJubKG/cMO2w@M2JspxWw6qeQNqHoOS8gy9gBJ81Ow5FG51MnWcOkD/kAcBJ9irmaNRrW0hY1Mn7I/1@k/6GuF7@KHQlWe7w2KqKyCruCBu0VmxBTcUA/J@eXikDM9777DHZwT6XwRRsQ3uFZGsTer5Oy687wp6jgnmf4bfbnUKz8zy7e0n "R – Try It Online") [Answer] ## JavaScript (ES6), 1275 bytes ``` f=(s=btoa`...`)=>/h/.test(s)?f(s.replace(/g([^gi]+)i/,(_,x)=>` ${(x=x.split`h`)[Math.random()*x.length|0]} `)):s.replace(/[a-f]/g,x=>" '-?,."['0x'+x-10]).replace(/ +(\W)/g,'$1') ``` where the `...` represents the result of running `atob()` on this string and replacing `\` with `\\`, ``` with `\``, 0x00 with `\0`, and 0x0D with `\r`: ``` DIDaYOUaKNOWaTHATgTHEgFALLhSPRINGiEQUINOXhTHEgWINTERhSUMMERigSOLSTICEhOLYMPICSihTHEgEARLIESThLATESTigSUNRISEhSUNSETihTHEgHARVESThSUPERhBLOODiMOONhDAYLIGHTgSAVINGhSAVINGSiTIMEhLEAPgDAYhYEARihEASTERhTOYOTAaTRUCKaMONTHhSHARKaWEEKigHAPPENSgEARLIERhLATERhATaTHEaWRONGaTIMEiEVERYaYEARhDRIFTSaOUTaOFaSYNCaWITHaTHEgSUNhMOONhZODIAChgGREGORIANhMAYANhLUNARhIPHONEiCALENDARhATOMICaCLOCKaINaCOLORADOihMIGHTgNOTaHAPPENhHAPPENaTWICEiTHISaYEARiBECAUSEaOFgTIMEaZONEaLEGISLATIONaINgINDIANAhARIZONAhRUSSIAihAaDECREEaBYaTHEaPOPEaINaTHEa1500ShgPRECESSIONhLIBRATIONhNUTATIONhLIBRATIONhECCENTRICITYhOBLIQUITYiOFaTHEgSUNhMOONhEARTHbSaAXIShEQUATORhPRIMEaMERIDIANhINTERNATIONALaDATEaLINEhMASONcDIXONaLINEihMAGNETICaFIELDaREVERSALhANaARBITRARYaDECISIONaBYgBENJAMINaFRANKLINhISSACaNEWTONhFDRiidaAPPARENTLYgITaCAUSESaAaPREDICTABLEaINCREASEaINaCARaACCIDENTShTHATbSaWHYaWEaHAVEaLEAPaSECONDShSCIENTISTSaAREaREALLYaWORRIEDhITaWASaEVENaMOREaEXTREMEaDURINGaTHEgBRONZEaAGEhICEaAGEhCRETACEOUSh1990SihTHEREbSaAaPROPOSALaTOaFIXaITeaBUTaITgWILLaNEVERaHAPPENhACTUALLYaMAKESaTHINGSaWORSEhISaSTALLEDaINaCONGRESShMIGHTaBEaUNCONSTITUTIONALihITbSaGETTINGaWORSEaANDaNOaONEaKNOWSaWHYifaWHILEaITaMAYaSEEMaLIKEaTRIVIAeaITgCAUSESaHUGEaHEADACHESaFORaSOFTWAREaDEVELOPERShISaTAKENaADVANTAGEaOFaBYaHIGHcSPEEDaTRADERShTRIGGEREDaTHEa2003aNORTHEASTaBLACKOUThHASaTOaBEaCORRECTEDaFORaBYaGPSaSATELLITEShISaNOWaRECOGNIZEDaASaAaMAJORaCAUSEaOFaWORLDaWARaIif ``` Try it here, minus the `btoa`: ``` f=(s="DIDaYOUaKNOWaTHATgTHEgFALLhSPRINGiEQUINOXhTHEgWINTERhSUMMERigSOLSTICEhOLYMPICSihTHEgEARLIESThLATESTigSUNRISEhSUNSETihTHEgHARVESThSUPERhBLOODiMOONhDAYLIGHTgSAVINGhSAVINGSiTIMEhLEAPgDAYhYEARihEASTERhTOYOTAaTRUCKaMONTHhSHARKaWEEKigHAPPENSgEARLIERhLATERhATaTHEaWRONGaTIMEiEVERYaYEARhDRIFTSaOUTaOFaSYNCaWITHaTHEgSUNhMOONhZODIAChgGREGORIANhMAYANhLUNARhIPHONEiCALENDARhATOMICaCLOCKaINaCOLORADOihMIGHTgNOTaHAPPENhHAPPENaTWICEiTHISaYEARiBECAUSEaOFgTIMEaZONEaLEGISLATIONaINgINDIANAhARIZONAhRUSSIAihAaDECREEaBYaTHEaPOPEaINaTHEa1500ShgPRECESSIONhLIBRATIONhNUTATIONhLIBRATIONhECCENTRICITYhOBLIQUITYiOFaTHEgSUNhMOONhEARTHbSaAXIShEQUATORhPRIMEaMERIDIANhINTERNATIONALaDATEaLINEhMASONcDIXONaLINEihMAGNETICaFIELDaREVERSALhANaARBITRARYaDECISIONaBYgBENJAMINaFRANKLINhISSACaNEWTONhFDRiidaAPPARENTLYgITaCAUSESaAaPREDICTABLEaINCREASEaINaCARaACCIDENTShTHATbSaWHYaWEaHAVEaLEAPaSECONDShSCIENTISTSaAREaREALLYaWORRIEDhITaWASaEVENaMOREaEXTREMEaDURINGaTHEgBRONZEaAGEhICEaAGEhCRETACEOUSh1990SihTHEREbSaAaPROPOSALaTOaFIXaITeaBUTaITgWILLaNEVERaHAPPENhACTUALLYaMAKESaTHINGSaWORSEhISaSTALLEDaINaCONGRESShMIGHTaBEaUNCONSTITUTIONALihITbSaGETTINGaWORSEaANDaNOaONEaKNOWSaWHYifaWHILEaITaMAYaSEEMaLIKEaTRIVIAeaITgCAUSESaHUGEaHEADACHESaFORaSOFTWAREaDEVELOPERShISaTAKENaADVANTAGEaOFaBYaHIGHcSPEEDaTRADERShTRIGGEREDaTHEa2003aNORTHEASTaBLACKOUThHASaTOaBEaCORRECTEDaFORaBYaGPSaSATELLITEShISaNOWaRECOGNIZEDaASaAaMAJORaCAUSEaOFaWORLDaWARaIif")=>/h/.test(s)?f(s.replace(/g([^gi]+)i/,(_,x)=>` ${(x=x.split`h`)[Math.random()*x.length|0]} `)):s.replace(/[a-f]/g,x=>" '-?,."['0x'+x-10]).replace(/ +(\W)/g,'$1') document.write(f()) ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 1302 [bytes](https://github.com/abrudz/SBCS) ``` '[a-z]'⎕R' \u&'⊢'⍠[^⍠⌸]*⌸'⎕R{(?∘≢⊃⊢)⍵.Match(∊⊆⊣)⎕AV}⍣≡'DIDyOUkNOWtHAT⍠tHE⍠fALL⌺sPRING⌸eQUINOX⌺tHE⍠wINTE⌺sUMME⌸R⍠sOLSTICE⌺oLYMPICS⌸⌺tHE⍠eARLI⌺lAT⌸ESTsUN⍠RISE⌺SET⌸⌺dAYLIGHTsAVING⍠ ⌺S ⌸TIME⌺lEAP⍠dAY⌺yEAR⌸⌺eASTER⌺tHE⍠hARVEST⌺sUPER⌺bLOOD⌸mOON⌺tOYOTAtRUCKmONTH⌺sHARKwEEK⌸⍠hAPPENS⍠eARLIER⌺lATER⌺aTtHEwRONGtIME⌸eVERYyEAR⌺dRIFTSoUToFsYNCwITHtHE⍠sUN⌺mOON⌺zODIAC⌺⍠gREGORIAN⌺mAYAN⌺lUNAR⌺iPHONE⌸cALENDAR⌺aTOMICcLOCKiNcOLORADO⌸⌺mIGHT⍠nOThAPPEN⌺hAPPENtWICE⌸tHISyEAR⌸bECAUSEoF⍠tIMEzONElEGISLATIONiN⍠iNDIAN⌺aRIZON⌺rUSSI⌸A⌺adECREEbYtHEpOPEiNtHE 1500S⌺⍠pRECESSION⌺lIBRATION⌺nUTATION⌺lIBATION⌺eCCENTRICITY⌺oBLIQUITY⌸oFtHE⍠mOON⌺sUN⌺eARTH''SaXIS⌺eQUATOR⌺pRIMEmERIDIAN⌺⍠iNTERNATIONALdATE⌺mASON-DIXON⌸lINE⌸⌺mAGNETICfIELDrEVERSAL⌺aNaRBITRARYdECISIONbY⍠bENJAMINfRANKLIN⌺iSAACnEWTON⌺fDR⌸⌸?aPPARENTLY⍠iTcAUSESapREDICTABLEiNCREASEiNcARaCCIDENTS⌺tHAT''SwHYwEhAVElEAPsECONDS⌺sCIENTISTSaRErEALLYwORRIED⌺iTwASmOREeXTREMEdURINGtHE ⍠BRONZEaGE⌺ICEaGE⌺CRETACEOUS⌺1990S⌸⌺tHERE''SapROPOSALtOfIXiT,bUTiT⍠wILLnEVERhAPPEN⌺aCTUALLYmAKEStHINGSwORSE⌺iSsTALLEDiNcONGRESS⌺mIGHTbEuNCONSTITUTIONAL⌸⌺iT''SgETTINGwORSEaNDnOoNEkNOWSwHY⌸.wHILEiTmAYsEEMlIKEtRIVIA,iT⍠cAUSEShUGEhEADACHESfORsOFTWAREdEVELOPERS⌺iStAKENaDVANTAGEoFbYhIGH-SPEEDtRADERS⌺tRIGGEREDtHE 2003nORTHEASTbLACKOUT⌺hAStObEcORRECTEDfORbYgPSsATELLITES⌺iSnOWrECOGNIZEDaSamAJORcAUSEoFwORLDwARi⌸.' ``` [Try it online!](https://tio.run/##RVTNbtxGDH6VnLpJEQdOix5yCugZWprs7Iw6Q60tpykg7Y9X6P4YloKFXfRUIEgMu@ilQI9p8gwFFn4cvYjLGdnuZYYiOeTHj6TKs@Xe9KJcbk7v7ro//uo@/Dl4W@5dvhvwhxs8@en9N4Pu6sugu/n89mc@uuvdu2/5iOZfn77uPv7dffrSXf3OTs@6m39fjMp2snjafbzqrj50V1@fsR@Mf@tuvnaf/hlIJS9s/ouxR20KxOHaFPmcg9bd9W2TOWUSDj77MVfGHrOqt2@VIQwO@WjE986xrrHakxJBvdHFKFPCs@XxyQycVvy15DTXO/TU5IbVTvnwwiP1zlMotEpSamAcUt98fhKsfOxIhVS3S4SM1ezHHxcIrn83A0/oHrMtwI05R4SYRX2lrZXsu7LWBDdbWILW5WK4sobS4JmCG24RhyFiCJFlaPwD9BiEwce7JE6zddYkbUS1m43RFT2a26lTh@Q3OW0Om8KIraK0BxUqvr69B3BppQLBAhtOHSbWKYhmKOK9zE2MVmepNSHFBDQaCX16O1Jioq0Y1mZitXUgbc/DKpDHIdeW@gJY1wvtUWzOrk2Vv@etQgG5x81haDwXcsmZlpgor4GUNXVoUG1kD6x06iQiP8@9507uICinKBxiVXCFZzbD2rDw5OUP@/u@L@3MoUD2jy@X6sDFyCyvc3oQWf0gzoRAQ04JRaG/mwOtePSCvNsc9ize89eTya2hdDDw5bEKCXlOgWyg6MxxPSt06h59rISbZ2Im0FOIA7wCb82eVMch5m6pItNRnxjkaZ4r1PIcubsewkaUpnQHihy4gitXoa6q4NgVmjcwUmbuwAy1ChlrDyDWeEQR7lz2g7p7XWYZOC5Sh3c1TUIHfMk8SSUIDjRzyJSC53sCrhRCSfb2cbSBuNZtWmxxAWMMq9CgsEYGayMU@ylPvnR4jrzBxdY6p1AGMLQFv7IOZ8fkcITTPGx26BWDOOBBPsEyCYTwjPQCYyAQaPMQ@@WrV/v/b7PDwPiZs5llVlo7V8c1Pa9yqin@G7ReB8Ye568UlAc4Kxii5/EziWdkce9r3xCbUIY5NonjUXkY4grfG66N/ymU9z3rAdSBg1Mk4jgxTGnk2m4Mhr9YIIfdXmxTxUQSL1ODOFqqIbZOjRU8jxB7zhd5ggsECSJFP7eusYd0xK2ZMnjNs@x8BNgyalPKMRiChHelKhYMb89niLLlxev9OHySMDMycPrd/v73a8uTyW2kSoMY2pziIvrWVjjhtqAglJy0Kk4z3/Awaq0I@4xre3TObU2MOkFZ@nIFb6yb9JvKFWu5BVeHKgd3d/8B "APL (Dyalog Unicode) – Try It Online") [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m) helped with this one...then challenged me to finish it. :P -11 thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m) (using his new SBCS tool I can abuse the encoding without extra cost). [Answer] # [Haskell](https://www.haskell.org/), ~~1949~~ 1938 bytes ``` import System.Random data T a=N a[T a](T a)|P Char(T a)|E l s=N s[]E t=N"the" w=map l.words k=map l.lines d=N"" g!a|(i,h)<-randomR(0,length a-1)g=(a!!i,h) g#E=("",g) g#(P c n)|(e,v)<-g#n=(c:e,v) g#(N s[]n)|(e,v)<-g#n=([' '|s>""]++s++e,v) g#(N s c n)|(p,q)<-g!c,(m,h)<-q#p,(e,v)<-h#n=([' '|s>""]++s++m++e,v) tail.fst.(#N"Did you know that"[t(w"fall spring")$l"equinox",t(w"winter summer")$d(w"solstice olympics")E,t(w"earliest latest")$d(w"sunrise sunset")E,N"daylight"(w"saving savings")$l"time",N"leap"(w"day year")E,l"easter",t(w"harvest super blood")$l"moon",l"Toyota truck month",l"shark week"](d[N"happens"(k"earlier\nlater\nat the wrong time")$l"every year",N"drifts out of sync with the"[l"sun",l"moon",l"zodiac",d(w"gregorian mayan lunar iPhone")$l"calendar",l"atomic clock in Colorado"]E,N"might"(k"not happen\nhappen twice")$l"this year"]$N"because of"[N"time zone legislation in"(w"Indiana Arizona Russia")E,l"a decree by the Pope in the 1500s",d(w"precession libration nutation libation eccentricity obliquity")$N"of the"(k"moon\nsun\nEarth's axis\nequator\nprime meridian\ninternational date line\nMason-Dixon line")E,l"magnetic field reversal",N"an arbitrary decision by"(k"Benjamin Franklin\nIsaac Newton\nFDR")E]$P '?'$N"Apparently"[l"it causes a predictable increase in car accidents",l"that's why we have leap seconds",l"scientists are really worried",N"it was even more extreme during the"[l"bronze age",l"ice age",l"cretaceous",l"1990's"]E,N"there's a proposal to fix it, but it"(k"will never happen\nactually makes things worse\nis stalled in congress\nmight be unconstitutional")E,l"it's getting worse and no one knows why"]$P '.'$N"While it may seem like trivia, it"(k"causes huge headaches for software developers\nis taken advantage of by high-speed traders\ntriggered the 2003 Northeast Blackout\nhas to be corrected for by GPS satellites\nis now recognized as a major cause of World War I")$P '.'E))<$>newStdGen ``` [Try it online!](https://tio.run/##bVVNb@M2EL37V0yUALYRJ8i26GGLeIv9yC4WaI0gWWAPsQ9jipa4pkgtSVlRkP@evqGcoih6sWhxOPPem8dRzXGvrX15MU3rQ6L7ISbdXN6xK30zKTkxfSNerogf8NzM8DN/vqWPNYdxfTOxFLEfHzY3k7RcFanWxaRfNtySvex9KONkf/xnjdNxUiKomFQn/Dwzi3p@fRFysbvZ1cJqV6Wa@OLNvFrO@OREAibV6c1yVhSLSpazW1Lk5s8zvTjgbHXqljP1u/yRzYzjP7sPU5o@x3dFsTk/j@fn/wo9ZmoXPyX2RC1mTQb087RdHDPU/5OhOSbZLRMbe7mL6XJ2uio@mZIG39He@Z5Szal4SLO@2LGFQm0wrirmZ7bQPzvj/GOxkM3euKQDxa5pdMB2iXfR25iM0uTt0LRGxWJ@k4M1B2t0TGQ54fEa3rlgokYOF3WS2FVR8mBNVadC9vmA0jQ@YoaQTKMLhFnNrYQgnAZkl8MAyLBAGPGhzQepGLsWMLfW@zJnaLx3BWK/@cHDIil0ak@Nd6mWtxHH9tRrvS82s/JhhTRtq10sZvsjibB2QgIPTtBKUx88QGZgWaSDDkdMQieYXYrku0R@R3FwinoDn4jVHqwoIFVfMT350rAqFiJOFXTlg2FHDQ/4tZ3jQOa29m4spBieK6WMLTj5xihS1oOMcfTRWx@49MVGNG1GQfeF84lGQms3Pin16NcobW3iiHtztiq2WnGH3vhdARWEHT2hMlldmQgBjHcoJC346gDaMb0PBhFMd12MhseGMJVaBa1pO2Stbn2rBZ@s3/x2dRVHrm3QSuMUclqzDWN216VxgVfjQiulXQpGmTSQ31oDP6YB4FcFxBVJwVG0XDsIu3Y3HFI9jcSPJq4d3AuZ0DcYGmzgWiPA1y4b2eUSbAmDAyxx3dfuL47eXXwyjxmEyC6cGq6chstpZ7QtKUjDI1vpNtrEYWtSYFgAzE2mtB0E1wftfnAD7p8xNPZIt3ZfI7Oile6TQP786Q4FNme3NP1jCkrv25YD@NpBnGIS5YaADUGu0qjEWytiQl@OWVUFg7BSpsSpKLaQqwz@fT3A0uj8QfqHeRa18q7MIVEZRJsIk6Ia2ODOI9qHYHQpnFC450hgCSd6hOjHFDQELDsZDK9O3uIWPGniSktWmQHHJeAlVtp3udybt2@vpnG0JU4GPR0J@dZDQ0oeqj6SSQva4sqY7NreYAw5kfkf87JKXQba8B6SwLoYEII6om2wcUzY1WUWBbczwFxrl68BbTV1Di8xqFI39nzsqxGpKp2SsMqpCNOdnCfxvYzGrGSRO3QpHfpeG@lAkhsKTXUDl@w1Roo5GF4c0R@7VncVOqC5ZFXj785jdPpd6kX0EtwsbkaIGXwCJxipPLBLEFEGB65PDfQXsdVgBX@VORiVqgoilvlC/XJ19Sut8CmsZQ7SB8tqj8EjVz2KsmCu0FetEg4IAGT9cnuP@ZrwHTUYzLm8fAMQ5CtnnhDI0qCGfyD@dSLQdx/g/O@w21fcvizHzXx@ffbO6f4@lV@0e2nYuGXbpfsU/nTL6@vdy98 "Haskell – Try It Online") (Has an extra 2 bytes for `f=`) Mostly wrote this just so I could create the data structure. This could definitely be improved but I'm tired and I have to leave soon anyway. I think capitalization is mostly right but I'll convert it all to caps if it's wrong. That won't change the byte count or anything since I haven't done anything weird with the string data. Basic idea is a linked list of trees where each node is either empty (`E`), a punctuation mark (`P`) or a string label with children. All nodes except `E` nodes have a "follower" node that comes after them. EDIT: just noticed a spelling mistake (I wrote "no one know why" instead of "no one knows why") so I had to add a byte to fix it but I also found some code that could be cut out [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 1593 bytes `C←?∘≢⊃⊢` `S←C'|'∘≠⊆⊢` `∊'Did you know that '(C('the '(S'Fall|Spring')' Equinox ')('the '(S'Winter |Summer ')(S'Solstice |Olympics '))('the '(S'Earliest |Latest ')(S'Sunrise |Sunset '))('Leap ',S'Day |Year ')'Easter '('the '(S'Harvest|Super|Blood')' Moon ')'Toyota Truck Month '('Daylight Savings Time '~C's∘')'Shark Week ')(C('happens '(S'earlier|later|at the wrong time')' every year ')('drifts out of sync with the '(S'Sun |Moon |Zodiac |atomic clock in Colorado|',' Calendar ',⍨S'Gregorian|Mayan|Lunar|iPhone'))('might '(S'not happen|happen twice')' this year '))'because of '(C('time zone legislation in ',S'Indiana|Arizona|Russia')'a decree by the pope in the 1500s'((S'precession|libration|nutation|libation|eccentricity|obliquity')' of the '(S'Moon|Sun|Earth''s axis|equator|prime meridian|',' line',⍨S'international date|mason-dixon'))'magnetic field reversal'('an arbitrary decision by ',S'Benjamin Franklin|Isaac Newton|FDR'))'? Apparently '(C'it causes a predictable increase in car accidents'('it was even more extreme during the ',S'Bronze Age|Ice Age|Cretaceous|1990s')'that''s why we have leap seconds'('there''s a proposal to fix it, but it ',S'will never happen|actually makes things worse|is stalled in congress|might be unconstitutional')'scientists are really worried' 'it''s getting worse and no one knows why')'. While it may seem like trivia, it '(S'causes huge headaches for software developers|is taken advantage of by high-speed traders|triggered the 2003 Northeast Blackout|has to be corrected for by GPS satellites|is now recognized as a major cause of World War I')'.'` [Try it online!](https://tio.run/##XVXBbtw2EL3nK@ZGG3AKp0UPOQX2Jk4NJGmQNWC0t1lqLDFLkQpJea2A6CVA6hoo0GOPRU79rv2R9I0UN0UvSy3FmXnvzRuKB/@wmdjH9vP@9tcV@zO25fNq//GPJ/vbP/e/fdrffdjffXqwxs7KVDNv/rW/@6ib@9s789Q1NMWRtiHuqHRcyBysDkzpBA9rc8be1/WQXGjNoaFn70YX4g2Zw69HLl0okqiux77Hildrs44@F2eF6o9@6gdnM/b/E/OMk3eSC9UXXHRdosaQXBZNFbKUJeSF8EDmaG2e8kT1J2EtgQRZi5qvKX/gdI1MiB0k1VMfY6OIX8YYNOAiTrEwXaTRbrEZSqfByOld2xVa8zUoZrpwPdL9sjIZSiFs3XHa0qXIViFCmI6HQUKeS8rMIlUPDqlCOsWySzG0VJBHy8u1pImmBfWBaZK7KpniWCheUZ6CpZ0DlHsSIE51hlx/jo1jS0gbe2fJ@gjgLtAq@pi4idUcGULDJTSa/Gj/@99r8zxJG5PjUF/yhN8XY@BU3esuBpnV7Ge2WirEQguZuixUduiYgi6dy/eYD81GLI/oCgAv1lCJ3iMheWldBnkHvECmTToPQB24niSHI1zfjDk7RlKmRmwSoc00sx3iIBqkz4@@Pz7O5gCghiRWEBFD9W6T5tQ1jGV5wNbyINZKKMlZV6YaN97BlmVS6AB5r6XKqE6qMFvpjMnENy5XeTdC0lThafCAY50intX0DiotQs6eDnM19tSgwbXnHMPDxt3EoLL03AaBx@nKiW8oaacze5iKA3HauJIYrQdrp3yUtwp0KuEt9yB@ljhsUbGeZ0afX8muAO/Z0zea/AmdDAMnkPSTqm5cobkLIEEQqXG28MarghCV8yylRcPYWtcgDHJqzI6zWjBQH5OQ3JQkIN2MOs@LUAoJjn0vdNJKPbfLukpS2Eocc330@DGac2j0blARd91EO4F1rtUAmM0sNoYmL6OYZBYaGOMQIQeVCIFuyJUj2sD1wKQld857CirZvQdxbY24aybqeQuWsKCO4y6mLBVuzAUvpZlpYr4STFIXL2@ExoA93DdlXPoFtNk6qOAyhg0yojtzbqRLThpD0EZxtlKKKjGXIQ4NhUjqbL0NZ6pI9Q1ddk6lLsA2ga70cMpWCAa8dnw0c4LfvvSnG1uoI9yw7fD3KibK8arsFEYDxh7GT1k5FTCFVZprDoXbecBgkg6sHuZBQBYOavQsCrUtpG3mln17fPwdvYrwNBpf6NSz3eJCwRRnVRt6WNAUW3BeqyPn89dryvCw9w63rdbW2x5nYhvce5xj7VnPb3H832G/jAm@voSpzlUFox@Yz1@@MA/@t/4D "APL (Dyalog Unicode) – Try It Online") Defines two helper functions and then uses them in one giant expression: `C←` C (for **C**hoose) is `?∘≢` a random number up to the number of elements in the argument `⊃` picks `⊢` from the arguments `S←` S (for **S**plit and **S**elect) is `C` choose among `'|'∘≠` the where-not-pipe `⊆` partitioned `⊢` argument `∊` **ϵ**nlist (flatten) `C` chooses from a list of strings and `S` chooses from the substrings of a `|` delimited string, and these are just used in combination to construct a "fact". ]
[Question] [ I do realise that this is a bit math-y, but - here goes. > > In mathematics, the hyperoperation sequence is an infinite sequence of arithmetic operations (called hyperoperations) that starts with the unary operation of successor, then continues with the binary operations of addition, multiplication and exponentiation, after which the sequence proceeds with further binary operations extending beyond exponentiation, using right- associativity. > > > Your goal is to write a program that takes three integers x, y and n as input and outputs the result of the nth hyperoperation on x and y. E.g. `1 1 1` outputs 2 `2 4 4` outputs 65536 `3 3 4` outputs 7625597484987 * The program must be written in the shortest bit of code. * You may take input either from `STDIN` or from a file. * Library functions not allowed. * Input constraints: n will be ≥ 1. <http://en.wikipedia.org/wiki/Tetration> has a good explanation in case you can't wrap your head around this. [Answer] ## APL, 62 ``` {1=3⌷⍵:2⌷+\⍵⋄0=2⌷⍵:(⍵[3]⌊3)⌷⍵[1],0,1⋄∇⍵[1],(∇⍵-0 1 0),3⌷⍵-1}⎕ ``` `{...}⎕`: Takes evaluated input (space-separated numbers evaluates to a numerical array) and apply function to it. `1=3⌷⍵:`: If n equals 1... `2⌷+\⍵`: Return sum of first 2 elements (x+y)... `⋄0=2⌷⍵:`: Else if y equals 0... `(⍵[3]⌊3)⌷⍵[1],0,1`: Create numerical array [x,0,1] and return index `min(n,3)`... `⋄∇⍵[1],(∇⍵-0 1 0),3⌷⍵-1`: Else return ∇(x,∇(x,y-1,n),n-1). (∇ is self-reference) --- I have got a "hyper-raiser" operator, which takes a function and return next hyperoperation ``` {⍺⍺/⊃⍴/⌽⍵} ``` For example, `+{⍺⍺/⊃⍴/⌽⍵}` would be the multiplication function and `+{⍺⍺/⊃⍴/⌽⍵}5 3` outputs 15. But can't get it to recurse. Maybe someone else can do it. [Answer] ### Ruby, slow, ~~86 84~~ 83 characters ``` def f x,y,n n>1?(c=x;2.upto(y){c=f(x,c,n-1)};c):x+y end p f *gets.split.map(&:to_i) ``` ### Ruby, fast, ~~96 94~~ 93 characters ``` def f x,y,n n>1?(n>2?(c=x;2.upto(y){c=f(x,c,n-1)};c):x*y):x+y end p f *gets.split.map(&:to_i) ``` The first version is *way* too slow with the last test case, so I added a version that uses multiplication as the base case instead of addition. The first version takes ages to calculate `3 3 4`; the second one is instanteneous (in the native IRB console; the web version is a bit slower). Several beauties of Ruby show up here: Almost every statement is an expression in ruby. Thus, you can stuff semicolons inside the ternary operator, provided you've got enough parentheses lying around. Coffeescript borrowed that one. It also borrowed Ruby's "no parens needed" call syntax. Implicit returns: this is a cool feature, and follows from the previous. Indeed, starting the last line of a function with `return` is considered lame, even when not golfing. Numbers are objects in ruby (even `null` is an object). In ruby, integers have the method `times`, which executes the block passed to it several times. This is just one of Ruby's many iterator methods. Here, the `upto` method lets us save two more characters over what `times` lets us. unary `*` is the splat operator here. It turns an array into an argument list. Just like Javascript's `Function#apply`, but it's shorter and better. unary `&` turns a procedure into a block. While `:to_i` is a symbol, it converts into a procedure pretty well. Namely, it turns into a procedure that calls `to_i` on its argument and returns the result. [More information on Stack Overflow.](https://stackoverflow.com/a/2259787/499214) It would be possible to get it even faster by using `n=3` as the base case, but I'm afraid it is not needed. It would only cost 11 characters, though, thanks to another beauty of ruby: the exponentiation operator `**`. Python has this operator, but it's not the first one (as @aka.nice noted - thanks -, Fortran already had this operator). online ruby interpreter available here: <http://repl.it/Ikj/1> [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~31~~ ~~23~~ 22 bytes ([SBCS](https://github.com/abrudz/SBCS)) *Saved 6 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)* ``` {×a←⍺-1:a∇⍣⍵×⍺-2⋄⍵+⍺⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rw9MRHbRMe9e7SNbRKfNTR/qh38aPerYeng0SMHnW3ADnaQDYQ1f5PA6vse9TVfGi98aO2iY/6pgYHOQPJEA/P4P8lqcUlQAXVFQqVCnlglVsVgAYo5CloVCikaSpU1nKBlBxaoaBhqACEmgoaJgpGcNoIShsDaWMFEzBtBKRNNOHajBQMwMpBtBGUNobSJpoA "APL (Dyalog Unicode) – Try It Online") Can be used as `n (x f) y`. ``` { ×a←⍺-1: ⍝ Check if n is greater than 1 a←⍺-1 ⍝ Assign n - 1 to a variable a to reuse later × ⍝ Sign of a (0 if addition, 1 otherwise) a∇⍣⍵×⍺-2 ⍝ Apply the (n-1)th hyperoperation y times to x ×⍺-2 ⍝ Sign of n-2 (the identity for the nth hyperoperation ⍣ ⍝ Power operator, apply ∇ ⍝ the derived function (f x) ⍵ ⍝ y times ×⍺-2 ⍝ to the identity a ⍝ With n-1 as the new n ⋄ ⍵ + ⍺⍺ ⍝ n is 1 (addition) } ``` ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ṛ+⁵ðx’ß@ƒ>2¥ðỊ? ``` [Try it online!](https://tio.run/##DcqhDoJAGAfwzlP8ow4MMhMBeRXAAz7HPhh3DK5p0hltzmCyUwzOJpvvwb3IyX71txdlqS1x3SoZgD1oD71DGRgkQSwpZ8oojVkF0G7vVKoQTUdSzHu1xkIjrWoScolG7NpUINEw51MEqeJGEefoSBXg0LfT@@6a42scenO4jY/odw3973Mcps9la63dzPw/ "Jelly – Try It Online") Writing a 3-argument program in Jelly is hard, though at least we need to use one of them only once in this problem. So this program takes three arguments in the order of `n y x` and recurses as a dyadic function. Roughly a hybrid of [this Ackermann solution](https://codegolf.stackexchange.com/a/235779/78410) with [user's APL answer](https://codegolf.stackexchange.com/a/215427/78410). ### How it works ``` ṛ+⁵ðx’ß@ƒ>2¥ðỊ? Main program as a dyadic link. Left = n, Right = y, 3rd arg (⁵) = x A..ðB.......ðC? If C then A else B Ị If n <= 1 ṛ+⁵ Then y + x x’ß@ƒ>2¥ Else... x’ y copies of n-1 ß@ƒ>2 Reduce with the program itself flipped, with the default value being n>2 (1 or 0) ``` [Answer] # Python, 83 (Based on [flornquake's answer](https://codegolf.stackexchange.com/a/11523/7971)) ``` def h(x,y,n):r=n>2;exec"r=h(x,r,n-1);"*y*(n>1);return(x+y,r)[n>1] print h(*input()) ``` **Very** slow for large results. For `2, 4, 4` the output is `65536`. [Answer] # Python, 96 92 ``` def h(x,y,n):r=1;exec(n>2)*y*"r=h(x,r,n-1);";return(r,(x+y,x*y)[n>1])[n<3] print h(*input()) ``` Input: `3, 3, 4` Output: `7625597484987` Shortened using a couple of [@WolframH's ideas](https://codegolf.stackexchange.com/a/11524/7409). [Answer] **Smalltalk Squeak 4.x flavour many bytes!** I could implement one of the recursive form in Integer in 71 char ``` f:y n:n n=1or:[^(2to:y)inject:self into:[:x :i|self f:x n:n-1]].^self+y ``` Then reading from a file or FileStream stdin will cost me an arm... Squeak was obviously not designed as a scripting language. So I will spend many bytes to create my own general purpose utilities unrelated to the problem: Implement this 21 char method in Stream (to skip seaparators) ``` s self skipSeparators ``` Implement this 20 char method in Behavior (to read an instance from a Stream) ``` <s^self readFrom:s s ``` Then 28 chars in String (to create a file handle) ``` f^FileDirectory default/self ``` Then 59 chars in FileDirectory (to create a readStream) ``` r^FileStream concreteStream readOnlyFileNamed:self fullName ``` Then 33 chars in BlockClosure (to evaluate it n times) ``` *n^(1to:n)collect:[:i|self value] ``` Then 63 chars in Array (evaluate the argument with receiver and arguments taken from the Array) ``` `s^self first perform:s asSymbol withArguments:self allButFirst ``` then solve the problem by evaluating this 31 char snippet anywhere to read from file named x ``` |s|s:='x'f r.[0class<s]*3`#f:n: ``` Even without counting the utilities, that's 71+31=102 chars already... Now, since I'm sure to lose the codeGolf, I have a funnier implementation in Integer: ``` doesNotUnderstand:m (m selector allSatisfy:[:c|c=$+])or:[^super doesNotUnderstand:m]. self class compile: m selector,'y y=0or:[^(2to:y)inject:self into:[:x :i|self' ,m selector allButLast,'x]].^' ,(Character digitValue:()asBit) ,(m selector size-2min:1)hex last. thisContext sender restart ``` This method will define (compile) a binary messages made of n + if it does not exist (is not understood by the receiver of the message m), and will restart execution at the beginning of sender context. I inserted additionnal carriage return and spaces for readability. Note that `(m selector size-2min:1)hex last` is a shorted form of `(m selector size>2)asBit printString`. If it was not to demonstrate Smalltalk evil superpowers, the last statement could be replaced by shorter and simpler ``` ^m sendTo:self ``` Now implement 28 chars utility in Character (to repeat it n times in a String) ``` *n^String new:n withAll:self ``` Then evaluate this 43 chars expression: ``` |i s|i:=0class.s:='x'f r.[i<s]*2`($+*(i<s)) ``` We can accelerate with 10 more chars by implementing in Integer: ``` ++y^self*y ``` and in this case we also have shorter code because we can replace `^',(m selector size-2min:1)hex last`with `^1'` For such a high price, the code work with second integer=0 :) [Answer] ### Golfscript, slow, 39 characters ``` ~{\(.{3${[4$\2$4$.~}4$(*}{;;+}if])\;}.~ ``` [(live link)](http://golfscript.apphb.com/?c=OyIxMSA0IDMiCn57XCguezMkezQkXDIkNCQufn00JCgqe1w7fTQqfXs7Oyt9aWZ9Ln4%3D) This is the standard recursive algorithm with a base case of n=1 (addition) (i.e. slow). The same I've used in [my Ruby solution](https://codegolf.stackexchange.com/a/11521/7209) Here's a version with my annotations (mostly stack-keeping). It doesn't include one optimisation I've added later: ``` ~{ #read the input and do (x y n f) \(.{ #(x y f n-1); if(n-1) 3${ #(x y f n-1 c) 4$\2$4$.~ #(x y f n-1 x c n-1 f); call }3$(* #y-1 times {\;}4* }{ #else ;;+ #return (x+y) }if }.~ #once ``` `~` is the eval operator. In case of strings, it treats the string as a GolfScript program. Luckily, a space-separated list of integers is a valid GolfScript program that pushes those integers on the stack. Compared to this, my previous version of the input routine (`" "/{~}/`, split by space and eval each) is pretty lame. In case of functions, it calls the function. When preceded by `.` (clone), it calls the function with itself as the first argument. Golfscript doesn't seem to be exactly well suited for making recursive algorithms. If you want a recursive algorithm that isn't tail-call optimisable, you need to create and destroy stack frames to preserve your variables. In most languages, this is done automatically. In golfscript, you have to actually clone the variables (actually, stack entries), and destroy the stack entries you no longer need. Golfscript has no concept of stack frames. Have I said GolfScript is a stack-based language? The first requirement is understandable. You have to specify the arguments somehow. It's only nice if they keep their original positions as well. The second requirement is unfortunate, especially since the return value is on the top of the stack, and golfscript lacks the ability to delete just any stack element. You can rotate the stack and discard the new top element, but that quickly builds up. `\;` is fine. `\;\;\;\;\;` isn't. You can do `\;` in a loop (`{\;}9*`; cost: 6 chars to discard up to 9 elements, or 7 chars to discard up to 99 elements), but we can do better: Golfscript has first-class arrays. It also has the array literal syntax `[1 2 3 4]`. What's unexpected is that `[` and `]` are not actually a part of the syntax. They are merely two operators: `[` marks the current position on the stack, and `]` collects every element until it finds the start-of-array mark or runs out of stack, and discards the mark. You can even tear these two apart and see what happens. Well, quite an interesting thing: Did I say golfscript has no concept of stack frames? I lied. This is a stack frame: `[`. You can discard it all at once: `];`. But what if we want to keep the return value? You could close the stack frame on function entry (then we have a slightly mangled version of pass-by-array - not an interesting concept), or we can close the stack frame and take its last element instead of discarding it completely: `]-1=` or we can uncons the last element instead, and *then* discard the frame: `])\;`. They're the same length, but the latter is slightly cooler, so I'm using it. So, instead of 6 or 7 characters to do a clean-up, we can do with 5. I still feel this could be golfed more, but hey, we've saved a character. [Answer] # Groovy - 77 ``` h={x,y,n->n<2?x+y:y<2?x:h(x,h(x,y-1,n),n-1)} print h(args.collect{it as int}) ``` Note: it requires obscene amounts of stack (and time) for non-tiny arguments. [Answer] # [R](https://www.r-project.org/), 70 bytes ``` h=function(x,y,n)`if`(n<2,x+y,{z=n>2;while(y){z=h(x,z,n-1);y=y-1};+z}) ``` [Try it online!](https://tio.run/##jY/BCsIwDIbvfYqCl1XjYJsn53wFH2EWrWuxa2WNuE589hnR01CQNGn78yfh60YdL6rzlBKNd9Woq9PVHV7vpIcITuzNaZ@4TQ79IsJ9qNw2L2/aWJVEQV9NtgHcMhNlrOIye5SL4SEmY5MMKASbqDmsYCXYjE/0AgrS@YyjNoHTCdbf0jTljLx0Bw8cPT@q1ruA1KTIKZGK4tI2vjOo21ff7rye7KwDyg6Na2qJdXu1aC7WHN7srPnBXkA//8befGVn/6/8kI5P "R – Try It Online") As other answers have noted, recursing back to the n=1 hyperoperation of addition is rather slow by the time that n>3 and the hyperoperation is tetration or worse. [TIO](https://tio.run/##jY/BCsIwDIbvfYqCl1XjYJsn53wFH2EWrWuxa2WNuE589hnR01CQNGn78yfh60YdL6rzlBKNd9Woq9PVHV7vpIcITuzNaZ@4TQ79IsJ9qNw2L2/aWJVEQV9NtgHcMhNlrOIye5SL4SEmY5MMKASbqDmsYCXYjE/0AgrS@YyjNoHTCdbf0jTljLx0Bw8cPT@q1ruA1KTIKZGK4tI2vjOo21ff7rye7KwDyg6Na2qJdXu1aC7WHN7srPnBXkA//8befGVn/6/8kI5P "R – Try It Online") link includes recursive version starting at n=2 (multiplication) to check that the approach is sound and works for the last test-case... --- # [R](https://www.r-project.org/), ~~78~~ 74 bytes **(for all n, including n=0)** ``` h=function(x,y=x,n)`if`(n<2,x^n+y,{z=n>2;while(y){z=h(x,z,n-1);y=y-1};+z}) ``` [Try it online!](https://tio.run/##hZDdjoIwEEav7VNMsjc2YsKPesPWR9nYwLA0gUJoXakbn50tKC6uZU1K0jJz5pucpstNjU1lP65FJVmXs@wok/6@bD3DWk/Sg8gOS/keeu2HXBnv@8zkPoxPuShwaah95rb17Ml1QGPDzDq4xKvzhXZCJg2WKPVkJIXF4jHSspL5lPA0FcMK03xnu7FAQEl5LLSoC5FwF@akQkqwrStpdxIOyg1FlGjUjavfDWwovIHOhQJ7VFGdIKsa4EUB2CZYa/jCxoAq@z/Am89j70gR8mdY4A9i7CzFSwRux41CbY0C20MQOKBo0DPBRrND8cpFM1w45R4F/9KRP0NHU/pR9CTb95/40NuM3kb8rrwvDuBuu412hFi1qDQkXKGCU44SDHMtdLeXYiYkpv1QswqGFWbaZ63dbM/FvLB2pefgF9Ju0c/G/P@MjRTpfgA "R – Try It Online") This was one of those frustrating problems where I couldn't resist going-ahead and trying to write the shortest *general* solution, even if n=0 wasn't required by the question. The behaviour of n=0 (increment) and n=1 (addition) is different to all subsequent hyperoperations, since y=1 is not an identity function for these two cases. I've worked-around this by stopping recursion when `n<2`, and returning `x^n+y`, which manages to satisfy both the n=1 and n=0 cases. For added niceness (at the cost of another +2 bytes), we can specify a default value for y of x, which means that it needn't be provided as an argument at all for n=0, since this is can be considered a unary operation on y. So: +4 bytes wasted, but I'm happier now. [Answer] # [Haskell](https://www.haskell.org/), 45 bytes ``` 1?x=(x+) n?x=(!!)$iterate((n-1)?x)$signum$n-2 ``` [Try it online!](https://tio.run/##JczBCoMwEIThu08xQg67dAON7VV9kLaHCKEN1UVMBN8@NRS@w38Y5uPTN8xzKW48ejou3GiNtmUTc9h8DkRqHY8HmxTfui9GbVeirntO6PEgJ6hYQJ3gfqp5FZxu/GoWH/UcrlvUDIPFr6AnecEkUIYdQDp6xsT4v5Yf "Haskell – Try It Online") Call it with `(n?a)b`. # [Haskell](https://www.haskell.org/), 51 bytes ``` (1?a)b=a+b (2?_)0=0 (_?_)0=1 (n?a)b=(n-1)?a$n?a$b-1 ``` [Try it online!](https://tio.run/##JY1BCsMgFET3nmIWLv6nCpp2az1IW8IXCpUmIk16fmssvMUMM8y8ZHs/l6U18lE4BTklRVOc2QWnaB7CKyojpGI9R9Hd6WR9y6V@9w0BN/IGB2xAk8Glc0hn0DnzQ62SSy/WTy47NFapoDuJQTIoDHvF@EBi/FfbDw "Haskell – Try It Online") Copied straight from the hyperoperation formula on [Wikipedia](https://en.wikipedia.org/wiki/Hyperoperation#Definition). Call it with `(n?a)b`. [Answer] # AXIOM Computer Algebra System, bytes 69 ``` p(x,y,n)==(n<=1=>y+x^n;n=2=>y*x;n=3=>x^y;y<=0=>1;p(x,p(x,y-1,n),n-1)) ``` test: ``` (2) -> p(1,1,1) (2) 2 Type: Expression Integer Time: 0.05 (IN) + 0.03 (OT) = 0.08 sec (3) -> p(2,4,4) (3) 65536 Type: Expression Integer Time: 0 sec (4) -> p(3,3,4) (4) 7625597484987 Type: Expression Integer Time: 0 sec ``` This would eliminate some recursion...Possible I swap in x and y in some return... are there other test values? [Answer] # APL(NARS), chars 61, bytes 122 ``` {(x y n)←⍵⋄n≤1:y+x*n⋄n=2:x×y⋄n=3:x*y⋄y≤0:1⋄∇x,(∇x(y-1)n),n-1} ``` test: ``` h←{(x y n)←⍵⋄n≤1:y+x*n⋄n=2:x×y⋄n=3:x*y⋄y≤0:1⋄∇x,(∇x(y-1)n),n-1} h 1 1 1 2 h 2 4 4 65536 h 3 4 4 ∞ h 3 3 4 7625597484987 ``` [Answer] # [Scala](http://www.scala-lang.org/), 90 bytes Port of [@John Dvorak's Ruby answer](https://codegolf.stackexchange.com/a/11521/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##XYtBC8IgGIbv/orvqOWCbZ0qB3Xr0LW7mYYhbmw2HOJvN2tdFrzwPDzwDoIbntrbUwoHF64tSO@kvQ9w7DoICKGRG1A7fNKPs3V0AcKaWYAl7OlEbS5aYduUJHxZkTDyHgTze9X2WB@KClwL00Zbd@XmJYlgKl8FtUVJ9iJKM8jgV1P82XqKCQF0fT4YixUuKXxGyKJWFLZ5f7WmUM8VxfQG) ``` (x,y,n)=>if(n>1){if(n>2){var c=x;for(i<-2 to y.intValue)c=f(x,c,n-1);c}else{x*y}}else{x+y} ``` Ungolfed version. [Try it online!](https://tio.run/##bY8/C8IwFMT3foobU02Ftk6igm4Oru4xTSQS0tJGSZF@9prW/hExvOH4vXfcpeJMs7bNr3fBLc5MGQhnhckqHIoCryAAMiEhidvgqG4nYynqWZpRhqPAzrvgn5IgBnvE4QBmlMwIeLIS3LvcRGRegihsIySwOeqVMvbC9EOQMJyO0Jt8LwrueyDyQdOSD6qB0JX4CnNYoB6XwZ8Th@Vw0K2b7v9F6fO1IZLEFN30LWaaUKz9/NCUIv3QoGnbNw) ``` object Main extends App { def f(x: BigInt, y: BigInt, n: BigInt): BigInt = { if (n > 1) { if (n > 2) { var c = x for (i <- 2 to y.intValue()) c = f(x, c, n - 1) c } else { x * y } } else { x + y } } println(f(1, 1, 1)) println(f(2, 4, 4)) println(f(3, 3, 4)) } ``` [Answer] # C (gcc), 90 bytes -2 bytes thanks to @ceilingcat! ``` _;h(a,b,n){int k=_++||!scanf("%d%d%d",&a,&b,&n),j=a;for(--n;n&&--b;)a=h(a,j,n);_*=k;a+=b;} ``` [Try it online!](https://tio.run/##RY7LCsIwEEX3@YqxYEhMAtoICmP@RChJSm1aTKWKm7bfHlvxcWcxi3vmMF5dvE@pwJpZ6WTkQ4gPaE0hxDiu7t7GimXrcplMUiupkzRy2RiLVdczpSJGSpVyyK1ZHM3swGJjWrTCOJzS4rvaENmzCyUnA4FP5ntgSxvAwBbndQKNIETg8Ke@ufUz@v7lHDMJNeMcf9BEppSDBk007CEnBzjCLr0A) Ungolfed and explained: ``` _; h(a,b,n) { int k = _++ || !scanf("%d %d %d", &a, &b, &n), j=a; for (--n; n && --b;) a=h(a,j,n); _*=k; a+=b; } ``` The code applies the `n`th hyperoperations to `a` and `b`, respectively. These inputs need not be provided by the caller, since they're immediately reinitialized anyways. `_++ || !scanf("%d %d %d", &a, &b, &n)` makes `a`, `b` and `c` be read from `stdin` if and only if `_` is non-zero (that is, if the current function call is not a recursive one - if it's called by another function rather than itself). The expression returns 0 if any new characters were read and nonzero if they weren't, making `k` an indicator for whether the current function call is a recursive one or not. Then, the `for` loop applies the `n-1`th hyperoperation to `a` `b` times, using `j` to store the initial value of `a` and `a` to store the intermediate values. Finally, `_*=k` makes `_` zero again if and only if the current call is not a recursive one, so that the next call will reread the values of `a`, `b` and `c`, and `b` is added to `a`. Usually, `b` would equal 0 after the `for` loop, but if `n` equaled 1, the for loop wouldn't be executed at all and the function returns `a + b`. Note that the value of `a` is returned after `a+=b` since [assignments and returns are usually stored in the same register](https://codegolf.stackexchange.com/a/106067/108622). ]
[Question] [ Every Brazilian citizen has a national identification number associated with them, named CPF. This number has 11 digits (formatted as XXX.XXX.XXX-XX) and it's validated by the following (real) algorithm1: 0. Take the 9 most significant digits of the number. Call it ***c***. 1. Multiply the ***n***-th least significant digit of ***c*** by ***n+1***, where ***1 ≤ n ≤ 9***. 2. Add all the products and evaluate the remainder of the division between that and 11. 3. If the remainder ***r*** is less than 2, consider 0. Otherwise, consider ***11 - r***. Update ***c*** to contain that as an appended least significant digit. 4. First time on step 4? Go back to step 1, but now ***1 ≤ n ≤ 10***. Otherwise, go to step 5. 5. Is ***c*** the same as your initial number? If yes, then your CPF is valid. Let's take **111.444.777-35**. 0. Take the 9 most significant digits of the number. Call it ***c***: ***c = 111444777*** 1. Multiply the ***n***-th least significant digit of ***c*** by ***n+1***, where ***1 ≤ n ≤ 9***: | ***c*** | 1 | 1 | 1 | 4 | 4 | 4 | 7 | 7 | 7 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | | result | 10 | 9 | 8 | 28 | 24 | 20 | 28 | 21 | 14 | 2. Add all the products and evaluate the remainder of the division between that and 11: ***10+9+8+28+24+20+28+21+14 = 162 mod 11 = 8*** 3. If the remainder ***r*** is less than 2, consider 0. Otherwise, consider ***11 - r***. Update ***c*** to contain that as an appended least significant digit: Considering ***11 - 8 = 3***, ***c = 1114447773***. 4. Go back to step 1, but now ***1 ≤ n ≤ 10***. | ***c*** | 1 | 1 | 1 | 4 | 4 | 4 | 7 | 7 | 7 | 3 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | | result | 11 | 10 | 9 | 32 | 28 | 24 | 35 | 28 | 21 | 6 | ***11+10+9+32+28+24+35+28+21+6 = 204 mod 11 = 6*** Considering ***11 - 6 = 5***, ***c = 11144477735***. 5. Is ***c*** the same as your initial number? Yes. Therefore, the CPF is valid. ## Input You can accept one of the following (or all of them): * a [string](https://codegolf.meta.stackexchange.com/q/2214/91472) containing exactly 11 digits * a string containing exactly 14 characters formatted as `XXX.XXX.XXX-XX`, where `X` is a digit * a number ***0 ≤ n ≤ 99999999999*** + you must read it from the most to the least significant digit: ***n = 12345678901*** corresponds to 123.456.789-01 + you must pad it to 11 digits: ***n = 3*** corresponds to 000.000.000-03 * a list/array of numbers ***0 ≤ n ≤ 9*** containing exactly 11 elements + you must read it from the left-most to the right-most element: ***[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]*** corresponds to 123.456.789-01 Always assume the input meets these constraints. ## Output Whether the input is a valid CPF. You may either * output truthy/falsy using your language's convention * use two distinct, fixed values to represent true and false ### Truthies ``` 11144477735 52398680002 05830033542 06865086376 39385258001 39290600780 01871863759 03337363466 66377805292 71462831435 54669275895 24029901557 83190130205 97727810509 70159591945 68730451957 55829849330 30162341903 56684732365 60505376660 29535063731 ``` ### Falsies ``` 10433218196 00133890838 63794026542 35116155940 78161849593 10341316475 25534192832 76483503056 41395376724 23884969653 28710122691 66978480184 51462704828 14893252880 95701543039 11718227824 89638346578 71331509839 30103105183 47382997376 ``` Try to create your code with fewest bytes as possible. The [standard I/O](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) is applied. --- 1 [Source](https://www.geradorcpf.com/algoritmo_do_cpf.htm) (in Portuguese). [Answer] # [JavaScript (Node.js)](https://nodejs.org), 43 bytes ``` a=>a.some((v,i)=>i>8&(y+=x+=v)%11>!v,x=y=0) ``` [Try it online!](https://tio.run/##RZExcxtBCIV7foXjmWROI@cMy8JCcSpTpnGZpDhLZ40ysuRItsb@9cq7ylsx8IDHt3/Hy3hen3Yvr98Px810fRqu47Aa@/Pxeeq6y91uMax2q/jWfSyH9@VwWXwVWX253L0PHwMvruvj4XzcT/3@uO1O07@33Wnqbp/Ot4v@NI2bH7v99PBxWHe86F@PD6@n3WHbzaWX/bieuvvfm@X99u7mfDOsbp66X33fn//0z@NL9/Pt@XE6LfCu/PlIRGqtrTU1sqIZHkgXYgtlVrWK2MONw7U5aWpYMYgEcUl25hZMLNFkllgS2rSpa3UnRwp1K1moSfUSKnXehWKWZpFGpXLJZDFrhDIi5cJG2VppIWyc1FBOS8lq5NGUq0lCbxYlo6Yqk7J40YoBSuYetWlRhx4TDObdmUqaGsOUCtEnByHhqlokJB15UY3k0CBIE/58BqEm4rCJBMGYCxZbKnqxVcVrwzFmswXciYO9BrYpmxMEOZtopVLRQKenm1IBN5ZSPAWwskUNsKxkM6zGNUqQ1EgtVgKgcTRQVGVNfB6YFzDCzEjXAHJrAdCqAmoBDaCwgqGEEoCAVjbY@A8 "JavaScript (Node.js) – Try It Online") -1 bug from Nick Kennedy Inversed output, 1 byte to invert [Answer] # JavaScript (ES6), 64 bytes Expects an array of digits. Returns \$0\$ or \$1\$. ``` a=>(g=k=>a[k]==(a.map(v=>x-=k&&v*~k--,x=0)|10*x%11%10))(9)&g(10) ``` [Try it online!](https://tio.run/##RZHNThtRDIX3fgqEBJqhZPDPta@9mCy76IIuWLYspmESpQkJTQCBVPXVUw8b7sqyj@3j7/4eXofj4rB@ep7t9g/jadmfhn7erPpNPx9@bO77vhm6x@Gpee3nb7N@c3n5evVvM5tdv/XY/iW8ersguiBs2ybay1WT0Wmx3x3327Hb7lfNYfzzsj6MzfnyeN52h3F4@Lrejnfvu0WDbfe8v3s@rHerZio9bYfF2Nz8fPhys7o@O57187Nvd99vu@OHZL18b5bNj67rjvcfhm5fHn@Nh3Z6J/x8QESllFqrKChLuHmmGVBdEEW0ZGxuim5SDSTElTVFlDEHGmJ1BCSvNEk0INukikkxA8tU1pWDoVIxdqEy7cpicFUPBS7IEUiqFbKckSCjQtTK1QkVA2qWQ4OiKJhXwaIUqVd1Di8hgiBIxlJygICaeanCYqnPCZrmzRA4VBTTlBDAJwcCwiLC5BSWeRLxQBeHlEb6swmEKJGlzUxAGjPKxRqSvblVyErNY1QnC3lnHmzFc5ugGqQgJhOVC7B4dlqYCnByQ2K2oIQV1YsnywI6wapYnB2oeAgre4LOoxNFEZTIz0vmnIxypoeJJ3KtnqBFKKl5ahIKSjIkF0ggSStq2vgP "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ÄÄ%11>¬ṫ-Ẹ ``` [Try it online!](https://tio.run/##FZDNaR1xDMTvqsKXHA2SRp8YXEYgBeQS3EBuJhjcRFJBfMzBSW55lbzXyGYWlkX8NZJmfl8@Pz19PY7Ly@Xlg9njv7fr75/31z/vx8Pt@fvd/ePd7fnHw@VVrn9/fbx9e@N3eeXv03GYWUR0N1LSsVOjqi6aA1Ugg3VNpU6hS7CY9KTIWPtqqfaoqE3bKckVjqFRiCopPrGfvi5tUT6wOG@xud45m@KhvquW2cI2K6hrynZ7j2nqSrO9ubaRUtPQSFvqM8d3YgEVqJUjuACSVRMNR1HPDUnzVSq@iVSagolpAG5jW8I8wKwORthdWqozO9Ks6IwPQi9lvJULzvIQrKLpP/O8ymjMWDE8AM0SCva82x7iGE7WVkKcqNTca418tieG@ELy5NMa4yMWs/D0IVvmZPqAYsWMmJ1YuHO2MKScPWQLGEENNeSgIDYbCBkQ0DZt/Ac "Jelly – Try It Online") A Jelly translation of [`l4m2`’s clever JavaScript answer](https://codegolf.stackexchange.com/a/269160/42248); be sure to upvote that one! A monadic link that takes a list of digits and returns 0 for true and 1 for false. ## Explanation ``` ÄÄ | Cumulative sum twice %11 | Mod 11 >¬ | Greater than not the original argument ṫ- | Last two Ẹ | Any true ``` ## Why does this work? The (sum of the cumulative sum of the first 10 digits) mod 11 is equivalent to (the answer to step 2 in the question plus the tenth digit) mod 11. For a valid CPF number, this should be zero unless the result from step 2 was one, in which case it will be one (and the tenth digit will be zero). As such, this can be checked to see if it is greater than the result of not (tenth digit); for valid CPF numbers, this comparison will return false. The same applies for checking the final digit, so in practice it’s possible to do the cumulative sum twice and then just take the final two values, as implemented above. To extend the table given in the question: | ***c*** | 1 | 1 | 1 | 4 | 4 | 4 | 7 | 7 | 7 | 3 | 5 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | | | | result | 10 | 9 | 8 | 28 | 24 | 20 | 28 | 21 | 14 | | | | cumsum c | 1 | 2 | 3 | 7 | 11 | 15 | 22 | 29 | 36 | 39 | 44 | | cs cs c | 1 | 3 | 6 | 13 | 24 | 39 | 61 | 90 | 126 | 165 | 209 | \$ 165 \bmod 11 = 0 \$ \$ 209 \bmod 11 = 0 \$ Therefore this number was valid. ## Alternative [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 17 bytes ``` J‘Uḋị⁵ḶUݤṭ ḣ9ÇÇ⁼ ``` [Try it online!](https://tio.run/##FZA7bhRhEITzPoUvgNTvhyxxAHJb4gAkyBdwtnaygS/gACIITQbWoiVi5YPMXGRcI/1B6@9HVX1fv9zd3W/bp/XwfLOcnpbz0/rwZzm93ryd//9c/v6i5fRjLsfLcX34t12vh29XHz5erYfv15cjLefft@vjCx7ajy@ft01E3L2qLCjUprOZWYmjjdksHHV2BndaJdlYhwaGBLUOJ3M1E0uX7CMxhDUrS/NMSnyhHzpKJZ7aJr5roTla0ROkzjrDElGENipj5aCp0mrh4KFCe2JkPCi7jD1kMB/ROu1jxmQsqeY4YBSZ7WVqiXlcCJjPZNIJC4YpExJ2M5WWSUIesx5ua0J3YCn37BYiCWf4IHhJgVaMYRdCJukF/xG7KqIhY3pDwDiSMDC7bqmTWmMzJ8NIgYpFNUfAZ6q9gc8pdj7F3tok3mMa2mCLnEjvxjYkAswKLLjZk9agHNVgayYA1ZgBBzZgkzYCAwCago13 "Jelly – Try It Online") A pair of links which is called as a monad with a list of 11 decimal digits as its argument and returns one true and zero for false. *Thanks to @JonathanAllan for saving 4 bytes!* ## Explanation ``` J‘Uḋị⁵ḶUݤṭ | Helper link, takes a list of integers and appends the next check digit J | Indices ‘ | Add 1 U | Reverse order ḋ | Dot product with original link argument ị | Modular index into: ⁵ḶUݤ | [0,9,…,2,1,0] ṭ | Concatenate to end of link argument ḣ9ÇÇ⁼ | Main link, takes a list of integers and returns 1 if valid and 0 if not ḣ9 | Head 9 (first 9 integers) ÇÇ | Call helper link twice ⁼ | Is this equal to original argument? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¨¨2FDā>R*O11%11αDT‹*ª}Q ``` Input as a list of digits. [Try it online](https://tio.run/##yy9OTMpM/f//0IpDK4zcXI402gVp@RsaqhoantvoEvKoYafWoVW1gf//RxvqgKAJGJqDobGOaSwA) or [verify all test cases](https://tio.run/##PZO9TlwxEIVfBSGlQS5sj38baFa0UaJ0KwqQKKgoIiFRICUND8BTILqUaVfUPAQvssx8411ZvnvveObMOcez97@vb@5u9w@PF6cnn88vJ6cXj5v97nX3mi8373/Pf559T@lbSh//Nr8@//w/2709/diH/Xabgq3C6iwJ9Spsa8j6NsMITXdkZY3HUPVb@BbL1TqPN3Krxu1XFKlp3DBEI4ZXF1Ja8azb6izW7QycpG@dp6PUMIkLy/hZvOjT8NvKop4uEz4dVU2/ja29H3RRSfcOo0k8azxSbZySntTQNe7VHhMyIvmTnpm@ic4Rnn1VT7ZVFvIbqgxBv4k7foVDxumCV4IPAk7jFspiIOQ3nC6gZdxwfOdQ3XlWRNckVnHa/TP/E0wEjISGiZ9xKRWcibg3wLfauVxqx3sX1BhT94wMfBgr6rrsRFZfVyScmw73v8LTtfqt@T1azlgKBIXG0xHmUa/dRQHHmHvPxq70zWuqTF1GwcQHn4VOxQg@fQWfD/PTccruaMC/4Iwwz5lekXmo4XD3BZ7CPJg3Ps15TYvzHHATlBVYdvD7cj/5RHE@j/MQOYl4PtDlczDW5Pb1v7v6Ag). **Explanation:** ``` ¨¨ # Remove the last two digits of the (implicit) input-list 2F # Loop 2 times: D # Duplicate the current list ā # Push a list in the range [1,length] (without popping) > # Increase each by 1 to range [2,length+1] R # Reverse it to range [length+1,2] * # Multiply the values of the two lists at the same positions together O # Sum 11% # Modulo-11 11α # Absolute difference with 11 D # Duplicate this value T‹ # Pop the copy, and check that it's smaller than 10 # (1 if its [1,9]; 0 if it's 10 or 11) * # Multiply that to the value ª # Append it to the list } # After the loop: Q # Check whether this list equals the (implicit) input-list # (after which the result is output implicitly) ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 29 bytes ``` .$ ¶$= . *$<%' .{11} ^0?¶0?$ ``` [Try it online!](https://tio.run/##FZA7TkRRDEP7rGMQiGKUxPlKIEp2gaCgoKFAdIhtsYDZ2ODXRTfOtX2@3r8/Pt/senP3/Ho9n@Tyd3qUs9yfHm5u5fxj9ivyok@XP306Xa9mFhHdjZR07NSoqovmQBXI4FxTqVPoEiwmPSkyzr5aqj0qatN2SHKFZ2gUokqKT9ynr0tblA8sDi8u1ztnUzzUd9UyW7jmBHVN2W7vMU1daa431zZSahoaaUt95vhOLKACtXIEP4Bk1UTDUdTzh2T4KhXfRCpDwcQ0ALexLWEfYFYHI9wuI9XRHWlWTMYHYZYyeuWCtzSCVTTzZx6urMaOFUMDaJZQsIdve4hjeFlbCXGiUnOvNfLZnhjiC8mDT2uMj1jMwtOHbNmT7QOKFTNidmLhn7OFIeXsIVvACGqoIQcFsdlAyICAthnjHw "Retina – Try It Online") Link includes test cases. Takes input as a string of `11` digits. Explanation: Same idea as @Arnauld's previous answer. ``` .$ ¶$= ``` Duplicate the input, but without the last digit. ``` . *$<%' ``` For each digit, repeats the substring starting at that digit by that many times. ``` .{11} ``` Reduce modulo `11`. ``` ^0?¶0?$ ``` Only a single `0` is allowed to be left over each time. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~24~~ 21 bytes ``` ⊙θ∧›κ⁹›﹪Σ⭆⊕κ…θ⊕λ¹¹¬Iι ``` [Try it online!](https://tio.run/##TYxNCsIwEIWvkuUE4iIYCeKqZCEuKoWeICSDLU2TGqeFnj5GQfBbPHi8HzfY7JINpXR5jARN3OEpWBM9XDNawgyTYGcu2M@2ya8hQb/O0FPdPFq7wC26jDNGQg9TLZvdBTRDWj5n/2HgFcGkrHJPBMa@CEb@5VKKlFIppbU@nsphC28 "Charcoal – Try It Online") Link is to verbose version of code. Outputs an inverted Charcoal boolean, i.e. `-` for invalid, nothing for invalid. Explanation: Now a port of @l4m2's JavaScript answer. ``` θ Input string ⊙ Any digit satisfies κ Current index › Is greater than ⁹ Literal integer `9` ∧ Logical And κ Current index ⊕ Incremented ⭆ Map over implicit range and join θ Input string … Truncated to length λ Current value ⊕ Incremented Σ Take the digital sum ﹪ Modulo ¹¹ Literal integer `11` › Is greater than ι Current digit I Cast to integer ¬ Logical Not Implicitly print ``` [Answer] # [R](https://www.r-project.org), 39 bytes ``` \(x,`+`=cumsum)any((++x%%11>!x)[10:11]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZLdahtBDIWhl3qKrcF0FztFGo00UmnyIk0hJlmXgOMarwMO9L4P0Zu00Idqn6Zn8VWvRujo5-hjfvw8vv7aXv9-Pm2v4s-72_68vlvdXd8_P03PT8Nm_9L3q9V5uRS5eXsePgl_EPk8XMr_vvk-nruPV91CRGqtrTU1sqIZHsxciC2UWdUqYg83DtfmpKlhxVAkiEuyM7dgYokmc4kloU2bulZ3cqSgW8lCTaqXUKnzLohZmkUalcolk8WsEWREyoWNsrXSQtg4qUFOS8lq5NGUq0mi3ixKRk1VJmXxohUDlMw9atOijnpMMJh3ZyppagxTKiRcVYuEpBPuUY3k0CCoCUs-364m4nCGBMGLC3ZZKnqxSMVrg3-zeStOw41eAwuUzQkFOe9tpVLRQKenm1IBKpZSPAV8skUN4KtkM5_GNUqQ1EgtVgJscSeur8qaJALMBVgwM9I1QNlagK2qAFSgBhxYgU1CCQwAKBtsLLpvN910Ok6H3eOpX9zuF8OcGXf98L9yye82h8Pupd9M7x_3p_HLeBzofnPqp0t6PK87fLlhOhwhb_vFcuqubrrlw2LdHTbTacR37O6_7jBlGrvrDkPX3RYNA95pPMyp2cHlP76-Xt5_) An R translation of [my Jelly answer](https://codegolf.stackexchange.com/a/269154/42248), itself a translation of [l4m2’s JavaScript answer](https://codegolf.stackexchange.com/a/269160/42248). A function that takes a list of digits and returns a logical value, with FALSE for valid and TRUE for invalid. [Answer] # [Perl 5](https://www.perl.org/) `-F`, 82 bytes ``` say"@{[map{$m=$_+2;($c=(sum map$_*$m--,@F[0..$_])%11)>1?11-$c:0}8,9]}"eq"@F[9,10]" ``` [Try it online!](https://tio.run/##FZLNaltRDIT3eopibiFpbaP/I7m4zSqrdplVMCaELAx249buooS8et3x6gppjmb0cY8vv/dxuZye/s7u3h4PT8e36bCetp/1y830vL45/Tl8QHPafpoOi8X87v6Rl8tpu7n9KHL7Vb6JLKbnFb/XvDfvs5dfMyh6LryZXS4i4u5jDAsKta4sZlbiKGM2C0edlcGVNpKsrUIDIkGtzck8iomlhlwl0YRnNizNMynRwjy0lYZ4apn41QvD1hHVQeqs3SwRgzBGZawc1GPoKOHgpoFxR0t7UNYw9pCGPqK0y9uMyVhSzbHAKDLLh6kl9NgQCJ/JpB0WjFAmJOxmKiWdhHvMqrmsCNNGpLzebiGSSIYGIUsKvKINb2Fkkj6QP@LqitNwY3rBwDiSIOir71AntcLL7AwjBSoW1WwBnx7lBXxOceUz2EuLxKtNQwtscSeud2NrEgFmBRbsrE4rUI5RYGsmAFXQgAMbsEkZgQEA9UCMf6/H8@715@my@BFLSPD9vjudV6uH826/xk90Wezv/wM "Perl 5 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 78 bytes ``` x#s|r<-mod(sum$zipWith(*)x[s+1,s..2])11=x!!s==last(0:[11-r|r>1]) f x=x#9&&x#10 ``` [Try it online!](https://tio.run/##TVPLbttADLz7KzZ2kUit4/Kx3CWNuMcCvRfoQdBBaBzEqJ0GkgMIRf7dpVpkldtqwCFnONRjN/zaH4@Xy7gaXvu729Pv@2p4OX34c3j@cTg/Vh/rsRk@4XrYbKitEXfj1dWw2x274VzBtkG87V/7L9jWi4cw7saVXV@PK4TLqTs8hV147g9P59CMN@E1VP06jEMd7m7DeT@cf3bDfnBk@h6nx830ak7ds1fuu/uwCdW2aevaS7bb0Hx7OrftOjxMhZ93oW8Xi9LGJzWLEKrv/ct@/e8ZwhIRY4w5Z5bl@j8kxKZJAYDeIBBlAGaJM5Q0CWjinN4gNlYhcSbOEBkkgKxQiKgZJ55YgZg5c@KYSq/kBU4SsjIxY0ykjPGdVGcYZVErEEUgM0CR/AY5xwEGglJlOVNWBIEiIjvHxNBiqUqaGaKgzb1ElEyjMRdDDJiIo8/gUpWSxszEae7ls8SXlVIhkgkLuFHGZVtPYPW1Ow7vwoHITKhoZS@@W2Y1UNbSmbO56fQuHBbE5CtwvNhTR1y4WFGJ4KoZU8zz9kQmJ77mee0pqstkkCLCWTZ5yRQLkdWbJ0tS2pPnDEiUDOdULWtUP4FClCnVDFGpGMKoxiSk89F4Ah5PZOCSF6KfEXmKswi1xOpXJFnno2FGT1lnoucF7NGjFqmelcdqeTpm/0tDaBeXvw "Haskell – Try It Online") [Answer] # APL+WIN, ~~61~~ 60 bytes Prompts for a vector of 11 digits and returns 1 if valid 0 if invalid. ``` e=+/c=v,e-e|+/(e,n)×v←v,(r>2)×e-r←(e←11)|+/(v←9↑c←⎕)×n←⌽1+⍳9 ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##HY1NCsIwEIX3OUWWLW1pktq/Rd0LimcoNRWhVGmhILiuLlR0IR7EtStvkovUN2EY8uabNy/loQk2x7LZb4OqKft@V03m/lotzfiIGNRiDSWZuZzrSRdeWBWDrwN98kJH@637ew/YD77TzRUGHXQYHU030iUTrXMzPiu8iIOnJXX9Ss/cPvmEYDbVTHKqma3UVsRjVrOYK6icZzxBC1uK1ZwJHgNEFkRkxiEWCBJQRBQCM3TOE3DyScszEGFvM/AEbwoyo2B8YnP@ "APL (Dyalog Classic) – Try It Online") [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 23 bytes ``` 9Θ2(DκṚꜝ×∑11%9z0JṚṙiJ}₌ ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCI5zpgyKETOuuG5muqcncOX4oiRMTElOXowSuG5muG5mWlKfeKCjCIsIiIsIls1LDIsMyw5LDgsNiw4LDAsMCwwLDJdIiwiMy40LjEiXQ==) ``` 9Θ2(DκṚꜝ×∑11%9z0JṚṙiJ}₌­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁢⁡‏⁠‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌­ 9Θ # ‎⁡Slice list from 0 to index 9 2( } # ‎⁢Repeat twice Dκ # ‎⁣ Triplicate top element and push range [1, length] Ṛꜝ× # ‎⁤ Reverse, increment and multiply range with list ∑11% # ‎⁢⁡ Sum list and mod 11 9z0JṚṙ # ‎⁢⁢ Push range [0,9], append 0, reverse and rotate list right => [0, 0, 9, 8, ..., 1] i # ‎⁢⁣ Index result into list J # ‎⁢⁤ Append to initial list ₌ # ‎⁣⁡Is equal to input? 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # TI-BASIC, 62 bytes ``` Prompt N For(X,11,12 X-cumSum(1 or ʟN 11-11fPart(11⁻¹sum(ʟNAns*(Ans>1 If Ans≤9≠Ans⁻¹ʟN(X 13→X End Ans≤9 ``` Takes input as a list of digits. [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~122~~ ~~116~~ 112 bytes The function takes as input the list of the digits of the CPF number. It returns `0` for true cases, `None` for false ones. ``` def f(n): for i in 10,9: s=sum(n[j]*(i-j+1)for j in range(i))%11 if 0if s<2else 11-s!=n[i]:return return 0 ``` [Try it online!](https://tio.run/##bVTLbtswELz7K9hDAalhAL4fQXLtF/Rm@BCgUisjVQzJPuTrXe6QbqNNQFCvHe7Ozu7q9Hb@/TrbdFqu15/DKMZu7h92YnxdxCSmWWglc3kX69N6@dPN@@PhWzfdH@90T5AjQZbn@dfQTX3/VeuCnEahyl4fzfCyDkLr@/XL07yfDg/LcL4s807Uu1DX0zLN5@7Hchn6XX0eu72WtBxWxLLSH/p3CC9N@ZZlkqFshWU2CCV9sVhYLJ0vvjgi4LwvCLrbEidsEBTBFhtF8y2O/oAwZZMvskZCsSi6fIu41hheZoawWJQlIVy5bnmEdhLewSazXCL0CsVCOdPzR8XgF3wjsskMYQpCwTflowvGy7hBVN/VaoFVzEcGSwOmGlwVyzY23xmbvDnmI0Av8l8sQHAeHvwN6u9QI8tUt4gS0CWucbbMR0D9HWIZaM95VP6@dgaWYoplWD3qXyv4rj9u9@/PZQo27a1QIAqrIVRmBVdNYosyKRQ1MXIULreShU/a20I8EqGWElhWitTsVUbCbEXSGB4HLoQksXjTeEhQRa7tx1uTzqUmk4Wg22yr//xPaGogx6KQEpVlwPaMqWlDRroZKJLZqNbmj/CSZB1Lx1riNkQRFaIWS0wPh4pY/BAMOCk2AF7eWtwhW8sGgGpSfwemDQrPNiFDC80cco2MR2zdoeuAAZk/GQAFjEInJKZYbfzUBj7@//1d/wI "Python 3.8 (pre-release) – Try It Online") * *-6 bytes thanks to [enzo](https://codegolf.stackexchange.com/users/91472/enzo)* * *-4 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* --- *Brief explanation* The `for` loop is to check the 2 last digits. `s` computes the sum of products, takes modulo 11 and finally the (corrected) value is compared to the corresponding last digit of the CPF number. If the values are different, the function returns `None`, else continues on the next loop. If both checks are ok, the function returns `0`. ]
[Question] [ Let us consider the following representation of the periodic table. ``` __________________________________________________________________________ | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |--------------------------------------------------------------------------| |1| 1 2 | | | | |2| 3 4 5 6 7 8 9 10 | | | | |3| 11 12 13 14 15 16 17 18 | | | | |4| 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | | | | |5| 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | | | | |6| 55 56 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | | | | |7| 87 88 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | | | | |8| 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | | | | |9| 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | |__________________________________________________________________________| ``` # Task Produce a program that takes an atomic number as input, and outputs the row and column of the element of given atomic number. For instance, giving the atomic number `1` should produce `1 1` (or `1, 1`, or anything that looks like a vector of two 1s). # Details The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are *all* in a dedicated row, hence there is no element that is placed at `6, 3` nor `7, 3`. You may take a look at the atomic number repartitions [here](https://en.wikipedia.org/wiki/Periodic_table#/media/File:Simple_Periodic_Table_Chart-blocks.svg). The atomic number is at least 1, at most 118. # test cases * `1` -> `1, 1` * `2` -> `1, 18` * `29` -> `4, 11` * `42` -> `5, 6` * `58` -> `8, 5` * `59` -> `8, 6` * `57` -> `8, 4` * `71` -> `8, 18` * `72` -> `6, 4` * `89` -> `9, 4` * `90` -> `9, 5` * `103` -> `9, 18` # Scoring This is code golf, standard rules applies, hence fewer bytes win. [Answer] # JavaScript (ES6), 79 bytes ``` n=>[(n+=--n?n<4?33:n<12?43:n<56?53:n<71?90:n<88?39:n<103?76:25:17)/18|0,n%18+1] ``` [Try it online!](https://tio.run/##Fck5DoMwEEDRPqeYJsKWgWDMYhbjQ1BGKRCbiNAYgZUmy9UJVO9L/9m8mq1dp8V6aLp@H9SOqroTZMrzUGMZaSFyLHmoo9M40fFpynUWHEqpRXb@QOg0ycM45ym9cfkJXLxyyfhjH8xKEBTwAhDKQy6PYozC@wLQGtzM3PuzGQn61tR2nXAk1F@arrbNaomgwMCBX@W4MBCktLh89z8 "JavaScript (Node.js) – Try It Online") (raw output) [Try it online!](https://tio.run/##PYzBboMwEETv@Yq9VLEFODiE4BAcq9@QI@VgJSEigjVyUBVU@u10kdqe3tPMaB720z4vvumHCN31Ntd6Rn0qGQY6itBgsTNJkmMht2a3MN2bdGEmzSEmKmWSw9LHicn2@TbNZcY3Uk1xiG9SBbKaa@dZBxrKKgQkyiOhIEpFFgQcvlYA5RjCq6K6ZsiPFLCuHCECuWT/Ok3w7r0dmVRc1E3bsjUArDkvX39bFIM7D77BO@Oit9fzYP3AEvr8Xl0cPl17E627s050tmce9Am8eLgG6YqOfvUDyecf "JavaScript (Node.js) – Try It Online") (builds the periodic table) Or **76 bytes** if 0-indexing is acceptable: ``` n=>[(n+=--n?n<4?15:n<12?25:n<56?35:n<71?72:n<88?21:n<103?58:7:-1)/18|0,n%18] ``` [Try it online!](https://tio.run/##LczBboMwDAbge5/Cl6mJgLSBMSJKGu0ZemQcorZUVOCgNKqGxp6dmWqn77ct/3f7tI@z78aQoLtcl1YvqI81w0gnCRqs3o3MS6xkatLV/MNkq4U0RUoqZVK53veZyVVZlInkO6nmfYxvUjVL6zwbQEPdxICkPBAVKRWlKOLwswGopxi@Gzq3DPmBFmyop3V@Mc/w6b2dmFRctF3fsy0AbDmvXz8ogjsF3@GNcTHayylYH1hGPb@bs8OH66@idzc2iMGOzIM@ghd31yHVUMl//ELKyx8 "JavaScript (Node.js) – Try It Online") [Answer] # JavaScript, 79 bytes Inspired by [Arnauld's answer](https://codegolf.stackexchange.com/a/248697/87728). I tried to golf it more, and ended up with this. ``` n=>[(n+=[113,417,1195,5429,6906,8487,9964].find(x=>n<x/96)%96||25)/18|0,1+n%18] ``` [Try it online!](https://tio.run/##pZHBjpswEIbvPMUcsoqtOCQGHJympOqhhz4DQTUizi4r1iAg26wSnj3FxtlmpayUqid@j2e@/x/znL6mTVbnVTtV5Vaed9FZResYqUkUc4/4ASXL5ZIELPQJ4x4jIWWU8GDuJ@4uV1t0iNbq62HGKX7gdOqdTiGeUX6aE/VAeXJeOY5wKEzXQAlQx7so7vhaeroYWOU5o2Psuu73uk7f0AIn7ktaIfSLKAzRGsToqGACrLPtw5H6ncDuc5kr4YjOocbL11jqWXkftwfZ/pvgawTlnzGWhhG8M/4d4YcGwW4jGNOXC70eW1j5cT3KPgGHXmcHhnPwAcxDfRlqMOdW3gmm86CzE7fIdzHYsDX/DwQf3n55GyHcts5fEHabqshbNN6oMXZ3Zf0jzZ5QK5tWk44OQCFbiAnkqtq3BOryN4GsLBKIQHf1zm0/MEOb7QRrOyPI8JlhOJ0gTlY9Jr6e/HswyQ/a6wBToFi3ZqXq7WvZ7Is@BexQldaN/KlaZELgq6YqbRrDM83xvIdHQ0ZboaainS5DZSHdonxEetS4V9q9gm8gNnsvnDMBXwYZZPbB0HiM319ATNfigicmgCtfZf1mOViDDALJQyWzVm4hHh37TJ3@EX2SLsGiX6HDq/Mf "JavaScript (Node.js) – Try It Online") The outside is the same as Arnauld's answer, but the lookup for what to offset `n` by is different. If we create a table the same size as the periodic table, where each item is equal to `column + 18 * row - 1 - Z` (where `Z` is the atomic number at that position), we can see some groups emerge: ``` || 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ==||========================================================================= 1 || 17 | 33 ||-----+ +--------------------------- 2 || 33 33 | 43 43 43 43 43 43 ||---------------------------------------------+ +------------------------ 3 || 43 43 | 53 53 53 53 53 53 ||------------------------------------------------+ 4 || 53 53 53 53 53 53 53 53 53 53 53 53 53 53 53 53 53 53 || 5 || 53 53 53 53 53 53 53 53 53 53 53 53 53 53 53 53 53 53 || +--------------------------------------------------------------- 6 || 53 53 | 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 ||---------+ +------------------------------------------------------------ 7 || 39 39 | 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 ||------------+------------------------------------------------------------ 8 || 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ||------------------------------------------------------------------------- 9 || 76 76 76 76 76 76 76 76 76 76 76 76 76 76 76 || ``` Once we have the right group, we can just add its value to `Z`, then the row will be `(new) Z / 18`, the column `Z % 18 + 1`. The lookup table `[113,417,1195,5429,6906,8487,9964]` will be more obvious in this solution with a factor of `100`, instead of `96`: ``` n=>[(n+=[117,433,1243,5653,7190,8839,10376].find(x=>n<x/100)%100||25)/18|0,1+n%18] ``` Each item `i` in the list `[117,433,1243,5653,7190,8839,10376]` corresponds to one of the groups such that the group value is `i % 100` and all atomic numbers in the group are less than `i / 100`. I reduced the factor to `96` to save bytes. --- ## Old invalid answer (0-indexed), 76 bytes ``` n=>[(n+=[82,341,999,4573,5825,7151,8403].find(x=>n<x/81)%81-2||7)/18|0,n%18] ``` [Try it online!](https://tio.run/##pZHdjpswEIXveYq5yCq24piY8GOakqoXvegzEFQQcXZZsQYB2WaV8OwpNs42K2WlVL3ieDzznTPmOXvN2rwp6m4uq60476KzjNYxkrMoZmxJXBYQxkKPeK4TEj9c@IS7PCBh6LsJ3RVyiw7RWn492KGPH0L/dHI8bDN@WhA2kw@MJ@eVZaUWg/kaGAFmORfFraWSjiq6RjnW5BhTSr83TfaGfJzQl6xG6BeRGKI1pJOjhBl4vWkfj2zZp5g@V4VMrbS3mPZaKixzjLyPO4BM/03wNYLxzxihZrjvjH9HLAON8G4jPE9d@mo9zzfy43rM@wQcOL0ZGM/uBzAP1GWgwJwbeSeYLdzeTNwi38Xwxq35fyD4@PbhbURKu6Z4QZi2dVl0aLqRU0x3VfMjy59QJ9pOkY4WQCk6iAkUst53BJrqN4G8KhOIQHUNzt0wYKPNdoaVnRZk/NgYTieIk9WAse34evbvQWc/KLcDzIFh1ZxXcgjQiHZfDjlgh@qsacVP2SEdA1811Vnbap5ujhcDPBpTmgrTFeV0GapKQcvqEalR7V4r9xq@QbrZO8HCS@HLKN3cPBmaTvH7G6TzdXrBEx2AilfRvBkOViCNQOJQi7wTW4gnxyFTr37FkKRPcDqs0OPV@Q8 "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` T•3¾§Ue•44вÝ•¨²>Ùö€•Ƶlв+ª˜18‰>Iè ``` [Try it online](https://tio.run/##yy9OTMpM/f8/5FHDIuND@w4tD00FskxMLmw6PBfIOLTi0Ca7wzMPb3vUtAbIPbY158Im7UOrTs8xtHjUsMHO8/CK//9NzQE) or [verify all test cases](https://tio.run/##yy9OTMpM/W9oaOHqZ6@k8KhtkoKS/f@QRw2LjA/tO7Q8NBXIMjG5sOnwXCDj0IpDm@wOzzy87VHTGiD32NacC5u0D606PcfQ4lHDBju/wyv@6/wHAA). (You can add [`--debug-stack` as argument to the singular TIO](https://tio.run/##yy9OTMpM/f8/5FHDIuND@w4tD00FskxMLmw6PBfIOLTi0Ca7wzMPb3vUtAbIPbY158Im7UOrTs8xtHjUsMHO8/CK//b/Tc3/6@qmpCaVpusWlyQmZwMA) to see all individual steps.) **Explanation:** ``` T # Push 10 •3¾§Ue• # Push compressed integer 15829433590 44в # Convert it to base-44 as list: [2,7,43,14,16,14,14] Ý # Convert each inner value to a list in the range [0,value] •¨²>Ùö€• # Push compressed integer 180810357611003 Ƶl # Push compressed integer 148 в # Convert to base-148 as list: [17,30,48,129,93,147,111] + # Add these to each value of the inner lists at the same positions ª # Append this list of lists, which will first implicitly converts # the initial 10 to list [1,0] ˜ # Flatten it 18‰ # Divmod-18 each inner integer > # Increase each integer in each pair by 1 Iè # 0-based index the input into this list of pairs # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•3¾§Ue•` is `15829433590`; `•3¾§Ue•44в` is `[2,7,43,14,16,14,14]`; `•¨²>Ùö€•` is `180810357611003`; `Ƶl` is `148`; and `•¨²>Ùö€•Ƶlв` is `[17,30,48,129,93,147,111]`. [Answer] # x86 32-bit machine code, ~~39~~ 36 bytes ``` 99 42 A9 FE 42 3C 02 76 1A 8D 4A 02 D1 E9 0F AF C9 D1 E1 28 C8 77 ED 4A 42 2C F1 7F 04 42 7B F8 4A 04 03 C3 ``` [Try it online!](https://tio.run/##XVNdj9owEHy2f8VChc4u4ZRAK0E4kKqqfevLPZ0ECDmJE3JyHOokqhHHXy9dJyVHG0XrjxnPzq6TeJLF8fUqqgLY85DRNCRx8pOSXMcgE0vJY3SqJfj2y8LD@P0bFeE7GBdHEMqDKSWvkQRJiZICZGw92CABxjDdUVIdTLcXoG7RqG6BwUHqBlUhqZqolYsV6gkQlCSyyxTdJb2xJsFnpGVQ37l9PZYQvR@rQyKSpGXPqAyJkTXlQ76k@72oa5NHTS33e8aMzI7CFCzgnIMqddaFXNeQMhcFnvmAWVSTSHiq6iQvHw9r6qBC5JpxesZuHISBWkRKbha7TTDfwQrO/mVJSVoaaHU0bgVLHJ5wDOY4G485JXiY/JvWIDFlGtMS4tYW106BGw9OODewXsNs2sIpMAtrCObw9obgGhZuYl0Ov9u6zTpzp0mw21gMmJmQo0HZlA0HgwGM8u7d6qEH2gO8mFNrQapKOvJ/AmhEI3y5q9CZ85c4DFawwLGvr2fYjmEdw7XAtpSujr/6qN6Z692NPuVoqe3APcd56831ZMBn2GLHpna3wh62@oF3Tm@krf4h4kOuJcRlIsOW39vDunGZlHDuNUf@9AUtnFaMNbrKMy0TcNofeco3WAOaucCvQ64ksLZ6336dOdFegWFv3d9U8ba/1oH4RTZGYz/o5Xr9HadKZNV1UsymGPCnXOFRqf4A "C (gcc) – Try It Online") This takes a 32-bit integer in EAX, following the `regparm(1)` convention. It returns two 32-bit integers in EAX and EDX; [this document](https://www.agner.org/optimize/calling_conventions.pdf) seems to say that this would be the standard way of returning a structure of two 32-bit integers, but [it apparently doesn't actually work that way](https://tio.run/##PY/BisIwEIbPnacYKkICVrbuzaoP4Vko2TTtBppYkolUxFc3TtnFy/AN83/DjK4GrXNW0aE4lwL6feGuNzRq3mANf9wx76AIhkCWsoG2VUTB/iQybStEMMOkghO1lBIjhaQJJ3xYT8jivXliL5ZGsbqyXo@pM3iI1Nnr9vcEy8gp64WEBxQfP5iYRsIjyzWLxRQ42ItybXFtL77c/Ce284fuS46vTMHjVwPPnF@6H9UQc@W@d1z4yyNvMeMb "C (gcc) – Try It Online") (or am I misreading that document?), which is why the linked TIO program is coded differently. -3 by calculating line lengths instead of hardcoding them. In assembly: ``` f: cdq inc edx .byte 0xA9, 0xFE a: inc edx cmp al, 2 jbe e lea ecx, [edx + 2] shr ecx, 1 imul ecx, ecx shl ecx, 1 s: sub al, cl ja a dec edx b: inc edx sub al, -15 jg t inc edx jpo b dec edx t: add al, 3 e: ret ``` The main part of the code works as follows: * If AL ≤ 2 (in the first two columns), jump straight to the end. * Calculate the length of the current line as \$ \lfloor\frac{\textrm{line number} + 2}{2}\rfloor^2\cdot 2\$ and subtract it from AL. * If the result is positive, jump back to repeat, moving to the next line. * Otherwise, add a net +18 to AL and return. Special cases are handled as follows: * `sub al, -15` is used to check for being in the extracted block and reused to adjust the horizontal position for elements in that block. * That check gives a false positive for elements 21 and 39 (the only ones in column 3). That is corrected for by looking at the parity flag after `inc edx`; the incremented value is 5 (1012) or 6 (1102), with even parity, for elements 21 and 39, whereas it is 7 (1112) or 8 (10002), with odd parity, for elements that do belong in the extracted block. * Helium (2) is dealt with by `.byte 0xA9, 0xFE`, which subsumes the following two instructions into a `test eax, 0x023C42FE`. The following `be` condition is (CF or ZF); CF is always 0 after a `test`, and in this case, ZF is 1 only for element 1. [Answer] # [Python](https://www.python.org), 124 bytes ``` def f(n): for m,z in zip(b'hYWH97%\x13\r\x0b\5\3\2\1',b'*,\x0f)+\x0e\r\x0cw\x0bv\n\xa2\t'): if m<=n:return z%9+1,z//9+n-m ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RZXNbtNAFIV3SM1TDIsqCXHp_P9UdM8bICRvKNiqJeJEqQuhwJOw6QZegieBpyFzzzHdRP7s6J7vjJOZH7_2X6bb3fj4-PN-6i_yn28ful71q3F9tTjrdwe1bR7UMKqHYb-6Wd6-ffO6pPP2aFx7aI_6pg2ta21rls3N8kVzutOvN6fPTp6-_1y_8qkd2-M7207LOvJs6NX21fV4deim-8Np7nnZmObh8rJsxostHP4--9197LbdON2pa_XVXKmVaZRZNwtleZ0ruBNYPvC4tvU68L6rEAm-QiKECpkQKxRCqmA0SWJMFXDMMRYgQcbxiSQZT5IoE0iSZSJJwkwiIS2TkFZN_FxXAyTNGoCEWQuQLOsAEmU9QJJsAEiQjQDJsQlQBDJDtdCsIA6ODkYkHCVQ2dEClR01UNnRA5UdRVDZ0YTvsaoEVnYZgLQCkDCvAZLlDUCivAVIkncACfIeIDk-AKSyjwyVyn5WwI-JDqjsKYHKgRaoHKiByoEeqBwogsqBJqgcqkpk5RAB-PFWk8yWIQMwvQBkeNQAmR0NQEZHC5CW0QHQMnqSxMZAktwYSfjX0AItIzXQMtIDLRNF0DLRBC2TRTH89xxAZiQPwAguBiZwMTAgAaRLylwz6ZIKSbpkTZIu2ZCkS6YFumRqcA-gB7rk-a2ISaYJuuSqkvjGcgYgrZoUtiwaINOLAWCHsQCZXRxARhcPkJYlANCyRJLElkSS3JJJ0rLQgruPpge3H00T7j-aLvN2RxvuQNqjHScFEAdFEOdwUTiGq8IpBVSwh2ounwYaIjZV2VXTXMzIvpr-76uGPqxmKMRqhkasZub3BCdDp1O174tFPdCGRu1UPdLmM-blMHXbu1U9nY6n86ZfDetFPaaO6vm12tUza38Yxklu87J-54l2T5frswXOsPk8_Qc) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes ``` NθIE↨⁺θ⊟⊟ΦI⪪⪪”←&“▷/»h⦄¤Ah)|J\-w~~∕↔AX”¶¦ ‹⊟ιθ¹⁸⁺ικ ``` [Try it online!](https://tio.run/##NU7LCsIwELz7FUtOCURomj7pTUEQVApec4lSMBjTtEn9/bgtuLAzszsDu8@Xnp@jtimdnV/ibfk8hplOrNv1s3GRHnWI9Ko9Pegw0N4ugU4c@tHTtU/GRoxvobu35o9E1JApJyUI5QoJhXIl6ly5NoOyQqeFGq26gqZRLi9BZJJwIMoRhgSEIV2GELYzBoeJrcVBNAjbH4bDe911KbV52n/tDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @Arnauld's JavaScript answer. ``` Nθ Input as a number ”...” Compressed lookup table ⪪ ¶ Split on newlines ⪪ Split each element on space I Cast to integer Φ Filtered where ι Current pair ⊟ Remove last element ‹ Is less than θ Input number ⊟ Get last matching element ⊟ Get first element ⁺ Plus θ Input number ↨ Base conversion (i.e. divmod) ¹⁸ Literal integer `18` E ⁺ικ Increment the second element I Cast to string Implicitly print ``` [Answer] # Rust Nightly, 239 bytes + `#![feature(exclusive_range_pattern)]` ``` |p:u32|match p{1=>(1,1),2=>(18,1),3|4|11|12=>(p%8-2,p/8+2),5..11|13..19=>((p-3)%8+11,(p-3)/8+2),19..57=>((p-1)%18+1,(p-1)/18+3),72..87|104..119=>((p-25)%32-11,(p-25)/32+5),87|88=>(p-86,7),57..72|89..104=>((p-25)%32+4,(p-25)/32+7),_=>(2,1)} ``` Basically just matches in some squares then uses some division and mod to format the remaining numbers. [Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=e3a588ea12237bca22368b1df6b3efd4) The actual original data is 236 bytes (118 \* 2) so this code is actually barely longer than the data it's trying to encode. I tried I guess :/ [Answer] # [R](https://www.r-project.org), 113 bytes ``` \(x,p=matrix(c(1,0:-15,2:4,0:-9,5:12,0:-9,13:56,0,72:88,0,104:118,0:-2,57:71,0:-2,89:103),9,,T))which(p==x,T)[1,] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY1BCsIwEEWvk8AvZJLGJAO5hbhRF1Ja2oWopWLxKm6q4KG8jYlx9d_wmf8ez3F5dfF9nbrKfy47MeMcj4dpHGbRCILiiiw015kCLJMuRIbtCgpOs_cpSdVM5HOpYR07KugDkzISAVhLeeuHphfnGOd0bQn7v9hs2mY6jcO9FZ38iTV0QJ2mPGzyOqRBl-cQssxIWV6XpeQX) Creates the matrix, then looks up values. Trying to redefine `+` so I can write ``` \(x,`+`=\(x)0:-x,p=matrix(c(1,+15,2:4,+9,5:12,+9,13:56,0,72:88,0,104:118,+2,57:71,+2,89:103),9,,T))which(p==x,T)[1,] ``` Is 116 characters. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 32 bytes ``` ₀f»#tṪİ□»₆τʀ»₃¡s↳‡∴»⁺/τ+Jf18vḋ›i ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoBmwrsjdOG5qsSw4pahwrvigobPhMqAwrvigoPCoXPihrPigKHiiLTCu+KBui/PhCtKZjE4duG4i+KAumkiLCIiLCI1NyJd) Port of 05AB1E. ## How? ``` ₀f»#tṪİ□»₆τʀ»₃¡s↳‡∴»⁺/τ+Jf18vḋ›i ₀f # Push ten converted to a list of digits: [1, 0] »#tṪİ□» # Push compressed integer 145680302990 ₆τ # Convert to base-64 as list: [2, 7, 43, 14, 16, 14, 14] ʀ # Convert each to a range [0, item] »₃¡s↳‡∴» # Push compressed integer 180810357611003 ⁺/τ # Convert to base-148 as list: [17, 30, 48, 129, 93, 147, 111] + # Add the values in these two lists at the same positions J # Join the [1, 0] and this list together f # Flatten this list 18vḋ # Divmod each by 18 › # Increment each i # 0-based index the input into this list ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 79 bytes ``` ->n{j=0 "hilt8GXg".bytes{|i|n>i%104&&M=n+"+^9lG=3#"[j-=1].ord} [M/18-1,M%18+1]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOsvWgEspIzOnxMI9Il1JL6myJLW4uiazJs8uU9XQwERNzdc2T1tJO84yx93WWFkpOkvX1jBWL78opZYr2lff0ELXUMdX1dBC2zC29r@GoZ6eoaGFpl5uYgHIjIKizLwShUxrhQKFtOhMoAIA "Ruby – Try It Online") Uses 1 based indexing per the question, and comes out the same length as a couple of other answers. The approach is similar to Arnauld's but I use a magic string and loop to iterate through all the discontinuities. The character is taken `mod 104` to be able to cover all the values from 0 to 103 without the need to use nonprintable characters. The raw output is stored in `M` (use a capital letter for a consonant, to avoid Ruby saying it can't find a variable that was defined inside a loop.) A second magic string is used to look up the correct offset. The output is given as row `M/18-1` (the `-1` is used to avoid offsets smaller than ASCII 32 in the magic string) and column `M%18+1` (`+1` is used because the columns are 1-indexed.) ]
[Question] [ Here's a pretty common pattern for sorting algorithms: ``` def sort(l): while not is_sorted(l): choose indices i, j assert i < j if l[i] > l[j]: l[i], l[j] = l[j], l[i] ``` These algorithms work well because the indices `i` and `j` are chosen carefully, based on the state of the list `l`. However, what if we couldn't see `l`, and just had to choose blindly? How fast could we sort the list then? --- Your challenge is to write a function that outputs a random pair of indices, given only the length of `l`. Specifically, you must output two indices, `i, j`, with `0 <= i < j < len(l)`. Your function should work on any length of list, but it will be scored on a list of length 100. Your score is the mean number of index choices necessary to sort a uniformly randomly shuffled list according to the above pattern, where the indices are chosen according to your function. I will score submissions, taking the mean number of index choices over 1000 trials on a uniformly randomly shuffled list of length 100 with no repeated entries. I reserve the right to run less trials if the submission is clearly non-competitive or does not terminate, and I will run more trials to differentiate the top competitors to find a single winner. If multiple top submissions remain within the margin of error at the limit of my computational resources, I will declare the earlier submission the winner, until further computational resources can be brought to bear. --- Here's an example scoring program, in Python: ``` import random def is_sorted(l): for x in range(len(l)-1): if l[x] > l[x+1]: return False return True def score(length, index_chooser): steps = 0 l = list(range(length)) random.shuffle(l) while not is_sorted(l): i, j = index_chooser(length) assert (i < j) if l[i] > l[j]: l[i], l[j] = l[j], l[i] steps += 1 return steps ``` --- Your function may not maintain any mutable state, interact with global variables, affect the list `l`, etc. Your function's only input must be the length of the list `l`, and it must output a ordered pair of integers in the range `[0, len(l)-1]` (or appropriate for your language's list indexing). Feel free to ask whether something's allowed in the comments. Submissions may be in any free-to-use language. Please include a scoring harness if one has not already been posted for your language. You may post a provisional score, but I will leave a comment with the official score. Scoring is the mean number of steps to a sorted list on a uniformly randomly shuffled list of length 100. Good luck. [Answer] # Python, score = 4508 ``` def half_life_3(length): h = int(random.uniform(1, (length / 2) ** -3 ** -0.5) ** -3 ** 0.5) i = random.randrange(length - h) return i, i + h ``` Half-Life 3 confirmed. # Python, score = 11009 ``` def bubble(length): i = random.randrange(length - 1) return i, i + 1 ``` Apparently a randomized bubble sort doesn’t do all that much worse than a normal bubble sort. # Optimal distributions for small length There’s no way this could be extended to length 100, but it’s interesting to look at anyway. I computed optimal distributions for small cases (length ≤ 7) using gradient descent and lots of matrix algebra. The *k*th column shows the probability of each swap at distance *k*. ``` length=1 score=0.0000 length=2 1.0000 score=0.5000 length=3 0.5000 0.0000 0.5000 score=2.8333 length=4 0.2957 0.0368 0.0000 0.3351 0.0368 0.2957 score=7.5106 length=5 0.2019 0.0396 0.0000 0.0000 0.2279 0.0613 0.0000 0.2279 0.0396 0.2019 score=14.4544 length=6 0.1499 0.0362 0.0000 0.0000 0.0000 0.1679 0.0558 0.0082 0.0000 0.1721 0.0558 0.0000 0.1679 0.0362 0.1499 score=23.4838 length=7 0.1168 0.0300 0.0041 0.0000 0.0000 0.0000 0.1313 0.0443 0.0156 0.0000 0.0000 0.1355 0.0450 0.0155 0.0000 0.1355 0.0443 0.0041 0.1313 0.0300 0.1168 score=34.4257 ``` [Answer] # Score: 4627 ``` def rand_step(n): step_size = random.choice([1, 1, 4, 16]) if step_size > n - 1: step_size = 1 start = random.randint(0, n - step_size - 1) return (start, start + step_size) ``` [Try it online!](https://tio.run/##fVLBbsMgDD2Hr/CRqHRLpmmHattX7FZVEWtJQ0YgArJl@/nOJk2bXipFMQb7vecH/W9snH066a53PoKX9uC600HVaVmFqHpu8w3LaFUF/afg7Vz1sG@c3iu@LQXg94z/l13OMpbpGq7l72BhDSVC3GCUQJUhSmS9IFLQNvJCpKZrPQIgsldx8BZ46hIwNa@uZXkSHvbOK26UPcZGgLYHNVYo1QXl50ECUhYsMxiMDpEj73FuyYlokhOaoa4NHuDWT6ONgg8/KJqkdh5GxIZl57ok/IzGN9txh5NjWJW7tJl9eiW/cKVMSBDzNEkP5lpAi3pu9M6S8FgGzCPX8Aot5YlETyTtREG5SCnNhUGkkrPxAVboOmNkkfw@VndsQveHropeSxNopFnp0PF75gK5UpEr42TLAiWHR6iNk3G5yVjv8boXcsoCr/7y8vBFFUWRn/4B "Python 2 – Try It Online") Outputs random indices whose distance apart is chosen uniformly from `[1,1,4,16]`. The idea is to have a mix of 1-step swaps with swaps at larger scales. I hand-tweaked these values for lists of length 100, and they are likely far from optimal. Some machine search could probably optimize the distribution over distances for the random-pair-with-chosen-distance strategy. [Answer] # Score: 28493 ``` def x_and_y(l): x = random.choice(range(l)) y = random.choice(range(l)) while y == x and l != 1: y = random.choice(range(l)) return sorted([x,y]) ``` [Try it online!](https://tio.run/##hVLLboMwELzzFdtTQHFbUG9R6Vf0FiFEwxJMDEa2UeHr6domiaxUyh78mvHu7GNcTCuHj5X3o1QGVDXUsl9rbGAu6VwusUgOEZDNkG/w26mV/IQx3c5IeOLw5Qn@23KBlpWTK@KBgJccssPTjwrNpAbQpA/r@DizpUicQn2Simg4nE3LwCheCc2ADzXOJXmSGtWmXU89BUnduZEKSmKBj@K/bTzHNTjqG9uaoJvg2lx1uYCbOCfQi9ft1DTC6r4hPudvNeHd/1XDfNfgPb5mSciyxhsQx7mAL7vts@KRYe1HYXUJEBQaH7mPPM6go/SCol0zDIiVJsTEHD6hCxEnkXuJ3T8CLcgcZutIG3NPAc8XfU/zcO8D9YweHBLMwdS/@6ZF0aj4YOId1X/H/DRkacrALdv8Up@i9Q8 "Python 3 – Try It Online") This solution just selects distinct values for `x` and `y` randomly from the range and returns them in sorted order. As far as I can tell, this performs better than choosing `x` then choosing `y` from the remaining values. [Answer] # Python, score: 39525 ``` def get_indices(l): x = random.choice(range(l-1)) y = random.choice(range(x+1,l)) return [x,y] ``` First it chooses a random value in the range \$[0, l-1)\$ for the \$x\$-index. After that it will choose another random value larger than \$x\$ in the range \$[x+1, l)\$ for the \$y\$-index. [Try it online.](https://tio.run/##dZLPboMwDMbvPIVvBZFtoN6qdS@x3SpUsdZA2pSgJGj06Znzh1HG5gOQfD/sL3a6u2lkux35rZPKgCrbs7yNZ6ygRnPk7ZmfUMci2UVAMcA@IM@nRpIU06rGWDzlSeKI@z/EkOZMBEah6VULh4HdC1dKn6SiJNjWpmFgFC@FZkDFcThSFqlRBQO6v1GBzH1XUsGRKPAV/G@Bc6zBTv/QNgStBNdmcu0KBlPOmDeum76qBOmz8tVwgfChepzzTx6G2YPPSM1YUjZ4BeIwFPBmX2lerAkbnwrL60JBoXHNrjnO4ELHWzRtOuECLDUpJubwCpel4ixyb/Hyh0ErMqfZPtKLua0F55ue7iGf50Azow2nPM6f9l/80KLo1yy3oYGd4q2JN@/2fuxgw8JNybOMgXs8XNIkGb8B) [Answer] # Python, score ≈ 5000 ``` def exponentialDistance(n): epsilon = 0.25 for dist in range(1, n): if random.random() < epsilon: break else: dist = 1 low = random.randrange(0, n - dist) high = low + dist return low, high ``` Tried with a bunch of epsilon values, 0.25 seems to be the best. ### Score ≈ 8881 ``` def segmentedShuffle(n): segments = 20 segmentLength = (n - 1) // segments + 1 if random.random() < 0.75: a = b = 0 while a == b or a >= n or b >= n: segment = random.randrange(segments) a = random.randrange(segmentLength) + segment * segmentLength b = random.randrange(segmentLength) + segment * segmentLength return sorted([a, b]) highSegment = random.randrange(1, segments) return highSegment * segmentLength - 1, highSegment * segmentLength ``` A different approach. Not as good, and it dies horribly with length not divisible by the number of segments, but still fun to build. [Answer] # Score: 4583 ``` def rand_shell(l): steps = [1, 3, 5, 9, 17, 33, 65, 129] candidates = [(left, left + step) for (step, nstep) in zip(steps, steps[1:]) for left in range(0, l - step) for i in range(nstep // step) ] return random.choice(candidates) ``` [Try it online!](https://tio.run/##hVPtjtowEPyfp1jpdLqk@I44gRDQXaV7hbb/EEIpOMQ0JJFjrrQvT3dtkwCtUksk7HhmP8ZO80sXdRWdz/LQ1EqDyqptffC8rcih3dRK@KWodrpgIKutOK03RV23QgULD3C1WjQtvEFoohL/lbLVPibZXYRBYPZs3pe2OOZ5iXsW/VnIUsA3dRQ2H628VnDCanCd5ZkHPYOWzKFcnlbwmV4jvrrdpfVdiexHh4qyFbccJfRRVXaEbkMy2OMUN7NeBulIWYuo9iW8wr5HTUfSdrS/64c2mMHJInwxA3Uc6@PoDbh1ntxat4Uoy/VOVEJlula@ITkbbkloZ19vg7DcZlrQwSyx@VxjNXzCyNQJ/nKKHDfZGVSGQe7/lo2tyGx3S75Y/VtqcnfnFWIxeB6oJHuuqQbj8R2798Wdkbs8eB5yI/x@QHe1epK14@r2fhGNyLSv5UHgIKWbxbnVKFlp/@krQQt4bJ/g0e3by00JjInuQ2BD5xLcD2dqBqubSiZjV8pEwTXh/QNz7sSF4fOXED5Bezz4jgxjsHkDz7sekKPtPMTHkjOIGUwZzBGZYYBRgiGP5qsAHuA9TOOYp94DDOlRyFEUY5TEJJ5ZMU/SJJwMiSOjn6COQWq7QIhjxDGMcCOiroiG2ASxKZHxN0MsxQxz4oap6zaMp2kyVBCVnCoSFvFONUmi/88YcdsC55ETxsk0mQ8JaQgSkzrlV6rBcnQAaMWEE3Y5iDhOosjzzuc/) I've no idea why. I just tried sequences listed on wikipedia artical for [shellsort](https://en.wikipedia.org/wiki/Shellsort). And this one seem works best. It get similar score with [the one xnor posted](https://codegolf.stackexchange.com/a/174166/44718). [Answer] # [Python 2](https://docs.python.org/2/), 4871 ``` import random def index_chooser(length): e= random.choice([int(length/i) for i in range(4,length*3/4)]) s =random.choice(range(length-e)) return [s,s+e] def score(length, index_chooser): steps = 0 l = list(range(length)) random.shuffle(l) while True: for x in range(length-1): if l[x] > l[x+1]: break else: return steps i, j = index_chooser(length) assert(i < j) if l[i] > l[j]: l[i], l[j] = l[j], l[i] steps += 1 print sum([score(100, index_chooser) for t in range(100)]) ``` [Try it online!](https://tio.run/##bZHBToQwEIbvPMUcwa0u6J6M@BTeCDEIw1IsLWlLxKfHactC2DgX4P@/DP/MjL@2U/J5WfgwKm1BV7JRQ9RgC1w2OH/WnVIGdSxQXm2XvEZAhfkKPpHNa4wLLu2KnHkCrdLAqYGjrhhfWLAeXs6XpEx8CwP5sUVAA/iISaA02klLKAwzJyx9LFMrfePYMeSazlgcqT2k/kvQm@DGHn5wax8SmG5qW0FeUH86LhA@9IShnys30bxPtMbMkp1wxVsQxVzCu3ucsvLouvrSWH1vKgqDR2Yd2I@wGZxBT1P8e5ANqgypNubwBv2u@kQ8JOrv8jiDed2tiB7MSxsT9njKIYuiUdOFwUxDXIQDZGl6v32/JLsviRC69rL8AQ "Python 2 – Try It Online") ]
[Question] [ What general tips do you have for golfing in Clean? Please post only ideas that can be applied to code golf problems in general, and are at least somewhat specific to Clean. If you've never heard of Clean, you can find out more [here](http://clean.cs.ru.nl/Clean). Or, you can join the [chat room](https://chat.stackexchange.com/rooms/70344/cleaning-up). [Answer] ## Avoid `import StdEnv` when possible To access built-in functions, even seemingly basic ones like `(==)` or `map`, an import statement is needed, usually `import StdEnv` because it imports the most common modules like `StdInt`, `StdBool` and so on (see [here](http://www.mbsd.cs.ru.nl/publications/papers/2010/CleanStdEnvAPI.pdf) for more info on `StdEnv`). However it can be possible to avoid this import for some challenges and just use the core language features like list comprehensions and pattern matching. For example, instead of ``` import StdEnv map f list ``` one can write ``` [f x\\x<-list] ``` ### List of alternatives: Some functions or function invocations that need `import StdEnv`, an alternative that does not need the import and a rough estimate of bytes saved. * `hd` -> `(\[h:_]=h)`, ~6 bytes * `tl` -> `(\[_:t]=t)`, ~6 bytes * `map f list` -> `[f x\\x<-list]`, ~10 bytes * `filter p list` -> `[x\\x<-list|p x]`, ~11 bytes * `(&&)` -> `%a b|a=b=a;%`, ~6 bytes * `(||)` -> `%a b|a=a=b;%`, ~6 bytes * `not` -> `%a|a=False=True;%`, ~1 byte * `and` -> `%[a:r]|a= %r=a;%_=True`, ~0 bytes * `or` -> `%[a:r]|a=a= %r;%_=False`, ~0 bytes The last few are unlikely to actually save bytes, because a direct replacement yields more bytes than the import, but it might be possible in cases where the recursion over the list is needed anyway. This tip has successfully been used [here](https://codegolf.stackexchange.com/a/153984/56433). [Answer] # Know how to learn the language After all, how can anyone golf in a language they can't use! **Online** Clean isn't a well-known or well-documented language, and the name certainly doesn't make it easy to find much-needed resources to remedy these issues... or does it? Clean was originally called *Concurrent Clean*, which is still used in the preface of almost every document related to Clean - so if you're looking for Clean, look for Concurrent Clean instead. One of Clean's more remarkable similarities to Haskell (of which there are many) is the existence of [Cloogle](https://cloogle.org/), which is a function search-engine covering the libraries that Clean ships with. **Locally** The libraries that Clean ships with are in the form of decently-commented, somewhat self-documenting Clean source files, which are able to be browsed through using the IDE. (It also comes with full example programs, under `$INSTALL/Examples`.) Speaking of which, the Windows version of Clean comes with an IDE - while it is fairly limited by modern standards, it's worlds better than using a text editor and the command-line. The two most useful features (in the context of learning) are: * You can double-click an error to see which line it's on * You can highlight a module name and press `[Ctrl]+[D]` to open the definition file (or use `[Ctrl]+[I]` for the implementation file), and toggle between the definition and implementation file with `[Ctrl]+[/]` [Answer] # Forget about character encoding Clean's compiler doesn't care about what encoding you think you've saved the source file as, just about the byte values in the file. This has some neat consequences. In the body of the source code, only bytes with code-points corresponding to the printable ASCII characters are allowed, in addition to those for `\t\r\n`. **Literals:** In `String` and `[Char]` literals (`"stuff"` and `['stuff']` respectively), *any bytes except 0* are allowed, with the caveat that `"` and `'` must be escaped (for `String` and `[Char]` respectively), and that newlines and carraige returns *must* be replaced with `\n` and `\r` (also respectively). In `Char` literals, *any byte except 0* is permitted, meaning that: ``` '\n' ``` # ``` ' ' ``` Are the same, but the second is one byte shorter. **Escaping:** Other than the standard letter escapes `\t\r\n` (etc.), all non-numeric escape sequences in Clean are either for the slash, or for the quote used to delimit the literal the escape is inside. For numeric escape sequences, the number is treated as an octal value terminated after three digits. This means that if you want a null followed by the character `1` in a `String`, you need to use `"\0001"` (or `"\0\61"`) and *not* `"\01"`. However, if you follow the escape with anything *but* numbers, you can omit the leading zeroes. **Consequences:** This quirk with how Clean handles its source files allows `String` and `['Char']` to effectively become sequences of base-256 single-digit numbers - which has a multitude of uses for code-golf, such as storing indexes (up to 255, of course). [Answer] # Name functions with symbols When defining a function, it is often shorter to use some combination of `!@$%^&*~-+=<:|>.?/\` than to use alphanumeric characters, because it allows you to omit white-space between identifiers. For example: `?a=a^2` is shorter than `f a=a^2`, and invoking it is shorter as well. **However**: If the function identifier is used adjacent to *other* symbols, which can combine to form a *different, but valid* identifier, they will all be parsed as one identifier and you'll see an error. For example: `?a+?b` parses as `? a +? b` **Additionally:** It is possible to overwrite imported identifiers in Clean, and so the only single-character symbol identifiers that aren't already used in `StdEnv` are `@$?`. Overwriting `^-+` (etc.) can be useful if you need more symbolic identifiers, but be wary that you don't overwrite one you're using. [Answer] # Know your ~~K~~nodes Some of the strongest constructs (for golfing) in functional languages are `let ... in ...`. Clean of course, has this, and something better - the `#`. **What is a node?** Clean's `#`, and the ubiquitous `|` (pattern guard) are both known as 'node expressions'. Notably, they allow you to program imperatively-*ish* in Clean (which is really good here!). **The `#` (let-before):** These both compute the value of an integer given as a string, multiplied by the sum of its chars ``` f s=let i=toInt s;n=sum[toInt c\\c<-:s]in n*i ``` # ``` f s#i=toInt s #s=sum[toInt c\\c<-:s] =s*i ``` Note how the version with `#` is shorter, and how we can redefine `s`. This is useful if we don't need the value that a variable has when we receive it, so we can just re-use the name. (`let` can run into issues when you do that) But using `let` is easier when you need something like `flip f = let g x y = f y x in g` **The `|` (pattern guard):** Clean's pattern guard can be used like those in many other functional languages - however it can also be used like an imperative `if ... else ...`. And a shorter version of the ternary expression. For example, these all return the sign of an integer: ``` s n|n<>0|n>0=1= -1 =0 ``` # ``` s n=if(n<>0)if(n>0)1(-1)0 ``` # ``` s n|n>0=1|n<0= -1=0 ``` Of course, the last one which uses the guard more traditionally is the shortest, but the first one shows that you can nest them (but only two unconditional return clauses can appear on the same line in layout rule), and the second shows what the first one does logically. ***A note:*** You can use these expressions basically anywhere. In lambdas, `case ... of`, `let ... in`, etc. [Answer] # If you're using a `String` you should be using `Text` Conversion to strings, and manipulation of strings (the `{#Char}` / `String` kind, not the `[Char]` kind) is quite lengthy and bad for golfing. The `Text` module remedies this. **Conversion:** `Text` defines the operator `<+` for any two types which have `toString` defined. This operator, used as `a<+b` is the same as `toString a+++toString b` - saving *at least 19 bytes*. Even if you include the extra import, `,Text`, and use it only once, *it still saves 14 bytes!* **Manipulation:** `Text` defines a few string-manipulation staples that are missing from `StdEnv`: * The operator `+` for strings, which is much shorter than `+++` (from `StdEnv`) * `indexOf`, with the C-like behaviour of returning `-1` instead of `Nothing` on failure * `concat`, which concatenates a list of strings * `join`, which joins a list of strings using a separator string * `split`, which splits a string into a list of strings on a substring [Answer] # Use shorter lambdas Sometimes you find yourself using a lambda expression (to pass to `map`, or `sortBy`, etc.). When you're doing this (writing lambdas), there's a bunch of ways you can do it. **The right way:** This is `sortBy`, with an idiomatic lambda sorting lists from longest to shortest ``` sortBy (\a b = length a > length b) ``` **The other right way:** If you're using `Data.Func`, you can also do ``` sortBy (on (>) length) ``` **The short way:** This is the same thing, but with a golfier syntax ``` sortBy(\a b=length a>length b) ``` **The other way:** Using composition isn't shorter this time, but it can be shorter *sometimes* ``` sortBy(\a=(>)(length a)o length) ``` **The other other way:** While it's a bit contrived here, you can use guards in lambdas ``` sortBy(\a b|length a>length b=True=False) ``` And also let-before node expressions ``` sortBy(\a b#l=length =l a>l b) ``` ***A note:*** There are two more forms of lambda, `(\a b . ...)` and `(\a b -> ...)`, the latter of which is identical to the `=` variant, and the former of which exists for some reason and often looks like you're trying to access a property of something instead of defining a lambda so don't use it. [Answer] # Use Character List Literals A character list literal is a shorthand way of writing something like `['h','e','l','l','o']` as `['hello']`. This isn't the limit of the notation, for example: * `repeat'c'` becomes `['c','c'..]` becomes `['cc'..]` * `['z','y'..'a']` becomes `['zy'..'a']` * `['beginning']++[a,b,c]++['end']` becomes `['beginning',a,b,c,'end']` * `['prefix']++suffix` becomes `['prefix':suffix]` These work in matching too: * `['I don't care about the next character',_,'but I do care about these ones!']` [Answer] # Sometimes `code` is shorter Clean has a bunch of really useful functions in the standard libraries, some of which are incredibly verbose to use without access to `*World`, and using `*World` in code-golf is generally a bad idea anyway. To get around this problem, there are often `ccall`s you can use inside `code` blocks instead. Some examples: **System Time** ``` import System.Time,System._Unsafe t=toInt(accUnsafe(time)) ``` The above is 58 bytes, but you can save 17 bytes (down to 40+1) with: ``` t::!Int->Int t _=code{ccall time "I:I" } ``` **Random Numbers** This one doesn't save bytes on its own, but avoids having to pass around a list from `genRandInt` ``` s::!Int->Int s _=code{ccall time "I:I"ccall srand "I:I" } r::!Int->Int r _=code{ccall rand "I:I" } ``` **Other Uses** In addition to these two, which are probably the main uses for this in code-golf, you can call any named function (including but not limited to every syscall), embed arbitrary assembly with `instruction <byte>`, and embed code for the ABC machine. ]
[Question] [ ## Challenge: Given an index integer `n`, either output the `n`'th item in this sequence, or output the sequence up to and including index `n`: ``` 25,25,7,28,29,20,21,22,23,14,35,26,7,28,29,20,16,29,12,15,28,21,14,17,30,13,16,29,12,15,28,21,10,6,12,18,15,11,7,13,19,17,13,9,15,21,18,14,10,16,22,19,15,11,17,23,20,16,12,18,24,21,17,13,19,25,23,19,15,21,27,24,20,16,22,28,25,21,17,23,29,16,13,9,15,21,18,14,10,16,22,20,16,12,18,24,21,17,13,19 ``` ## How does this sequence work? *NOTE: In this explanation, index `n` is 1-indexed.* Put the numbers `1` through `x` on two lines of length `n*6 - 1`, where `x` depends on the current iteration and the length of the numbers used, and then sum the digits of the `n`'th/right-most Olympic Rings of those two lines. *The first number in the sequence is calculated as follows:* ``` The length of the lines are 5 (because 1*6 - 1 = 5): 12345 67891(0) Then leave the digits in an Olympic Rings pattern: 1 3 5 7 9 And sum them: 1+3+5+7+9 = 25 ``` So `n=1` results in `25`. *The second number in the sequence is calculated as follows:* ``` The length of the lines are 11 (because 2*6 - 1 = 11): 12345678910 11121314151(6) Then leave the digits in the second/right-most Olympic Rings pattern: 7 9 0 4 5 And sum them: 7+9+0+4+5 = 25 ``` So `n=2` results in `25`. *The third number in the sequence is calculated as follows:* ``` The length of the lines are 17 (because 3*6 - 1 = 17): 12345678910111213 14151617181920212(2) Then leave the digits in the third/right-most Olympic Rings pattern: 1 2 3 0 1 And sum them: 1+2+3+0+1 = 7 ``` So `n=3` results in `7`. *etc.* ## Challenge rules: * When you output the `n`'th item in the sequence, you are allowed to take the input as 0-indexed instead of 1-indexed, but keep in mind that the calculations of `n*6 - 1` will then become `(n+1)*6 - 1` or `(n+1)*5 + n`. * Single numbers of more than one digit can be split up at the end of the first line when we've reached the length `n*5 + n-1`, so it is possible that a number with 2 or more digits is partially the trailing part of line 1, and partially the leading part of line 2. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. ## Test cases: [Here is a paste-bin of the test cases 1-1,000](https://pastebin.com/KNgWq1mb), so feel free to choose any of them. Some additional higher test cases: ``` 1010: 24 1011: 24 2500: 19 5000: 23 7500: 8 10000: 8 100000: 25 ``` [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~70~~ ~~68~~ 62 bytes ``` .+ 10** . $.>` ~(`.+ 6*$+* )`.(.+) L`.{$.1} %,-6`. ,2,9`. * _ ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@by9BAS4tLj0tFzy6Bq04jAShipqWircWlmaCnoaetyeWToFetomdYy6Wqo2uWoMfFpWOkYwmktbji//83NAQA "Retina – Try It Online") ### Explanation Let's call the input **n**, and we'll use `3` as an example. ``` .+ 10** ``` The `10**` is short for `10*$&*_` which replaces the input with a string of **10n** underscores. ``` . $.>` ``` Now we replace each underscore with the length of the string up to and including that underscore. So this just results in the number from **1** to **10n** all concatenated together (**10n** is always enough to fill up two lines of the required length). ``` ~(`.+ 6*$+* ``` Eval! This and the next stage will generate the source code of another program, which is then run against that string of concatenated integers. To generate that program, this stage first replaces the integers with a string of **6n** underscores (`$+` refers to the program's original input). ``` )`.(.+) L`.{$.1} ``` Then replace those underscores with `L`.{…}`, where `…` is **6n-1** (the length of the lines we're looking at). So we've generated a regex, whose quantifier depends on the original input. When this program gets eval'ed it matches chunks of length **6n-1**, of which there will be at least two. For our example input `3`, we end up with: ``` 12345678910111213 14151617181920212 22324252627282930 ``` Now we just need to extract the relevant digits. ``` %,-6`. ``` First, on each line (`%`) we remove all but the last five digits (`,-6`). That gives us ``` 11213 20212 82930 ``` Finally: ``` ,2,9`. * ``` We expand every other digit (`2`) in the first ten (`9`, this is 0-based) in unary. Those happen to be those in the Olympic Rings positions. ``` _ ``` And we count the number of resulting underscores, to sum them and convert the result to decimal. [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` ΣĊ2ṁ↑_5↑2CṁdN←*6 ``` [Try it online!](https://tio.run/##yygtzv7//9ziI11GD3c2PmqbGG8KJIycgZwUv0dtE7TM/v//b2hgYAAA "Husk – Try It Online") -3 bytes thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz). (Rushed) explanation: ``` ΣĊ2ṁ↑_5↑2CṁdN←*6⁰ Σ Sum Ċ2 Drop every second element ṁ↑_5 Map "take last 5 elements", then concatenate ↑2 Take first 2 elements C Cut x into sublists of length y ṁdN [1,2,3,4,5,6,7,8,9,1,0,1,1,1,2,1,3,...] (x) ← Decrement (y) *6 Multiply with 6 ⁰ First argument ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~94~~ 90 bytes ``` n=input()*6 s=''.join(map(str,range(n*2))) print sum(map(int,s[n-5:n:2]+s[n*2-5:n*2-1:2])) ``` [Try it online!](https://tio.run/##HYk7DoAgFAR7T2EnD9EIiRYknMRYWBjFxJXwKTw9os1kZtc98bihcoaxcCky4lMVTNP0523BrtWxEL3wK/aNgSsiqpy3iHVI138XF2FGN2potbRFufqiUJaBKGc5yOEF "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~33~~ ~~32~~ ~~30~~ ~~29~~ ~~28~~ 27 bytes Oh, this is not pretty! Outputs the *n*th term, 1-indexed. ``` *6É *2 õ ¬òU mt5n)¬¬ë2 ¯5 x ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=KjbJCioyIPUgrPJVIG10NW4prKzrMiCvNSB4&input=OA==) --- ## Explanation ``` :Implicit input of integer U :e.g., 3 *6É *6 :Input times 6 :18 É :Subtract 1 :17 \n :Assign the above to variable U *2 õ ¬òU mt5n)¬¬ë2 ¯5 x *2 õ :[1,U*2] :[1,2,3,...,33,34] ¬ :Join to a string :"123...3334" òU :Partitions of length U :["123...13","1415...212","22324...30","31323334"] m :Map t5n) : Get last 5 characters :["11213","20212","82930","23334"] ¬ :Join to a string :"11213202128293023334" ¬ :Split to an array :["1","1","2","1","3","2","0","2","1","2","8","2","9","3","0"],["2","3","3","3","4"]] ë2 :Get every second element :["1","2","3","0","1","8","9","0","3","3"] ¯5 :Get first 5 elements :["1","2","3","0","1"] x :Reduce by addition :7 :Implicit output of result ``` [Answer] # [Python 2](https://docs.python.org/2/), 97 bytes ``` n=input()*6;k=1;s='' exec's+=`k`;k+=1;'*n*2 print sum(int(s[p])for p in(n-2,n-4,n-6,n*2-4,n*2-6)) ``` [Try it online!](https://tio.run/##HU1LCoMwFNy/UwQ3@aiQpDYuJCcpBcGmVKQvwURoT58@u5gPwzCTvuUV0dYlPoJvmqaiXzEdRUjlps2bKXvOIXzCwnPr522etpZSrlBZSPuKheXjLUhFvqW7fMadJbaiwN522A8E11H3dMROykov/0F2fqqxGrBwgQGMNhquWmsYiX8 "Python 2 – Try It Online") [Answer] # Python 3, ~~129~~ 123 bytes ``` p=lambda r,x='',i=1:sum(map(int,str(x[6*r-2]+x[6*r-4]+x[6*r-6]+x[12*r-4]+x[12*r-6])))if len(x)>12*r-2else p(r,x+str(i),i+1) ``` [Try It Online](https://tio.run/##VY1BDsIgEEX3noJdZyxNhComJngR00VVjCQUCdQET48UUxNW897PzHz3mZ8v23e3MlNy0ozT9T4ST6NsGqolO4X3BNPoQNuZhtlDvIit7/jQ/mC/gliA8TUqJAZE1A9ilIWI55JxZYIiDnJFu/zTSHXLMDmfGwAcsHyz@RuvrK/sUNmxMrarddlNXw) This is pretty much messed up though, but works. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ ~~21~~ 20 bytes ``` 6*<xLJsô2£íε5£}SāÉÏO ``` [Try it online!](https://tio.run/##ASoA1f8wNWFiMWX//zYqPHhMSnPDtDLCo8OtzrU1wqN9U8SBw4nDj0///zI1MDA "05AB1E – Try It Online") **Explanation** ``` 6*< # push input*6-1 xL # leave it on the stack while pushing [1 ... 12*input-2] J # join the numbers to a single string sô # split the string into pieces of size input*6-1 2£ # take the first 2 such pieces í # reverse each string ε5£} # take the first 5 chars of each S # split to a single list of digits ā # push range [1 ... len(list)] ÉÏ # keep only the numbers in the list of digits which are odd in this O # sum ``` **Alternative 21 byte approach** ``` 6*<©·LJƵYS24S®-ì®-(èO ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ×6’µḤD€Ẏsḣ2ṫ€-4Ẏm2S ``` [Try it online!](https://tio.run/##y0rNyan8///wdLNHDTMPbX24Y4nLo6Y1D3f1FT/csdjo4c7VQJ6uCZCfaxT8//9/QwMDAwA "Jelly – Try It Online") ``` ×6’µḤD€Ẏsḣ2ṫ€-4Ẏm2S Arguments: n (1-indexed) ×6 Multiply by 6 ’ Decrement µ Call that value N and start a new chain with argument N Ḥ Double € Create an inclusive range from 1 to 2N and call this link on it D Get the decimal digits of each integer in the range Ẏ Concatenate the lists of digits s Split into length-N chunks ḣ2 Get the first two elements €-4 Map this link over the length-2 list with right argument -4 ṫ Get elements from this index onwards (supports negative indices too) Ẏ Concatenate the two length-5 lists into one length-10 list m2 Take every second element starting from the first S Sum ``` [Answer] # [J](http://jsoftware.com/), 61, 58 57 bytes ``` g=.3 :'+/".,_2(2{.{.)\,_5{."1(2{.(-.6*y)]\;":&.>1+i.9*y)' ``` [Try it online!](https://tio.run/##y/r/P91Wz1jBSl1bX0lPJ95Iw6har1pPM0Yn3rRaT8kQxNXQ1TPTqtSMjbFWslLTszPUztSzBPLV/3OlJmfkK6QrpJalFlUqGBoYGoAIQwUjUwMDBSA2UDAHsQwNDGCkwX8A "J – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~65 63~~ 56 bytes ``` ->n{[2,4,6,4-n*=6,6-n].sum{|a|([*1..n*2]*'')[n-a].to_i}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtpIx0THTMdEN0/L1kzHTDcvVq@4NLe6JrFGI1rLUE8vT8soVktdXTM6TzcxVq8kPz6ztvZ/gYIGUMrQQFMvN7GguqaiJi26Irb2PwA "Ruby – Try It Online") [Answer] # [Clean](https://clean.cs.ru.nl), ~~138~~ 101 bytes ``` import StdEnv $n=sum(tl[toInt([c-'0'\\i<-[1..],c<-:toString i]!!(6*i+j))\\i<-[2*n-1,n-1],j<-[4,0,2]]) ``` [Try it online!](https://tio.run/##JY27CoMwFED3fkUEwUcT8VE6FN3aQehQcNQMIT6IJDdFr4X@fFPB4QwHDhypBwHO2H7TAzFCgVPmbRckDfYP@Jx8qNbNhKhbtDVg2EoWpEHXqZK1WZJwKkt2Q9vgomAiinteeI3VeY6io8ljYBnd4XTe9UJTmnMeuQbFPqmITwr3k6MW0@pY/XT3Lwij5CEvLXC0i/kD "Clean – Try It Online") [Answer] # Java 8, ~~138~~ ~~111~~ 109 bytes ``` n->{String s="";int r=0,i=1;for(n=n*6-1;i<3*n;s+=i++);for(i=5;i>0;r+=s.charAt(n+n*(i%2^1)-i--)-48);return r;} ``` I'll of course have to answer my own challenge. :) I lost my initial code that I've used to create the test results in the challenge description, so I've just started over. **Explanation:** [Try it online.](https://tio.run/##bZDfSsMwFMbvfYpDQUgWU9JpRcwy8AHczS5FIXadntmdliQdk9Fnr@mfCxEhJ/CdE873@3KwJyvrpqTD7qsvKus9PFukyxUAUijd3hYlbAY5NqBgw01cx04XKx4fbMACNkBgoCe5vmyDQ/oAb5JED8@dUTdoMr2vHSNDi3uZaVzdLkh7YVAIPk7Q5BrXSjthfFp8WvcUGAlaMLxevmVcopRc3j1w7crQOgKnu15PCE37XkWEmeRU4w6OMQWbQF5eLZ8SjDYRaIDBlcmVHtzHEUAofWA4JptFpjL1R2e/9TJX6p@fGP2nbdHrPHtvv30oj2ndhrSJVKEidhbJIySC0oKd@byo638A) ``` n->{ // Method with integer as both parameter and return-type String s=""; // Temp String int r=0, // Result-sum, starting at 0 i=1; // Index integer, starting at 1 for(n=n*6-1; // Replace the input with `n*6-1` i<3*n; // Loop from 1 up to 3*n (exclusive) s+=i++); // And append the temp-String with `i` for(i=5;i>0; // Loop from 5 down to 0 (exclusive) r+= // Add to the result-sum: s.charAt( )-48); // The character at index X, converted to a number, n+n*(i%2^1)-i-- // with X being `n-i` (i=odd) or `n+n-i` (i=even) return r;} // Return the result-sum ``` ]
[Question] [ Left and right [Riemann sums](https://en.wikipedia.org/wiki/Riemann_sum) are approximations to [definite integrals](https://en.wikipedia.org/wiki/Integral). Of course, in mathematics we need to be very accurate, so we aim to calculate them with a number of subdivisions that approaches infinity, but that's not needed for the purposes of this challenge. You should instead try to write the shortest program, taking input and providing output through any of the [default methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487), which does the following: # Task Given two rational numbers \$a\$ and \$b\$ (the limits of the definite integral), a positive integer \$n\$, a boolean \$k\$ representing left / right and a [black-box function](https://codegolf.meta.stackexchange.com/a/13706/59487) \$f\$, calculate the left or right Riemann sum (depending on \$k\$) of \$\int\_a^b f(x)\mathrm{d}x\$, using \$n\$ *equal* subdivisions. # I/O Specs * \$a\$ and \$b\$ can be rational / floating-point numbers or fractions. * \$k\$ can be represented by any two distinct and consistent values, but please keep in mind that [you aren't allowed](https://codegolf.meta.stackexchange.com/a/14110) to take complete or partial functions as input. * \$f\$ is a black-box function. Citing the meta answer linked above, *the content (i.e. the code) of black-box-functions may not be accessed, you can only call them (passing arguments if applicable) and observe their output*. If needed, please include the necessary information about the syntax your language uses such that we can test your submission. As output, you must provide a rational / floating-point / fraction representing the Riemann sum you are asked for. As [discussed in the past](https://codegolf.meta.stackexchange.com/questions/14407/how-should-a-challenge-allow-floating-point-imprecision-to-be-ignored), floating-point imprecision can be ignored, as long as your output is accurate to at least three decimal places when rounded to the nearest multiple of 1 / 1000 (e.g. `1.4529999` is fine instead of `1.453`). # Math Specs * \$f\$ is guaranteed to be continuous between \$a\$ and \$b\$ (no jumps, no holes, no vertical asymptotes). * There are three possible cases you have to handle: \$a = b\$ (The result should be \$0\$ or its equivalents), \$a < b\$ or \$a > b\$. * If \$b < a\$, the integral changes its sign. Also, the right sense of the integral in this case is towards \$a\$. * Areas under the graph are negative and those above the graph are positive. # Examples / Test Cases The resolution is not optimal, because I had to shrink them down a bit, but they're still readable. * \$f(x) = 2x + 1,\: a = 5,\: b = 13,\: n = 4\$, k = right: [![2x+1](https://i.stack.imgur.com/AXNGt.png)](https://i.stack.imgur.com/AXNGt.png) The result should be \$15 \cdot 2 + 19 \cdot 2 + 23 \cdot 2 + 27 \cdot 2 = 168\$, because the width of each rectangle is \$\frac{|b - a|}{n} = 2\$ and the corresponding heights are \$f(7) = 15,\:f(9) = 19,\:f(11) = 23,\:f(13) = 27\$. * \$f(x)=\sqrt{x},\: a = 1,\: b = 2.5,\: n = 3\$, k = left: [![Square Root](https://i.stack.imgur.com/dOtoe.png)](https://i.stack.imgur.com/dOtoe.png) The output should be \$1.8194792169\$. * \$f(x) = -3x + 4 + \frac{x^2}{5},\: a = 12.5,\: b = 2.5,\: n = 10\$, k = right: [![-3x+4+1/5x^2](https://i.stack.imgur.com/xEaHy.png)](https://i.stack.imgur.com/xEaHy.png) The expected output value is \$- (- 4.05 - 5.45 - 6.45 - 7.05 - 7.25 - 7.05 - 6.45 - 5.45 - 4.05 - 2.25) = 55.5\$, because [the integral changes signs when flipping the boundaries (\$b<a\$)](https://math.stackexchange.com/questions/1316529/why-does-an-integral-change-signs-when-flipping-the-boundaries). * \$f(x) = 9 - 4x + \frac{2x^2}{7},\: a = 0,\: b = 15,\: n = 3\$, k = left: [![9-4x+2/7x^2](https://i.stack.imgur.com/iu3IS.png)](https://i.stack.imgur.com/iu3IS.png) Calculating our Riemann sum, we get \$13.5714285715\$. * \$f(x) = 6,\: a = 1,\: b = 4,\: n = 2\$, k = right — Output: \$18\$. * \$f(x) = x^7 + 165x + 1,\: a = 7,\: b = 7,\: n = 4\$, k = left — Output: \$0\$. * \$f(x) = x \cdot \sin(x^{-1}),\: a = 0,\: b = 1,\: n = 50\$, k = right — Output: \$0.385723952885505\$. Note that sine uses radians here, but feel free to use degrees instead. [Answer] # [R](https://www.r-project.org/), ~~69~~ ~~65~~ ~~63~~ 57 bytes ``` function(a,b,n,k,f,w=(b-a)/n)sum(sapply(a+w*(1:n-k),f))*w ``` [Try it online!](https://tio.run/##K/qfk5pWomCjqxASFOrKVZSZngHmuTn6BLtypQOZ/9NK85JLMvPzNBJ1knTydLJ10nTKbTWSdBM19fM0i0tzNYoTCwpyKjUStcu1NAyt8nSzNXXSNDW1yv@naxjoGOqYGuiAjdWBG1ShWaFVnJmnYahfoan5HwA "R – Try It Online") Takes `k=FALSE` for right-hand sums, although the TIO link now includes aliases for "left" and "right" for ease of use. `a+w*(1:n-k)` generates appropriate left- or right-hand points. Then `sapply` applies `f` to each element of the result, which we then `sum` up and multiply by the interval width `(b-a)/n` to yield the result. This last also neatly takes care of any sign issues we might have. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 127 bytes ``` DEFINE('R(a,b,n,k,p)') R l =(b - a) / n i =1 l R =R + eval(p '(a + l * (i - k))') i =lt(i,n) i + 1 :s(l) R =R * l :(return) ``` [Try it online!](https://tio.run/##RY/JDoIwEIbP06eYG1OtWlwuJNzExIuHvgHEVhuaQlgMb48jJnqZ9ftn6WNTNeE4w7m4XG8FJY4mmUgBwboB81RA5x9PjvQfMVSqSkVVq5ZRyMhKYSBgThVusJS4wyjAf9QBDOYG12hfZaAWEyo5CbhC8szWctnFaBjIqyjRczuFrKfA9UW7Yjyjzg5jF@XswGE@cXHiLSeGjzzmsOQ/SFhoxqEd@WpD6X570lp9baq3mt3ykkrc9/h4Z0W8z28 "SNOBOL4 (CSNOBOL4) – Try It Online") Assuming that the function `p` is defined somewhere, this takes `a,b,n,k,(name of p)`, with `k=0` for right and `l=1` for left. catspaw's `SNOBOL4+` supports `REAL`s but doesn't have builtin trig functions. However, I suppose one could come up with a reasonable `sin` function using a taylor series. I'm not 100% sure this is the "right" way to pass a black-box function in SNOBOL (which, to my knowledge, doesn't have first-class functions), but it seems reasonable-ish to me. I suppose that assuming the function is defined as `f` would be shorter, as line `l` could be ``` l R =R + f(a + l * (i - k)) ``` but then it's not passed as an argument, which feels a bit like "cheating". Note that the TIO link has a `:(e)` after the `DEFINE` statement, which is so that the code will actually run properly. [Answer] # [Julia 0.6](http://julialang.org/), 50 bytes ``` R(f,a,b,n,k)=(c=(b-a)/n;sum(f.(a+[k:n+k-1...]c))c) ``` [Try it online!](https://tio.run/##ddBLDsIgEAbgdT3FLEEG6mAfUVMP4dZoUhurtZUYHwlH8Awez4tUShdGjRvC4mP@fzjcmipP2nO1218hAxo027K7jNoFKzHHDRqsecaKjG1kzkMzu9yOrFQsF8t6akQtSSm1KjgveHs6V@baGLZgVs5BW0FBgDECjREiBB/C@eCTPe8P6xghaOWso12FHybHVkSCwnho19pxj/1Bo3@jJzKyQodp/8Qx@gj40knQ13BN9b@Jdp0KSuJuM0wRUq/9l/3S4aUyjELL@2iE@F20fQE "Julia 0.6 – Try It Online") A normalized range is constructed, collected into a vector and then scaled. Collecting the range into a vector using `[X...]` is necessary to avoid the `inexact error` when multiplying the range directly with 0 when `a=b`. Similarly, constructing a range directly with `:` or `range()` is not possible when `a=b`. The usage of k is very similar to the solution of [Guiseppe](https://codegolf.stackexchange.com/users/67312/giuseppe), with `k=1` for `right` and `k=0` for `left`. [Answer] # [Haskell](https://www.haskell.org/), ~~73~~ 67 bytes Thanks to H.PWiz and Bruce Forte for the tips! ``` (f&a)b n k|d<-(b-a)/realToFrac n=d*sum(f<$>take n(drop k[a,a+d..])) ``` [Try it online!](https://tio.run/##dY4xbsJAEEX7nOIXCM3Mxja7trEiAWVOkC5JsWAjLJs1WTvSFrm7s1ASotFM9f6bf7Jj1/T9PNNxaXkPh@6n3iS0TyxnvrH92/Dq7QFuW8v4fabjZrGbbNfAUe2HC7p3@2xVnaafzPPZtg5b1MMTcPGtm7AALRlEWnFKRphRQucooO@Q8ctP0DBpiRyr@/xHSHaU5CxBFYqCiOGsZOgrfl29@iO8ZYIEMVmlXpJCAiNSD/WHwY0T1lEYm5n/VFIpvS5jBc2o4hSPewYZW0c6C3x7iDKe@Rc "Haskell – Try It Online") Pretty straightforward solution. `k` is `0` for left and `1` for right. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` ƓḶ+Ɠ÷ IḢ×¢A+ṂɠvЀÆm×I ``` [Try it online!](https://tio.run/##AT4Awf9qZWxsef//xpPhuLYrxpPDtwpJ4biiw5fCokEr4bmCyaB2w5DigqzDhm3Dl0n//zQKMQrhuKTigJj/NSwxMw "Jelly – Try It Online") Take `a,b` from arguments, and ``` n right f ``` from stdin. --- If you are not familiar with Jelly, you can use Python to write the black box function `f`: [***f(x)*** = 2x + 1; **a** = 5; **b** = 13; **n** = 4; **k** = right](https://tio.run/##AW4Akf9qZWxsef//xpPhuLYrxpPDtwpJ4biiw5fCokEr4bmCyaB2w5DigqzDhm3Dl0n//zQKMQrCucKp4bmb4oCcKGxhbWJkYSB4OiAyKngrMSApKGF0b21zWyfCriddLmNhbGwoKSnigJ3Fklb/NSwxMw "Jelly – Try It Online") [***f(x)*** = √x; **a** = 1; **b** = 2.5; **n** = 3; **k** = left](https://tio.run/##AXYAif9qZWxsef//xpPhuLYrxpPDtwpJ4biiw5fCokEr4bmCyaB2w5DigqzDhm3Dl0n//zMKMArCucKp4bmb4oCcKGxhbWJkYSB4OiBtYXRoLnNxcnQoeCkgKShhdG9tc1snwq4nXS5jYWxsKCkp4oCdxZJW/zEsMi41) [***f(x)*** = -3x + 4 + 1/5 \* x2; **a** = 12.5; **b** = 2.5; **n** = 10; **k** = right](https://tio.run/##AYMAfP9qZWxsef//xpPhuLYrxpPDtwpJ4biiw5fCokEr4bmCyaB2w5DigqzDhm3Dl0n//zEwCjEKwrnCqeG5m@KAnChsYW1iZGEgeDogLTMqeCArIDQgKyAxLzUgKiB4KioyICkoYXRvbXNbJ8KuJ10uY2FsbCgpKeKAncWSVv8xMi41LDIuNQ) [***f(x)*** = 9 - 4x + 2/7 \* x2 ; **a** = 0; **b** = 15; **n** = 3; **k** = left](https://tio.run/##AX0Agv9qZWxsef//xpPhuLYrxpPDtwpJ4biiw5fCokEr4bmCyaB2w5DigqzDhm3Dl0n//zMKMArCucKp4bmb4oCcKGxhbWJkYSB4OiA5IC0gNCp4ICsgMi83ICogeCoqMiApKGF0b21zWyfCriddLmNhbGwoKSnigJ3Fklb/MCwxNQ) [***f(x)*** = 6; **a** = 1; **b** = 4; **n** = 2; **k** = right](https://tio.run/##AWkAlv9qZWxsef//xpPhuLYrxpPDtwpJ4biiw5fCokEr4bmCyaB2w5DigqzDhm3Dl0n//zIKMQrCucKp4bmb4oCcKGxhbWJkYSB4OiA2ICkoYXRvbXNbJ8KuJ10uY2FsbCgpKeKAncWSVv8xLDQ) [***f(x)*** = x \* sin(1 / x); **a** = 0; **b** = 1; **n** = 50; **k** = right](https://tio.run/##AXoAhf9qZWxsef//xpPhuLYrxpPDtwpJ4biiw5fCokEr4bmCyaB2w5DigqzDhm3Dl0n//zUwCjEKwrnCqeG5m@KAnChsYW1iZGEgeDogeCAqIG1hdGguc2luKDEveCkgKShhdG9tc1snwq4nXS5jYWxsKCkp4oCdxZJW/zAsMQ) --- Explanation: ``` ƓḶ+Ɠ÷ Helper niladic link. Ɠ First line from stdin. (n). Assume n = 4. Ḷ Lowered range (unlength). Get [0, 1, 2, 3]. +Ɠ Add second line from stdin (k). Assume k = 1 (right). Get [1, 2, 3, 4]. ÷ Divide by (n). Get [0.25,0.5,0.75,1]. IḢ×¢A+ṂɠvЀÆm×I Main monadic link. Take input `[a, b]`, assume `a=2,b=6`. IḢ `a-b`. Get `-4`. ×¢ Multiply by value of niladic link above. Get `[-1,-2,-3,-4]`. A Absolute value. Get `[1,2,3,4]`. +Ṃ Add min(a, b) = 2. Get `[3,4,5,6]`. vЀ For each number, evaluate with... ɠ input line from stdin. Æm Arithmetic mean. ×I Multiply by `a-b`. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~99~~ 94 bytes A bit of a naive solution. ``` def R(f,a,b,n,k):s=cmp(b,a);d=s*(b-a)/n;return s*sum(d*f([0,a,b][s]+i*d)for i in range(k,n+k)) ``` [**Try it online!**](https://tio.run/##bZHNcoMgAITvPAWTSwB/Iv7EqQ4v0VNmkhwwasMY0QKZoU9vJaZt2vTEgW@X3WX8MOdBxlOrhh723Jyh6MdBGTLVTQtfUetzv/Kl3@FCs1M/osrnuKyZJqgKON7IUjXmqiTURF97VJMW7SOnOe710ROkxu2goIBCQsXlW4M6X3odxtOOrVYr0LIL76uaQ1vExHoUcJaFUQkrRhN3SpaWsGMUPJL6XRlk8czShY3DzKGJQ6NfaJDMrqlnid1kjr@R3wIaPZu/BOksmcPMknyWRPc42RLnnze2P0HSBYqfbS0huUe32b1kvvD5Q8foD6@FRHRzq/mVYaGze2q3H3Drnoa6cQPvQj1ehEHrgzzINS4AbGxzQu4aAzgqIQ16/FE8fQI "Python 2 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~73~~ ~~71~~ 59 bytes ``` (a,b,n,k,f)=>(g=i=>i--&&g(i)+f(a+k++/n)/n)(n,k^=a>b,n/=b-a) ``` [Try it online!](https://tio.run/##bY9dS8MwFIbv9ytyVfJx0jTduiIjBS@cCnozvBOVdLa1diSSjK3@@pqOwYYbJBA4z/ucN996p/3atT9bbuxnNSzVgDWUYKCDmqgCN6pVRct5FDW4JazGmnWMCUPCwYF6V7oIuFAl12QQAp3i4FUSFK@1dfgD2Rof4ZIrDbfO6V9sCCGeqaOVlgcvLd@iyKO9dZ1H1iBT7SuHdpXzrTWTp7vlC1IoWUxWj/cP41MuJmtrvN1U8cY2eIkzkFOYwWEOvSpS2jNJyH9MQhpnMIXROGI9pXF2BRup8crkpOTT4JxRKTLa0/4ylIA8V9/wWeBTkV@nZWibnuTzSyKHPDBnTXMm59n1f4XdkJ117emz3n7FvjVYirA9BIY/ "JavaScript (Node.js) – Try It Online\"ine") [Answer] # [Perl 6](http://perl6.org/), 65 bytes ``` {my \d=($^b-$^a)/$^n;sum ($a,*+d...*)[($^k+^0>d)+ ^$n]».&^f X*d} ``` [Try it online!](https://tio.run/##HYlNCoJAAEav8i0GmX@1sk3oKVoE2YAxzsaUUIQR8VJt23mxaWjxHg/eux1f59AvSBzKsMaobUmJeSpiGpYSM1ymuQcljeTCaq05u8fdCZNVlgkYMjz2r06Mw43bLUzNAkfzgy4k/lIVao8V6ggOD4FTxO8fpCiwSVzHuZXIMxZ@ "Perl 6 – Try It Online") Relatively straightforward. The only complication is handling the `a > b` case, which I do by xor-ing the input flag `$^k` with `0 > d`, which inverts it when `a > b`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L<+¹/I`α©*³ß+Iδ.VÅA®*Ä ``` Inputs in the order \$n\$, \$k\$, \$[a,b]\$, \$f\$, with \$k\$ being `1` for right and `0` for left. [Try it online](https://tio.run/##ATYAyf9vc2FiaWX//0w8K8K5L0nDhsOEwqkqwrPDnytJzrQuVsOFQcKuKv//NAoxCls1LDEzXQrCtz4) or [verify all test cases](https://tio.run/##JYxPS8MwGMbv76co76kmcWvWZMGpC8IQBoInx6QU3GDToqtisqM3d/cbeBZBEMSdZJDc95Vq2t6eP7/neTSzebGo1DmOy6e1NYOoPEU99m8aj6P7Vhb4XNzeWfSf@LBYWnxBv4tivztAbQKVzdg8r8nRVT1aNnLCAC/XNlwOItTVxQk13enN/tt9kKl/p9f7n87Eb87cF/GvFXO/uhLAIZOMpzm47RBSSCDjrNeROVjgSd3y4NpklMZEUFPKLm3JhPE6FuTIHJrSbVUoes2GiRz6IGpIMRUYtTK8LwkdgmxewzSkPF75jfsj/w). **Explanation:** ``` L # Push a list in the range [1, (implicit) input n] < # Decrease each by 1 to make the range: [0, n) + # Add the (implicit) input k to each ¹/ # Divide each by the first input n I # Push the next input [a,b] `α # Push both separated to the stack, and take their absolute difference © # Store this in variable `®` (without popping) * # Multiply it to each value in the list ³ß # Push the third input [a,b] again, and pop and push its minimum + # Add it to each value in the list δ # Apply to each value in the list, I # using the next input f: .V # Evalutate the it as 05AB1E code ÅA # Then pop and push the arithmetic mean of the list ®* # Multiply it by |a-b| from variable `®` Ä # And take the absolute value of this result # (after which it is output implicitly) ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 37 bytes ``` {(a b n k)←⍵⋄l←n÷⍨b-a⋄l×+/⍺⍺a+l×k+⍳n} ``` [Try it online!](https://tio.run/##nZHBasJAEIbvfYr/ZnSNZpJdpY@zKkoxpIWciniTXiSlF8kr9OahiODRfZN9kXQ2oTHG0oLZBHZn5vvn34l@if3Zq46fF/401mn6NC2KlacxQYJl17592Oxgt5uYd4k52uxz4mt3NrkY2uzErxZ8WAqbfSXrYs519@MP9n3HlZ0VidDkjK47fTSeSxxzKFAEiaCGON4bqBaCnzAThHCgEOG8pxqSwjvvo1K0yyYO5c7k5lgJ/ZV3ik7QfRQ0jDw6Rt4wocPGLPtPAesGoLbRkR/8OpI6Xl5QImwYIeHRSF369Lg7@tUgbzLMj3nJq66lL7L51v28Vu92svIN5UZRfAM "APL (Dyalog Classic) – Try It Online") # APL NARS, 37 chars The function has the argument in the left the function, in the right numeric argument a b n k. In the question k=left here it means k=¯1; k=right here it means k=0. Test: ``` f←{(a b n k)←⍵⋄l←n÷⍨b-a⋄l×+/⍺⍺a+l×k+⍳n} {1+2×⍵} f 5 13 4 0 168 {√⍵} f 1 2.5 3 ¯1 1.819479217 {4+(¯3×⍵)+0.2×⍵×⍵} f 12.5 2.5 10 0 55.5 {9+(¯4×⍵)+7÷⍨2×⍵×⍵} f 0 15 3 ¯1 13.57142857 {6-0×⍵} f 1 4 2 0 18 {1+(165×⍵)+⍵*7} f 7 7 4 ¯1 0 {⍵×1○÷⍵} f 0 1 50 0 0.3857239529 ``` ]
[Question] [ We all know that whenever a rational number is written in decimal, the result is either terminating or (eventually) periodic. For example, when 41/42 is written in decimal, the result is ``` 0.9 761904 761904 761904 761904 761904 761904 761904 ... ``` with an initial sequence of digits `0.9` followed by the sequence `761904` repeated over and over again. (A convenient notation for this is `0.9(761904)` where the parentheses surround the block of repeating digits.) Your goal in this challenge is to take a positive rational number, delete the first digit that's part of the repeating sequence, and return the resulting rational number. For example, if we do this to 41/42, we get ``` 0.9 61904 761904 761904 761904 761904 761904 761904 ... ``` or `0.9(619047)` for short, which is 101/105. If the rational number has a terminating decimal expansion, like 1/4 = `0.25` does, nothing should happen. You can think of 1/4 either as `0.250000000...` or as `0.249999999...` but in either case, deleting the first digit of the repeating part leaves the number unchanged. ## Details * The input is a positive rational number, either as a pair of positive integers representing the numerator and denominator, or (if your language of choice allows it and you want to) as some sort of rational-number object. * The output is also a rational number, also in either form. If the result is an integer, you may return the integer instead of a rational number. * If taking a pair of numbers as input, you may assume they're relatively prime; if producing a pair of numbers as output, you must make them be relatively prime. * Be careful that you find the *first* digit that starts a repeating block. For example, one could write 41/42 as `0.97(619047)` but that doesn't make 2041/2100 (with the decimal expansion `0.97(190476)`) a valid answer. * You may assume that in the input you get, the first periodic digit is *after* the decimal point, making `120/11` = `10.909090909...` invalid input: (its first periodic digit could be considered the `0` in `10`). You may do anything you like on such input. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest solution wins. ## Test cases ``` 41/42 => 101/105 101/105 => 193/210 193/210 => 104/105 104/105 => 19/21 1/3 => 1/3 1/4 => 1/4 2017/1 => 2017/1 1/7 => 3/7 1/26 => 11/130 1234/9999 => 2341/9999 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes ``` FromDigits@MapAt[RotateLeft@*List@@#&,RealDigits@#,{1,-1}]& ``` [Try it online!](https://tio.run/##LYqxCsIwFEX3/Eahg0ReXhItHYQI4lRBuopDkKQGjJX2baXfHhPoHQ73Hm609HbRUnjZ5E/pOo3xEoZAs7nZ35ke/UiWXOc8mV0XZjKmqnnv7Gd7VXxBvsf1Waf7FL755cEsjGkELTlDgYDikEurQKIoRm8GVIHmTApsAMtoCuQxUyoNbQ5ja/oD "Wolfram Language (Mathematica) – Try It Online") ### Explanation ``` RealDigits@# ``` Find the decimal digits of the input. ``` MapAt[RotateLeft@*List@@#&, ..., {1,-1}] ``` If there are repeating digits, `RotateLeft` them. (`List@@#` prevents the code from attempting to rotate the last decimal digit if the rational number is terminating). ``` FromDigits@ ``` Convert to rational. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~36~~ ~~32~~ ~~31~~ 30 bytes -1 byte thanks to [*Erik the Outgolfer*](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)! ``` ọ2,5Ṁ⁵*©×Ɠ÷µ×⁵_Ḟ$+Ḟ,®×³+.Ḟ÷g/$ ``` [Try it online!](https://tio.run/##y0rNyan8///h7l4jHdOHOxseNW7VOrTy8PRjkw9vP7T18HQgP/7hjnkq2kBC59C6w9MPbdbWA7IPb0/XV/n/39DI2OS/JRAAAA "Jelly – Try It Online") Should be correct. Floating point imprecision add 3 bytes for `+.Ḟ`. Relies on the input being irreducible. --- ## Explanation This relies on: * Let the numerator be `n/d` in its simplest form. Then the link `ọ2,5Ṁ` applied to `d` will give the number of non-periodic digit after the radix point. ``` ọ2,5Ṁ⁵*©×Ɠ÷µ×⁵_Ḟ$+Ḟ,®×³+.Ḟ÷g/$ Main link (monad take d as input) Ṁ Maximum ọ order of 2,5 2 or 5 on d ⁵* 10 power © Store value to register ®. ×Ɠ Multiply by eval(input()) (n) ÷ Divide by first argument (d). Now the current value is n÷d×®. µ With that value, ×⁵ Multiply by ⁵ = 10 _Ḟ$ subtract floor of self +Ḟ add floor or value (above) Given 123.45678, will get 123.5678 (this remove first digit after `.`) ,® Pair with ®. ׳ Scale +.Ḟ Round to integer ÷g/$ Simplify fraction ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~237~~ ~~235~~ 214 bytes -21 bytes thanks to Mr. Xcoder ``` from fractions import* F=Fraction n,d=input() i=n/d n%=d R=[] D=[] while~-(n in R):R+=n,;n*=10;g=n/d;n%=d;D+=g, x=R.index(n) r=D[x+1:]+[D[x]] print i+F(`r`[1::3])/F('9'*len(r))/10**x+F("0."+"".join(map(str,D[:x]))) ``` [Try it online!](https://tio.run/##LYvBisMgFEX3foUESn3qJLFdDDW4C/mAbEVomaStQ/MU6zDOZn4908BsDpfDPfEn3wMe1vWawkKv6fKRfcAn9UsMKXMymOHfEZST8Ri/MgPiDTYTwZ2ZyGisI/2G77t/zL9vDKlHOoIehUHZITeq7W5b0G1B1wtzk6SYsfY4zYUhkGR6W4TSTtjXcI7E5DFTLwZ2TmertD46aAa2P@35Y0aWABrVcl5eh6qtK1FV9WfwyJZLZM@cZG91cQCwruzQqndJFfwB "Python 2 – Try It Online") Input is done as a tuple `(numerator, denominator)`; output is a `fractions.Fraction` object. This uses a long-division-style method to get the starting and repeating digits of the answer, then moves the first repeating digit to the end and uses string manipulation and `fraction.Fraction` to convert it back to a ratio. Ungolfed version: ``` import fractions num, denom = input() integer_part, num = divmod(num, denom) remainders = [] digits = [] current_remainder = num while current_remainder not in remainders: remainders.append(current_remainder) current_remainder *= 10 digit, current_remainder = divmod(current_remainder, denom) digits.append(digit) remainder_index = remainders.index(current_remainder) start_digits = digits[:remainder_index] repeated_digits = digits[remainder_index:] repeated_digits.append(repeated_digits.pop(0)) start_digits_str = "".join(map(str, start_digits)) repeated_digits_str = "".join(map(str, repeated_digits)) print(integer_part+int(repeated_digits_str)/fractions.Fraction('9'*(len(repeated_digits_str)))/10**len(start_digits_str)+fractions.Fraction("0."+start_digits_str)) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~177~~ ~~173~~ 169 bytes ``` from fractions import* def f(n,d): i=1;r=[] while~-(i%d in r):r+=[i%d];i*=10 r=10**r.index(i%d);u=i-r;v=i//r-1;t=u//d*n return Fraction(t-t%v+t%v*10//v+t%v*10%-~v,u) ``` [Try it online!](https://tio.run/##NY1BDoIwFET3nOJvSNpCrVVWNN16CcLC2Db8RAr5FtQNV8ea6GIm85KXzPxOwxTP@x5oGiHQ9ZZwig/AcZ4oicL5AIHF2vG2ALTakO36Ap4D3v0mGZYOMALxlirbZeoNCquPBVBuIeiA0fnX1@NmsSjJrBaVIqlNsotSTsTs@rRQhMvvnSWZyrXKEfqo1H@Vclvrhe8zYUwssEbXzYnz/QM "Python 3 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~70~~ 67 bytes Thanks to [this tip](https://codegolf.stackexchange.com/a/38422) (now deleted) for -3 byte! ``` (x=10^Max@IntegerExponent[#,{2,5}];(Floor@#+Mod[10#,1])/x&[x#2/#])& ``` [Try it online!](https://tio.run/##Zc1BC4IwGMbxe59CGIjSwL1zJiKCl4IOQvexYOQsIbeQHQbRZ1@7BJPe2//HA@8i7UMt0s436afOZ64Dch2k68/aqrtaj@5ltNKWI/ymuPqINjs9jVl7tB/MyIEgDCIvXModogUSeeov66xtP3FGccJAtLsfAKlwAiQmCiRQU/6vWERlgCjZNgEnlEAdSb0d0MO2m3BBaBl@@C8 "Wolfram Language (Mathematica) – Try It Online") A port of my [Jelly answer](https://codegolf.stackexchange.com/a/150851). Longer than the existing Mathematica answer by 8 bytes... The function take 2 input `[denominator, numerator]`, such that `GCD[denominator, numerator] == 1`. [Answer] # [Perl 6](https://perl6.org), 102 bytes ``` {$/=.base-repeating;(+$0//$0~0)+([~]([$1.comb].rotate)/(9 x$1.chars)*.1**(($0~~/\.<(.*/).chars)if $1)} ``` [Try it](https://tio.run/##fZDdboMwDIXveQpLQ2tC1TghGQhlvd0D7LarpkDTjWmFip9pVVVenUFBayeV@c4@n4@ts7fFZ9DWpYWvgCXa2R3gPsk3Fpbt0cUli01pF4XdW1Ol2Zsmc5cjurzhdE5WzZqsXMGSfBevWZFXprIUSQTf/fDdFCX1mPA8QrqFBl/YI2Ee0lFKt@AKemrLOgZTLraFSao0z4DAk6meTUUouK9A4QgsqzeWfeRpRmY4o3BynNIc/iydX1YCla@hrzsQXKDgD7fJUdQDGUn0BZ8gB3EkufrPU117dlsTHMrhxzOHcopS15S6TflchCj0QA3NlF14sZMYTlF@oH@PdhHJqVR8qTDqSvd3ZRd837Q/ "Perl 6 – Try It Online") Takes a [Rational](https://docs.perl6.org/type/Rational) number and returns a [Rational](https://docs.perl6.org/type/Rational) or [Int](https://docs.perl6.org/type/Int) number. ## Expanded: ``` { # bare block lambda with implicit Rational parameter 「$_」 $/ = .base-repeating; # store in 「$/」 the two strings '0.9' '761904' # handle the non-repeating part ( +$0 # turn into a number // $0 ~ 0 # if that fails append 0 (handle cases like '0.') ) + # handle the repeating part ( [~]( [$1.comb].rotate ) # rotate the repeating part / ( 9 x $1.chars ) # use a divisor that will result in a repeating number * # offset it an appropriate amount .1 ** ( ( $0 ~~ / \. <( .* / ).chars # count the characters after '.' ) if $1 # only do the repeating part if there was a repeating part ) } ``` Note will handle denominators upto `uint64.Range.max` to handle larger denominators use `FatRat(9 x$1.chars)` [Try it](https://tio.run/##fZDNboMwEITvPMVKRY1NFK@NXRByc@0D9JpGlSFOS9VAxE/VKAqvTiGgJpVC97aab2ZXs7fFZ9DWpYWvgCXa2R3gPsk3Fpbt0cUli01pF4XdW1Ol2Zsmc5cjurzhdE5WzZqsXMGSfBevWZFXprIUn0z1bCoSwXcvvZuipB4TnkdIZ2vwhT0S5iEdpXQLrqCntqxjMOViW5ikSvMMCIw5FNxXoHAEltUbyz7yNCMznFE4OU5pDn9M58eVQOVr6OcOBBco@MNtchT1QEYSfcEnyEEcSa7@y1TXmZ1rgkM5/HjmUE5R6ppStymfixCFHqhhmYoLL3ESwynKD/Tv0a4iOdWKLxVG3ej@ruyK75f2Bw "Perl 6 – Try It Online"). ]
[Question] [ [Lost](https://tio.run/#lost) is a 2-D programming language where the start position and direction of the ip are entirely random. This makes it very difficult to make deterministic Lost programs. However today we are not writing a deterministic program, we are writing an RNG. Write a Lost program that takes no input and outputs a single digit (0,1,2,3,4,5,6,7,8, or 9), with all digits having an equal probability of being output. Since Lost's start location and direction is the only source of randomness, the only way to do this is to have every location in your source output a different number from 0 to 9 with an equal number outputting each digit. You can calculate the probability of each digit by using the `-Q` flag and piping it into this python script ``` import sys a=sys.stdin.read().split()[:-1] for x in range(10):print x,':',a.count(`x`) print[x for x in a if x not in list("1234567890")] ``` [Try it online!](https://tio.run/##PYvLCoMwFAX39yuCGxOwwfhW6JeIYKjaBjQJyS3Er09tF90cZhiOPfFldBGjOqxxSPzpQd6v5R4Xpblb5UIZ93ZXSNk43MQEm3EkEKWJk/q5UpGzwTqlkYQsHdJM8od5a6RzmBn8whjI/yOJ2i7SBr@2K480EUVZ1U3b9XnCphhzEFBACRXU0EALHfQf "Python 2 – Try It Online") This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better. --- ## An overview of Lost Lost is a wrapping implicit IO 2D language taking much from the mold of Klein. Here is a quick cheatsheet of what lost commands do * `\`,`/`,`|` Mirrors the ip * `<`,`^`,`>`,`v` Points the ip in a direction * `[` Reflects the ip if it is moving east; becomes `]` if the ip is moving horizontally * `]` Reflects the ip if it is moving west; becomes `[` if the ip is moving horizontally * `!` Skips the next operation * `?` Pops off the top of the stack and jumps if not zero * `:` Duplicates the top of the stack * `$` Swaps the top two items of the stack * `(` Pops from the stack and pushes to the scope * `)` Pops from the scope and pushes to the stack * `0`-`9` pushes n to the top of the stack * `"` Starts and ends a string literal. During a string literal commands are not run and instead their character values are pushed to the stack. * `+` Adds the top two numbers * `*` Multiplies the top two numbers * `-` Multiplies the top by -1 * `%` Turns the safety off * `#` Turns the safety on * `@` Ends execution if the safety is off (starts on) [Answer] # ~~81~~ 101 bytes This might be golfable further ... ``` >%(0@>%(1@>%(2@>%(3@>%(4@>%(5@>%(6@>%(7@>%(8@>%(9@ ^<<<<^<<<<^<<<<^<<<<^<<<<^<<<<^<<<<^<<<<^<<<<^<<<< ``` [Try it online!](https://tio.run/##ldBNa8QgEAbgu79iWCirsOsm2e@QLntor4Wely3YxO0KqYpOSwL976mTftBrPTw4qMzrPKt4HWqFcIDaNVq2LiJU1f3D3XC44dkxkRMFsSRWxJrYEFtiR@yP7KlK618MqRNjYwD9rlrp@6/uzLx6FxBiH5m6TcqIjbEyaNVwIaNvDXJxKuf5mV1cgA6MhaDsi@Z5JkofjEXoZtNyOlOydm8WedA@8E4INh6eOvh9p8Bc0s46pKo1EfkkL5ar9Wa722cTcWZjSt/j1dkCFs7jggY1QpHnj3@m9wE/F79/NHwC "Try It Online") [Answer] # [Lost](https://github.com/Wheatwizard/Lost), 54 bytes ``` >%(0@>%(1@ @>%(2@>%(3 5@>%(4@>%( (7@>%(6@>% %(9@>%(8@> ``` [Try it online!](https://tio.run/##y8kvLvn/305Vw8ABSBg6cIEoIxBhzGUKokxABJeGOYgyAxJcqhqWILaFg93///91AwE "Lost – Try It Online") Just copied from [pppery's answer](https://codegolf.stackexchange.com/a/138276/44718) and do some random stuff. I know nothing about Lost language. And I even do not know what happening for above codes. Is this work? (I don't know) ]
[Question] [ ***UPDATE***: **The gist-files are updated (including new submissions) as the Controller.java did not catch Exceptions (only errors). It does now catch errors and exceptions and also prints them.** *This challenge consists of two threads, this is the catcher thread, the cat thread can be found [here](https://codegolf.stackexchange.com/questions/51029/assymetrical-koth-catch-the-cat-cat-thread).* The controller can be downloaded [here](https://gist.github.com/flawr/7f2ad5d6f20e84e9d52b). This is an asymmetrical KOTH: Each submission is either a *cat* or a *catcher*. There are games between each pair of each a cat and a catcher. The cats and the catchers have separate rankings. ## Catcher There is a cat on a hexagonal grid. Your task is to catch it as fast as possible. Every turn, you can place a water bucket on one grid cell in order to prevent the cat from being able to go there. But the cat is not (perhaps) that dumb, and whenever you place a bucket, the cat will move to another grid cell. Since the grid is hexagonal, the cat can go in 6 different directions. Your goal is to surround the cat with water buckets, the faster the better. ## Cat You know the catcher wants to catch you by placing water buckets around you. Of course you try to evade, but as you are a lazy cat (as cats are) you exactly take one step at the time. This means you cannot stay on the same place you, but you have to move to one of the six surrounding spots. Whenever you see that the catcher placed a new water bucket you go to another cell. Of course you try to evade as long as possible. ## Grid The grid is hexagonal, but as we do not have hexagonal data structures, we take a `11 x 11` square 2d array and mimic the hexagonal 'behavior' that the cat can only move in 6 directions: ![enter image description here](https://i.stack.imgur.com/RXNRd.png) The topology is toroidal, that means if you step on a cell 'outside' of the array, you will just be transferred to the corresponding cell on the other side of the array. ## Game The cat starts out at given position in the grid. The catcher can do the first move, then the cat and its catcher alternate moves until the cat is caught. The number of steps is the score for that game. The cat tries to get a score as great as possible, the catcher tries to get a score as low as possible. The average sum over all the games you participated in will be the score of your submission. There are two separate rankings, one for the cat, one for the catchers. # Controller The given controller is written in Java. As a catcher or a cat you each have to each complete implement a Java class (there are already some primitive examples) and place it in the `players` package (and update the list of cats/catchers in the Controller class), but you also may write additional functions within that class. The controller comes with each two working examples of simple cats/catcher classes. The field is a `11 x 11` 2D- `int` array that stores the values of the current states of the cells. If a cell is empty, it has value `0`, if there is a cat it has value `-1` and if there is a bucket there is a `1`. There are a few given functions you can use: `isValidMove()`/`isValidPosition()` are for checking whether your move (cat) / position (catcher) is valid. Each time it is your turn, your function `takeTurn()` is called. The argument contains the a copy of the current grid an has methods like `read(i,j)` for reading the cell at `(i,j)`, as well as `isValidMove()/ isValidPosition()` that checks the validity of your answer. This also manages the wrapping over of the toroidal topology, that means even if the grid is only 11 x 11, you still can access the cell (-5,13). The method should return a `int` array of two elements, which represent possible moves. For the cats these are `{-1,1},{0,1},{-1,0},{1,0},{0,-1},{1,-1}` which represent the relative position of where the cat wants to go, and the catchers return the absolute coordinates of where they want to place a bucket `{i,j}`. If your method produces an invalid move, your submission will be disqualified. The move is considered as invalid, if at your destination is already a bucket or the move is not allowed / destination already occupied (as a cat), or if there is already a bucket/cat (as a catcher). You can check that before hand with the given functions. Your submission should work reasonably fast. If your method takes longer than 200ms for each step it will also be disqualified. (Preferably much less...) The programs are allowed to store information between the steps. ## Submissions * You can make as many submissions as you want. * Please do not significantly alter submissions you've already submitted. * Please each submissions in a new answer. * Each submission should preferably have it's unique name. * The submission should consist of the code of your class as well as a description that tells us how your submission works. * You can write the line `<!-- language: lang-java -->` before your source code in order to get automatic syntax highlighting. ## Scoring All *cats* will compete against all *catchers* the same number of times. I'll try to update the current scores frequently, the winners will be determined when the activity has decreased. This challenge is inspired by [this old flash game](http://www.gamedesign.jp/flash/chatnoir/chatnoir.html) Thanks @PhiNotPi for testing and giving some constructive feedback. ## Current Scores (100 Games per pairing) | Name (Catcher) | Score | Rank | Author | | --- | --- | --- | --- | | RandCatcher | 191674 | 8 | flawr | | StupidFill | 214246 | 9 | flawr | | Achilles | 76820 | 6 | The E | | Agamemnon | 74844 | 5 | The E | | CloseCatcher | 54920 | 4 | randomra | | ForwordCatcher | 94246 | 7 | MegaTom | | Dijkstra | 46500 | 2 | TheNumberOne | | HexCatcher | 48832 | 3 | randomra | | ChoiceCatcher | 43828 | 1 | randomra | | Name (Cat) | Score | Rank | Author | | --- | --- | --- | --- | | RandCat | 77928 | 7 | flawr | | StupidRightCat | 81794 | 6 | flawr | | SpiralCat | 93868 | 5 | CoolGuy | | StraightCat | 82452 | 9 | CoolGuy | | FreeCat | 106304 | 3 | randomra | | RabidCat | 77770 | 8 | cain | | Dijkstra's Cat | 114670 | 1 | TheNumberOne | | MaxCat | 97768 | 4 | Manu | | ChoiceCat | 113356 | 2 | randomra | [Answer] # Achilles Achilles isn't too bright but he is ruthlessly efficient. First he stops the cat from using the wrap around of the board, then he divides the board into two. Then he keeps on dividing the part of the board the cat is in into half until the cat is trapped. Demonstration RandCat vs Achilles ![randcat vs achilles](https://i.stack.imgur.com/AZSAU.gif) ``` package players; /** * @author The E */ import main.*; public class Achilles implements Catcher { public Achilles() { } @Override public String getName() { return "Achilles"; } @Override public int[] takeTurn(Field f) { try{ if(f.read(0, f.SIZE-1)!=Field.BUCKET) { //Make the first line for(int j = 0; j<f.SIZE; j++) { if(f.read(0, j) == Field.EMPTY) { return new int[]{0,j}; } } return WasteGo(f); } else if (f.read(f.SIZE-1, 0)!=Field.BUCKET) { //Make the second line for(int i = 0; i<f.SIZE; i++) { if(f.read(i, 0) == Field.EMPTY) { return new int[]{i,0}; } } //The cat got in the way for(int j = 0; j<f.SIZE; j++) { if(f.read(1, j) == Field.EMPTY) { return new int[]{1,j}; } } return WasteGo(f); } else { return TrapCat(1,1,f.SIZE-1, f.SIZE-1, false, f); } } catch (Exception e) { return WasteGo(f); } } private int[] TrapCat(int i1, int j1, int i2, int j2, Boolean direction, Field f) { for(int a = 0; a<f.SIZE+10; a++) { if(direction) { int height = j2-j1+1; int row = j1 + height/2; for(int i = i1; i<=i2; i++) { if(f.read(i, row)==Field.EMPTY) { return new int[]{i,row}; } } //Done that Row //Find cat if(f.findCat()[1]>row) { //he's above the line j1 = row+1; direction = !direction; //return TrapCat(i1, row+1, i2, j2, !direction, f); } else { //he's below the line j2 = row - 1; direction = !direction; //return TrapCat(i1, j1, i2, row-1, !direction, f); } } else { int bredth = i2-i1+1; int column = i1 + bredth/2; //Continue making the line for(int j = j1; j<=j2; j++) { if(f.read(column,j)==Field.EMPTY) { return new int[]{column,j}; } } //Done that Column //Find cat if(f.findCat()[0]>column) { //he's right of the line i1 = column + 1; direction = !direction; //return TrapCat(column+1, j1, i2, j2, !direction, f); } else { //he's left of the line i2 = column -1; direction = !direction; //return TrapCat(i1, j1, column-1, j2, !direction, f); } } } return WasteGo(f); } private int[] WasteGo(Field f) { for (int i = 0; i<f.SIZE;i++) { for(int j=0;j<f.SIZE;j++) { if(f.read(i,j)==Field.EMPTY) { return new int[]{i,j}; } } } //Something drastic happened return new int[]{0,0}; } } ``` [Answer] # Agamemnon Agamemnon splits the cats area in half with a vertical line until the cat only has a strip of width 2 to move in, at which point he traps the cat. Agamemnon vs RandCat: ![enter image description here](https://i.stack.imgur.com/wlgHl.gif) ``` package players; /** * @author The E */ import main.*; public class Agamemnon implements Catcher { boolean up = true; @Override public String getName() { return "Agamemnon"; } @Override public int[] takeTurn(Field f) { //First Make Line in column 1 for(int j = 0; j<f.SIZE; j++) { if(f.read(0, j)==Field.EMPTY) { return new int[]{0,j}; } } //Then in column SIZE/2 for(int j = 0; j<f.SIZE; j++) { if(f.read(f.SIZE/2, j)==Field.EMPTY) { return new int[]{f.SIZE/2,j}; } } //Then work out where the cat is int left, right; int cati = f.findCat()[0]; if(cati<f.SIZE/2) { left = 1; right = f.SIZE/2-1; } else { left = f.SIZE/2+1; right = f.SIZE-1; } while(right-left>1) { //If the cat is not in a two width column //Split the area the cat is in in half int middleColumn = (left+right)/2; for(int j = 0; j<f.SIZE; j++) { if(f.read(middleColumn, j)==Field.EMPTY) { return new int[]{middleColumn,j}; } } //If we got here we had finished that column //So update left and/or right if(cati<middleColumn) { //he's left of the middle Column right = middleColumn - 1; } else { //he's right of the middle Column left = middleColumn+1; } //Repeat } //Otherwise try to trap the cat //Make a line up and down on the opposite side of the cat int catj = f.findCat()[1]; if(left!=right){ if(cati==left) { if(f.read(right, catj)==Field.EMPTY) { return new int[]{right, catj}; } if(f.read(right, catj-1)==Field.EMPTY) { return new int[]{right, catj-1}; } if(f.read(right, catj+1)==Field.EMPTY) { return new int[]{right, catj+1}; } } else { if(f.read(left, catj)==Field.EMPTY) { return new int[]{left, catj}; } if(f.read(left, catj-1)==Field.EMPTY) { return new int[]{left, catj-1}; } if(f.read(left, catj+1)==Field.EMPTY) { return new int[]{left, catj+1}; } } } //Alternate between above and below if(up) { up = !up; if(f.read(cati, catj+1)==Field.EMPTY) { return new int[]{cati, catj+1}; } } up = !up; if(f.read(cati, catj-1)==Field.EMPTY) { return new int[]{cati, catj-1}; } return WasteGo(f); } private int[] WasteGo(Field f) { for (int i = 0; i<f.SIZE;i++) { for(int j=0;j<f.SIZE;j++) { if(f.read(i,j)==Field.EMPTY) { return new int[]{i,j}; } } } //Something drastic happened return new int[]{0,0}; } } ``` This catcher does consistently better than Achilles and I think he's different enough to warrant a new answer. [Answer] # HexCatcher If the catcher can get the cat in the inside of a big hexagon with 3 units sides where the corners of the hexagon are already occupied by buckets, the catcher can keep the cat in this area and catch him. The hexagon looks like this: ![enter image description here](https://i.stack.imgur.com/e0XY8.png) This is what HexCatcher tries to achieve. It mentally tiles the field with these big hexagons in a way that each corner cell is part of 3 big hexagons. If there is a chance to keep the cat in the current area by connecting two corners next to the cat, the bot will do that. (E.g. in the image if the cat is at 7,5 we choose 7,6 even if only the 6,6 and 8,5 cells are occupied yet.) If the previous is not an option we chooses to play a corner which is a part of the area where the cat is. If all such corners are already chosen (like in the image) we choose a cell next to the cat. Multiple small improvements are possible such as handling wrap-around better (the tiling breaks there) or doing the last couple moves optimally. I might do some of these. If it is not allowed, I will just append it (out of competition) for the ones interested. DijkstrasCat vs HexCatcher: ![enter image description here](https://i.stack.imgur.com/1efGD.gif) ``` package players; /** * @author randomra */ import main.Field; public class HexCatcher implements Catcher { public String getName() { return "HexCatcher"; } final int[][] o = { { -1, 1 }, { 0, 1 }, { -1, 0 }, { 1, 0 }, { 0, -1 }, { 1, -1 } };// all valid moves final int[][] t = { { -2, 2 }, { 0, 2 }, { -2, 0 }, { 2, 0 }, { 0, -2 }, { 2, -2 } };// all valid double moves in one direction final int[][] h = { { -1, 2 }, { -2, 1 }, { -1, -1 }, { 1, -2 }, { 2, -1 }, { 1, 1 } };// all valid moves in not one direction int opp = 0; public int[] takeTurn(Field f) { int[] p = f.findCat(); // center of the hexagon the cat is in int[] c = { ((int) p[0] / 3) * 3 + 1, ((int) p[1] / 3) * 3 + 1 }; // change priority of catching direction at every turn opp = 1 - opp; // check missing corner piece next to cat for (int i = 0; i < 6; i++) { int ind = (i + opp * 3) % 6; boolean close = false; for (int k = 0; k < 6; k++) { if (c[0] + h[ind][0] == p[0] + o[k][0] && c[1] + h[ind][1] == p[1] + o[k][1]) { close = true; } } if (f.read(c[0] + h[ind][0], c[1] + h[ind][1]) == 0 && close) { return new int[] { c[0] + h[ind][0], c[1] + h[ind][1] }; } } // cut off escape route if needed for (int i = 0; i < 6; i++) { int ind = (i + opp * 3) % 6; if (f.read(c[0] + o[ind][0], c[1] + o[ind][1]) == -1 && f.read(c[0] + t[ind][0], c[1] + t[ind][1]) == 0) { return new int[] { c[0] + t[ind][0], c[1] + t[ind][1] }; } } // check any missing corner piece in the area for (int i = 0; i < 6; i++) { int ind = (i + opp * 3) % 6; if (f.read(c[0] + h[ind][0], c[1] + h[ind][1]) == 0) { return new int[] { c[0] + h[ind][0], c[1] + h[ind][1] }; } } // choose an empty cell next to the cat for (int i = 0; i < 6; i++) { int ind = (i + opp * 3) % 6; if (f.read(p[0] + o[ind][0], p[1] + o[ind][1]) == 0) { return new int[] { p[0] + o[ind][0], p[1] + o[ind][1] }; } } return null; } } ``` [Answer] # Dijkstra He doesn't like cats very much (:`v{ >` FreeCat vs Dijkstra ~~(needs updated)~~: ![enter image description here](https://i.stack.imgur.com/apx3u.gif) ``` package players; import main.Controller; import main.Field; import java.util.*; /** * @author TheNumberOne * * Catches the cat. */ public class Dijkstra implements Catcher{ private static final int[][][] CACHE; static { CACHE = new int[Controller.FIELD_SIZE][Controller.FIELD_SIZE][2]; for (int x = 0; x < Controller.FIELD_SIZE; x++){ for (int y = 0; y < Controller.FIELD_SIZE; y++){ CACHE[x][y] = new int[]{x,y}; } } } private static final int[][] possibleMoves = {{-1,1},{0,1},{-1,0},{1,0},{0,-1},{1,-1}}; @Override public String getName() { return "Dijkstra"; } @Override public int[] takeTurn(Field f) { long startTime = System.nanoTime(); final int[] theCat = f.findCat(); int[] bestMove = {-1,1}; int[] bestOpenness = {Integer.MAX_VALUE, 0}; List<int[]> possiblePositions = new ArrayList<>(); for (int x = 0; x < 11; x++){ for (int y = 0; y < 11; y++){ int[] pos = {x,y}; if (f.isValidPosition(pos)){ possiblePositions.add(pos); } } } Collections.sort(possiblePositions, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return distance(o1, theCat) - distance(o2, theCat); } }); for (int i = 0; i < possiblePositions.size() && System.nanoTime() - startTime < Controller.MAX_TURN_TIME/2; i++){ int[] pos = possiblePositions.get(i); int before = f.field[pos[0]][pos[1]]; f.placeBucket(pos); int[] openness = openness(theCat, f, true); if (openness[0] < bestOpenness[0] || (openness[0] == bestOpenness[0] && (openness[1] > bestOpenness[1]) ) ){ bestOpenness = openness; bestMove = pos; } f.field[pos[0]][pos[1]] = before; } return bestMove; } /** * * @param pos The pos to calculate the openness of. * @param f The field to use. * @return Two integers. The first integer represents the number of reachable hexagons. * The second integer represents how strung out the squares are relative to the pos. */ public static int[] openness(int[] pos, Field f, boolean catZeroWeight){ Map<int[], Integer> lengths = new HashMap<>(); PriorityQueue<int[]> open = new PriorityQueue<>(10,new Comparator<int[]>() { Map<int[], Integer> lengths; @Override public int compare(int[] o1, int[] o2) { return lengths.get(o1) - lengths.get(o2); } public Comparator<int[]> init(Map<int[], Integer> lengths){ this.lengths = lengths; return this; } }.init(lengths)); Set<int[]> closed = new HashSet<>(); lengths.put(pos, catZeroWeight ? 0 : 6 - pointsAround(pos, f).size()); open.add(pos); while (open.size() > 0){ int[] top = open.remove(); if (closed.contains(top)){ continue; } closed.add(top); int l = lengths.get(top); List<int[]> pointsAround = pointsAround(top, f); for (ListIterator<int[]> iter = pointsAround.listIterator(); iter.hasNext();){ int[] point = iter.next(); if (closed.contains(point)){ iter.remove(); } } for (int[] p : pointsAround){ int length = l + 7 - pointsAround(p, f).size(); if (lengths.containsKey(p)){ length = Math.min(length, lengths.get(p)); } lengths.put(p, length); open.add(p); } } int sum = 0; for (int integer : lengths.values()){ sum += integer; } return new int[]{lengths.size(),sum}; } public static int distance(int[] p1, int[] p2){ p2 = Arrays.copyOf(p2, 2); while (p2[0] < p1[0]){ p2[0] += 11; } while (p2[1] < p2[0]){ p2[1] += 11; } int lowestDistance = 0; for (int dx = 0; dx == 0; dx -= 11){ for (int dy = 0; dy == 0; dy -= 11){ lowestDistance = Math.min(lowestDistance,Math.min(Math.abs(p1[0]-p2[0]-dx),Math.min(Math.abs(p1[1]-p2[1]-dy),Math.abs(p1[0]+p1[1]-p2[0]-dx-p2[1]-dy)))); } } return Math.min(Math.abs(p1[0]-p2[0]),Math.min(Math.abs(p1[1]-p2[1]),Math.abs(p1[0]+p1[1]-p2[0]-p2[1]))); } public static int[] normalize(int[] p){ return CACHE[(p[0]%11+11)%11][(p[1]%11+11)%11]; } public static List<int[]> pointsAround(int[] p, Field f){ int[] cat = f.findCat(); List<int[]> locations = new ArrayList<>(); for (int[] move : possibleMoves){ int[] location = normalize(new int[]{p[0]+move[0], p[1] + move[1]}); if (f.isValidPosition(location) || Arrays.equals(cat, location)){ locations.add(location); } } return locations; } } ``` **How he tries to catch the cat:** He analyzes all squares of the board and tries to find the square that minimizes the openness of the board, and maximizes how much the board is strung out; in relation to the cat. The openness and stringiness of a board are computed using a modification of his [famous algorithm](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm). **Openness:** The openness of a board relative to a position is the number of reachable positions from that position. **Stringiness:** The stringiness of a board relative to a position is the sum of the distances between the reachable positions and the position. **With last update:** Now, he is much better at catching ~~FreeCat and his own cat~~ all cats. ~~Unfortunately, he is also much worse at catching the crazy uncooperative cats. He could be improved by detecting if the cat is one of the crazy ones and then acting as CloseCatcher.~~ Bug fixed. [Answer] # CloseCatcher Chooses one of the positions where the cat could step in the next step. It chooses the one which would give the most possible paths after 3 steps for the cat if it would move there and the field wouldn't change. Code is almost identical to my Cat entry, [FreeCat](https://codegolf.stackexchange.com/a/51113/7311), which chooses the direction in a very similar way. SpiralCat vs CloseCatcher: ![SpiralCat vs CloseCatcher](https://i.stack.imgur.com/X9z7N.gif) ``` package players; /** * @author randomra */ import main.Field; import java.util.Arrays; public class CloseCatcher implements Catcher { public String getName() { return "CloseCatcher"; } final int[][] turns = { { -1, 1 }, { 0, 1 }, { -1, 0 }, { 1, 0 }, { 0, -1 }, { 1, -1 } };// all valid moves final int turnCheck = 3; public int[] takeTurn(Field f) { int[] pos = f.findCat(); int[] bestMove = { 0, 1 }; int bestMoveCount = -1; for (int[] t : turns) { int[] currPos = { pos[0] + t[0], pos[1] + t[1] }; int moveCount = free_count(currPos, turnCheck, f); if (moveCount > bestMoveCount) { bestMoveCount = moveCount; bestMove = t; } } int[] bestPos = { pos[0] + bestMove[0], pos[1] + bestMove[1] }; return bestPos; } private int free_count(int[] pos, int turnsLeft, Field f) { if (f.isValidPosition(pos) || Arrays.equals(pos, f.findCat())) { if (turnsLeft == 0) { return 1; } int routeCount = 0; for (int[] t : turns) { int[] currPos = { pos[0] + t[0], pos[1] + t[1] }; int moveCount = free_count(currPos, turnsLeft - 1, f); routeCount += moveCount; } return routeCount; } return 0; } } ``` [Answer] # ForwordCatcher Places a bucket in front of the cat, or if that is taken, places behind. RabidCat vs ForwordCatcher: ![RabidCat vs ForwordCatcher:](https://i.stack.imgur.com/fVulc.gif) ``` package players; import main.Field; import java.util.Arrays; public class ForwordCatcher implements Catcher { public String getName() { return "ForwordCatcher"; } private int[] lastPos = {0,0}; public int[] takeTurn(Field f) { int[] temp = lastPos; int[] pos = f.findCat(); lastPos = pos; int[] Move = {pos[0]*2-temp[0], pos[1]*2-temp[1]}; if(f.isValidPosition(Move)){return Move;} if(f.isValidPosition(temp)){return temp;} Move[0] = pos[0];Move[1] = pos[1]+1; return Move; } } ``` [Answer] # ChoiceCatcher Uses the same scoring mechanism as [my ChoiceCat entry](https://codegolf.stackexchange.com/a/51578/7311). There is a little modification which helps to choose relevant cells at the first few steps as ChoiceCat doesn't care about the first few buckets as it doesn't see them as threat. ChoiceCatcher seems to score considerably better than the current catchers. ChoiceCat vs ChoiceCatcher: ![ChoiceCat vs ChoiceCatcher](https://i.stack.imgur.com/b3jCf.gif) ``` package players; /** * @author randomra */ import java.util.Arrays; import main.Field; public class ChoiceCatcher implements Catcher { private class Values { public final int size; private double[][] f; Values(int size) { this.size = size; f = new double[size][size]; } public double read(int[] p) { int i = p[0]; int j = p[1]; i = (i % size + size) % size; j = (j % size + size) % size; return f[i][j]; } private double write(int[] p, double v) { int i = p[0]; int j = p[1]; i = (i % size + size) % size; j = (j % size + size) % size; return f[i][j] = v; } } final int[][] turns = { { -1, 1 }, { 0, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, 0 } };// all valid moves CW order final int stepCheck = 5; public String getName() { return "ChoiceCatcher"; } @Override public int[] takeTurn(Field f) { int[] bestPos = null; double bestPosValue = Double.MAX_VALUE; for (int i = 0; i < f.SIZE; i++) { for (int j = 0; j < f.SIZE; j++) { if (f.read(i, j) == Field.EMPTY) { Field myField = new Field(f); myField.placeBucket(new int[] { i, j }); double posValue = catTurnValue(myField); if (posValue < bestPosValue) { bestPosValue = posValue; bestPos = new int[] { i, j }; } } } } return bestPos; } private double catTurnValue(Field f) { int[] pos = f.findCat(); double[] values = new double[6]; int count=0; for (int[] t : turns) { int[] currPos = { pos[0] + t[0], pos[1] + t[1] }; double moveValue = movePosValue(currPos, f); values[count++]=moveValue; } Arrays.sort(values); return values[5]; } private double movePosValue(int[] pos, Field f) { Values v = new Values(f.SIZE); for (int ring = stepCheck; ring >= 0; ring--) { for (int phase = 0; phase < 2; phase++) { for (int sidepos = 0; sidepos < Math.max(1, ring); sidepos++) { for (int side = 0; side < 6; side++) { int[] evalPos = new int[2]; for (int coord = 0; coord < 2; coord++) { evalPos[coord] = pos[coord] + turns[side][coord] * sidepos + turns[(side + 1) % 6][coord] * (ring - sidepos); } if (phase == 0) { if (ring == stepCheck) { // on outmost ring, init value v.write(evalPos, -1); } else { v.write(evalPos, posValue(evalPos, v, f)); } } else { // finalize position value for next turn v.write(evalPos, -v.read(evalPos)); } } } } } return -v.read(pos); } private double posValue(int[] pos, Values v, Field f) { if (f.read(pos[0], pos[1]) == Field.BUCKET) { return 0; } int count = 0; int maxRoutes = 2; double[] product = new double[6]; for (int[] t : turns) { int[] tPos = new int[] { pos[0] + t[0], pos[1] + t[1] }; if (v.read(tPos) > 0) { product[count] = 1 - 1 / (v.read(tPos) + 1); count++; } } Arrays.sort(product); double fp = 1; for (int i = 0; i < Math.min(count, maxRoutes); i++) { fp *= product[5 - i]; } double fp2 = 1; for (int i = 0; i < Math.min(count, 6); i++) { fp2 *= product[5 - i]; } double retValue = Math.min(count, maxRoutes) + fp; double retValue2 = Math.min(count, 6) + fp2; return -retValue - retValue2 / 1000000; } } ``` [Answer] # RandCatcher This was made just for testing the controller and just randomly places the buckets (very inefficiently). ``` package players; import main.Field; public class RandCatcher implements Catcher { public String getName(){ return "RandCatcher"; } public int[] takeTurn(Field f){ int[] pos = {0,0}; do { pos[0] = (int) (Math.random()*f.SIZE); pos[1] = (int) (Math.random()*f.SIZE); } while( f.isValidPosition(pos)==false ); return pos; } } ``` [Answer] # StupidFillCatcher This was made just for testing the controller. It just fills up column by column until the cat is caught. ``` package players; import main.Field; public class StupidFillCatcher implements Catcher { public String getName(){ return "StupidFillCatcher"; } public int[] takeTurn(Field f){ for(int i=0; i < f.SIZE; i++){ for(int j=0; j < f.SIZE; j++){ if(f.isValidPosition(new int[] {i,j})){ return new int[] {i,j}; } } } return new int[] {0,0}; } } ``` ]
[Question] [ ## Challenge Write the shortest code that can sum all the time durations that appear in the stdin. The program must only consider the strings that match with one of the following patterns and ignore the rest. ``` HH:MM:SS (it will be interpreted as HH hours, MM minutes and SS seconds) H:MM:SS (it will be interpreted as H hours, MM minutes and SS seconds) MM:SS (it will be interpreted as MM minutes, SS seconds) M:SS (it will be interpreted as M minutes, SS seconds) ``` *examples of strings that match with the enumerated patterns:* ``` 12:00:01 2:03:22 00:53 9:13 ``` The output should be of the form ``` HHh MMm SSs (that means HH hours, MM minutes and SS seconds with non-zero-padding) ``` ## Example **STDIN** > > View the Welcome video. > > Video: 10:37 min. > > View the video introduction to the course. > > Video: 3:30 min. > View the video of how to use the Lesson Overview. > > Video: 9:13 min. > > View the video overview of how to use the Epsilen system to share your work. > > Video: 03:15 min. > > View the video to learn about the State of Texas Assessment of Academic Readiness (STAAR). > > Video: 1:05:26 min. > > > **STDOUT** > > 1h 32m 1s > > > [Answer] ## Javascript ES6, 138 chars ### Function, 139 Takes string as an argument and writes output to console: ``` f=s=>(r=0,s.replace(/(\d\d?):(\d\d)(:(\d\d))?/g,(m,a,b,x,c)=>r+=x?+c+b*60+a*3600:+b+a*60),console.log("%dh %dm %ds",r/3600,r%3600/60,r%60)) ``` ### Program, 138 ``` prompt(r=0).replace(/(\d\d?):(\d\d)(:(\d\d))?/g,(m,a,b,x,c)=>r+=x?+c+b*60+a*3600:+b+a*60),console.log("%dh %dm %ds",r/3600,r%3600/60,r%60) ``` ### Test for function ``` f("View the Welcome video.\n\ Video: 10:37 min.\n\ View the video introduction to the course.\n\ Video: 3:30 min. View the video of how to use the Lesson Overview.\n\ Video: 9:13 min.\n\ View the video overview of how to use the Epsilen system to share your work.\n\ Video: 03:15 min.\n\ View the video to learn about the State of Texas Assessment of Academic Readiness (STAAR).\n\ Video: 1:05:26 min.") ``` ### Output ``` "1h 32m 1s" ``` [Answer] # JavaScript, ES6, ~~208 200~~ 197 bytes I know this is super long, but I wanted to explore the latest features of ES6, reverse, map-reduce, arrow functions and array comprehension (spread operator). ``` alert(prompt().match(/\d\d?:\d\d(:\d\d)?/g).map(x=>[...x.split(":").reverse(),z=0].slice(0,3)).reduce((a,b)=>b.map((y,i)=>+y+ +a[i])).map((x,i)=>(z=(t=x+z|0)/60,t%60+"smh"[i])).reverse().join(" ")) ``` Just run the snippet in a latest Firefox. **How it works (ungolfed a bit)** ``` alert( // Alert the final result prompt() // Take the input via prompt .match(/\d\d?:\d\d(:\d\d)?/g) // Match only correct time formats .map( // Map all matches using this method x=>[ // Take each element as argument x ...x.split(":").reverse(), // split x on ":" and reverse the array, then spread it z=0 // put 0 as last element of return array ].slice(0,3) // Take only first 3 elements of the array ).reduce( // Reduce the result using this method (a,b)=> // Pairwise elements of the array b.map( // Map array b (y,i)=>~~y+~~a[i] // Convert b[i] to b[i]+a[i] ) // Now we have array like [SS, MM, HH] ).map( // Map these three values for carry over calculation (x,i)=>( t=x+z, // z contains carryover amount, add it to this value z=(t/60)|0, // Carryover is now floor(t/60) t%60+"smh"[i] // Remove overflow from t and add "s", "m" or "h" ) // Now we have array like ["SSs", "MMm", "HHh"] ).reverse().join(" ") // Reverse it and join by space ) ``` [Answer] ### Bash (with grep, sed, awk and date): 124 bytes, 120 bytes Just pipe the text into this: ``` grep -o '[:0-9]*'|sed 's/^[^:]*:[^:]*$/:\0/'|awk -F: '{T+=3600*$1+60*$2+$3}END{print"@"T}'|xargs date +"%Hh %Mm %Ss" -ud ``` How it works * grep: outputs strings from the input containing only `0123456789:` * sed: turns MM:SS and M:SS into :M:SS * awk: calculates the seconds, empty string is 0 * xargs: passes input as argument to date * date: converts seconds since epoch (prefixed with @) to the required format [Answer] ## [Pyth](https://github.com/isaacg1/pyth) 105 ``` K"smh"J"\D\D+|\d+:(?=\d:)|:\d\D"W:QJ1=Q:QJd;FN_msdCfn2lTm+*]0</k\:2msbck\:cQ)~k+d+hK_`%+NZ60=Z/N60=KtK;_k ``` [Try it online.](http://isaacg.scripts.mit.edu/pyth/index.py) This requires input from STDIN in the same way that the Javascript answer does, as quoted text with newlines as `\n`s. Sample: ``` "View the Welcome video.\nVideo: 10:37 min.\nView the video introduction to the course.\nVideo: 3:30 min. View the video of how to use the Lesson Overview.\nVideo: 9:13 min.\nView the video overview of how to use the Epsilen system to share your work.\nVideo: 03:15 min.\nView the video to learn about the State of Texas Assessment of Academic Readiness (STAAR).\nVideo: 1:05:26 min." ``` Output ``` 1h 32m 1s ``` Example working with weirder dates: ``` "10:10:5 and 5:1:10 and 27 or 16: or 1:1:1 or 11:1\n" ``` Output ``` 0h 11m 20s ``` (Only the 10:10 and the 1:10 are legitimate times) The main reason that this is so long is that Pyth won't let you extract positive matches. This instead matches everything that isn't a valid time, and replaces it with a space character. Then, splitting on whitespace leaves only times and some wayward numbers. The excess numbers are removed by checking for `:` characters, which will have been removed from non-valid times. This could almost certainly be golfed further ;) [Answer] ## Perl - ~~228~~ 201 ``` use integer;$h=0,$m=0,$s=0;while(<>){if(/(\d+:){1,2}\d+/){@a=reverse(split(/:/,$&));push @a,(0)x(3-@a);$s+=@a[0];$m+=@a[1];$h+=@a[2];}}$m+=$s/60;$s=$s%60;$h+=$m/60;$m=$m%60;print $h."h ".$m."m ".$s."s" ``` It happens to be the same algorithm as Optimizer's (grep,split,reverse,add). I am no Perl expert, so maybe the byte count can be reduced. ## Ungolfed ``` use integer; # will do integer division $h=0,$m=0,$s=0; while(<>){ if(/(\d+:){1,2}\d+/) { # extract date formats @a = reverse(split(/:/,$&)); # split by ":" and reverse push @a,(0)x(3-@a); # pad with zeros (minutes and hours) $s+=@a[0]; # sum seconds $m+=@a[1]; # sum minutes $h+=@a[2]; # sum hours } } # convert seconds as minutes $m += $s / 60; $s = $s % 60; # convert minutes as hours $h += $m / 60; $m = $m % 60; print $h."h ".$m."m ".$s."s"; ``` [Answer] # Rebol - 174 ``` n: charset"1234567890"a:[1 2 n]b:[":"2 n]c: 0 parse input[any[copy x[a b b](c: c + do x)| copy x[a b](c: c + do join"0:"x)| skip]]print reword"$1h $2m $3s"[1 c/1 2 c/2 3 c/3] ``` Ungolfed + annotated: ``` n: charset "1234567890" ; setup \d regex equiv a: [1 2 n] ; parse rule for \d{1,2} b: [":" 2 n] ; parse rule for :\d\d c: 0 ; time counter parse input [ ; parse the input (STDIN) ; (no regex in Rebol) any [ ; match zero or more... ; copy x [a b b] (c: c + do x) ; HH:MM:SS or H:MM:SS ; - copy match to x ; - increment time (c) by x ; OR | copy x [a b] (c: c + do join "0:" x) ; MM:SS or M:SS ; - copy match to x ; - "MM:SS" into "0:MM:SS" (join) ; - then increment time (c) ; OR | skip ; no match so move through input ] ] print reword "$1h $2m $3s" [1 c/1 2 c/2 3 c/3] ``` Rebol comes with its own [`time!`](http://www.rebol.com/r3/docs/datatypes/time.html) datatype. You can see how the above code makes use of this from example below (from within the Rebol console): ``` >> 0:10:37 + 0:3:30 + 0:9:13 + 0:3:15 + 1:05:26 == 1:32:01 ;; Rebol would treat 10:37 as 10 hours & 37 minutes (and not MM:SS) ;; So we have to prefix the "0:" >> join "0:" 10:37 == "0:10:37" ;; This is a string so we use Rebol DO evaluator to convert to time! >> do join "0:" 10:37 == 0:10:37 >> type? do join "0:" 10:37 == time! >> hms: do join "0:" 10:37 == 0:10:37 >> hms/hour == 0 >> hms/second == 37 >> hms/minute == 10 ``` [Answer] ## Groovy - 195 ``` M=60 r=(System.in.text=~/((\d?\d):)?(\d\d):(\d\d)/).collect{it[2..4]*.toInteger().inject{s,i->(s?:0)*M+i}}.inject{s,i->s+=i} f=[];(2..0).each{j=M**it;s=r%j;f<<(r-s)/j;r=s} printf("%sh %sm %ss",f) ``` I can't figure out how to compress it more. ## Ungolfed ``` M=60 r=(System.in.text=~/((\d?\d):)?(\d\d):(\d\d)/).collect{ // extract dates it[2..4]*.toInteger().inject{ s,i -> // convert to seconds (s?:0)*M+i } }.inject{s,i -> s+=i // sum seconds } f=[]; (2..0).each{ // convert to h,m,s j=M**it; s=r%j; f<<(r-s)/j; r=s } printf("%sh %sm %ss",f) ``` [Answer] # Mathematica 300 chars This little exercise took up a lot of code, even for Mathematica. Surely there are more efficient ways to do this. **Golfed** Assuming that the input is stored in `txt`, ``` n=NumberString; t=ToExpression; o=TimeObject; QuotientRemainder[QuantityMagnitude[Plus@@((o[#]-o[{0,0,0}])&/@ (StringSplit[StringCases[w,{(n~~":"~~n~~":"~~n),(n~~":"~~n)}],":"] /.{{a_,b_}:> {0,t@a,t@b},{a_,b_,c_}:> {t@a,t@b,t@c}}))],60]/.{h_,m_}:> Row[{h,"h ",IntegerPart@m,"m ",Round[60 FractionalPart[m]],"s "}] ``` **How it works** (using unGolfed code): 1-Find the times. ``` StringCases[txt,{(NumberString~~":"~~NumberString~~":"~~NumberString), (NumberString~~":"~~NumberString)}]; ``` > > {"10:37", "3:30", "9:13", "03:15", "1:05:26"} > > > --- 2-Break into hours, minutes, seconds ``` StringSplit[%,":"]/.{{a_,b_}:> {0,ToExpression@a,ToExpression@b},{a_,b_,c_}:> {ToExpression@a,ToExpression@b,ToExpression@c}} ``` > > {{0, 10, 37}, {0, 3, 30}, {0, 9, 13}, {0, 3, 15}, {1, 5, 26}} > > > --- 3-Sum the times. Time objects are clock times. Subtracting one time object from another returns a duration, in this case 92.0167 minutes. `QuantityMagnitude` drops the unit of measure. ``` q=QuantityMagnitude[Plus@@((TimeObject[#]-TimeObject[{0,0,0}])&/@%)] ``` > > 92.0167 > > > --- 4-Convert 92.0167 minutes into hours, minutes, seconds. ``` QuotientRemainder[q,60]/.{h_,m_}:> Row[{h,"h ",IntegerPart@m,"m ", Round[60 FractionalPart[m]],"s "}] ``` > > 1h 32m 1s > > > [Answer] # Perl, 146 My entry prints the output with a trailing space - I hope that's ok ``` while(<>){for(/(\d?\d(?::\d\d){1,2})/g){$m=1;for(reverse split/:/,$_){$t+=$m*$_;$m*=60}}}for('s','m'){$o=($t%60)."$_ $o";$t/=60}print int$t,"h $o" ``` If we can assume there will be only one time per line of input, we can chop 4 characters: ``` while(<>){if(/(\d?\d(:\d\d){1,2})/){$m=1;for(reverse split/:/,$&){$t+=$m*$_;$m*=60}}}for('s','m'){$o=($t%60)."$_ $o";$t/=60}print int$t,"h $o" ``` These work by accumulating the total seconds elapsed and formatting that value afterwards. ]
[Question] [ If someone facing north at point A in this grid wanted directions to follow the green path (as they can only follow gridlines) to point B you might tell them: Go `North, North, West, East, East, South, East, East`. *or equivalently* Go `Forward, Forward, Left, Back, Forward, Right, Left, Forward`. (Where a command of *Right*, *Left*, or *Back* implicitly means turn in that direction, then go forward.) ![A to B path](https://i.stack.imgur.com/Y71mN.png) Write a function with one argument that translates between these absolute and relative directions **along the same path**, not just to the same point. Assume the directed person always starts facing north. If the argument is a string of the letters `NSEW`, return the equivalent relative directions. e.g. `f("NNWEESEE")` returns the string `FFLBFRLF`. If the argument is a string of the letters `FBLR`, return the equivalent absolute directions. e.g. `f("FFLBFRLF")` returns the string `NNWEESEE`. The empty string yields itself. Assume no other input cases. If your language does not have functions or strings use whatever seems most appropriate. The shortest code [in bytes](https://mothereff.in/byte-counter) wins. [Answer] # CJam, 57 53 49 ``` {"NESW""FRBL"_3$&!!:Q$:R^^f#0\{{+0\}Q*_@-R=\}%);} ``` ### Previous version ``` {"NESW""FRBL"_3$0=#W>:Q{\}*:R;f#0\{{+0\}Q*_@-R=\}%);} ``` Example: ``` {"NESW""FRBL"_3$0=#W>:Q{\}*:R;f#0\{{+0\}Q*_@-R=\}%);}:T; "NNWEESEE"T N "FFLBFRLF"T ``` Output: ``` FFLBFRLF NNWEESEE ``` ### How it works ``` { "NESW""FRBL" " Push the two strings. "; _3$0=#W> " Check if the first character is in FRBL. "; :Q " Assign the result to Q. "; {\}* " Swap the two strings if true. "; :R; " Assign the top string to R and discard it. "; f# " Find each character of the input in the string. "; 0\ " Push a 0 under the top of the stack. "; { " For each item (index of character): "; { " If Q: "; +0\ " A B -> 0 (A+B) "; }Q* _@- " C D -> D (D-C) "; R= " E -> E-th character in R "; \ " Swap the top two items. "; }% ); " Discard the last item in the list. "; } ``` [Answer] # JavaScript (E6) 84 ~~86 88 92 104~~ Edit: using & instead of %, different operator precedence (less brackets) and works better with negative numbers Edit2: | instead of +, op precedence again, -2. Thanks DocMax Edit3: array comprehension is 2 chars shorter than map(), for strings ``` F=p=>[o+=c[d=n,n=c.search(i),n<4?4|n-d&3:n=n+d&3]for(i of n=o='',c='NESWFRBL',p)]&&o ``` **Test** In FireFox/FireBug console ``` console.log(F('NNWEESEE'),F('FFLBFRLF')) ``` *Output* ``` FFLBFRLF NNWEESEE ``` [Answer] # C++, 99 97 94 bytes −3 bytes thans to **ceilingcat** The following is formatted as a lambda expression. It takes one `char*` argument and overwrites it. ``` [](char*s){for(int d=0,n=0,c=*s*9%37&4;*s;*s++="NESWFRBL"[c|n&3])d+=n=c?*s%11/3-d:n+*s%73%10;} ``` For those who are not familiar with this feature (like myself 1 hour ago), use it as follows: ``` #include <iostream> int main() { char s[] = "NNWEESEE"; auto x = [](char*s){for(int d=0,n=0,c=*s*9%37&4;*s;d+=n)c?n=*s%11/3-d:n+=*s%73%10,*s++="NESWFRBL"[c|n&3];}; x(s); // transform from absolute to relative std::cout << s << '\n'; x(s); // transform from relative to absolute std::cout << s << '\n'; } ``` Some explanations: * When using code like `flag ? (x = y) : (x += z)`, the second pair of parentheses is required in C. So I used C++ instead! * C++ requires specifying a return type for a function. Unless I use a lambda expression, that is! An added bonus is I don't need to waste 1 character on the name of the function. * The code `*s*9%37&4` tests the first byte; the result is 4 if it's one of `NESW`; 0 otherwise * The code `*s%11/3` converts the bytes `NESW` to 0, 1, 2, 3 * The code `*s%73%10` converts the bytes `FRBL` to 0, 9, 6, 3 (which is 0, 1, 2, 3 modulo 4) * When converting relative directions to absolute, I don't need the `d` variable. I tried rearranging code to eliminate it completely, but it seems impossible... [Answer] ## APL, [72](https://mothereff.in/byte-counter#%7B%5E%2F%E2%8D%B5%E2%88%8AA%E2%86%90%27NESW%27%3A%27FRBL%27%5B1%2B4%7C-2-%2F4%2C3%2BA%E2%8D%B3%E2%8D%B5%5D%E2%8B%84A%5B1%2B4%7C%2B%5C%27RBLF%27%E2%8D%B3%E2%8D%B5%5D%7D) ``` {^/⍵∊A←'NESW':'FRBL'[1+4|-2-/4,3+A⍳⍵]⋄A[1+4|+\'RBLF'⍳⍵]} ``` If the interpreter configurations can be changed without penalty, then score is [66](https://mothereff.in/byte-counter#%7B%5E%2F%E2%8D%B5%E2%88%8AA%E2%86%90%27NESW%27%3A%27FRBL%27%5B4%7C-2-%2F0%2CA%E2%8D%B3%E2%8D%B5%5D%E2%8B%84A%5B4%7C%2B%5C%27FRBL%27%E2%8D%B3%E2%8D%B5%5D%7D), by changing `⎕IO` to `0`: ``` {^/⍵∊A←'NESW':'FRBL'[4|-2-/0,A⍳⍵]⋄A[4|+\'FRBL'⍳⍵]} ``` [Answer] # Python, 171 139 No way near as short as the other solutions, but I guess it should be relatively good for what can be done with Python: ``` def f(i):a,b='NWSE','FLBR';I=map(a.find,'N'+i);return''.join((b[I[k+1]-I[k]],a[sum(map(b.find,i)[:k+1])%4])[-1in I]for k in range(len(i))) ``` Expanded version for slightly better readability: ``` def f(i): a, b = 'NWSE', 'FLBR' I = map(a.find,'N'+i) # translate to numbers assuming abs. directions J = map(b.index,i) # translate to numbers assuming rel. directions if not -1 in I: o = [b[I[k+1]-I[k]] for k in range(len(i))] # rel. dir. is differences of abs. dir. else: o = [a[sum(J[:k+1])%4] for k in range(len(i))] # abs. dir. is sum of all rel. dir. so far return ''.join(o) ``` [Answer] **Go, 201** ``` type q string;func F(s q)q{d,z:=byte(0),make([]byte,len(s));for i,c:=range[]byte(s){if(c^4)*167%3<2{c=c*156%5;z[i],d="LBRF"[(d-c)%4],c-1;}else{c=(c^43)*3%7-1;d=(d+c)%4;z[i]="NESW"[d];};};return q(z);} ``` Readable version: ``` func F(s string) string { d, z, R, A := 0, make([]byte, len(s)), "LBRFLBR", "NESW" for i, c := range []byte(s) { switch c { case 'N': c = R[d+3]; d = 0 case 'E': c = R[d+2]; d = 1 case 'S': c = R[d+1]; d = 2 case 'W': c = R[d]; d = 3 case 'F': c = A[d] case 'R': d = (d + 1) % 4; c = A[d] case 'B': d = (d + 2) % 4; c = A[d] case 'L': d = (d + 3) % 4; c = A[d] } z[i] = c } return string(z) } ``` [Answer] ## GNU sed, 356 bytes The challenge calls for a simple transformation on a stream of characters. `sed`, the stream editor is the obvious choice of language ;-) ``` /[FRBL]/bx # Jump to label x if relative :y # label y (start of abs->rel loop) /[FRBL]$/q # quit if string ends in rel char s/(^|[FRBL])N/\1F/;ty # Substitute next abs char with s/(^|[FRBL])E/\1R/;tr # rel char, then jump to s/(^|[FRBL])S/\1B/;tb # relevant rotation label if s/(^|[FRBL])W/\1L/;tl # a match was found by # loop back to y :r;y/NESW/WNES/;by # Rotation labels: transform then :b;y/NESW/SWNE/;by # loop back to y :l;y/NESW/ESWN/;by :x # label x (start of rel->abs loop) /^[NESW]/q # quit if string starts w/ abs char /F([NESW]|$)/s/F([NESW]|$)/N\1/ # Matches for each direction: /R([NESW]|$)/y/NESW/ESWN/;s/R([NESW]|$)/E\1/ # rotate, then substitute /B([NESW]|$)/y/NESW/SWNE/;s/B([NESW]|$)/S\1/ /L([NESW]|$)/y/NESW/WNES/;s/L([NESW]|$)/W\1/ bx # loop back to x ``` (Comments and spaces stripped for the purposes of golf score calculation) ### Output: ``` $ sed -rf absrel.sed <<< NNWEESEE FFLBFRLF $ sed -rf absrel.sed <<< FFLBFRLF NNWEESEE $ ``` ### Explanation: The idea here is that when we change the frame of reference, there is always a direct mapping between `{N, E, S, W}` and `{F, R, B, L}`. In the case of absolute to relative, we work fowards through the string. For each character we map `{N, E, S, W}` to `{F, R, B, L}`, then rotate the remaining `[NESW]` characters according to the character we just mapped, then move onto the next character. For the case of relative to absolute we do the reverse. We work backwards through the string, rotating all following `[NESW]` characters according to the character immediately in front. Then we map that character `{N, E, S, W}` to `{F, R, B, L}`, until we get to the start of the string. [Answer] # Haskell, 224 ``` import Data.Function i=flip(\x->length.takeWhile(/=x)) r=['F','R','B','L'] a=['N','E','S','W'] f s@(x:_)|elem x a=map((r!!).(`mod`4).(4-))$zipWith((-)`on`(i a))('N':s)(s)|True=tail$map((a!!).(`mod`4)).scanl(+)(0)$map(i r) s ``` This assigns rotation numbers to the relative directions, and orientation numbers to the absolute directions, then either finds the rotations between successive orientations or the orientations after successive rotations. The `i` function finds the index within the two legends. ]
[Question] [ [Today's Daily WTF](http://thedailywtf.com/Articles/One-Bad-Ternary-Operator-Deserves-Another.aspx) quotes the following line of code... ``` FailSafe==0?'No technical alarms':((FailSafe&1)!=0&&(FailSafe&2)!=0&&(FailSafe&4)!=0&&(FailSafe&8)!=0?'Detection zones staying in a given state; Bad visibility; Initialization; Bad configuration':((FailSafe&1)!=0&&(FailSafe&2)!=0&&(FailSafe&4)!=0?'Detection zones staying in a given state; Bad visibility; Initialization': ((FailSafe&1)!=0&&(FailSafe&2)!=0&&(FailSafe&8)!=0?'Detection zones staying in a given state; Bad visibility; Bad configuration':((FailSafe&1)!=0&&(FailSafe&4)!=0&& (FailSafe&8)!=0?'Detection zones staying in a given state; Initialization; Bad configuration':((FailSafe&2)!=0&&(FailSafe&4)!=0&&(FailSafe&8)!=0?'Bad visibility; Initialization; Bad configuration':((FailSafe&1)!=0&&(FailSafe&2)!=0?'Detection zones staying in a given state; Bad visibility':((FailSafe&1)!=0&&(FailSafe&4)!=0?'Detection zones staying in a given state; Initialization':((FailSafe&1)!=0&&(FailSafe&8)!=0?'Detection zones staying in a given state; Bad configuration':((FailSafe&2)!=0&& (FailSafe&4)!=0?'Bad visibility; Initialization':((FailSafe&2)!=0&&(FailSafe&8)!=0?'Bad visibility; Bad configuration':((FailSafe&4)!=0&&(FailSafe&8)!=0?'Initialization; Bad configuration':((FailSafe&1)!=0?'Detection zones staying in a given state':((FailSafe&2)!=0?'Bad visibility':((FailSafe&4)!=0?'Initialization':((FailSafe&8)!=0?'Bad configuration':'Unknown'))))))))))))))) ``` Write some code that takes an integer value named FailSafe and returns the same string that the above code would produce from the same integer value. * The challenge is to rewrite that line, so "boilerplate" code is free, including any code that loads an integer value and outputs the string. Only the code that performs the above transformation from an integer to a string counts. * You may use a different name to "FailSafe" if you wish, as long as your chosen identifier has the same golf score. * No calling external resources to perform the lookup. * Normal code-golf rules apply. [Answer] ### Ruby, 210 characters Similar to @Jan Dvorak's solution but a bit more functional and a bit shorter. ``` f=FailSafe e=[f&1,f&2,f&4,f&8,1-f].zip(["Detection zones staying in a given state","Bad visibility","Initialization","Bad configuration","No technical alarms"]).map{|a,b|a>0&&b}-[!0] e[0]||="Unknown" e.join"; " ``` [Answer] ### GolfScript, 167 characters ``` FailSafe.15&["Unknown"][""]"Bad configuration Initialization Bad visibility Detection zones staying in a given state" n/{`{n+1$+}+%}/1>+=n%"; "*"No technical alarms"if ``` The code assumes the value in variable `FailSafe` and pushes the result on the stack (i.e. output the string if run as standalone program). You can test the code [online](http://golfscript.apphb.com/?c=OzA6RmFpbFNhZmU7CgpGYWlsU2FmZS4xNSZbIlVua25vd24iXVsiIl0iQmFkIGNvbmZpZ3VyYXRpb24KSW5pdGlhbGl6YXRpb24KQmFkIHZpc2liaWxpdHkKRGV0ZWN0aW9uIHpvbmVzIHN0YXlpbmcgaW4gYSBnaXZlbiBzdGF0ZSIKbi97YHtuKzEkK30rJX0vMT4rPW4lIjsgIioiTm8gdGVjaG5pY2FsIGFsYXJtcyJpZgo%3D&run=true). The code basically generates an array of all 16 possible outcomes, selects the error message depending on the four lowest bits of `FailSafe`. The outermost `if` then handles the zero case. [Answer] ## Rebol/Red: 208 chars I'm not as interested in golfing this as in agreeing that nested ternary operators are annoying...and mentioning this is actually a nice instance for Rebol/Red's [CASE](https://stackoverflow.com/questions/23307263/if-else-if-else-in-rebol). It's related to SWITCH and really helps flatten things like this out: ``` f: FailSafe append case [ 0 < f and 1 ["Detection zones staying in a given state"] 1 < f and 2 ["Bad visibility"] 3 < f and 4 ["Initialization"] 7 < f and 8 ["Bad configuration"] f > 0 ["Unknown"] true ["No technical alarms"] ] "; " ``` There's a variant called CASE/ALL that will actually run all the conditions, but the default just stops after the first true one. I'll "golf" it a little to 208: > > x: func[y][y < (f: FailSafe) and ++ y]append case[x 0["Detection zones staying in a given state"]x 1["Bad visibility"]x 3["Initialization"]y 7["Bad configuration"]f > 0["Unknown"]1["No technical alarms"]]"; " > > > [Answer] ## APL (172) ``` 2↓⊃,/'; '∘,¨{⍵=0:⊂'No technical alarms'⋄0=16|⍵:⊂'Unknown'⋄'Detection zones staying in a given state' 'Bad visibility' 'Initialization' 'Bad configuration'/⍨⌽⍵⊤⍨4/2}FailSafe ``` Explanation: * `{`...`}FailSafe`: generate the strings + `⍵=0:⊂'No technical alarms'`: the `0` case + `0=16|⍵:⊂'Unknown'`: the `Unknown` case (FailSafe is not 0 but the first four bits are) + `'Detection zones staying in a given state' 'Bad visibility' 'Initialization' 'Bad configuration'/⍨⌽⍵⊤⍨4/2`: get the lowest 4 bits in the argument (`⍵⊤⍨4/2`), reverse (`⌽`), and select the strings for the bits that are on (`/⍨`). * `'; '∘,¨`: add `'; '` to the front of each returned string, * `⊃,/`: join all the strings together, * `2↓`: and remove the first two characters (because there's an extra `'; '` at the front.) [Answer] ## Ruby, 183 characters ``` [(f=FailSafe)<1?"No technical alarms":f&15<1?:Unknown:["Detection zones staying in a given state"*f[0],"Bad visibility"*f[1],"Initialization"*f[2],"Bad configuration"*f[3]]-[""]]*"; " ``` Yet another Ruby solution, but a bit shorter than the others. This is a single expression that uses the constant `FailSafe` (in Ruby, all uppercase identifiers are constants) to create the output string. [Answer] ## JavaScript, ~~197~~195 characters ``` FailSafe?['Detection zones staying in a given state','Bad visibility','Initialization','Bad configuration'].filter(function(_,i){return FailSafe&1<<i}).join('; ')||'Unknown':'No technical alarms' ``` formatted: ``` FailSafe ? [ 'Detection zones staying in a given state', 'Bad visibility', 'Initialization', 'Bad configuration' ].filter(function(_, i) { return FailSafe & 1<<i; }).join('; ') || 'Unknown' : 'No technical alarms'; ``` Could be further reduced by using ES6 or Coffeescript function expressions. [Answer] # Ruby, 213 characters ``` f=failSafe e=f&1>0?["Detection zones staying in a given state"]:[] e+=["Bad visibility"]if f&2>1 e+=["Initialization"]if f&4>3 e+=["Bad configuration"]if f&8>7 e[0]||=f>0?"Unknown":"No technical alarms" e.join"; " ``` This will work just fine wrapped in a function body (`def transform failSafe; ...; end`). It can also be used as a single expression (wrap in parentheses because a semicolon/newline has the lowest priority) or as a sequence of statements with the last expression (`e.join"; "`) used within an expression. [Answer] # VBScript, 204 234 232 characters (edit: improved score by 2 by using array() instead of split(). 232 now.) ``` f=failsafe:for b=0to 3:s=s&split(",; Detection zones staying in a given state,; Bad visibility,,; Initialization,,,,; Bad configuration",",")(f and 2^b):next:array("No technical alarms","Unknown",mid(s,3))(2+(f=0)+(len(s)=0)) ``` (edit: forgot the "unknown" part. 234 chars now.) f=failsafe:for b=0to 3:s=s&split(",; Detection zones staying in a given state,; Bad visibility,,; Initialization,,,,; Bad configuration",",")(f and 2^b):next:split("No technical alarms,Unknown,"&mid(s,3),",")(2+(f=0)+(len(s)=0)) (original, 230) for b=0to 3:s=s&split(",; Detection zones staying in a given state,; Bad visibility,,; Initialization,,,,; Bad configuration",",")(FailSafe and 2^b):next:array(mid(s,3),"No technical alarms")(-(len(s)=0)) Of course, this is just part of a script. to test it, try something like this: ``` FailSafe=cint(inputbox("Please enter Failsafe as an integer")) f=failsafe:for b=0to 3:s=s&split(",; Detection zones staying in a given state,; Bad visibility,,; Initialization,,,,; Bad configuration",",")(f and 2^b):next msgbox array("No technical alarms","Unknown",mid(s,3))(2+(f=0)+(len(s)=0)) ``` [Answer] ## Smalltalk, 243 characters ``` FailSave>15ifTrue:'Unknown'ifFalse:[((((1to:4)select:[:b|FailSafe isBitSet:b])collect:[:b|#('Detection zones staying in a given state' 'Bad visibility' 'Initialization' 'Bad configuration')at:b])asStringWith:'; ')ifEmpty:'No technical alarms'] ``` formatted for readability: ``` FailSafe > 15 ifTrue:'Unknown' ifFalse:[ ((((1 to:4) select:[:b | FailSafe isBitSet:b ]) collect:[:b| #( 'Detection zones staying in a given state' 'Bad visibility' 'Initialization' 'Bad configuration') at:b ] ) asStringWith:'; ') ifEmpty:'No technical alarms'] ``` Thanks to Bergi, for pointing to the bug in the first version. This brings up an idea: if I map the FailSafe value into a 6-bit mask, (mapping 0 -> 16 and greater-than-15 -> 32), I can get rid of the final tests. The mapping to the 6bit mask m can be done with: `m := {16},(1 to: 15) at:FailSafe+1 ifAbsent:32.` that is, m will be 16 for a zero FailSafe, and 32 for out-of-bounds values. Then select and collect strings as above. This gives the new code: ``` m := {16},(1 to:15) at:FailSafe+1 ifAbsent:32. (((1 to:6) select:[:b | m isBitSet:b ]) collect:[:b| #( 'Detection zones staying in a given state' 'Bad visibility' 'Initialization' 'Bad configuration' 'No technical alarms' 'Unknown') at:b ] ) joinWithAll:'; ' ``` (I also replaced asStringWith: by joinWithAll:, which is an alias). Although this seems to be a nice idea, this has the same character count - sigh. Maybe some other programming language with denser operator names scores better here! I could save a few chars by not using a temporary variable for m, but recompute it in the loop and by not using a literal array for the string vector, to get a count slighty below 240 chars. Finally, the mask m could also be computed by `m:={32},(1 to: 16) at:(FailSafe+1 min:17)`, which might be shorter in APL. Then exchange the last two strings in the vector. PS: The first version assumes FailSafe is non-negative, like some other solutions here do. The second can deal with anything, even nil or other non-numbers. [Answer] ## CoffeeScript, 161 160 221 chars ``` F = FailSafe;F<16 and (F and [0..3].filter((i)->(1<<i)&F).map((i)->(['Detection zones staying in a given state','Bad visibility','Initialization','Bad configuration'])[i]).join('; ') or 'No technical alarms') or 'Unknown' ``` [Answer] **VB.net** ``` Function StateText(f As FailFlag) As String If f=0 Then Return "No Technical Alarm" Dim t="" If f.HasFlag(f1) Then t &= "Detection zones staying in a given state; " If f.HasFlag(f2) Then t &= "Bad visibility; " If f.HasFlag(f4) Then t &= "Initialization; " If f.HasFlag(f8) Then t &= "Bad configuration; " Return If( t<>"", t.TrimEnd("; "),"Unknown") End Function <Flags> Enum FailFlag f1 = 1 f2 = 2 f4 = 4 f8 = 8 End Enum ``` Edit: Better Entry ``` Function StateText(f As FailFlag) As String If f = 0 Then Return "No Technical Alarm" Dim t = String.Join("; ", From e In [Enum].GetValues(GetType(FailFlag)) Where f.HasFlag(e) Select [Enum].GetName(GetType(FailFlag), e).Replace("_", " ")) Return If( t<>"", t,"Unknown") End Function <Flags> Enum FailFlag Detection_zones_staying_in_a_given_state = 1 Bad_visibility = 2 Initialization = 4 Bad_configuration = 8 End Enum ``` [Answer] ## Perl, 208 197 Characters ``` $f=$FailSafe;%m=(1,'Detection zones staying in a given state',2,'Bad visibility',4,'Initialization',8,'Bad configuration');($f?join'; ',@m{map{$f&$_?$_:()}1,2,4,8}:'No technical alarms')||'Unknown' ``` With boilerplate code to make it work: ``` #!/usr/bin/env perl $FailSafe=17; print failmsg() . "\n"; sub failmsg { $f=$FailSafe;%m=(1,'Detection zones staying in a given state',2,'Bad visibility',4,'Initialization',8,'Bad configuration');($f?join'; ',@m{map{$f&$_?$_:()}1,2,4,8}:'No technical alarms')||'Unknown' } ``` [Answer] **Java 275 characters** (not counting **unnecessary** white space) ``` String s = ""; int b = 1; for (String m : new String[]{"Detection zones staying in a given state; ","Bad visibility; ", "Initialization; ", "Bad configuration; "}) { if ((FailSafe & b) != 0) s = s + m; b <<= 1; } return (s.length() == 0) ? (FailSafe == 0) ? "No technical alarms" : "Unknown" : s.substring(0, s.length() - 2); ``` ]
[Question] [ Given two positive integer fractions \$x\$ and \$y\$ such that \$x < y\$, give the fraction \$z\$ with the smallest positive integer denominator such that it is between \$x\$ and \$y\$. For example \$x=2/5\$, \$y=4/5\$, the answer is \$1/2\$. Other fractions such as \$3/5\$ are also in between the two, but \$1/2\$ has a denominator of \$2\$ which is smaller. As input you will receive 4 positive integers, the numerators and the denominators of \$x\$ and \$y\$, you may assume these fractions are fully reduced. You should output the numerator and the denominator of \$z\$. If there are multiple valid numerators, you may output any or all of them. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. ### Test cases ``` 2/5 4/5 -> 1/2 1/1 2/1 -> 3/2 3/5 1/1 -> 2/3 5/13 7/18 -> 12/31 12/31 7/18 -> 19/49 ``` [Sample implementation in Haskell](https://tio.run/##TU8xDsIwENvzCg8MDXRJM8AAj6mUK40IV9RW8PzgFNTWy1lnnxP37fSQlHLuUKmrEZwlaUgai5sB7gMcx6eXUTiXRfCLVJBk/jNAtzUR4hsVnUcoM4PDaQkqiLraYrdd4OducL3x@UL9Ks696M7JTxyKfcsEJE2ys1Tq2cJbY8yzjQpmDpRfY9SZx@zrWNOXvuca7mJz/gI "Haskell – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~20~~ ~~12~~ 11 bytes ``` ḟ<⁰MS/ȯ→⌊*N ``` [Try it online!](https://tio.run/##AScA2P9odXNr///huJ884oGwTVMvyK/ihpLijIoqTv///zcvMTj/MTIvMzE "Husk – Try It Online") Generates an infinite list of fractions by going through each integer `N` as denominator in turn and constructing the numerator `floor(N*x)+1`. Then searches for the first one that is `<y`. ``` ḟ<⁰MS/ȯ→⌊*N M N # map over all integers starting at 1: * # multiply it by (implicit input) x ⌊ # get the floor → # and increment it, S/ȯ # and now divide all of that by itself; ḟ # finally, get the first result that <⁰ # is less than y ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 36 bytes ``` f(a,b,d)=until(b*d++>n=a*d\1+1,);n/d ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5BCoMwEEWvEqSLxIwMoxWFohexUsYGSyCEIHHRs3TjpvRMvU21trv3Pw_-f7wCT_ZyC8vynOOY1e_DKBkGMKqZfbRODqnRuvUNp-ZMmkCdPJqfazgEd5csslaEyfq4YrKFRFzZOTmCYKVAdF2OJRyx7FcmJMiRNizWlnYskQqokOqvkmNBe-rVvvX_9wE) Takes two fractions and outputs a fraction. For inputs \$a,b\$, let \$d\$ loops over all positive integers until \$b\ d>\lfloor a\ d\rfloor+1\$, and returns \$(\lfloor a\ d\rfloor+1)/d\$. [Answer] # [Python 2](https://docs.python.org/2/), 61 bytes ``` a,p,b,q=input();r=c=0 while r*b<=q*c:r+=1;c=r*a/p+1 print c,r ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMH68ozMnFQFQ6vUitRkJSWlpaUlaboWN20TdQp0knQKbTPzCkpLNDSti2yTbQ24IIqLtJJsbAu1kq2KtG0NrZNti7QS9Qu0DbkKijLzShSSdYoghiyGG7fgprWRjoKpjoIJkOQy1FEAIqCAIZcxWBQkwAWigVxzIGXBZQiUNTaE8iBmAAA) Rather naïve. --- # [Python](https://www.python.org) with [`fractions`](https://docs.python.org/3/library/fractions.html), 57 bytes ``` def f(x,y,d=0): while(n:=x*d//1+1)>=y*d:d+=1 return n,d ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Zc5LDoIwEAbgPaeYxE2LNTgiEUnqsvcglgYSKaSUCAdx5YaN3onbKI-EoKuZzDfzZ57vsrVpobt-o0yRgzLx1WaFriDLy8JYEPMA4grEq7ZqF_ZnmShQpGEtk3xPIwfuaXZLiI5440rPwy3SC29dGcktRwdMYmujQTM5BzxKk2lLFBHkwAAgoAwEObKho9RZFAfFUYdFXKu_3OK_BsPIH_XEAMOf5G-ejyudnuu6qX4A) Port of [alephalpha's PARI/GP answer](https://codegolf.stackexchange.com/a/247655). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes ``` ƒ/Þ∞*⌊›Þ∞/'⁰ƒ/<;h ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGki/DnuKInirijIrigLrDnuKIni8n4oGwxpIvPDtoIiwiIiwiWzEyLDMxXVxuWzcsMThdIl0=) Port of Husk answer. [Answer] # [C (clang)](http://clang.llvm.org/), ~~67~~ 62 bytes ``` n;d;f(*i,*j,k,l){for(d=n=0;*i*d<=*j*n;)n=++d*k/l+1;*i=n;*j=d;} ``` [Try it online!](https://tio.run/##bZJtb4IwEIC/@ysuJhooNb6g2Uztviz7FdMYQ4trYdUAyciMf33sSmGig/SOcvfcS3tEkyg9mGNVGSZY7BFFiaYJTf1LfMo8wQ2fMaKI2HCiiWG@4UEgSDJNgznauWFEc8GulTIFfB6U8Xy4DAAfayhkXuyT9x1wuCwozCmEFFa4WVzZPZQ6aFVDViMYzh8p5aglBZftCdcjo7uZ7Hq20qFkeZZRIcXeONJ1ZRNaWfeR4u8IixoOMWbZktHJ5AVEH4eMoJZRIjOHD7fl22Jbrl9RVkMK3e9w2ETjLYNniykjZIlhM9ZsN5Crb3mKvVsb/rQxkY6NQRDUEX6d0N1@ewSFGZurq5kdu3Pr1q173UnrTnrdaetOe92FLa4ebLaivtlib6zo2P1x96QUSHYm0FdBmi5j/jHnDKnYG47EdCTA6clLsxnlW4NTSSikFHtF0RTwhbodoxSc6/FYGs7VrunvOrhWP1GcHo55Nfn6BQ "C (clang) – Try It Online") Inputs the two fractions as \$2\$ pointers to integers for the numerator and denominator of the second fraction. And then \$2\$ integers as the numerator and denominator of the first fraction. Returns the in between fraction through the two pointers. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes ``` n&@For[d=1,(n=⌊d#+1⌋/d++)>=#2,]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P0/NwS2/KDrF1lBHI8/2UU9XirK24aOebv0UbW1NO1tlI51Ytf8BRZl5JdHKunZpDg7KsWp1wcmJeXXVXNVG@qY6JvqmtTpc1YY6RiDKGChiCGKY6hsa65jrG1qAJY30jQ0hPK7a/wA "Wolfram Language (Mathematica) – Try It Online") Port of alephalpha's [PARI/GP solution](https://codegolf.stackexchange.com/a/247655). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` NθNηNζNεI§ΦE⊕⁺ηε⟦⊕÷×θκηκ⟧›×ζκ×§ι⁰ε⁰ ``` [Try it online!](https://tio.run/##XY0xC8IwEIV3f0XGC0SwiCh0EkXJoHRwE4fYHiQ0jW16LdI/H1OLUFyO9/E93uVa@fylbAjS1R1du@qJHhqeLuas/3j4Y4yceeMIDqol2JN0Bb7hZCxFe1E1SJd7rNARFpDZrgUtGHIu2H1upKOj6U2BcDMVttAIVsaOHovlI56zRzVOTnqY9AS/p0awFf@O8zFxnoawYcmabVmyC8vefgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ Numerator of `x` as an integer Nη Denominator of `x` as an integer Nζ Numerator of `y` as an integer Nε Denominator of `y` as an integer η Denominator of `x` ⁺ Plus ε Denominator of `y` ⊕ Incremented E Map over implicit range θ Numerator of `x` × Multiplied by κ Current index ÷ Integer divided by η Denominator of `x` ⊕ Incremented κ Current index ⟦ ⟧ Make into list Φ Filtered where ζ Numerator of `y` × Multiplied by κ Current index › Is greater than § ⁰ First index of ι Current list × Multiplied by ε Denominator of `y` § ⁰ First element I Cast to string Implicitly print ``` The sum of the denominators is a sufficient limit since \$ \frac a b < \frac { a + b } { c + d } < \frac c d \$ if \$ \frac a b < \frac c d \$. [Answer] # JavaScript (ES6), 50 bytes Expects \$p/q\$ and \$P/Q\$ as `(p,q,P)(Q)` and returns \$m/n\$ as `[m,n]`. Based on [alephalpha's method](https://codegolf.stackexchange.com/a/247655/58563). ``` (p,q,P,n=0)=>g=Q=>++n*P>(m=-~(n*p/q))*Q?[m,n]:g(Q) ``` [Try it online!](https://tio.run/##Zc3BDoIwEATQu1/R4y4s1m0hiknxF@BsPBAUooEWxHj01ytGEyMmc5uXmUt5L8fqeu5vkXXHk6@Nh54GysmaFZqsMYXJwtAGeQadiR5gg14OiEGx23dkD9sGCvSVs6NrT8vWNVCDUCQSihFEgiikFCzVYkaYpqiJ8Jvof6JfK/wlSuo5mXpNawTefI4mwzPEijT/oFTGqfBP "JavaScript (Node.js) – Try It Online") [Answer] # TI-Basic, 30 bytes ``` Prompt A,B Repeat BAns>1+int(AAns Ans+1 End 1/Ans(1+int(AAns ``` Port of [alealpha's answer](https://codegolf.stackexchange.com/a/247655). Takes input as 2 fractions and output a fraction. The `/` symbol represents the fraction slash. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞ε¹.E*ï>y‚D¿÷'/ý}.Δ‚.E`› ``` Port of [*@DominicVanEssen*'s Husk answer](https://codegolf.stackexchange.com/a/247656/52210), but without implicit fraction support. [Try it online](https://tio.run/##yy9OTMpM/f//Uce8c1sP7dRz1Tq83q7yUcMsl0P7D29X1z@8t1bv3BQgX8814VHDrv//DY30jQ25zPUNLQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaNj/Rx3zzm2N1HPVOrzervJRwyyXQ/sPb1fXP7y3Vu/clIhioIiea8Kjhl3/a3X@R0crGembKukomQDJWB2FaCVDfUMg1whIgrnGYFlDGNdU39AYyDfXN7SAKjfSNzaEi8QCAA). **Explanation:** ``` ∞ # Push an infinite positive list: [1,2,3,...] ε # Map over each value: ¹ # Push the first input .E # Evaluate it as Elixir * # Multiply it to the current value ï # Floor it > # Increase it by 1 y‚ # Pair it with the current value D # Duplicate this pair ¿ # Pop and push the gcd (greatest common divisor) ÷ # Integer-divide the pair by this gcd '/ý '# Join the pair with "/"-delimiter to a string }.Δ # After the map: find the first value which is truthy for: ‚ # Pair it with the (implicit) second input .E # Evaluate both strings as Elixir ` # Pop and push both values to the stack › # Check that the first is larger than the second # (after which the found fraction-string is output implicitly) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 24 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Settled with a port of [Arnauld's solution](https://codegolf.stackexchange.com/a/247665/58974) for now. ``` T=°Y*U/VW*Y§X*ÒT?ß:[ÒTY] ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=VD2wWSpVL1ZXKlmnWCrSVD/fOlvSVFld&input=NQoxMwo3CjE4) [Answer] # x86\_64 assembly, 48 bytes This routine expects arguments `eax/ebx, ecx/edx` and returns the result in `r9/r11` (and registers `r8` and `r10` are clobbered). ``` .text .globl f f: xor %r8, %r8 xor %r9, %r9 xor %r10, %r10 inc %r8 mov %r8, %r11 .Lloop: cmp %rdx, %rcx ja .L1 # a/b < c/d <= 1: return 1 / f(d/c,b/a) xchg %rax, %rdx xchg %rbx, %rcx # 1/ matrix to multiply on right is [0 1; 1 0] xchg %r8, %r9 xchg %r10, %r11 jmp .Lloop .L1: # 1+ matrix to multiply on right is [1 1; 0 1] add %r8, %r9 add %r10, %r11 # 1 <= a/b < c/d: return 1 + f(a/b-1, c/d-1) sub %rdx, %rcx sub %rbx, %rax jae .Lloop # a/b < 1 < c/d: # return 0/1 (which becomes a return of 1/1 with the 1+ matrix # merged between this case and the previous one) ret ``` C test driver (requires GCC): ``` #include <stdio.h> void f_wrap(unsigned long a, unsigned long b, unsigned long c, unsigned long d, unsigned long *e, unsigned long *f) { register unsigned long r9 __asm__("r9"); register unsigned long r11 __asm__("r11"); __asm__("call f" : "=a"(a), "=b"(b), "=c"(c), "=d"(d), "=r"(r9), "=r"(r11) : "0"(a), "1"(b), "2"(c), "3"(d) : "r8", "r10"); *e = r9; *f = r11; } void test_f(unsigned long a, unsigned long b, unsigned long c, unsigned long d) { unsigned long e; unsigned long f; f_wrap(a, b, c, d, &e, &f); printf("%lu/%lu %lu/%lu -> %lu/%lu\n", a, b, c, d, e, f); } int main() { test_f(2, 5, 4, 5); test_f(1, 1, 2, 1); test_f(3, 5, 1, 1); test_f(5, 13, 7, 18); test_f(12, 31, 7, 18); test_f(2, 5, 1, 2); test_f(3, 7, 1, 2); // 3.14 = 314/100 = 157/50; 3.15 = 315/100 = 63/20 test_f(157, 50, 63, 20); // 3.1415 = 31415/10000 = 6283/2000; 3.1416 = 31416/10000 = 3927/1250 test_f(6283, 2000, 3927, 1250); return 0; } ``` And disassembly of the code as it ended up in the executable: ``` 0000000000001229 <f>: 1229: 4d 31 c0 xor %r8,%r8 122c: 4d 31 c9 xor %r9,%r9 122f: 4d 31 d2 xor %r10,%r10 1232: 49 ff c0 inc %r8 1235: 4d 89 c3 mov %r8,%r11 1238: 48 39 d1 cmp %rdx,%rcx 123b: 77 0d ja 124a <f+0x21> 123d: 48 92 xchg %rax,%rdx 123f: 48 87 d9 xchg %rbx,%rcx 1242: 4d 87 c1 xchg %r8,%r9 1245: 4d 87 d3 xchg %r10,%r11 1248: eb ee jmp 1238 <f+0xf> 124a: 4d 01 c1 add %r8,%r9 124d: 4d 01 d3 add %r10,%r11 1250: 48 29 d1 sub %rdx,%rcx 1253: 48 29 d8 sub %rbx,%rax 1256: 73 e0 jae 1238 <f+0xf> 1258: c3 ret ``` --- The basic idea in pseudocode behind this implementation is inspired by continued fractions: ``` f(x,y): if y <= 1 return 1 / f(1/y, 1/x) else if x >= 1 return 1 + f(x-1, y-1) else return 1/1 ``` (Do note, however, that in certain cases, this makes a recursive call to `f` with `y = 1 / 0` where we treat that as infinity.) Now, the biggest optimization I made was to note that at any point, the transformations on the stack to the return value form a projective linear transformation. So, in the assembly version, instead of maintaining a call stack, I maintain a 2x2 matrix representing the required projective linear transformation so far in registers `[r8 r9; r10 r11]`. Aside from that, and some usual optimizations, there was a folding of common code between the second and third cases: both involve taking the sum of the two columns of the transformation matrix. (However, I didn't make any effort to try different register allocations, and see if others might end up saving a couple bytes.) ]
[Question] [ [![In Dimensional Chess, every move is annotated '?!'.](https://i.stack.imgur.com/tQ23P.png)](https://i.stack.imgur.com/tQ23P.png) ## Task Any one of these two: * Determine if a given position (an ordered non-empty collection of integers in the range ‒8 to 8, or ‒7 to 7 if you want) is a valid [Dimensional Chess](https://www.explainxkcd.com/wiki/index.php/2465:_Dimensional_Chess) position. * List all the valid positions in any order. Make sure to describe your input (if not listing all) and output formats. The 2368 valid positions are (assuming 1-based enumeration of the first two dimensions): ``` 1,1;1,2;1,3;1,4;1,5;1,6;1,7;1,8;2,1,-3;2,1,-2;2,1,-1;2,1,0;2,1,1;2,1,2;2,1,3;2,2,-3;2,2,-2;2,2,-1;2,2,0;2,2,1;2,2,2;2,2,3;2,3,-3;2,3,-2;2,3,-1;2,3,0;2,3,1;2,3,2;2,3,3;2,4,-3;2,4,-2;2,4,-1;2,4,0;2,4,1;2,4,2;2,4,3;2,5,-3;2,5,-2;2,5,-1;2,5,0;2,5,1;2,5,2;2,5,3;2,6,-3;2,6,-2;2,6,-1;2,6,0;2,6,1;2,6,2;2,6,3;2,7,-3;2,7,-2;2,7,-1;2,7,0;2,7,1;2,7,2;2,7,3;2,8,-3;2,8,-2;2,8,-1;2,8,0;2,8,1;2,8,2;2,8,3;3,1,-3,-2;3,1,-3,-1;3,1,-3,0;3,1,-3,1;3,1,-3,2;3,1,-2,-2;3,1,-2,-1;3,1,-2,0;3,1,-2,1;3,1,-2,2;3,1,-1,-2;3,1,-1,-1;3,1,-1,0;3,1,-1,1;3,1,-1,2;3,1,0,-2;3,1,0,-1;3,1,0,0;3,1,0,1;3,1,0,2;3,1,1,-2;3,1,1,-1;3,1,1,0;3,1,1,1;3,1,1,2;3,1,2,-2;3,1,2,-1;3,1,2,0;3,1,2,1;3,1,2,2;3,1,3,-2;3,1,3,-1;3,1,3,0;3,1,3,1;3,1,3,2;3,2,-3,-2;3,2,-3,-1;3,2,-3,0;3,2,-3,1;3,2,-3,2;3,2,-2,-2;3,2,-2,-1;3,2,-2,0;3,2,-2,1;3,2,-2,2;3,2,-1,-2;3,2,-1,-1;3,2,-1,0;3,2,-1,1;3,2,-1,2;3,2,0,-2;3,2,0,-1;3,2,0,0;3,2,0,1;3,2,0,2;3,2,1,-2;3,2,1,-1;3,2,1,0;3,2,1,1;3,2,1,2;3,2,2,-2;3,2,2,-1;3,2,2,0;3,2,2,1;3,2,2,2;3,2,3,-2;3,2,3,-1;3,2,3,0;3,2,3,1;3,2,3,2;3,3,-3,-2;3,3,-3,-1;3,3,-3,0;3,3,-3,1;3,3,-3,2;3,3,-2,-2;3,3,-2,-1;3,3,-2,0;3,3,-2,1;3,3,-2,2;3,3,-1,-2;3,3,-1,-1;3,3,-1,0;3,3,-1,1;3,3,-1,2;3,3,0,-2;3,3,0,-1;3,3,0,0;3,3,0,1;3,3,0,2;3,3,1,-2;3,3,1,-1;3,3,1,0;3,3,1,1;3,3,1,2;3,3,2,-2;3,3,2,-1;3,3,2,0;3,3,2,1;3,3,2,2;3,3,3,-2;3,3,3,-1;3,3,3,0;3,3,3,1;3,3,3,2;3,4,-3,-2;3,4,-3,-1;3,4,-3,0;3,4,-3,1;3,4,-3,2;3,4,-2,-2;3,4,-2,-1;3,4,-2,0;3,4,-2,1;3,4,-2,2;3,4,-1,-2;3,4,-1,-1;3,4,-1,0;3,4,-1,1;3,4,-1,2;3,4,0,-2;3,4,0,-1;3,4,0,0;3,4,0,1;3,4,0,2;3,4,1,-2;3,4,1,-1;3,4,1,0;3,4,1,1;3,4,1,2;3,4,2,-2;3,4,2,-1;3,4,2,0;3,4,2,1;3,4,2,2;3,4,3,-2;3,4,3,-1;3,4,3,0;3,4,3,1;3,4,3,2;3,5,-3,-2;3,5,-3,-1;3,5,-3,0;3,5,-3,1;3,5,-3,2;3,5,-2,-2;3,5,-2,-1;3,5,-2,0;3,5,-2,1;3,5,-2,2;3,5,-1,-2;3,5,-1,-1;3,5,-1,0;3,5,-1,1;3,5,-1,2;3,5,0,-2;3,5,0,-1;3,5,0,0;3,5,0,1;3,5,0,2;3,5,1,-2;3,5,1,-1;3,5,1,0;3,5,1,1;3,5,1,2;3,5,2,-2;3,5,2,-1;3,5,2,0;3,5,2,1;3,5,2,2;3,5,3,-2;3,5,3,-1;3,5,3,0;3,5,3,1;3,5,3,2;3,6,-3,-2;3,6,-3,-1;3,6,-3,0;3,6,-3,1;3,6,-3,2;3,6,-2,-2;3,6,-2,-1;3,6,-2,0;3,6,-2,1;3,6,-2,2;3,6,-1,-2;3,6,-1,-1;3,6,-1,0;3,6,-1,1;3,6,-1,2;3,6,0,-2;3,6,0,-1;3,6,0,0;3,6,0,1;3,6,0,2;3,6,1,-2;3,6,1,-1;3,6,1,0;3,6,1,1;3,6,1,2;3,6,2,-2;3,6,2,-1;3,6,2,0;3,6,2,1;3,6,2,2;3,6,3,-2;3,6,3,-1;3,6,3,0;3,6,3,1;3,6,3,2;3,7,-3,-2;3,7,-3,-1;3,7,-3,0;3,7,-3,1;3,7,-3,2;3,7,-2,-2;3,7,-2,-1;3,7,-2,0;3,7,-2,1;3,7,-2,2;3,7,-1,-2;3,7,-1,-1;3,7,-1,0;3,7,-1,1;3,7,-1,2;3,7,0,-2;3,7,0,-1;3,7,0,0;3,7,0,1;3,7,0,2;3,7,1,-2;3,7,1,-1;3,7,1,0;3,7,1,1;3,7,1,2;3,7,2,-2;3,7,2,-1;3,7,2,0;3,7,2,1;3,7,2,2;3,7,3,-2;3,7,3,-1;3,7,3,0;3,7,3,1;3,7,3,2;3,8,-3,-2;3,8,-3,-1;3,8,-3,0;3,8,-3,1;3,8,-3,2;3,8,-2,-2;3,8,-2,-1;3,8,-2,0;3,8,-2,1;3,8,-2,2;3,8,-1,-2;3,8,-1,-1;3,8,-1,0;3,8,-1,1;3,8,-1,2;3,8,0,-2;3,8,0,-1;3,8,0,0;3,8,0,1;3,8,0,2;3,8,1,-2;3,8,1,-1;3,8,1,0;3,8,1,1;3,8,1,2;3,8,2,-2;3,8,2,-1;3,8,2,0;3,8,2,1;3,8,2,2;3,8,3,-2;3,8,3,-1;3,8,3,0;3,8,3,1;3,8,3,2;4,1,-3,-2,-1;4,1,-3,-2,0;4,1,-3,-2,1;4,1,-3,-1,-1;4,1,-3,-1,0;4,1,-3,-1,1;4,1,-3,0,-1;4,1,-3,0,0;4,1,-3,0,1;4,1,-3,1,-1;4,1,-3,1,0;4,1,-3,1,1;4,1,-3,2,-1;4,1,-3,2,0;4,1,-3,2,1;4,1,-2,-2,-1;4,1,-2,-2,0;4,1,-2,-2,1;4,1,-2,-1,-1;4,1,-2,-1,0;4,1,-2,-1,1;4,1,-2,0,-1;4,1,-2,0,0;4,1,-2,0,1;4,1,-2,1,-1;4,1,-2,1,0;4,1,-2,1,1;4,1,-2,2,-1;4,1,-2,2,0;4,1,-2,2,1;4,1,-1,-2,-1;4,1,-1,-2,0;4,1,-1,-2,1;4,1,-1,-1,-1;4,1,-1,-1,0;4,1,-1,-1,1;4,1,-1,0,-1;4,1,-1,0,0;4,1,-1,0,1;4,1,-1,1,-1;4,1,-1,1,0;4,1,-1,1,1;4,1,-1,2,-1;4,1,-1,2,0;4,1,-1,2,1;4,1,0,-2,-1;4,1,0,-2,0;4,1,0,-2,1;4,1,0,-1,-1;4,1,0,-1,0;4,1,0,-1,1;4,1,0,0,-1;4,1,0,0,0;4,1,0,0,1;4,1,0,1,-1;4,1,0,1,0;4,1,0,1,1;4,1,0,2,-1;4,1,0,2,0;4,1,0,2,1;4,1,1,-2,-1;4,1,1,-2,0;4,1,1,-2,1;4,1,1,-1,-1;4,1,1,-1,0;4,1,1,-1,1;4,1,1,0,-1;4,1,1,0,0;4,1,1,0,1;4,1,1,1,-1;4,1,1,1,0;4,1,1,1,1;4,1,1,2,-1;4,1,1,2,0;4,1,1,2,1;4,1,2,-2,-1;4,1,2,-2,0;4,1,2,-2,1;4,1,2,-1,-1;4,1,2,-1,0;4,1,2,-1,1;4,1,2,0,-1;4,1,2,0,0;4,1,2,0,1;4,1,2,1,-1;4,1,2,1,0;4,1,2,1,1;4,1,2,2,-1;4,1,2,2,0;4,1,2,2,1;4,1,3,-2,-1;4,1,3,-2,0;4,1,3,-2,1;4,1,3,-1,-1;4,1,3,-1,0;4,1,3,-1,1;4,1,3,0,-1;4,1,3,0,0;4,1,3,0,1;4,1,3,1,-1;4,1,3,1,0;4,1,3,1,1;4,1,3,2,-1;4,1,3,2,0;4,1,3,2,1;4,2,-3,-2,-1;4,2,-3,-2,0;4,2,-3,-2,1;4,2,-3,-1,-1;4,2,-3,-1,0;4,2,-3,-1,1;4,2,-3,0,-1;4,2,-3,0,0;4,2,-3,0,1;4,2,-3,1,-1;4,2,-3,1,0;4,2,-3,1,1;4,2,-3,2,-1;4,2,-3,2,0;4,2,-3,2,1;4,2,-2,-2,-1;4,2,-2,-2,0;4,2,-2,-2,1;4,2,-2,-1,-1;4,2,-2,-1,0;4,2,-2,-1,1;4,2,-2,0,-1;4,2,-2,0,0;4,2,-2,0,1;4,2,-2,1,-1;4,2,-2,1,0;4,2,-2,1,1;4,2,-2,2,-1;4,2,-2,2,0;4,2,-2,2,1;4,2,-1,-2,-1;4,2,-1,-2,0;4,2,-1,-2,1;4,2,-1,-1,-1;4,2,-1,-1,0;4,2,-1,-1,1;4,2,-1,0,-1;4,2,-1,0,0;4,2,-1,0,1;4,2,-1,1,-1;4,2,-1,1,0;4,2,-1,1,1;4,2,-1,2,-1;4,2,-1,2,0;4,2,-1,2,1;4,2,0,-2,-1;4,2,0,-2,0;4,2,0,-2,1;4,2,0,-1,-1;4,2,0,-1,0;4,2,0,-1,1;4,2,0,0,-1;4,2,0,0,0;4,2,0,0,1;4,2,0,1,-1;4,2,0,1,0;4,2,0,1,1;4,2,0,2,-1;4,2,0,2,0;4,2,0,2,1;4,2,1,-2,-1;4,2,1,-2,0;4,2,1,-2,1;4,2,1,-1,-1;4,2,1,-1,0;4,2,1,-1,1;4,2,1,0,-1;4,2,1,0,0;4,2,1,0,1;4,2,1,1,-1;4,2,1,1,0;4,2,1,1,1;4,2,1,2,-1;4,2,1,2,0;4,2,1,2,1;4,2,2,-2,-1;4,2,2,-2,0;4,2,2,-2,1;4,2,2,-1,-1;4,2,2,-1,0;4,2,2,-1,1;4,2,2,0,-1;4,2,2,0,0;4,2,2,0,1;4,2,2,1,-1;4,2,2,1,0;4,2,2,1,1;4,2,2,2,-1;4,2,2,2,0;4,2,2,2,1;4,2,3,-2,-1;4,2,3,-2,0;4,2,3,-2,1;4,2,3,-1,-1;4,2,3,-1,0;4,2,3,-1,1;4,2,3,0,-1;4,2,3,0,0;4,2,3,0,1;4,2,3,1,-1;4,2,3,1,0;4,2,3,1,1;4,2,3,2,-1;4,2,3,2,0;4,2,3,2,1;4,3,-3,-2,-1;4,3,-3,-2,0;4,3,-3,-2,1;4,3,-3,-1,-1;4,3,-3,-1,0;4,3,-3,-1,1;4,3,-3,0,-1;4,3,-3,0,0;4,3,-3,0,1;4,3,-3,1,-1;4,3,-3,1,0;4,3,-3,1,1;4,3,-3,2,-1;4,3,-3,2,0;4,3,-3,2,1;4,3,-2,-2,-1;4,3,-2,-2,0;4,3,-2,-2,1;4,3,-2,-1,-1;4,3,-2,-1,0;4,3,-2,-1,1;4,3,-2,0,-1;4,3,-2,0,0;4,3,-2,0,1;4,3,-2,1,-1;4,3,-2,1,0;4,3,-2,1,1;4,3,-2,2,-1;4,3,-2,2,0;4,3,-2,2,1;4,3,-1,-2,-1;4,3,-1,-2,0;4,3,-1,-2,1;4,3,-1,-1,-1;4,3,-1,-1,0;4,3,-1,-1,1;4,3,-1,0,-1;4,3,-1,0,0;4,3,-1,0,1;4,3,-1,1,-1;4,3,-1,1,0;4,3,-1,1,1;4,3,-1,2,-1;4,3,-1,2,0;4,3,-1,2,1;4,3,0,-2,-1;4,3,0,-2,0;4,3,0,-2,1;4,3,0,-1,-1;4,3,0,-1,0;4,3,0,-1,1;4,3,0,0,-1;4,3,0,0,0;4,3,0,0,1;4,3,0,1,-1;4,3,0,1,0;4,3,0,1,1;4,3,0,2,-1;4,3,0,2,0;4,3,0,2,1;4,3,1,-2,-1;4,3,1,-2,0;4,3,1,-2,1;4,3,1,-1,-1;4,3,1,-1,0;4,3,1,-1,1;4,3,1,0,-1;4,3,1,0,0;4,3,1,0,1;4,3,1,1,-1;4,3,1,1,0;4,3,1,1,1;4,3,1,2,-1;4,3,1,2,0;4,3,1,2,1;4,3,2,-2,-1;4,3,2,-2,0;4,3,2,-2,1;4,3,2,-1,-1;4,3,2,-1,0;4,3,2,-1,1;4,3,2,0,-1;4,3,2,0,0;4,3,2,0,1;4,3,2,1,-1;4,3,2,1,0;4,3,2,1,1;4,3,2,2,-1;4,3,2,2,0;4,3,2,2,1;4,3,3,-2,-1;4,3,3,-2,0;4,3,3,-2,1;4,3,3,-1,-1;4,3,3,-1,0;4,3,3,-1,1;4,3,3,0,-1;4,3,3,0,0;4,3,3,0,1;4,3,3,1,-1;4,3,3,1,0;4,3,3,1,1;4,3,3,2,-1;4,3,3,2,0;4,3,3,2,1;4,4,-3,-2,-1;4,4,-3,-2,0;4,4,-3,-2,1;4,4,-3,-1,-1;4,4,-3,-1,0;4,4,-3,-1,1;4,4,-3,0,-1;4,4,-3,0,0;4,4,-3,0,1;4,4,-3,1,-1;4,4,-3,1,0;4,4,-3,1,1;4,4,-3,2,-1;4,4,-3,2,0;4,4,-3,2,1;4,4,-2,-2,-1;4,4,-2,-2,0;4,4,-2,-2,1;4,4,-2,-1,-1;4,4,-2,-1,0;4,4,-2,-1,1;4,4,-2,0,-1;4,4,-2,0,0;4,4,-2,0,1;4,4,-2,1,-1;4,4,-2,1,0;4,4,-2,1,1;4,4,-2,2,-1;4,4,-2,2,0;4,4,-2,2,1;4,4,-1,-2,-1;4,4,-1,-2,0;4,4,-1,-2,1;4,4,-1,-1,-1;4,4,-1,-1,0;4,4,-1,-1,1;4,4,-1,0,-1;4,4,-1,0,0;4,4,-1,0,1;4,4,-1,1,-1;4,4,-1,1,0;4,4,-1,1,1;4,4,-1,2,-1;4,4,-1,2,0;4,4,-1,2,1;4,4,0,-2,-1;4,4,0,-2,0;4,4,0,-2,1;4,4,0,-1,-1;4,4,0,-1,0;4,4,0,-1,1;4,4,0,0,-1;4,4,0,0,0;4,4,0,0,1;4,4,0,1,-1;4,4,0,1,0;4,4,0,1,1;4,4,0,2,-1;4,4,0,2,0;4,4,0,2,1;4,4,1,-2,-1;4,4,1,-2,0;4,4,1,-2,1;4,4,1,-1,-1;4,4,1,-1,0;4,4,1,-1,1;4,4,1,0,-1;4,4,1,0,0;4,4,1,0,1;4,4,1,1,-1;4,4,1,1,0;4,4,1,1,1;4,4,1,2,-1;4,4,1,2,0;4,4,1,2,1;4,4,2,-2,-1;4,4,2,-2,0;4,4,2,-2,1;4,4,2,-1,-1;4,4,2,-1,0;4,4,2,-1,1;4,4,2,0,-1;4,4,2,0,0;4,4,2,0,1;4,4,2,1,-1;4,4,2,1,0;4,4,2,1,1;4,4,2,2,-1;4,4,2,2,0;4,4,2,2,1;4,4,3,-2,-1;4,4,3,-2,0;4,4,3,-2,1;4,4,3,-1,-1;4,4,3,-1,0;4,4,3,-1,1;4,4,3,0,-1;4,4,3,0,0;4,4,3,0,1;4,4,3,1,-1;4,4,3,1,0;4,4,3,1,1;4,4,3,2,-1;4,4,3,2,0;4,4,3,2,1;4,5,-3,-2,-1;4,5,-3,-2,0;4,5,-3,-2,1;4,5,-3,-1,-1;4,5,-3,-1,0;4,5,-3,-1,1;4,5,-3,0,-1;4,5,-3,0,0;4,5,-3,0,1;4,5,-3,1,-1;4,5,-3,1,0;4,5,-3,1,1;4,5,-3,2,-1;4,5,-3,2,0;4,5,-3,2,1;4,5,-2,-2,-1;4,5,-2,-2,0;4,5,-2,-2,1;4,5,-2,-1,-1;4,5,-2,-1,0;4,5,-2,-1,1;4,5,-2,0,-1;4,5,-2,0,0;4,5,-2,0,1;4,5,-2,1,-1;4,5,-2,1,0;4,5,-2,1,1;4,5,-2,2,-1;4,5,-2,2,0;4,5,-2,2,1;4,5,-1,-2,-1;4,5,-1,-2,0;4,5,-1,-2,1;4,5,-1,-1,-1;4,5,-1,-1,0;4,5,-1,-1,1;4,5,-1,0,-1;4,5,-1,0,0;4,5,-1,0,1;4,5,-1,1,-1;4,5,-1,1,0;4,5,-1,1,1;4,5,-1,2,-1;4,5,-1,2,0;4,5,-1,2,1;4,5,0,-2,-1;4,5,0,-2,0;4,5,0,-2,1;4,5,0,-1,-1;4,5,0,-1,0;4,5,0,-1,1;4,5,0,0,-1;4,5,0,0,0;4,5,0,0,1;4,5,0,1,-1;4,5,0,1,0;4,5,0,1,1;4,5,0,2,-1;4,5,0,2,0;4,5,0,2,1;4,5,1,-2,-1;4,5,1,-2,0;4,5,1,-2,1;4,5,1,-1,-1;4,5,1,-1,0;4,5,1,-1,1;4,5,1,0,-1;4,5,1,0,0;4,5,1,0,1;4,5,1,1,-1;4,5,1,1,0;4,5,1,1,1;4,5,1,2,-1;4,5,1,2,0;4,5,1,2,1;4,5,2,-2,-1;4,5,2,-2,0;4,5,2,-2,1;4,5,2,-1,-1;4,5,2,-1,0;4,5,2,-1,1;4,5,2,0,-1;4,5,2,0,0;4,5,2,0,1;4,5,2,1,-1;4,5,2,1,0;4,5,2,1,1;4,5,2,2,-1;4,5,2,2,0;4,5,2,2,1;4,5,3,-2,-1;4,5,3,-2,0;4,5,3,-2,1;4,5,3,-1,-1;4,5,3,-1,0;4,5,3,-1,1;4,5,3,0,-1;4,5,3,0,0;4,5,3,0,1;4,5,3,1,-1;4,5,3,1,0;4,5,3,1,1;4,5,3,2,-1;4,5,3,2,0;4,5,3,2,1;4,6,-3,-2,-1;4,6,-3,-2,0;4,6,-3,-2,1;4,6,-3,-1,-1;4,6,-3,-1,0;4,6,-3,-1,1;4,6,-3,0,-1;4,6,-3,0,0;4,6,-3,0,1;4,6,-3,1,-1;4,6,-3,1,0;4,6,-3,1,1;4,6,-3,2,-1;4,6,-3,2,0;4,6,-3,2,1;4,6,-2,-2,-1;4,6,-2,-2,0;4,6,-2,-2,1;4,6,-2,-1,-1;4,6,-2,-1,0;4,6,-2,-1,1;4,6,-2,0,-1;4,6,-2,0,0;4,6,-2,0,1;4,6,-2,1,-1;4,6,-2,1,0;4,6,-2,1,1;4,6,-2,2,-1;4,6,-2,2,0;4,6,-2,2,1;4,6,-1,-2,-1;4,6,-1,-2,0;4,6,-1,-2,1;4,6,-1,-1,-1;4,6,-1,-1,0;4,6,-1,-1,1;4,6,-1,0,-1;4,6,-1,0,0;4,6,-1,0,1;4,6,-1,1,-1;4,6,-1,1,0;4,6,-1,1,1;4,6,-1,2,-1;4,6,-1,2,0;4,6,-1,2,1;4,6,0,-2,-1;4,6,0,-2,0;4,6,0,-2,1;4,6,0,-1,-1;4,6,0,-1,0;4,6,0,-1,1;4,6,0,0,-1;4,6,0,0,0;4,6,0,0,1;4,6,0,1,-1;4,6,0,1,0;4,6,0,1,1;4,6,0,2,-1;4,6,0,2,0;4,6,0,2,1;4,6,1,-2,-1;4,6,1,-2,0;4,6,1,-2,1;4,6,1,-1,-1;4,6,1,-1,0;4,6,1,-1,1;4,6,1,0,-1;4,6,1,0,0;4,6,1,0,1;4,6,1,1,-1;4,6,1,1,0;4,6,1,1,1;4,6,1,2,-1;4,6,1,2,0;4,6,1,2,1;4,6,2,-2,-1;4,6,2,-2,0;4,6,2,-2,1;4,6,2,-1,-1;4,6,2,-1,0;4,6,2,-1,1;4,6,2,0,-1;4,6,2,0,0;4,6,2,0,1;4,6,2,1,-1;4,6,2,1,0;4,6,2,1,1;4,6,2,2,-1;4,6,2,2,0;4,6,2,2,1;4,6,3,-2,-1;4,6,3,-2,0;4,6,3,-2,1;4,6,3,-1,-1;4,6,3,-1,0;4,6,3,-1,1;4,6,3,0,-1;4,6,3,0,0;4,6,3,0,1;4,6,3,1,-1;4,6,3,1,0;4,6,3,1,1;4,6,3,2,-1;4,6,3,2,0;4,6,3,2,1;4,7,-3,-2,-1;4,7,-3,-2,0;4,7,-3,-2,1;4,7,-3,-1,-1;4,7,-3,-1,0;4,7,-3,-1,1;4,7,-3,0,-1;4,7,-3,0,0;4,7,-3,0,1;4,7,-3,1,-1;4,7,-3,1,0;4,7,-3,1,1;4,7,-3,2,-1;4,7,-3,2,0;4,7,-3,2,1;4,7,-2,-2,-1;4,7,-2,-2,0;4,7,-2,-2,1;4,7,-2,-1,-1;4,7,-2,-1,0;4,7,-2,-1,1;4,7,-2,0,-1;4,7,-2,0,0;4,7,-2,0,1;4,7,-2,1,-1;4,7,-2,1,0;4,7,-2,1,1;4,7,-2,2,-1;4,7,-2,2,0;4,7,-2,2,1;4,7,-1,-2,-1;4,7,-1,-2,0;4,7,-1,-2,1;4,7,-1,-1,-1;4,7,-1,-1,0;4,7,-1,-1,1;4,7,-1,0,-1;4,7,-1,0,0;4,7,-1,0,1;4,7,-1,1,-1;4,7,-1,1,0;4,7,-1,1,1;4,7,-1,2,-1;4,7,-1,2,0;4,7,-1,2,1;4,7,0,-2,-1;4,7,0,-2,0;4,7,0,-2,1;4,7,0,-1,-1;4,7,0,-1,0;4,7,0,-1,1;4,7,0,0,-1;4,7,0,0,0;4,7,0,0,1;4,7,0,1,-1;4,7,0,1,0;4,7,0,1,1;4,7,0,2,-1;4,7,0,2,0;4,7,0,2,1;4,7,1,-2,-1;4,7,1,-2,0;4,7,1,-2,1;4,7,1,-1,-1;4,7,1,-1,0;4,7,1,-1,1;4,7,1,0,-1;4,7,1,0,0;4,7,1,0,1;4,7,1,1,-1;4,7,1,1,0;4,7,1,1,1;4,7,1,2,-1;4,7,1,2,0;4,7,1,2,1;4,7,2,-2,-1;4,7,2,-2,0;4,7,2,-2,1;4,7,2,-1,-1;4,7,2,-1,0;4,7,2,-1,1;4,7,2,0,-1;4,7,2,0,0;4,7,2,0,1;4,7,2,1,-1;4,7,2,1,0;4,7,2,1,1;4,7,2,2,-1;4,7,2,2,0;4,7,2,2,1;4,7,3,-2,-1;4,7,3,-2,0;4,7,3,-2,1;4,7,3,-1,-1;4,7,3,-1,0;4,7,3,-1,1;4,7,3,0,-1;4,7,3,0,0;4,7,3,0,1;4,7,3,1,-1;4,7,3,1,0;4,7,3,1,1;4,7,3,2,-1;4,7,3,2,0;4,7,3,2,1;4,8,-3,-2,-1;4,8,-3,-2,0;4,8,-3,-2,1;4,8,-3,-1,-1;4,8,-3,-1,0;4,8,-3,-1,1;4,8,-3,0,-1;4,8,-3,0,0;4,8,-3,0,1;4,8,-3,1,-1;4,8,-3,1,0;4,8,-3,1,1;4,8,-3,2,-1;4,8,-3,2,0;4,8,-3,2,1;4,8,-2,-2,-1;4,8,-2,-2,0;4,8,-2,-2,1;4,8,-2,-1,-1;4,8,-2,-1,0;4,8,-2,-1,1;4,8,-2,0,-1;4,8,-2,0,0;4,8,-2,0,1;4,8,-2,1,-1;4,8,-2,1,0;4,8,-2,1,1;4,8,-2,2,-1;4,8,-2,2,0;4,8,-2,2,1;4,8,-1,-2,-1;4,8,-1,-2,0;4,8,-1,-2,1;4,8,-1,-1,-1;4,8,-1,-1,0;4,8,-1,-1,1;4,8,-1,0,-1;4,8,-1,0,0;4,8,-1,0,1;4,8,-1,1,-1;4,8,-1,1,0;4,8,-1,1,1;4,8,-1,2,-1;4,8,-1,2,0;4,8,-1,2,1;4,8,0,-2,-1;4,8,0,-2,0;4,8,0,-2,1;4,8,0,-1,-1;4,8,0,-1,0;4,8,0,-1,1;4,8,0,0,-1;4,8,0,0,0;4,8,0,0,1;4,8,0,1,-1;4,8,0,1,0;4,8,0,1,1;4,8,0,2,-1;4,8,0,2,0;4,8,0,2,1;4,8,1,-2,-1;4,8,1,-2,0;4,8,1,-2,1;4,8,1,-1,-1;4,8,1,-1,0;4,8,1,-1,1;4,8,1,0,-1;4,8,1,0,0;4,8,1,0,1;4,8,1,1,-1;4,8,1,1,0;4,8,1,1,1;4,8,1,2,-1;4,8,1,2,0;4,8,1,2,1;4,8,2,-2,-1;4,8,2,-2,0;4,8,2,-2,1;4,8,2,-1,-1;4,8,2,-1,0;4,8,2,-1,1;4,8,2,0,-1;4,8,2,0,0;4,8,2,0,1;4,8,2,1,-1;4,8,2,1,0;4,8,2,1,1;4,8,2,2,-1;4,8,2,2,0;4,8,2,2,1;4,8,3,-2,-1;4,8,3,-2,0;4,8,3,-2,1;4,8,3,-1,-1;4,8,3,-1,0;4,8,3,-1,1;4,8,3,0,-1;4,8,3,0,0;4,8,3,0,1;4,8,3,1,-1;4,8,3,1,0;4,8,3,1,1;4,8,3,2,-1;4,8,3,2,0;4,8,3,2,1;5,1,-3,-2,-1;5,1,-3,-2,0;5,1,-3,-2,1;5,1,-3,-1,-1;5,1,-3,-1,0;5,1,-3,-1,1;5,1,-3,0,-1;5,1,-3,0,0;5,1,-3,0,1;5,1,-3,1,-1;5,1,-3,1,0;5,1,-3,1,1;5,1,-3,2,-1;5,1,-3,2,0;5,1,-3,2,1;5,1,-2,-2,-1;5,1,-2,-2,0;5,1,-2,-2,1;5,1,-2,-1,-1;5,1,-2,-1,0;5,1,-2,-1,1;5,1,-2,0,-1;5,1,-2,0,0;5,1,-2,0,1;5,1,-2,1,-1;5,1,-2,1,0;5,1,-2,1,1;5,1,-2,2,-1;5,1,-2,2,0;5,1,-2,2,1;5,1,-1,-2,-1;5,1,-1,-2,0;5,1,-1,-2,1;5,1,-1,-1,-1;5,1,-1,-1,0;5,1,-1,-1,1;5,1,-1,0,-1;5,1,-1,0,0;5,1,-1,0,1;5,1,-1,1,-1;5,1,-1,1,0;5,1,-1,1,1;5,1,-1,2,-1;5,1,-1,2,0;5,1,-1,2,1;5,1,0,-2,-1;5,1,0,-2,0;5,1,0,-2,1;5,1,0,-1,-1;5,1,0,-1,0;5,1,0,-1,1;5,1,0,0,-1;5,1,0,0,0;5,1,0,0,1;5,1,0,1,-1;5,1,0,1,0;5,1,0,1,1;5,1,0,2,-1;5,1,0,2,0;5,1,0,2,1;5,1,1,-2,-1;5,1,1,-2,0;5,1,1,-2,1;5,1,1,-1,-1;5,1,1,-1,0;5,1,1,-1,1;5,1,1,0,-1;5,1,1,0,0;5,1,1,0,1;5,1,1,1,-1;5,1,1,1,0;5,1,1,1,1;5,1,1,2,-1;5,1,1,2,0;5,1,1,2,1;5,1,2,-2,-1;5,1,2,-2,0;5,1,2,-2,1;5,1,2,-1,-1;5,1,2,-1,0;5,1,2,-1,1;5,1,2,0,-1;5,1,2,0,0;5,1,2,0,1;5,1,2,1,-1;5,1,2,1,0;5,1,2,1,1;5,1,2,2,-1;5,1,2,2,0;5,1,2,2,1;5,1,3,-2,-1;5,1,3,-2,0;5,1,3,-2,1;5,1,3,-1,-1;5,1,3,-1,0;5,1,3,-1,1;5,1,3,0,-1;5,1,3,0,0;5,1,3,0,1;5,1,3,1,-1;5,1,3,1,0;5,1,3,1,1;5,1,3,2,-1;5,1,3,2,0;5,1,3,2,1;5,2,-3,-2,-1;5,2,-3,-2,0;5,2,-3,-2,1;5,2,-3,-1,-1;5,2,-3,-1,0;5,2,-3,-1,1;5,2,-3,0,-1;5,2,-3,0,0;5,2,-3,0,1;5,2,-3,1,-1;5,2,-3,1,0;5,2,-3,1,1;5,2,-3,2,-1;5,2,-3,2,0;5,2,-3,2,1;5,2,-2,-2,-1;5,2,-2,-2,0;5,2,-2,-2,1;5,2,-2,-1,-1;5,2,-2,-1,0;5,2,-2,-1,1;5,2,-2,0,-1;5,2,-2,0,0;5,2,-2,0,1;5,2,-2,1,-1;5,2,-2,1,0;5,2,-2,1,1;5,2,-2,2,-1;5,2,-2,2,0;5,2,-2,2,1;5,2,-1,-2,-1;5,2,-1,-2,0;5,2,-1,-2,1;5,2,-1,-1,-1;5,2,-1,-1,0;5,2,-1,-1,1;5,2,-1,0,-1;5,2,-1,0,0;5,2,-1,0,1;5,2,-1,1,-1;5,2,-1,1,0;5,2,-1,1,1;5,2,-1,2,-1;5,2,-1,2,0;5,2,-1,2,1;5,2,0,-2,-1;5,2,0,-2,0;5,2,0,-2,1;5,2,0,-1,-1;5,2,0,-1,0;5,2,0,-1,1;5,2,0,0,-1;5,2,0,0,0;5,2,0,0,1;5,2,0,1,-1;5,2,0,1,0;5,2,0,1,1;5,2,0,2,-1;5,2,0,2,0;5,2,0,2,1;5,2,1,-2,-1;5,2,1,-2,0;5,2,1,-2,1;5,2,1,-1,-1;5,2,1,-1,0;5,2,1,-1,1;5,2,1,0,-1;5,2,1,0,0;5,2,1,0,1;5,2,1,1,-1;5,2,1,1,0;5,2,1,1,1;5,2,1,2,-1;5,2,1,2,0;5,2,1,2,1;5,2,2,-2,-1;5,2,2,-2,0;5,2,2,-2,1;5,2,2,-1,-1;5,2,2,-1,0;5,2,2,-1,1;5,2,2,0,-1;5,2,2,0,0;5,2,2,0,1;5,2,2,1,-1;5,2,2,1,0;5,2,2,1,1;5,2,2,2,-1;5,2,2,2,0;5,2,2,2,1;5,2,3,-2,-1;5,2,3,-2,0;5,2,3,-2,1;5,2,3,-1,-1;5,2,3,-1,0;5,2,3,-1,1;5,2,3,0,-1;5,2,3,0,0;5,2,3,0,1;5,2,3,1,-1;5,2,3,1,0;5,2,3,1,1;5,2,3,2,-1;5,2,3,2,0;5,2,3,2,1;5,3,-3,-2,-1;5,3,-3,-2,0;5,3,-3,-2,1;5,3,-3,-1,-1;5,3,-3,-1,0;5,3,-3,-1,1;5,3,-3,0,-1;5,3,-3,0,0;5,3,-3,0,1;5,3,-3,1,-1;5,3,-3,1,0;5,3,-3,1,1;5,3,-3,2,-1;5,3,-3,2,0;5,3,-3,2,1;5,3,-2,-2,-1;5,3,-2,-2,0;5,3,-2,-2,1;5,3,-2,-1,-1;5,3,-2,-1,0;5,3,-2,-1,1;5,3,-2,0,-1;5,3,-2,0,0;5,3,-2,0,1;5,3,-2,1,-1;5,3,-2,1,0;5,3,-2,1,1;5,3,-2,2,-1;5,3,-2,2,0;5,3,-2,2,1;5,3,-1,-2,-1;5,3,-1,-2,0;5,3,-1,-2,1;5,3,-1,-1,-1;5,3,-1,-1,0;5,3,-1,-1,1;5,3,-1,0,-1;5,3,-1,0,0;5,3,-1,0,1;5,3,-1,1,-1;5,3,-1,1,0;5,3,-1,1,1;5,3,-1,2,-1;5,3,-1,2,0;5,3,-1,2,1;5,3,0,-2,-1;5,3,0,-2,0;5,3,0,-2,1;5,3,0,-1,-1;5,3,0,-1,0;5,3,0,-1,1;5,3,0,0,-1;5,3,0,0,0;5,3,0,0,1;5,3,0,1,-1;5,3,0,1,0;5,3,0,1,1;5,3,0,2,-1;5,3,0,2,0;5,3,0,2,1;5,3,1,-2,-1;5,3,1,-2,0;5,3,1,-2,1;5,3,1,-1,-1;5,3,1,-1,0;5,3,1,-1,1;5,3,1,0,-1;5,3,1,0,0;5,3,1,0,1;5,3,1,1,-1;5,3,1,1,0;5,3,1,1,1;5,3,1,2,-1;5,3,1,2,0;5,3,1,2,1;5,3,2,-2,-1;5,3,2,-2,0;5,3,2,-2,1;5,3,2,-1,-1;5,3,2,-1,0;5,3,2,-1,1;5,3,2,0,-1;5,3,2,0,0;5,3,2,0,1;5,3,2,1,-1;5,3,2,1,0;5,3,2,1,1;5,3,2,2,-1;5,3,2,2,0;5,3,2,2,1;5,3,3,-2,-1;5,3,3,-2,0;5,3,3,-2,1;5,3,3,-1,-1;5,3,3,-1,0;5,3,3,-1,1;5,3,3,0,-1;5,3,3,0,0;5,3,3,0,1;5,3,3,1,-1;5,3,3,1,0;5,3,3,1,1;5,3,3,2,-1;5,3,3,2,0;5,3,3,2,1;5,4,-3,-2,-1;5,4,-3,-2,0;5,4,-3,-2,1;5,4,-3,-1,-1;5,4,-3,-1,0;5,4,-3,-1,1;5,4,-3,0,-1;5,4,-3,0,0;5,4,-3,0,1;5,4,-3,1,-1;5,4,-3,1,0;5,4,-3,1,1;5,4,-3,2,-1;5,4,-3,2,0;5,4,-3,2,1;5,4,-2,-2,-1;5,4,-2,-2,0;5,4,-2,-2,1;5,4,-2,-1,-1;5,4,-2,-1,0;5,4,-2,-1,1;5,4,-2,0,-1;5,4,-2,0,0;5,4,-2,0,1;5,4,-2,1,-1;5,4,-2,1,0;5,4,-2,1,1;5,4,-2,2,-1;5,4,-2,2,0;5,4,-2,2,1;5,4,-1,-2,-1;5,4,-1,-2,0;5,4,-1,-2,1;5,4,-1,-1,-1;5,4,-1,-1,0;5,4,-1,-1,1;5,4,-1,0,-1;5,4,-1,0,0;5,4,-1,0,1;5,4,-1,1,-1;5,4,-1,1,0;5,4,-1,1,1;5,4,-1,2,-1;5,4,-1,2,0;5,4,-1,2,1;5,4,0,-2,-1;5,4,0,-2,0;5,4,0,-2,1;5,4,0,-1,-1;5,4,0,-1,0;5,4,0,-1,1;5,4,0,0,-1;5,4,0,0,0;5,4,0,0,1;5,4,0,1,-1;5,4,0,1,0;5,4,0,1,1;5,4,0,2,-1;5,4,0,2,0;5,4,0,2,1;5,4,1,-2,-1;5,4,1,-2,0;5,4,1,-2,1;5,4,1,-1,-1;5,4,1,-1,0;5,4,1,-1,1;5,4,1,0,-1;5,4,1,0,0;5,4,1,0,1;5,4,1,1,-1;5,4,1,1,0;5,4,1,1,1;5,4,1,2,-1;5,4,1,2,0;5,4,1,2,1;5,4,2,-2,-1;5,4,2,-2,0;5,4,2,-2,1;5,4,2,-1,-1;5,4,2,-1,0;5,4,2,-1,1;5,4,2,0,-1;5,4,2,0,0;5,4,2,0,1;5,4,2,1,-1;5,4,2,1,0;5,4,2,1,1;5,4,2,2,-1;5,4,2,2,0;5,4,2,2,1;5,4,3,-2,-1;5,4,3,-2,0;5,4,3,-2,1;5,4,3,-1,-1;5,4,3,-1,0;5,4,3,-1,1;5,4,3,0,-1;5,4,3,0,0;5,4,3,0,1;5,4,3,1,-1;5,4,3,1,0;5,4,3,1,1;5,4,3,2,-1;5,4,3,2,0;5,4,3,2,1;5,5,-3,-2,-1;5,5,-3,-2,0;5,5,-3,-2,1;5,5,-3,-1,-1;5,5,-3,-1,0;5,5,-3,-1,1;5,5,-3,0,-1;5,5,-3,0,0;5,5,-3,0,1;5,5,-3,1,-1;5,5,-3,1,0;5,5,-3,1,1;5,5,-3,2,-1;5,5,-3,2,0;5,5,-3,2,1;5,5,-2,-2,-1;5,5,-2,-2,0;5,5,-2,-2,1;5,5,-2,-1,-1;5,5,-2,-1,0;5,5,-2,-1,1;5,5,-2,0,-1;5,5,-2,0,0;5,5,-2,0,1;5,5,-2,1,-1;5,5,-2,1,0;5,5,-2,1,1;5,5,-2,2,-1;5,5,-2,2,0;5,5,-2,2,1;5,5,-1,-2,-1;5,5,-1,-2,0;5,5,-1,-2,1;5,5,-1,-1,-1;5,5,-1,-1,0;5,5,-1,-1,1;5,5,-1,0,-1;5,5,-1,0,0;5,5,-1,0,1;5,5,-1,1,-1;5,5,-1,1,0;5,5,-1,1,1;5,5,-1,2,-1;5,5,-1,2,0;5,5,-1,2,1;5,5,0,-2,-1;5,5,0,-2,0;5,5,0,-2,1;5,5,0,-1,-1;5,5,0,-1,0;5,5,0,-1,1;5,5,0,0,-1;5,5,0,0,0;5,5,0,0,1;5,5,0,1,-1;5,5,0,1,0;5,5,0,1,1;5,5,0,2,-1;5,5,0,2,0;5,5,0,2,1;5,5,1,-2,-1;5,5,1,-2,0;5,5,1,-2,1;5,5,1,-1,-1;5,5,1,-1,0;5,5,1,-1,1;5,5,1,0,-1;5,5,1,0,0;5,5,1,0,1;5,5,1,1,-1;5,5,1,1,0;5,5,1,1,1;5,5,1,2,-1;5,5,1,2,0;5,5,1,2,1;5,5,2,-2,-1;5,5,2,-2,0;5,5,2,-2,1;5,5,2,-1,-1;5,5,2,-1,0;5,5,2,-1,1;5,5,2,0,-1;5,5,2,0,0;5,5,2,0,1;5,5,2,1,-1;5,5,2,1,0;5,5,2,1,1;5,5,2,2,-1;5,5,2,2,0;5,5,2,2,1;5,5,3,-2,-1;5,5,3,-2,0;5,5,3,-2,1;5,5,3,-1,-1;5,5,3,-1,0;5,5,3,-1,1;5,5,3,0,-1;5,5,3,0,0;5,5,3,0,1;5,5,3,1,-1;5,5,3,1,0;5,5,3,1,1;5,5,3,2,-1;5,5,3,2,0;5,5,3,2,1;5,6,-3,-2,-1;5,6,-3,-2,0;5,6,-3,-2,1;5,6,-3,-1,-1;5,6,-3,-1,0;5,6,-3,-1,1;5,6,-3,0,-1;5,6,-3,0,0;5,6,-3,0,1;5,6,-3,1,-1;5,6,-3,1,0;5,6,-3,1,1;5,6,-3,2,-1;5,6,-3,2,0;5,6,-3,2,1;5,6,-2,-2,-1;5,6,-2,-2,0;5,6,-2,-2,1;5,6,-2,-1,-1;5,6,-2,-1,0;5,6,-2,-1,1;5,6,-2,0,-1;5,6,-2,0,0;5,6,-2,0,1;5,6,-2,1,-1;5,6,-2,1,0;5,6,-2,1,1;5,6,-2,2,-1;5,6,-2,2,0;5,6,-2,2,1;5,6,-1,-2,-1;5,6,-1,-2,0;5,6,-1,-2,1;5,6,-1,-1,-1;5,6,-1,-1,0;5,6,-1,-1,1;5,6,-1,0,-1;5,6,-1,0,0;5,6,-1,0,1;5,6,-1,1,-1;5,6,-1,1,0;5,6,-1,1,1;5,6,-1,2,-1;5,6,-1,2,0;5,6,-1,2,1;5,6,0,-2,-1;5,6,0,-2,0;5,6,0,-2,1;5,6,0,-1,-1;5,6,0,-1,0;5,6,0,-1,1;5,6,0,0,-1;5,6,0,0,0;5,6,0,0,1;5,6,0,1,-1;5,6,0,1,0;5,6,0,1,1;5,6,0,2,-1;5,6,0,2,0;5,6,0,2,1;5,6,1,-2,-1;5,6,1,-2,0;5,6,1,-2,1;5,6,1,-1,-1;5,6,1,-1,0;5,6,1,-1,1;5,6,1,0,-1;5,6,1,0,0;5,6,1,0,1;5,6,1,1,-1;5,6,1,1,0;5,6,1,1,1;5,6,1,2,-1;5,6,1,2,0;5,6,1,2,1;5,6,2,-2,-1;5,6,2,-2,0;5,6,2,-2,1;5,6,2,-1,-1;5,6,2,-1,0;5,6,2,-1,1;5,6,2,0,-1;5,6,2,0,0;5,6,2,0,1;5,6,2,1,-1;5,6,2,1,0;5,6,2,1,1;5,6,2,2,-1;5,6,2,2,0;5,6,2,2,1;5,6,3,-2,-1;5,6,3,-2,0;5,6,3,-2,1;5,6,3,-1,-1;5,6,3,-1,0;5,6,3,-1,1;5,6,3,0,-1;5,6,3,0,0;5,6,3,0,1;5,6,3,1,-1;5,6,3,1,0;5,6,3,1,1;5,6,3,2,-1;5,6,3,2,0;5,6,3,2,1;5,7,-3,-2,-1;5,7,-3,-2,0;5,7,-3,-2,1;5,7,-3,-1,-1;5,7,-3,-1,0;5,7,-3,-1,1;5,7,-3,0,-1;5,7,-3,0,0;5,7,-3,0,1;5,7,-3,1,-1;5,7,-3,1,0;5,7,-3,1,1;5,7,-3,2,-1;5,7,-3,2,0;5,7,-3,2,1;5,7,-2,-2,-1;5,7,-2,-2,0;5,7,-2,-2,1;5,7,-2,-1,-1;5,7,-2,-1,0;5,7,-2,-1,1;5,7,-2,0,-1;5,7,-2,0,0;5,7,-2,0,1;5,7,-2,1,-1;5,7,-2,1,0;5,7,-2,1,1;5,7,-2,2,-1;5,7,-2,2,0;5,7,-2,2,1;5,7,-1,-2,-1;5,7,-1,-2,0;5,7,-1,-2,1;5,7,-1,-1,-1;5,7,-1,-1,0;5,7,-1,-1,1;5,7,-1,0,-1;5,7,-1,0,0;5,7,-1,0,1;5,7,-1,1,-1;5,7,-1,1,0;5,7,-1,1,1;5,7,-1,2,-1;5,7,-1,2,0;5,7,-1,2,1;5,7,0,-2,-1;5,7,0,-2,0;5,7,0,-2,1;5,7,0,-1,-1;5,7,0,-1,0;5,7,0,-1,1;5,7,0,0,-1;5,7,0,0,0;5,7,0,0,1;5,7,0,1,-1;5,7,0,1,0;5,7,0,1,1;5,7,0,2,-1;5,7,0,2,0;5,7,0,2,1;5,7,1,-2,-1;5,7,1,-2,0;5,7,1,-2,1;5,7,1,-1,-1;5,7,1,-1,0;5,7,1,-1,1;5,7,1,0,-1;5,7,1,0,0;5,7,1,0,1;5,7,1,1,-1;5,7,1,1,0;5,7,1,1,1;5,7,1,2,-1;5,7,1,2,0;5,7,1,2,1;5,7,2,-2,-1;5,7,2,-2,0;5,7,2,-2,1;5,7,2,-1,-1;5,7,2,-1,0;5,7,2,-1,1;5,7,2,0,-1;5,7,2,0,0;5,7,2,0,1;5,7,2,1,-1;5,7,2,1,0;5,7,2,1,1;5,7,2,2,-1;5,7,2,2,0;5,7,2,2,1;5,7,3,-2,-1;5,7,3,-2,0;5,7,3,-2,1;5,7,3,-1,-1;5,7,3,-1,0;5,7,3,-1,1;5,7,3,0,-1;5,7,3,0,0;5,7,3,0,1;5,7,3,1,-1;5,7,3,1,0;5,7,3,1,1;5,7,3,2,-1;5,7,3,2,0;5,7,3,2,1;5,8,-3,-2,-1;5,8,-3,-2,0;5,8,-3,-2,1;5,8,-3,-1,-1;5,8,-3,-1,0;5,8,-3,-1,1;5,8,-3,0,-1;5,8,-3,0,0;5,8,-3,0,1;5,8,-3,1,-1;5,8,-3,1,0;5,8,-3,1,1;5,8,-3,2,-1;5,8,-3,2,0;5,8,-3,2,1;5,8,-2,-2,-1;5,8,-2,-2,0;5,8,-2,-2,1;5,8,-2,-1,-1;5,8,-2,-1,0;5,8,-2,-1,1;5,8,-2,0,-1;5,8,-2,0,0;5,8,-2,0,1;5,8,-2,1,-1;5,8,-2,1,0;5,8,-2,1,1;5,8,-2,2,-1;5,8,-2,2,0;5,8,-2,2,1;5,8,-1,-2,-1;5,8,-1,-2,0;5,8,-1,-2,1;5,8,-1,-1,-1;5,8,-1,-1,0;5,8,-1,-1,1;5,8,-1,0,-1;5,8,-1,0,0;5,8,-1,0,1;5,8,-1,1,-1;5,8,-1,1,0;5,8,-1,1,1;5,8,-1,2,-1;5,8,-1,2,0;5,8,-1,2,1;5,8,0,-2,-1;5,8,0,-2,0;5,8,0,-2,1;5,8,0,-1,-1;5,8,0,-1,0;5,8,0,-1,1;5,8,0,0,-1;5,8,0,0,0;5,8,0,0,1;5,8,0,1,-1;5,8,0,1,0;5,8,0,1,1;5,8,0,2,-1;5,8,0,2,0;5,8,0,2,1;5,8,1,-2,-1;5,8,1,-2,0;5,8,1,-2,1;5,8,1,-1,-1;5,8,1,-1,0;5,8,1,-1,1;5,8,1,0,-1;5,8,1,0,0;5,8,1,0,1;5,8,1,1,-1;5,8,1,1,0;5,8,1,1,1;5,8,1,2,-1;5,8,1,2,0;5,8,1,2,1;5,8,2,-2,-1;5,8,2,-2,0;5,8,2,-2,1;5,8,2,-1,-1;5,8,2,-1,0;5,8,2,-1,1;5,8,2,0,-1;5,8,2,0,0;5,8,2,0,1;5,8,2,1,-1;5,8,2,1,0;5,8,2,1,1;5,8,2,2,-1;5,8,2,2,0;5,8,2,2,1;5,8,3,-2,-1;5,8,3,-2,0;5,8,3,-2,1;5,8,3,-1,-1;5,8,3,-1,0;5,8,3,-1,1;5,8,3,0,-1;5,8,3,0,0;5,8,3,0,1;5,8,3,1,-1;5,8,3,1,0;5,8,3,1,1;5,8,3,2,-1;5,8,3,2,0;5,8,3,2,1;6,1,-3,-2;6,1,-3,-1;6,1,-3,0;6,1,-3,1;6,1,-3,2;6,1,-2,-2;6,1,-2,-1;6,1,-2,0;6,1,-2,1;6,1,-2,2;6,1,-1,-2;6,1,-1,-1;6,1,-1,0;6,1,-1,1;6,1,-1,2;6,1,0,-2;6,1,0,-1;6,1,0,0;6,1,0,1;6,1,0,2;6,1,1,-2;6,1,1,-1;6,1,1,0;6,1,1,1;6,1,1,2;6,1,2,-2;6,1,2,-1;6,1,2,0;6,1,2,1;6,1,2,2;6,1,3,-2;6,1,3,-1;6,1,3,0;6,1,3,1;6,1,3,2;6,2,-3,-2;6,2,-3,-1;6,2,-3,0;6,2,-3,1;6,2,-3,2;6,2,-2,-2;6,2,-2,-1;6,2,-2,0;6,2,-2,1;6,2,-2,2;6,2,-1,-2;6,2,-1,-1;6,2,-1,0;6,2,-1,1;6,2,-1,2;6,2,0,-2;6,2,0,-1;6,2,0,0;6,2,0,1;6,2,0,2;6,2,1,-2;6,2,1,-1;6,2,1,0;6,2,1,1;6,2,1,2;6,2,2,-2;6,2,2,-1;6,2,2,0;6,2,2,1;6,2,2,2;6,2,3,-2;6,2,3,-1;6,2,3,0;6,2,3,1;6,2,3,2;6,3,-3,-2;6,3,-3,-1;6,3,-3,0;6,3,-3,1;6,3,-3,2;6,3,-2,-2;6,3,-2,-1;6,3,-2,0;6,3,-2,1;6,3,-2,2;6,3,-1,-2;6,3,-1,-1;6,3,-1,0;6,3,-1,1;6,3,-1,2;6,3,0,-2;6,3,0,-1;6,3,0,0;6,3,0,1;6,3,0,2;6,3,1,-2;6,3,1,-1;6,3,1,0;6,3,1,1;6,3,1,2;6,3,2,-2;6,3,2,-1;6,3,2,0;6,3,2,1;6,3,2,2;6,3,3,-2;6,3,3,-1;6,3,3,0;6,3,3,1;6,3,3,2;6,4,-3,-2;6,4,-3,-1;6,4,-3,0;6,4,-3,1;6,4,-3,2;6,4,-2,-2;6,4,-2,-1;6,4,-2,0;6,4,-2,1;6,4,-2,2;6,4,-1,-2;6,4,-1,-1;6,4,-1,0;6,4,-1,1;6,4,-1,2;6,4,0,-2;6,4,0,-1;6,4,0,0;6,4,0,1;6,4,0,2;6,4,1,-2;6,4,1,-1;6,4,1,0;6,4,1,1;6,4,1,2;6,4,2,-2;6,4,2,-1;6,4,2,0;6,4,2,1;6,4,2,2;6,4,3,-2;6,4,3,-1;6,4,3,0;6,4,3,1;6,4,3,2;6,5,-3,-2;6,5,-3,-1;6,5,-3,0;6,5,-3,1;6,5,-3,2;6,5,-2,-2;6,5,-2,-1;6,5,-2,0;6,5,-2,1;6,5,-2,2;6,5,-1,-2;6,5,-1,-1;6,5,-1,0;6,5,-1,1;6,5,-1,2;6,5,0,-2;6,5,0,-1;6,5,0,0;6,5,0,1;6,5,0,2;6,5,1,-2;6,5,1,-1;6,5,1,0;6,5,1,1;6,5,1,2;6,5,2,-2;6,5,2,-1;6,5,2,0;6,5,2,1;6,5,2,2;6,5,3,-2;6,5,3,-1;6,5,3,0;6,5,3,1;6,5,3,2;6,6,-3,-2;6,6,-3,-1;6,6,-3,0;6,6,-3,1;6,6,-3,2;6,6,-2,-2;6,6,-2,-1;6,6,-2,0;6,6,-2,1;6,6,-2,2;6,6,-1,-2;6,6,-1,-1;6,6,-1,0;6,6,-1,1;6,6,-1,2;6,6,0,-2;6,6,0,-1;6,6,0,0;6,6,0,1;6,6,0,2;6,6,1,-2;6,6,1,-1;6,6,1,0;6,6,1,1;6,6,1,2;6,6,2,-2;6,6,2,-1;6,6,2,0;6,6,2,1;6,6,2,2;6,6,3,-2;6,6,3,-1;6,6,3,0;6,6,3,1;6,6,3,2;6,7,-3,-2;6,7,-3,-1;6,7,-3,0;6,7,-3,1;6,7,-3,2;6,7,-2,-2;6,7,-2,-1;6,7,-2,0;6,7,-2,1;6,7,-2,2;6,7,-1,-2;6,7,-1,-1;6,7,-1,0;6,7,-1,1;6,7,-1,2;6,7,0,-2;6,7,0,-1;6,7,0,0;6,7,0,1;6,7,0,2;6,7,1,-2;6,7,1,-1;6,7,1,0;6,7,1,1;6,7,1,2;6,7,2,-2;6,7,2,-1;6,7,2,0;6,7,2,1;6,7,2,2;6,7,3,-2;6,7,3,-1;6,7,3,0;6,7,3,1;6,7,3,2;6,8,-3,-2;6,8,-3,-1;6,8,-3,0;6,8,-3,1;6,8,-3,2;6,8,-2,-2;6,8,-2,-1;6,8,-2,0;6,8,-2,1;6,8,-2,2;6,8,-1,-2;6,8,-1,-1;6,8,-1,0;6,8,-1,1;6,8,-1,2;6,8,0,-2;6,8,0,-1;6,8,0,0;6,8,0,1;6,8,0,2;6,8,1,-2;6,8,1,-1;6,8,1,0;6,8,1,1;6,8,1,2;6,8,2,-2;6,8,2,-1;6,8,2,0;6,8,2,1;6,8,2,2;6,8,3,-2;6,8,3,-1;6,8,3,0;6,8,3,1;6,8,3,2;7,1,-3;7,1,-2;7,1,-1;7,1,0;7,1,1;7,1,2;7,1,3;7,2,-3;7,2,-2;7,2,-1;7,2,0;7,2,1;7,2,2;7,2,3;7,3,-3;7,3,-2;7,3,-1;7,3,0;7,3,1;7,3,2;7,3,3;7,4,-3;7,4,-2;7,4,-1;7,4,0;7,4,1;7,4,2;7,4,3;7,5,-3;7,5,-2;7,5,-1;7,5,0;7,5,1;7,5,2;7,5,3;7,6,-3;7,6,-2;7,6,-1;7,6,0;7,6,1;7,6,2;7,6,3;7,7,-3;7,7,-2;7,7,-1;7,7,0;7,7,1;7,7,2;7,7,3;7,8,-3;7,8,-2;7,8,-1;7,8,0;7,8,1;7,8,2;7,8,3;8,1;8,2;8,3;8,4;8,5;8,6;8,7;8,8 ``` ### Pattern All ranges are inclusive: * The first index is in the range 1 to 8 (or 0 to 7 if you want), and is always included. * The second index is in the range 1 to 8 (or 0 to 7 if you want), and is always included. * The third index is in the range ‒3 to 3, but is only included if the first index is in the range 2 to 7. * The fourth index is in the range ‒2 to 2, but is only included if the first index is in the range 3 to 6. * The fifth index is in the range ‒1 to 1, but is only included if the first index is 4 or 5. ## Examples Compute all valid indices or (assuming 1-based enumeration of the first two dimensions): ### Valid: ``` 1,6 2,2,-3 2,2,2 3,1,2,1 5,1,2,1,0 7,1,-1 8,8 ``` ### Invalid ``` 1 1,6,1 2,1 2,2,-4 3,1,2 7,7 8,0 8,1,1 8,-1 ``` [Answer] # JavaScript (ES6), ~~74 66~~ 60 bytes Expects the first two dimensions in 0-indexed format. Returns `0` for *true* or a positive integer for *false*. ``` a=>a.some(x=>x<-(q=i--&3)|x>(q||7),i=.5)|-i^"12344321"[a[0]] ``` [Try it online!](https://tio.run/##dY/NDoIwEAbvPgYHaZMtaQvCxfIiFZMGQWuQyo8GE94dUS8al@tMt/nmbO6my1t77VntDsVUqsmo1ASduxRkUOmwZaRRlrF1SMchJc04JhSsCjZ0ZHbvCRlGUSiFp43mWTblru5cVQSVOxJf9@2tPz0yn66@eUk0h01G/6gAASxcEBLhEjhIEIiJPgY44uLZMewogeRFf7C/q3Vpqg6tQP6Yy9BB@JR3cbRUhm6P0eELPRzE8vPpCQ "JavaScript (Node.js) – Try It Online") ### How? For each value \$x\$ at position \$i\$: * we compute \$q = (1/2-i)\operatorname{AND} 3\$ which maps \$[0,1,2,3,4]\$ to \$[0,0,3,2,1]\$ * we make sure that we have \$x\ge -q\$ and either \$x \le q\$ if \$q\neq 0\$, or \$x\le 7\$ if \$q=0\$ In the actual implementation, we start with \$i=1/2\$ and subtract \$1\$ after each iteration. We finally make sure that the length is consistent with the leading dimension: ``` -i ^ "12344321"[a[0]] ``` An empty list would pass this test, but the list is guaranteed to be non-empty as per the challenge rules. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~91...~~ 63 bytes ``` n=>n.some(e=>i++<2?e<1|e>8:e<i-6|e>6-i,i=0)|i^' 23455432'[n[0]] ``` [Try it online!](https://tio.run/##nc69boMwEAfwvU/hThjFRth8BMWYDp2y9AWiVKHkUjkyBmGKVCnvTh2gbVp16nA@63T/n@5cDqWtOtX21DRHGE9yNLIwgW1qwCALtVrl/AFydoEi20CuaOp@KVVEydC/qGcP8ShOkjji3s7swv1@rBpjezSUWh0fSwsWSXRgJBWccEKjqXEREeY6E8ncSSjW7qVMZCQ7iLvZUOaXIpzjQnwqp8Wz47JrFwxdMXIlKPsyqiX8LQW21arHnvD8oC5bDBrJAoH@nJNl/vRWv0Dn@z@kraNuz/of1mgIdPOKJzKAAbp3DNfg/QmD/@fW9nZt2Ro/AA "JavaScript (Node.js) – Try It Online") The ultra-long function. I would appreciate a trick that can get rid of all these annoying `&`s. Partial credit to @Arnauld as I did not think of the string indexing trick. [I really need to improve my critical thinking skills.] ## How does it work? Nothing really complex, unlike in some of my more complex answers. Really just checking to see if the length is incorrect. This is done by performing an XOR (the bitwise equivalent of `!=` which saves one byte) against the character at `n[0]` of `23455432` [the first element is at least 1, so no worries about selecting the space]. We also check if, for some element in `n`, that either it is outside the required bounds. This saved 1 byte as some is 1 byte shorter than every. Returns `0` for valid and a positive integer for invalid. If I **must** return a boolean, please let me know, and I will change the XOR to a `&&`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~39~~ 33 bytes ``` ∧⁼LθI§”)⊟&1x”§θ⁰⬤θ⎇‹κ²⁼﹪ι⁸ι‹↔ι⁻⁶κ ``` [Try it online!](https://tio.run/##NYzLCsIwFER/JXR1C7dgXyK4KuJCsODCXekitsGGXhKah@jXx7TowCzmzDDDxM2gOYVwM1I5aNQI58VzsnAV6ukmWFJkJ25j5S5qFG9IirKq66osEmR/tiDbpVGREK3pLozi5hNPrIUZWRGr32@rR08aJLJDhDJ6GzUPq8k7AStppfIW9sjmdNMxhK7LMces7PuQvegL "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Outputs a Charcoal boolean, i.e. `-` for valid, nothing for invalid. Explanation: ``` ∧⁼LθI§”)⊟&1x”§θ⁰ ``` Check that the number of elements is correct, and... ``` ⬤θ⎇‹κ²⁼﹪ι⁸ι‹↔ι⁻⁶κ ``` ... that the first two elements are from 0 to 7, and the remaining elements are within the desired absolute range. [Answer] # JavaScript (ES6), 53 bytes ``` a=>a.some(x=>i++<0?x&~7:x*x>15-i*4,i=-2)|(a[0]^i)%7|a ``` [Try it online!](https://tio.run/##hVTLTsMwELz3K3yBJq3dxk7SVIiUH0BC4sAlFMmkThOUxigPlEoVvx76UIEqu@51Ztfy7Mzuh/ySVVxmnzUr9Ep1SdjJcCEnld4oqw0X2Xh87zy0t9/BXTtqF9xn2cijWciEvbNk5CzfMvsm2Mku1kWlczXJ9doaRnXZ1Ol2ObQHg@mUPMtirci7boqVLLeD/6WJFTnUWdp2Hw0AlFOHMhckAgrh4thAmQC5fQ@FGPfcRRkH6WMjhTjPyBmf9dH/@AYVM0T5DBtVAE42OLlwsOupTlVJYlmpqj9mjs2fU4HMHx/GngHNP/6d43@/gIevRZTIvPqN26Mq1nVKNlm1kXWcXhT3c9Z776AGUgIFAdIF@QdphOSBiwAvCMdQpF6YcIRzrzEI611jENY34Qg3QxME1yPh/4v/i8wbRXRTE52Q8nC6zAlisBNz5KyBud7Dc@zceQjhoWYyF6Vcg5dMGEhx7TrAm9XT6YPHAAszh@WL84d6roNbhd0Sh3K8vPsB "JavaScript (Node.js) – Try It Online") Some ideas are based on Arnauld's and ophact's answer, some how. -3 bytes by Arnauld. Take input as an array. First 2 dimension are 0-indexed. Output falsy (zero) for valid Dimensional Chess position, and truthy (non-zero) otherwise. The first part `a.some(x=>i++<0?x<0|x>7:x*x>15-i*4,i=-2)` check 1. every digits are in given range 2. given list contains no more than 5 elements | n-th Dim | `i++<0` | `i` | `15-i*4` | explain | | --- | --- | --- | --- | --- | | 0 | true | -1 | N/A | \$x<0\lor x>7\$ | | 1 | true | 0 | N/A | \$x<0\lor x>7\$ | | 2 | false | 1 | 11 | \$x>3 \lor x < -3\$ | | 3 | false | 2 | 7 | \$x>2 \lor x < -2\$ | | 4 | false | 3 | 3 | \$x>1 \lor x < -1\$ | | 5 | false | 4 | -1 | \$x^2>-1\$ always truthy | The second part `(a[0]^i)%7` checks if given list has correct length. After first part (if it successfully returned falsy): | `a[0]` | length | `i` | `a[0]^i` | `(a[0]^i)%7` | | --- | --- | --- | --- | --- | | 0 | 2 | 0 | 0 | 0 | | 1 | 3 | 1 | 0 | 0 | | 2 | 4 | 2 | 0 | 0 | | 3 | 5 | 3 | 0 | 0 | | 4 | 5 | 3 | 7 | 0 | | 5 | 4 | 2 | 7 | 0 | | 6 | 3 | 1 | 7 | 0 | | 7 | 2 | 0 | 7 | 0 | We can safely assume \$i<4\$ here, since otherwise \$x^2>15-4i\$ already reports the input invalid. And therefore, the length is valid iff `(a[0]^i)%7` is `0`. [Answer] # [Haskell](https://www.haskell.org/), 74 bytes ``` do i<-[1..4];z<-mapM id$take i[[1..8],[-3..3],[-2..2],[-1..1]];[i:z,9-i:z] ``` [Try it online!](https://tio.run/##LYk7DoMwEAX7nGILSrwSnyIJcIScwHGxwg6sWIwVXHH4GCylmdG8N9O@OJEkwzvZDbhXukJsTXf0aqXwArZFpMUB63zcTalVg9hk14h19rVXxnSan0f5UBdNWon9YLcbhC/7WIjzU5xB/g2SfuNHaNqTGkM4AQ "Haskell – Try It Online") To switch things up a bit, the code above computes the list of all valid positions, 1-indexed. [Answer] # [R](https://www.r-project.org/), 102 bytes ``` function(x){while(!is.na(a<-x[F<-F+1]))T=T&"if"(F<3,a>0&a<9,abs(a)<7-F);T&sum(x|1)==5.5-abs(x[1]-4.5)} ``` [Try it online!](https://tio.run/##VY3BboJAFEX3/kVZkPfie4QBEUiHJi46K1dKV@piJBJJLCYCkaTttyMNOKW7c3KTe25dnnR5U2Z1cS2hxa/7ubic4KWonFKDltzulGQ1FwfENEltq8gtUNIn/ebaWsakjxVolCErfE3tqvmE9ltgkgROwL9buxMHXjgB/nSZrsFiTjcf78z70sJZDhkIWuJAHnnE/kS8kX0SvYnRgsHIHT3smZ9jRFFPszGlVuvtvxaaprnzJtT3F9OmKYTm3jUk6C9q@jHFiN0D "R – Try It Online") Horribly long, but at last it's working. Go look at much better [@Nick's answer](https://codegolf.stackexchange.com/a/226152/55372). [Answer] # [R](https://www.r-project.org/) >= 4.1, ~~77~~ 71 bytes ``` \(x)all(x[1:2]>0,abs(x)<c(9,9,4:2)[1:(l=sum(x|1))],l==c(2:5,5:2)[x[1]]) ``` [Try it online!](https://tio.run/##XY3dCoJAEIXvewoRglmYDXfL/EF7kfJi2zSCzczVkOjdbSQzaWHgnDl7vqn7IuFFW@rmciuhY1o1YKv6UjYFuEvr8J2ztC46p7xStc3hmfDjvb01OZxhRf/poZM/lIHnoNxD6bLFOeH9jKmMgW4vYpntPFRHS6tEQ4QRbmLJKACT2vYK3UswlqFJUw0y9tEfUipmGesL0OCjQEnjMbYYvMDtqCTt@Xpm5KjXn8ro/gEBaf4NQwy/3B9/qsqZolubOX@iBRPKm5TA34HhVv8G "R – Try It Online") A function taking a vector of integers and returning `TRUE` or `FALSE`. Note on TIO, `\` is substituted by `function` since TIO is currently still running R 3.5.2, but this is functionally identical. Thanks to @pajonk for saving 6 bytes! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 27 bytes ``` 99432D>Aaḣ2>0ƊẠaL’=ị4Rm0¤Ḣ$ ``` [Try it online!](https://tio.run/##y0rNyan8/9/S0sTYyMXOMfHhjsVGdgbHuh7uWpDo86hhpu3D3d0mQbkGh5Y83LFI5f/RSQ93zrB@1DBHQddO4VHDXOvD7VyH2x81rYn8/z862lBHwSxWRyHaSEcBiHSNEWwjENNYR8EQzDME8UzhPB0FA5CAOZipC5a00FGwANFgDshYqCYjBA2ywQTJWKgR5lDtBlDaEKrDAmx0LAA "Jelly – Try It Online") A monadic link taking a list of integers and returning 1 for true and 0 for false. Uses 1-indexing for the first two dimensions. [Answer] # [Stax](https://github.com/tomtheisen/stax), 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ünà<0(↑P⌡◙«VLR¬Θ☺úG▀╓pé▓2 ``` [Run and debug it](https://staxlang.xyz/#p=816e853c30281850f50aae564c52aae901a347dfd67082b232&i=%5B1,6%5D%0A%5B2,2,-3%5D%0A%5B2,2,2%5D%0A%5B3,1,2,1%5D%0A%5B5,1,2,1,0%5D%0A%5B7,1,-1%5D%0A%5B8,8%5D%0A%5B1%5D%0A%5B1,6,1%5D%0A%5B2,1%5D%0A%5B2,2,-4%5D%0A%5B3,1,2%5D%0A%5B7,7%5D%0A%5B8,0%5D%0A%5B8,1,1%5D%0A%5B8,-1%5D%0A&m=2) Removed `:b`! nonzero if truthy, zero if falsy. ]
[Question] [ Given a binary sequence of finite length, find the starting position where this sequence first appears in the binary digits of π (after the decimal). You can assume that an answer exists for any input sequence. The binary digits of π start with ``` 11.001001000011111101101010100010001000010110100011... ``` and digits will be counted such that the first one after the decimal (the first 0 digit) has index 1. ### Examples The requested function is related to [OEIS A178707](https://oeis.org/A178707) but differs in that input sequences may have leading zeros. [OEIS A178708](https://oeis.org/A178708) and [OEIS A178709](https://oeis.org/A178709) provide good test cases for large sequences of 0's and 1's. Some test cases below 10^9: * 00100 → 1 * 11 → 11 * 00000000 → 189 * 11111111 → 645 * 0101000001101001 → 45038 * 00000000000000000000 → 726844 * 11111111111111111111 → 1962901 * 01000111010011110100110001000110 → 105394114 * 111111111111111111111111111111 → 207861698 * 100000000110000001100111100001 → 987654321 ### Input/output formats You can use any input and output formats: strings, lists, encoding the binary digits in integers, etc. Just use what is convenient for you. ### Limitations Your program must be able to accept sequences of arbitrary (finite) length if run on an infinite-size computer, and terminate in finite time (assuming that a match always exists, which is what most people seem to believe in 2021 based on the pseudo-randomness of the digits of π). ### Scoring This is [code golf](https://en.wikipedia.org/wiki/Code_golf), so the shortest program (in bytes or bits/8) wins. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~ 167 ~~ 165 bytes This is long and slow ... but it should work for any input in theory. ``` s=>{for(k=t=1n,l=q=2n,n=0n,r=6n,o='#';!~(i=o.search(s));)n=4n*q+t*~n<r?(o+=n,q+(q+=q)-r)/t-n<<(r+=r+t*n*2n)/r:(q*7n*k+2n-r*++l)/(r=(r-q-q)*l,q*=k++,t*=l++);return i} ``` [Try it online!](https://tio.run/##ZY5NU4MwEIbv/RWxHpovSoK0VmH17MmLf4BBUIRuzJI64zj2ryMoXtrnkp28z7y7b8VH0ZfUvIcI3XM11DD0cPdVO@ItBLCoO/CQoEYwqAm2qB2sLlfZxZE34NZ9VVD5ynshMoGQovQqyCPmdM@dAtReca/Ai4hEPK7Ic04KaHRQJihiuuVeXqNsVYIRSaU6EXMCTpGPvJCd9hJapXSQ0CklMqrCgZA130PpsHddte7cC6/50hhrzFIINhLHzC5OcmvncM7PBDMzaZOwuzmv@GM2tulmsRjfffHJQrOvmDsE5pA9PTxO36f1djpwxP4O/yXpxlzthh8 "JavaScript (Node.js) – Try It Online") This is derived from [the C# entry](https://rosettacode.org/wiki/Pi#C.23) on [this Rosetta Code page](https://rosettacode.org/wiki/Pi). The C# code is derived from Java, which is derived from Icon, which is derived from PicoLisp, which is derived from Haskell, which is based on [this paper](http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf). :-p [Answer] # [MATL](https://github.com/lmendo/MATL), 28 bytes ``` `YPX$3-@X$W*kc4Y22@&ZaGXftn~ ``` [**Try it online!**](https://tio.run/##y00syfn/PyEyIELFWNchQiVcKzvZJNLIyEEtKtE9Iq0kr@7//2hDBcNYAA) The code is very inefficient. Test cases beyond the second time out in the online compiler, but work offline. Here's an example with the fourth case (it takes about 25 seconds): [![enter image description here](https://i.stack.imgur.com/X5Nsk.gif)](https://i.stack.imgur.com/X5Nsk.gif) ### Explanation The code keeps trying increasingly long truncated binary expansions of the fractional part of 𝜋, until the input is contained in the expansion. ``` ` % Do...while YP % Push pi as a double X$ % Convert to symbolic. This recognizes pi's double representation 3- % Subtract 3 @ % Push iteration index, n, starting at 1 X$ % Convert to symbolic. This avoids overflow in the next operation W % Exponential with base 2 * % Multiply k % Floor(round down). This gives floor((pi-3)*2^n) as a symbolic variable c % Convert to char. This gives a sequence of decimal digits 4Y2 % Push '0123456789' (input alphabet for base conversion) 2 % Push 2 (output base for conversion) @ % Push n (number of digits in the output) &Za % Base conversion. This gives the binary expansion with n digits G % Push input Xf % Index of ocurrences of the input. May be empty t % Duplicate n~ % Number of elements, negate. This gives 1 if the input was not found % End (implicit). A new iteration is run if the top of the stack is 1 % Display (implicit). The stack contains several empty arrays, and a % non-empty array with the solution. Empty arrays are not displayed ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes ``` 0//.n_/;RealDigits[Pi,2,Tr[1^#],-n][[1]]!=#:>n+1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n27730BfXy8vXt86KDUxxyUzPbOkODogU8dIJ6Qo2jBOOVZHNy82OtowNlbRVtnKLk/bUO1/QFFmXomCQ3p0tYGOgY4hEBvUxnIhRA11DFH4IFVIEF0tMqyN/f8fAA "Wolfram Language (Mathematica) – Try It Online") thanks @Roman for -2bytes and @att for -3 bytes [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 114 bytes ``` ≔²η≔±⁶ρ≔¹τ≔¹κ≔⁰ν≔³λW¬№ψθ¿‹⁺×⁴ηρ×⊕ντ«≔⁺ψνψ≔⊗⁻ρ×τνσ≔⁻÷⊗⁺׳ηρτ⊗νν≦⊗η≔σρ»«≔×⁺⊗ηρλσ≧×κη≧×λτ≔÷⁺⁺×⁷η²×ρλτν≧⁺²λ≦⊕κ≔σρ»I⌕ψθ ``` [Try it online!](https://tio.run/##bZLBTsMwDIbP61P4mEhBohuCw05oE9IkNk2IFyhtaCMyF5J0qEI8e0iaps3QjnZ@@/Nvp2wKVbaFtPZRa1EjWTJo6DobowOvC8PJPWWg5mzOwFxEH3N0ywDnaMVAuui7EZIDObSGbNoODekZfFFKQbwDeeZak6PsNHkVJ67JnZ/A8xiExA5LxU8cDa8IUs92lT/ZYmQMpb3HMugdLOa3bfcmXcleoBOo2M14JXVanWiDZodmK86i4lNtMtYqjjVMwCBK0Ce85cW@@LxEh1VGhg47/AUuNU/mD@0HUuwZ/cs45tT6RdSNCSVu7SPg@qsMV4qY2dyASpw9BGfLaeHKk0ebeAXga50@3DaxnRwq/In/1rOjEu76m0Ib8iSwiv9gbW2e25uz/AM "Charcoal – Try It Online") Link is to verbose version of code. Uses the same source as @Arnauld's answer, so you can read up on the spigot algorithm there. Builds up the entire binary expansion as it goes and searches from the beginning on each loop but that turns out to be faster than just keeping the necessary number of bits. [Answer] # [R](https://www.r-project.org/), ~~261~~ 259 bytes ``` function(x,p=''){while((a=regexpr(x,p<-paste0(c(p,(16*(4*s(F,1)-2*s(F,4)-s(F,5)-s(F,6))%%1)%/%2^(3:0)%%2),collapse='')))<0)F=F+1;a} s=function(n,d){for(k in 0:n){p=1;for(i in seq(l=n-k))p=(16*p)%%d;F=(F+p/d)%%1;d=d+8};while((f=(T=T/16)/(d=d+8))>2e-16)F=F+f;F} ``` [Try it online!](https://tio.run/##fVDBbsIwDL3zFRGoagztSDqoGCU79gs4D5XWhYiSZknKkBDf3rWj4rADvjj2e/ZznmlLqYrdXjq7k2qnpWjLRuVO1opeAy18H24/R1khpZkweMCrNj2wCXVmHTKaUx1QHk/pYmppGnAIo7/HAsI@LR8pBvA8Dt7ci77o@5p1VQRBXldVpi32KgAbBqlIZzzJ7iMrnleooIBbWRt6IlIRtlZw04InfUf2HYvftBIqPAFo0V@iu@VFkgqazvS86HWTQhSz1T0ZPlIKuhXbOY9hTv8QgM8Iw67u9cskvbeZfbtg7jqNf/bQMWOcsTEAmRA@esHjfCC9ZLEhBu7q4/XKRzzI8WI5mhBVO1wT/znld57kVVNgQY5okLiaGDzXFyTSGKzwkilHMueM3DcOLSlNfSZ143TjSOfpuYOkOrS/ "R – Try It Online") This is pretty long and can almost certainly be golfed better... The function `s` calculates the value of one of the four summations of the [Bailey–Borwein–Plouffe forumla](https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula). We then use four calls to `s` to implement a [spigot algorithm](https://en.wikipedia.org/wiki/Spigot_algorithm) to sequentially calculate each hexadecimal digit of pi, and convert these into groups of 4 bits. Finally, each iteration of the `while` loop adds these next 4 bits to the string `a`, and checks whether it now contains the search string `x`, halting and ouputting the index if this is true. ]
[Question] [ ## Background Perfect shuffle algorithms like [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) don't produce great results when it comes to music playlist shuffling, because it often produces clusters of songs from the same album. In an attempt to solve this problem, Spotify introduced [an interesting shuffle algorithm in 2014](https://engineering.atspotify.com/2014/02/how-to-shuffle-songs/). At the end of the article, they claimed (emphasis mine): > > All in all the algorithm is **very simple** and it can be implemented in **just a couple of lines**. It’s also very fast and produces decent results. > > > Let's see if this is indeed the case. ## Task Implement the modified Spotify shuffle. The algorithm described in the article has some gaps in its specification, so I present a refined one here. ### The algorithm Let's assume we have a list of items grouped into categories, e.g.: ``` [['A', 'AA', 'AAA'], ['B'], ['C', 'CC'], ['D'], ['E', 'EE', 'EEE', 'EEEE']] ``` 1. Shuffle items within each category. * You may use any shuffle algorithm that can produce every possible permutation with nonzero probability. ``` [['AAA', 'A', 'AA'], ['B'], ['C', 'CC'], ['D'], ['EEE', 'EEEE', 'EE', 'E']] ``` 2. Assign each item a "positional value". Items in one category should be uniformly spaced, but with some randomness. To achieve this, do the following operations on each category having `n` items: 3. Initialize the positional value vector `v` of length `n` with the values `v[k] = k/n` for `0 <= k < n` (i.e. 0-indexed), so that the items have default spacing of `1/n`. 4. Generate an initial random offset `io` within the range of `0 <= io <= 1/n`, and add it to every `v[k]`. 5. Generate `n` individual random offsets `o[k]` within the range of `-1/10n <= o[k] <= 1/10n`, and apply `v[k] += o[k]` for each `k`. So the positional value of `k`-th item (0-indexed) within an `n`-item category will be `v[k] = k/n + io + o[k]`. * The random offsets `io` and `o[k]` should ideally be picked from a uniform random variable, but can be approximated by picking from a discrete distribution with at least 5 distinct equally-spaced outcomes, including both lower and upper bounds. (e.g. you can choose to randomly pick `io` from `[0, 1/4n, 2/4n, 3/4n, 1/n]`.) * Don't do extra processing even if `v[k] < 0` or `v[k] > 1`. ``` [['AAA' -> 0.1, 'A' -> 0.41, 'AA' -> 0.79], ['B' -> 0.2], ['C' -> 0.49, 'CC' -> 1.01], ['D' -> 0.03], ['EEE' -> 0.12, 'EEEE' -> 0.37, 'EE' -> 0.6, 'E' -> 0.88]] ``` 3. Sort all items by the positional values. ``` ['D', 'AAA', 'EEE', 'B', 'EEEE', 'A', 'C', 'EE', 'AA', 'E', 'CC'] ``` The shuffled result roughly looks like this (from the article): [![](https://i.stack.imgur.com/ljMTX.png)](https://i.stack.imgur.com/ljMTX.png) (source: [wordpress.com](https://spotifylabscom.files.wordpress.com/2014/02/algorithm.png?w=533&h=458)) Here is Python-like pseudocode of the above algorithm: ``` x = nested array of items uniform(a,b) = uniformly generate a random value between a and b items = [] v = [] for i in range(len(x)): # for each category shuffle(x[i]) # shuffle items within category in place items += x[i] n = len(x[i]) # size of the current category io = uniform(0, 1/n) # initial offset o = [uniform(-0.1/n, 0.1/n) for k in range(n)] # individual offsets v += [k/n + io + o[k] for k in range(n)] # resulting positional values sort items by v print items ``` ## Input and output The input is a list of groups of items (i.e. a nested list) as shown in the example above. An item is a string made of only uppercase letters (or only lowercase if you want). You can assume that all items are distinct, within and across categories. The output is a shuffled list including all items in the input, which is produced by the algorithm described above. The randomness requirements are covered in the algorithm description. ## Scoring and winning criterion Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~125~~ 124 bytes *Saved 1 byte thanks to @KevinCruijssen* ``` a=>a.flatMap(a=>a.sort(_=>R()-.5).map(v=>[(o++-.1+R()/5)/a.length,v],o=R()),R=Math.random).sort(([a],[b])=>a-b).map(a=>a[1]) ``` [Try it online!](https://tio.run/##NY3LCoMwEEV/xV0yGCMuXEaw1qUbtyGU8d2iRjT4@2ls7OZe7hk488ETj3Z/byZaddfbQVgUGfJhRlPhRn/j0LuhL5HVFCKeAl/c4RSZpDoMI56EjscpxMjnfh3NxE7FtHAQWC0qNBPfce30Al5EJSomGwVOHTXedr2RiQLb6vXQc89nPdKBSklywgKS35kTxQJJHr6KCxaFH09f5cXKO/9VEqUA7Bc "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input a.flatMap(a => // for each category a[] in a[]: a.sort(_ => R() - .5) // shuffle a[] .map(v => // for each value v in a[]: [ // build a pair [position, value]: ( o++ // increment o - .1 // subtract 1/10 + R() / 5 // add 2/10 * random value in [0,1) ) / a.length, // divide the result by the length of a[] v // use v as the 2nd element ], // end of pair o = R() // start with o in [0,1) ), // end of map() R = Math.random // R = alias for Math.random ) // end of flatMap() .sort(([a], [b]) => a - b) // sort by first element, in ascending order .map(a => a[1]) // keep only the 2nd element ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~244~~ ~~218~~ 200 bytes ``` from random import* l,r,u=len,range,uniform def f(x): I,v=[],[] for i in r(l(x)):shuffle(x[i]);I+=x[i];n=l(x[i]);t=0.1/n;v+=[k/n+u(0,1/n)+u(-t,t)for k in r(n)] return[s[1]for s in sorted(zip(v,I))] ``` [Try it online!](https://tio.run/##NY7NboQwDITvPEVuiYu7P@ptUQ6U5cAzRDlUIulGGwwKAW378jQR9OIZzyeNPf3Ex0gf22bDOLDwRX0SN0xjiG@Fx4CL9IYwgW@DCzk7hqHojWVWvOBWsA5XqTQqXbCEmGOOWBA@QbjNj8Vab8RLOQ1VV8psKpL@SKK8nK5nqtZSqueZykVcMO2QzHvECLnwuRcSpAPBxCWQmtVVZzRnNKdHTS9@3SRW7AD0NgVHUVihFK85Ml4fs@YameKfuzQ5bJp9ue/S5qw95r@0XGuA7Q8 "Python 3 – Try It Online") Literally just a golfed version of the algorithm in the challenge. I mean, someone had to do it! Thanks to ValueInk for golfing suggestions! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes ``` ‘9xX€’÷8Ḣ__.÷5ƊƊ_@Ẋ÷ ẈÇ€FỤịẎ ``` [Try it online!](https://tio.run/##y0rNyan8//9RwwzLiohHTWseNcw8vN3i4Y5F8fF6h7ebHus61hXv8HBX1@HtXA93dRxuBypxe7h7ycPd3Q939f0/3P5w577//6Oj1R3VdRTUHaGko3qsjkK0uhOEcgYJOjtDOC4QyhUk5golYZSremwsAA "Jelly – Try It Online") A pair of links that is called monadically with input and output as described in the question. Jelly doesn’t generate random uniform numbers so a random rational number between 0 and 1 in increments of 0.125 is used instead. Incidentally, per the question’s quote, I’ve implemented it in a **couple of lines**. ## Explanation ### Helper link, generates scores for each collection Argument is the length of the collection ``` ‘ | Increment by 1 9x | 9 repeated that many times X€ | Generate a random number from 1..9 for each ’ | Decrement by 1 ÷8 | Divide by 8 Ɗ | Following as a monad: Ḣ | - Head _ Ɗ | - Subtract following as a monad: _. | - (Remainder of list) subtract 0.5 ÷5 | - Divide by 5 _@Ẋ | Subtract this from shuffled list from 1..original argument (subtracted to get zero-based number) ÷ | Divide by original argument ``` # Main link ``` Ẉ | Lengths of collections Ç€ | Call helper link for each F | Flatten Ụ | Sort indices by values ịẎ | Index into original argument joined into one list of strings ``` [Answer] # [J](http://jsoftware.com/), ~~52~~ ~~42~~ 32 bytes ``` /:&;(%~_.1+?~+?@0+5%~?@#&0)@#&.> ``` [Try it online!](https://tio.run/##JYVNC4IwAIbv@xVvik5RlzsUuGl@Zafo0DVCpJQIUph49a8vLXg@3jraCH7fb0REKS4FQ9WPk2pHqKZ/Dh@oNlBTPxJiMNohEaDwEUIsBgzl9XzSW2FLx5prxr109tIs9HbWnGamHbpL2EG7pEkYnJuIY8lq7q4BlciRr@QShUSJspQ4SlSoVn5WlJD28RrQ/Od0BnfBQ9MXDSH6Cw "J – Try It Online") [Answer] # [Red](http://www.red-lang.org), 180 bytes ``` func[b][random/seed now extract next sort/skip collect[forall b[i: random 1.0 /(d: length? t: random b/1)repeat n d[keep n - 1.0 / d + i +(0.1 / d - random 0.2 / d)keep t/:n]]]2 2] ``` [Try it online!](https://tio.run/##PYxBboMwEEX3nOLLq0RRMLBkUxHKBbIdzQLw0KK4NjKO2ttTatpunv78mTdBzHYXQ5xN9TY93UgDU@id8R96FTFw/hPyFUM/Rrg9YPUh6vUxLxi9tTJGmnzorc0GmmscKsq8gD6ZGlbcW3x/QfxfDbo8B1mk3/9lhh4iCxyuhwKDC2ZcTkVepun6pxV59VOc033UtWPmChVvS5hdxAQi1Sio5kCjGKRuie3etG2Kr4ndXnQHftkp5u0b "Red – Try It Online") Just a straightforward implementation of the algorithm [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ε.rDg©т*ÝΩVεN®/тD(ŸΩY‚₄/O+‚]˜2ôΣθ}€¨ ``` Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/198096/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##yy9OTMpM/f//3Fa9Ipf00EdNLYfnAgn9QyvPrQw7tzXSTzukSvfQunMrTfW1I/QfNcyKPT3H6PCWc4vP7ah91LTm0Ir//6OjlRyVdJQcIYSjUqxOtJITmHQGijg7g5kuYNIVKOAKIaCkq1JsLAA) (feel free to remove the last 2 or 3 bytes (`}€¨`) to see the resulting \$v[k]\$ values it sorts on). **Explanation:** ``` ε # Map each group of the (implicit) 2D integer-list to: .r # Randomly shuffle the group Dg # Duplicate, and pop and push the length: n U # Pop and store this length in variable `X` ₄Ý # Push a list in the range [0,1000] ₄/ # Divide each value by 1000 to make the range [0,1] in increments of 0.001 © # Store this list in variable `®` (without popping) Ω # Pop and push a random value from this list V # Pop and store that random value in variable `Y` ε # Map over each value in this shuffled group: Y # Push the random value from variable `Y` N+ # Add the 0-based loop index to it Tz- # Subtract 1/10 from it ® # Push the [0,1] list from variable `®` again Ω # Pop and push a random value r from this list 5/ # Divide it by 5 + # Add it to the earlier Y-0.1 X/ # And divide it all by the length of the group from variable `X` ‚ # And pair this v[k] with the value name ] # After both maps: ˜ # Flatten the entire list of list of value,key pairs 2ô # And then split it into parts of size 2 # (so we now have a flattened value,key paired list) Σ } # Sort these key-value pairs by: θ # The last item (so by the key v[k]) €¨ # And then remove the last item (so the key v[k]) from each pair # (after which the resulting list of (wrapped) values is output implicitly) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 93 bytes Another straightforward implementation. -9 bytes from borrowing ideas from Arnauld's value generation code, which I saw right before I posted my answer. ``` ->a{v=a.flat_map{|e|i=rand-1;e.shuffle.map{|s|[(rand/5-0.1+i+=1)/e.size,s]}}.sort.map &:last} ``` [Try it online!](https://tio.run/##NYpBDsIgFESvwko0LdQu3GgwqbWnIMR8FVIS1KZQE205O4rUzbzMm@mH8ysoFsgexicDqgy40w26cZKTZj3cr6TcSWrbQSkj6W@xE1/GpdiQNS0znbFyVXw/@i1zK7yn9tG7eEWLrQHrfOgGZ5GiFzAGcY4rnCNczVlhkSOODwl1lHWdyjGhia6Z848GCxE@ "Ruby – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes ``` Fθ«≔⟦⟧ηW⁻ιη⊞η‽κ≔∕‽⁵¦⁴ιFEη⟦∕⁺λ⁺ι∕⊖⊘‽⁵χLηκ⟧⊞υκ»W⌊υ«≔Φυ¬⁼ικυ⟦⊟ι ``` [Try it online!](https://tio.run/##TVDBTsQgFDxvv4Ibj6QmmujJU21rPLim8Uo4kBa3L6WwS0s9GL@9QsuqB97AMG/eQNtL11qp1/XDOgIXRr6yQzFNeDLARU569pgdPnvUisARjZ8AI8lI46ce@py8S9PZEQYWhamxwgU7BenqgeXkPiyMim3KUZ5jK0@6RgdbnZMNg32iK9U6NSozqw5epF4C/Dqy4Hd3u8GrMqc5RIn7QVyT@XAI876zv@w4@hE8@//CZ9SzclH8ZmeoL17qLcGwOfsYuHFoZuCNPQMyES3XlXNOC5oTWqRa0PBVnD7tUEayLPdDtUMduTrVK9RUCLHeLPoH "Charcoal – Try It Online") Link is to verbose version of code. Uses 5 distinct equally-spaced random numbers each time as allowed by the question. Explanation: ``` Fθ« ``` Loop over each category. ``` ≔⟦⟧η ``` Start with no shuffled items. ``` W⁻ιη ``` Repeat until the set difference between the items and shuffled items is empty. ``` ⊞η‽κ ``` Randomly pick one element of the difference to append to the shuffled items. ``` ≔∕‽⁵¦⁴ι ``` Pick a random number between `0` and `1` which represents `io*n`. ``` ∕⁺λ⁺ι∕⊖⊘‽⁵χLη ``` For each item, add its index within its category `v*n` to `io*n` and a randomly generated offset `o*n` between `-0.1` and `0.1`, then divide the sum by `n` to get the final positional value. ``` FEη⟦...κ⟧⊞υκ» ``` Save each random value and item in a separate list. ``` W⌊υ« ``` Repeat while the (minimum of) the list of random values and items is not empty. ``` ≔Φυ¬⁼ικυ ``` Filter out the minimum value from the list. ``` ⟦⊟ι ``` Output the item with that value. [Answer] # [R](https://www.r-project.org/), ~~104~~ 101 bytes ``` function(x,`!`=unlist,`+`=runif)(!x)[order(!lapply(lengths(x),function(l)(sample(l)-+1--+l/5-.1)/l))] ``` [Try it online!](https://tio.run/##PYxBCsMgFETPElf/ozZk0WUWaeIpSsGQxjbwa8Qo2NNbi6WbN8ODGZ9Nn020S9h2C0noRvfR0nYEobnufbSbQWgSXnd/Xz00NDtHb6DVPsLzgITivyaEY345WkuTvJOSU3uWpw5bQrxlA99bWIANTLChYmAoirnUGIsbx9qnGqooVfGjYoiYPw "R – Try It Online") A function taking a list of character vectors and returning a character vector. Thanks to @RobinRyder for saving 3 bytes! [Answer] # [Python 3](https://docs.python.org/3/), 147 bytes ``` lambda a:[*zip(*sorted(((j+l.index(k)+random()/5-.1)/len(l),k)for j,l in((random(),sample(m,len(m)))for m in a)for k in l))][1] from random import* ``` [Try it online!](https://tio.run/##NY3NDoIwEITvPkVv3cUKIcaLiQdEnqL2UAPEQv9SOKgvX/m9zMxOvs347/h29hzb2zNqaV61JPLKk5/ykAwujE0NAN1Rp8rWzQd6PAZpa2cAs8spzTHTjQWNrMfWBdIxTZQF2Bk2SON1A4bNmEFcKDMxRC6xn6NGFDwXhzY4Q9ZXooyf1pPog7IjtMA5LSgjtNi0oIIRTu@rlXNZluvxWK2au2rT3SoqBGL8Aw "Python 3 – Try It Online") Assumes no duplicates ]
[Question] [ This is the inverse of [negative seven's question](https://codegolf.stackexchange.com/questions/193640/injection-from-two-strings-to-one-string). Write a program or function which, given **any** single, possibly-empty string of printable ASCII (codes \$[32,126]\$) outputs or returns two strings of printable ASCII. For any two ordered, possibly empty strings \$s\_1\$ and \$s\_2\$, there **must** be third string \$s\_0\$, which input to your program, outputs \$s\_1\$ and \$s\_2\$. --- In other words, if \$\mathbb S\$ is the set of all ASCII strings (including the empty string): \$f\$ is well-defined on \$\mathbb S\$: \$(\forall s\in\mathbb S)(f(s)\in\mathbb S\times\mathbb S)\$ \$f\$ is a surjection to \$\mathbb S\times\mathbb S\$: \$(\forall s\_1,s\_2\in\mathbb S)(\exists s\_0\in\mathbb S)(f(s\_0)=(s\_1,s\_2))\$ ## Test cases: For each of these strings (surrounding «quotes» excluded), your output should be two strings: ``` «» «hello world» «'one' 'two' 'three' 'four'» «"one" "two" "three" "four"» «["one", "two", "three"]» «; exit()» ``` For each of these pairs of strings, there must be at least one string you can provide to your program such that that pair is output (surrounding «quotes» excluded): ``` s_1 | s_2 ---------|---------- «hello » | «world» «hell» | «o world» «hello» | « world» « » | «» «» | « » «» | « !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~» «\r\n» | «\r\n» ``` As always, you are encouraged to add test cases pertinent to your method. ## Rules: * Input must be a single string/character array/byte array consisting of only ASCII characters. * Output is *ordered*; \$(a,b)\neq(b,a)\$. Output can be any ordered structure in your language, or printed with a newline (LF or CR LF) separator and optional trailing newline. * I/O must be consistent. If one case handles input as an argument and outputs to stdout with a trailing newline, all cases must handle input as an argument and output to stdout with a trailing newline. * Standard loopholes are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shorter programs are better! As a reminder, this is only a surjection, not a bijection: Your program/function will likely map many different strings to the same output. [Answer] # [Python 2](https://docs.python.org/2/), 42 bytes ``` lambda s:(s.split("1"+len(s)/2*"0")*2)[:2] ``` [Try it online!](https://tio.run/##jY7BboMwDIbvPIXFhQTQ2nFE2rUvsU3IEaZEDQmK0yl9eppWSB3dpM0Xy/7/77fnSxidbZbh7WMxOKkegVvBLzwbHUT@mleGrGC5a8p8n8uyke9t87n0NMBBYK1km4GncPYWsLrZk6u8IVgpWaksm722QQyiKKR8DOwmAuv8hEbzCByScKzB6BPVgGZyHFIzq8AblmL6bC83uzASKOdO4AagLrr@zDAiA1r47juIAu0FjvqL7Jpd1PeVSwl@K8ifYBdTdb@QMf7JPh19tvz7j5Vdrg "Python 2 – Try It Online") The inverse is: ``` def F(a,b): return a+"1"+len(a+b)*"0"+b ``` A tempting idea for the inverse is to encode the pair of input strings by putting some separator string in between them. That way, we can extract the pair by splitting on this separator. The issue is that the separator may appear in the inputs string. We get around this by making the separator longer than the total length of both strings. We use `1` followed by a number of `0`'s equal to the number of characters in both strings. For example, ``` abc, defgh -> abc100000000defgh ``` Note that no matter how many 0's and 1's are in the two inputs, there's no way to get another copy of the separator to appear. We can recover the separator from the combined string by using a number of zeroes equal to half its length rounded down. I had wanted to compute this as `10**_`, but Python's repr appends an annoying `L` to large numbers, which messes it up. We need to the submission function still give two outputs when the input string doesn't contain the required separator. In this case, splitting just gives the original string, but we copy it twice to be compliant. --- **[Python 2](https://docs.python.org/2/), 35 bytes** (not working) ``` lambda s:s.split(s[:len(s)/3])[-2:] ``` [Try it online!](https://tio.run/##hY7BbsMgEETvfMXIORhqt03Tm6Vc8xNJZIGMYxQMlpdE5OtdkkZVnVYt0gp25s2ywyV03q2mdr2brOxVI0EVvdBgTeC0rax2nMTr@15sn1fVfmp0iw2XpRIVA@kBa2RvGQpcQVkogSdky4xh1OE0uhtSQKb6fCnGFsNoXOAtz3Mh2FdDvtdwfuylNdSBQjIOJaw56hLS9p5CuuzdoFlWx7TtUsy00Gko74/wLXQdfXMidJIgHb5zG55Ld8HBnLW7z87Lm@TThHFuiJ/BOqZT/5KM8d/sw6ePyN97LObkVZs@AA "Python 2 – Try It Online") This would work except it gives an error for the empty string. The idea is to have the inverse encode `a,b -> sep + a + sep + b`, where the separator `sep` has the same length as `a+b` so we can extract it as the first third of the string. A similar idea of putting the separator interspersed runs into the same issue. --- **[Python 2](https://docs.python.org/2/), 43 bytes** ``` lambda s:[s[i::2].lstrip()[1:]for i in 0,1] ``` [Try it online!](https://tio.run/##jZDBboMwDIbvPIXFhUSNqpbekHrtS1CEHBFKWkiqJExh2rszs1Xb2k7acon925/9J9cpdNbkc7s/zj0OskHwRelLXRR5te59cPrKeLktqtY60KANbMS2mhvVwoGhkLxIAHPYQ/qWwgowAfmdyQQGjHWvDEkUMYoY5lzAEsicc4J3VMN87c6jD@zWTrpcdPmsOxVGZyBN12erDSvjaoLFWxTT4u6V/OJOEM4rniRXp01gLcsy2vWVeDsoMNYN2GvfwfJKcyJT@qIEYD9YH@jqbwV/x6qoA9vwOy10CqS1F7AtqDraZvTQoQc08LPvwDI0E5z0C33I5@xMfEiWJrj7An8G60in/oWM8U/2Yeljy7993Nj5HQ "Python 2 – Try It Online") The idea for encoding is to intersperse the two input strings with alternating characters. The problem there is that they may have different lengths. So, we pad them to the same length by prepending each one with some number of leading spaces then `|` (any non-space char will do). For example, `abcd, ef` goes to ``` |abcd |ef ``` This can be undone for each string by stripping off all leading spaces then removing the first character. Note that any spaces or `|` in the actual strings are left unharmed. **[Python 3.8 (pre-release)](https://docs.python.org/3.8/), 44 bytes** ``` lambda s:(s[(i:=s.find('_'))+1:2*i],s[2*i:]) ``` [Try it online!](https://tio.run/##jY7dasMwDIXv@xQiN7YbM/ZzMwxhd32JrhiFOI2pY4XIG@7TZ2YEtnSDTTdCOuc70nRNA8Wn52le@uZ1CTi2HQIbyUfpTcN3vY@dFFYoVT@Yx70/aT6WZk5qOTSrHXVrZHBRYjGpffVS1ZWtaqzb3W6afUyyl6IkfA1Mo4NI84jB8wCcinDWEPzFacAwEqfSwirwhnXZJ3mvNrs0OGiJLkA9OJupe2MYkAEjfPcdpMB4hbN/d3HNFvpzRSVh3grqJ2hzKfsLmfOf7M3RW8u//1jZ5QM "Python 3.8 (pre-release) – Try It Online") Inverse: ``` F=lambda a,b:(len(a)+1)*"?"+"_"+a+b ``` For instance, `F("ab","cdef") = ???_abcdef`. The number of symbols before the `_` tells us where to split the remainder -- it's one more than the length of the first string. We need the submission not to error when there's no `_`, but this works out because Python's string `find` uses `-1` for missing, which still gives valid slices. [Answer] # [Haskell](https://www.haskell.org/), 38 bytes ``` f(' ':a:b)=(a:)<$>f b f s=(drop 1s,"") ``` [Try it online!](https://tio.run/##hY7haoMwFIX/@xSHUDChKWx/ZfYN@gS1yNUmKsZETDoc7NnnTCcbGxvL/XFvcs6Xc1vyvTJmWTRPkWaUVSLnlImn3VGjSjR8zq@TG/HoJWNiaTjJaKmdrSmcaAQvahyOOK@4RH0RqAT2e7BXFhslyUCdRY6BxhPGqbMBu3iBxpkxCebdoGDdNJDpfAsfVk8jYbpeSZAZnA9rM5vgI6LmLvAHEcc0tAqVcz2chipnd715tORBFmk0FDGk4YzsC5ruWdntIybvT27lp@@C@PSX83rKX4B5/gv5EbEp/4V9OYtYxcfi90lclrdaG2r8cqjH8R0 "Haskell – Try It Online") Not using built-in parsing. --- **21 bytes (doesn't quite work)** ``` last.(("",""):).reads ``` [Try it online!](https://tio.run/##hU/bTsQgEH3fr5gQk4Vs3Xh9Mekn@AXWNNNdCqRcmg4q/rwIbqPRaISHOcw5Z86gkSZpbR7bLlukuOecsYYxcSf2i8QjZcWxGURLOrwA7nbDZuPQeGjB4XwP82J8hLP6gBEeihcYBSfBh8WhNaSBYtGoBqyZZANoXaBYil0JqhaZTOQXosJt1BKGECYII8g@heMTgUYC9LCtgq6GKM7Qv4Iyz9Kvg8ratRWKf/lOiE99n8rpfzGk9JflR8TK/Bf2pezq7U6LfyBxgt3l1fXNbfnMY347jBYV5fPDPL8D "Haskell – Try It Online") (As pointed out by @benrg, this produces unprintable characters outside the valid range on some inputs like `"\1"` that decode to escape characters.) The inverse is ``` g(a,b)=show a++b ``` This puts the first string in quotes, escaping any characters as needed, and appends the second string. This is undone by `reads`, which looks for a prefix that's a string representation of the correct type (here, string), reads it, and puts it in a pair with the remainder. To make the function total, if this fails, we just return two empty strings. Note that `reads` only does lexing, not evaluation, so it won't mess up on weird inputs. If we may output a singleton list of a two-string pair, we can save 3 bytes: **18 bytes** ``` max[("","")].reads ``` [Try it online!](https://tio.run/##hY9bbsMgEEX/s4oRqhSjOFU34CV0BTayxgk2yDwsD0no5kMgjfpSq8IHA/eeuYNCmqUxaWy6ZDG2FWM1Y1w8rxKPlKa2wnrgoiHlL4C73bDZWNQOGrC4vMKyahfgqVxghDbDwMhbCc6vFo0mBRSyZ6rB6FnWgMZ6CvkwD4EKIqMO1Qsv5TYoCYP3M/gRZB/98USgkAAdbIuhKyF5LobuDSZ9lu7RKQ9ennxusH4XuPgk@phX/wsS49/Qj5gP7f/Ir@6u7O79D/eKC5Guh9HgRGl/WJYb "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~53~~ 52 bytes ``` lambda s:(s.split('_x'+s.count('x')/2*'x')+[''])[:2] ``` [Try it online!](https://tio.run/##jY/BboMwDIbvPIWlHUwalk0ckdiRF@DYVShtQ4kaEoRDlV726iydmMa6SZsvjv37@@0MV985m89t@Tob2e@PEqhISdBgtE@xCchJHNxkYxGQPeWbW@JbxB3bFvlufgDfKdD2okZS0E724LWzUEEBdaihfIEahBBJVX7aZ74gjg3y6LR5fEuJe7ZawX2SDKO2HtoUkX29yfUKrBt7aTR1QD4KpwyMPqsMpOkd@ZjMItAaVSF@5pmtW7er986dwbWgmuCOE0EnCaSF1ViVorRXOOmLsosxZh8tFw3G7wL7wTUhRvMLGMJf6N3Ku4n/HrGQMeZ3 "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` g2÷°¡2∍ ``` -1 byte thanks to *@Grimy*. [Try it online](https://tio.run/##yy9OTMpM/f8/3ejw9kMbDi00etTR@/9/YlKyoQEYpKSmAQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCvZLCo7ZJCkr2/9ONDm8/tOHQQqNHHb3/df5HKynpKChlpObk5CuU5xflpIC46vl5qeoK6iXl@SAyoygVxEvLLy1SB8nGKAGlY5QUYpSACiA0SAmYBVIUAzYyGqpMB6ZOB6EwFqTAWiG1IrNEQxNhv6EBAsDdApJClkByJlgXshxCCmgWiDI0UIBQtAUKijFKyiqqauoamlraOrp6@gaGRsYmpmbmFpZW1ja2dvYOjk7OLq5u7h6eXt4@vn7@AYFBwSGhYeERkVHRMTGxcfEJiUnJKalp6RmZWdk5uXn5BYVFxSWlZeUVlVXVNbV14GAviskDegREgf0EIoC6oH4DalaKBQA). **Inverse (4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):** ``` Jg°ý ``` [Try it online](https://tio.run/##yy9OTMpM/f/fK/3QhsN7//@PVkpMSlbSUUpJTVOKBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCvZLCo7ZJCkr2/73SD204vPe/zv/oaKWM1JycfIXy/KKcFCUdFF6sjgJMGiiDJgYUwVQHFEQWA2mDsEASCJZijJKyiqqauoamlraOrp6@gaGRsYmpmbmFpZW1ja2dvYOjk7OLq5u7h6eXt4@vn39AYFBwSGhYeERkVHRMTGxcfEJiUnJKalp6RmZWdk5uXn5BYVFxSWlZeUVlVXVNbR3EppiimDygbWAKZjWEAdQNZAMNUIqNBQA). Port of [*@xnor*'s first Python 2 approach](https://codegolf.stackexchange.com/a/194545/52210), so make sure to upvote him as well!! **Explanation:** ``` g # Get the length of the (implicit) input-string 2÷ # Integer-divide it by 2 ° # Take 10 to the power this ¡ # And split the (implicit) input-string by this integer 2∍ # Extend this list to (or keep it at) size 2 # (after which this pair is output implicitly as result) J # Join the strings in the (implicit) input-list together to a single string g # Get the length of this ° # Take 10 the power this ý # And join the strings of the (implicit) input-list with this as delimiter # (after which the resulting string is output implicitly as result) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes ``` ^(("[^"]*")*),? $1¶ %`^"|"("?) $1 ``` [Try it online!](https://tio.run/##PY1NCoMwEIX3c4rwqCSRbLruwmUPYRQLTVEQA8Gii56rB@jF0hm13cz7@RJeCvMw3XJhrl1ujUHdoilhS@sqOp0/byq6Fi8YVJZzztSHcYxqiWm8k45T0ErPS5TbpyDpEZ9JExhBgZFcQayCQPXG3A7djzZ0UWEdZmMJ@wYcthnsBcdj9yj4M/6FvGaRSkQMpPBsvBezOTHJT2JFvg "Retina 0.8.2 – Try It Online") Link includes test cases. Takes as input the output from my Charcoal answer to @negativeseven's question and outputs the two strings on separate lines. Explanation: ``` ^(("[^"]*")*),? $1¶ ``` My Charcoal answer always outputs a number of quote-surrounded strings followed by a comma. Find that comma and split the strings there. If there's no comma, the split happens after the quote-surrounded strings, if any. ``` %`^"|"("?) $1 ``` Decode each string by deleting the first quote, one quote of each pair, and the last quote. (Assuming this is an encoded string, of course... otherwise this just deletes arbitrary quotes.) [Answer] # [Ruby](https://www.ruby-lang.org/), 81 bytes ``` ->s{s.match(/^(\d+)\.(.*)/m){|m|l=m[1].to_i;[m[2][0,l],m[2][l..-1]||'']}||['',s]} ``` [Try it online!](https://tio.run/##bY/RbsIgFIbv@xSEmwMbHlejV8a9CLBlm21qAmIojRrx2TuoK8kSSTh8nPOF/Pjh@zq2OzUu3vtbj/Yr/HRs@cHU/pUrZPjCl5bfoo1mZ2WtMbjPw1ZaudLyTRgtJjKIi1rHCKDvMUoA0ev7eCItMloj5dUDC3SNMY6cnTf70gN3bIBAOLtcO9/kW@sGD7MCNCmU0KTkmpV0ZoXCrMjJEQ9JzJae53RLmsshMJ7erE5D6AlA9Tfa4BTrf6o1Psu6edqtkRQuBOn/JV5S1LSKt0Ll1TFvysdf "Ruby – Try It Online") I don't golf much in Ruby so this can surely be shortened -- tips appreciated. Idea is to to provide a meta-prefix `<number>.rest of string` which will split "rest of string" at number. Strings without the meta-prefix just return `["", <original string>]` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 17 bytes ``` ^(.*)(.*)\1\1 $2¶ ``` [Try it online!](https://tio.run/##K0otycxL/P8/TkNPSxOEYwxjDLlUjA5t@//f0AAEMlJzcvIhTAhZnl@UkwIA "Retina 0.8.2 – Try It Online") This parses the string as \$xs\_1xxs\_2\$ for the longest possible \$x\$ due to the greedy nature of regexes. We may choose \$x = 10^{\max \{|s\_1|, |s\_2|\}}\$ to ensure the desired parse. [Answer] # [Haskell](https://www.haskell.org/), 67 bytes ``` p""=["",""] p(' ':c)="":p c p('#':b:c)|h:t<-p c=(b:h):t p c=p$'#':c ``` [Try it online!](https://tio.run/##FYk7CoQwEIZ7TzH8EaKgFxhMt7dYttAQSDDGQafcu0fTfY@43nvIuVYB3BeYgF8ngyXLfnQAC/nmxvL2ln9kXea3uWHjOLJ2jaVv39djTcXJlYr2gs9pqJxKt@SkhmK4AuoD "Haskell – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 37 bytes ``` a=("${(@Q)${(z)1}}") <<<$a[1]' '$a[2] ``` [Try it online!](https://tio.run/##vVDpWsIwEPxNnmJd0VAVFbyhIN7ijbeSqoWmtFoa6GEFrK@OKcIruD92vpnNN5udvm8NzYwyGOqlDKYHmUpNkb2v5OIYFaKqalqv5zRKqMS8NowJiSzb4eBx3YCsB47t8iIYgqR40xKAVbcTBgVQ6@lkopWRpKQJzSZFScoEHA3GcikpSgzh8iGlQGEKp9Mzs5RRmlHm5heyi0vLufzK6tr6xuZWoaiWytuVnd29/YPDo@PqyenZ@cXlVe365vbu/uHx6bnOtJfXN73RNLjZsuz3D6ftik7X84PwM/rq9Qff8Y@85D@WWNxxAAVEwnMMHFEZzoQib3eCHvi8KVwDgVKCCGPRtKUVyl@OxAQYAkM0RNiQuXdDEXBkSJgsYEyix5gLf0BkiPIs33Zbk7fSRqYr7YNIJN3yeMJMEXpIfgE "Zsh – Try It Online") * `(z)` splits a string according to shell grammar * `(Q)` removes quotes * `(@)` prevents array joining in quotes * `" "` are needed to preserve empty elements Finally we print the first two strings with a quoted newline between them. ]
[Question] [ Output the following table: ``` 一一得一 一二得二 二二得四 一三得三 二三得六 三三得九 一四得四 二四得八 三四十二 四四十六 一五得五 二五一十 三五十五 四五二十 五五二十五 一六得六 二六十二 三六十八 四六二十四 五六三十 六六三十六 一七得七 二七十四 三七二十一 四七二十八 五七三十五 六七四十二 七七四十九 一八得八 二八十六 三八二十四 四八三十二 五八四十 六八四十八 七八五十六 八八六十四 一九得九 二九十八 三九二十七 四九三十六 五九四十五 六九五十四 七九六十三 八九七十二 九九八十一 ``` Or you can use the first three letters in its English word, in case that some languages don't support Chinese characters: ``` OneOneGetOne OneTwoGetTwo TwoTwoGetFou OneThrGetThr TwoThrGetSix ThrThrGetNin OneFouGetFou TwoFouGetEig ThrFouTenTwo FouFouTenSix OneFivGetFiv TwoFivOneTen ThrFivTenFiv FouFivTwoTen FivFivTwoTenFiv OneSixGetSix TwoSixTenTwo ThrSixTenEig FouSixTwoTenFou FivSixThrTen SixSixThrTenSix OneSevGetSev TwoSevTenFou ThrSevTwoTenOne FouSevTwoTenEig FivSevThrTenFiv SixSevFouTenTwo SevSevFouTenNin OneEigGetEig TwoEigTenSix ThrEigTwoTenFou FouEigThrTenTwo FivEigFouTen SixEigFouTenEig SevEigFivTenSix EigEigSixTenFou OneNinGetNin TwoNinTenEig ThrNinTwoTenSev FouNinThrTenSix FivNinFouTenFiv SixNinFivTenFou SevNinSixTenThr EigNinSevTenTwo NinNinEigTenOne ``` You can output in any reasonable format, e.g. plain text separated with space/comma/tab and newline, 2D array where empty places are empty or don't exist (The 2\*1 place is empty so there shouldn't be anything in the array). Code golf, shortest code in bytes win. GBK encoding is allowed, where each Chinese character use 2 bytes. Converting Table: | Character | Number | | --- | --- | | 一 | One | | 二 | Two | | 三 | Thr | | 四 | Fou | | 五 | Fiv | | 六 | Six | | 七 | Sev | | 八 | Eig | | 九 | Nin | | 十 | Ten | | 得 | Get | [Answer] # [Stax](https://github.com/tomtheisen/stax), 66 characters ``` 9mYF"得一二三四五六七八九"cacy*~@ny@\p;11AH:b!n;A/X@]z?px'十z?p,A%sn@]z?' +qD ``` Number of bytes depends on the encoding used for Chinese characters. [Run and debug online!](https://staxlang.xyz/#c=9mYF%22%E5%BE%97%E4%B8%80%E4%BA%8C%E4%B8%89%E5%9B%9B%E4%BA%94%E5%85%AD%E4%B8%83%E5%85%AB%E4%B9%9D%22cacy*%7E%40ny%40%5Cp%3B11AH%3Ab%21n%3BA%2FX%40%5Dz%3Fpx%27%E5%8D%81z%3Fp,A%25sn%40%5Dz%3F%27+%2BqD&i=&a=1) ## Explanation ``` 9mYF...D Loop `n` times and print a newline after each loop, `n`=1..9 "..."cay*~@ny@\p "..."c Push the string and duplicate it ay Fetch the outer loop variable * Multiply with the inner loop variable ~ Move the product to input stack for later use @ Take character at the index specified by inner loop variable ny@ Take character at the index specified by outer loop variable \p Print the two characters ;11AH:b!n;A/X@]z?p ;11AH:b! ?p Is the product not in range [11,20)? Output (*) if true, (**) if false. n;A/X@ Character at the index of the "ten" digit of product ] Convert character to string (*) z Empty string (**) x'十z?p,A%sn@]z?' +q x'十z?p Print "十" if the "ten" digit is non-zero, nothing otherwise ,A%sn@]z? Get the character specified by the last digit if that digit is non-zero, empty string otherwise ' +q Append a space and print ``` ## Alternative version (Stax 1.0.6), 59 bytes (by @recursive) This uses [a feature](https://github.com/tomtheisen/stax/blob/master/docs/compressed.md#crammed-integer-arrays) that is inspired by this challenge and is only included in Stax 1.0.6 which postdates the challenge. ``` éz░╖▐5à{│`9[mLùÜ•ëO╞îπl▼Γ─§╥|▒╛Δ◙Φµ'r╠eƒÿQ╫s♪Ω]£ï♪D3╚F◙δÿ%‼ ``` The ASCII version is ``` 9mX{x\_x*YA/]yA-y20<*!*+y9>A*+yA%]0-+"NT|,,t.%,p&()(!'^pq kzi !X6"!s@mJ ``` This version constructs the index array and then uses it to index the string of Chinese characters to avoid redundant stack operations (`c`,`a`,`n`) and multiple `@`s. ## Explanation ``` 9mX{...m Loop `n` times and map `1..n` to a list of strings, `n`=1..9 J Join the strings with space and print with a newline x\_x*YA/]yA-y20<*!*+y9>A*+yA%]0-+"..."!s@ x\ A pair: (inner loop variable, outer loop variable) _x*Y Product of inner and outer loop variable A/ floor(product/10) ] [floor(product/10)] yA- Product does not equal 10 y20< Product is less than 20 *! `Nand` of them This is true (1) if the product is in the range {10}U[20,81] * Repeat [floor(product/10)] this many times This results in itself if the predicate above is true, or empty array if it is false + Add it to the list of [inner loop var, outer loop var] This list will be used to index the string "得一二三四五六七八九十" y9>A* Evaluates to 10 if the product is larger than 9, 0 otherwise When indexed, they become "十" and "得", respectively + Append to the list of indices yA% Product modulo 10 ]0- [Product modulo 10] if that value is not zero, empty array otherwise + Append to the list of index "..."! "得一二三四五六七八九十" s@ Index with constructed array ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~151~~ ~~149~~ 146 bytes -3 bytes thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod). ``` l=" 一二三四五六七八九" for i in range(1,10):print([l[j//i]+l[i]+('得',l[j//10][10<j<20:]+'十')[j>9]+l[j%10]for j in range(i,i*i+1,i)]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8dWSeHJjoYnu3qe7Oh8Onv2k11TnraufbKj@Wnr6ic75ypxpeUXKWQqZOYpFCXmpadqGOoYGmhaFRRl5pVoROdEZ@nrZ8Zq50QDCQ31p/umq@uAxQwNYqMNDWyybIwMrGK11Z/2NqprRmfZWYKUZqkCZUGmZiFMzdTJ1MrUNtTJ1IzV/P8fAA "Python 3 – Try It Online") [Answer] ## Javascript, 190 bytes ``` (_="得一二三四五六七八九十")=>{for(i=1;i<10;i++){for(t="",v=0;v<i;t+=_[++v]+_[i]+[...(v*i+'')].map((a,b,c) => c.length>1&&b==0?(a>1?_[a]+'十':'十'):b==0?'得'+_[a]:_[a]).join``+' ');console.log(t)}} ``` ``` a=(_=" 一二三四五六七八九")=>{for(i=1;i<10;i++){for(t="",v=0;v<i;t+=_[++v]+_[i]+[...(v*i+'')].map((a,b,c) => c.length>1&&b==0?(a>1||c[1]==0?_[a]+'十':'十'):b==0?'得'+_[a]:_[a]).join``+' ');console.log(t)}} a() ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 166 bytes ``` ->{(1..9).map{|a|(1..a).map{|b|p=a*b;([b,a]+(p<10?[0,p]:p<11?[1,10]:p<20?[10,p%10]:[p/10,10]+(p%10<1?[]:[p%10]))).map{|d|"得一二三四五六七八九十"[d]}*""}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165aw1BPz1JTLzexoLomsQbES4TykmoKbBO1kqw1opN0EmO1NQpsDA3sow10CmKtgExD@2hDHUMDENsIKGwIFFcFcaML9IFsIAuoAShgA1QHEgTJaWpCTU6pUXq6b/qTHQ1PdvU82dH5dPbsJ7umPG1d@2RH89PW1U92zn3a26gUnRJbq6WkVFtb@z8tOlYvNTE5QyElX6GmKL@8hktBoUAByOBKzUv5DwA "Ruby – Try It Online") A lambda returning a 2D array of strings. ``` ->{ (1..9).map{|b| # b is the multiplier (1..b).map{|a| # a is the multiplicand p=a*b; # p is the product ( # We will build an array of indexes into a ref string: [a,b] + ( # The first two indexes will be a and b p<10 ? [0,p] : # Case 1: abGp (single digit sums) p<11 ? [1,10] : # Case 2: 251X (only happens once) p<20 ? [10,p%10] : # Case 3: abXd (12-18, d is the ones digit) [p/10,10]+( # (Cases 4 and 5 share a prefix) p%10<1 ? [] : # Case 4: abcX (20, 30, 40, c is the tens digit) [p%10])) # Case 5: abcXd (two-digit product, p = 10*c+d) ).map{|d| "得一二三四五六七八九十"[d] # Fetch the character for each index }*"" # Join the characters into words } } } ``` [Answer] # [Yabasic](http://www.yabasic.de), ~~250~~ ~~242~~ 238 bytes A [basic](/questions/tagged/basic "show questions tagged 'basic'") answer with unicode characters?! What? An anonymous function and declared helper function, `c(n)` that takes no input and outputs to STDOUT ``` For r=1To 9 For c=1To r c(c) c(r) If!r*c>9Then?"得";Fi c(r*c) ?" "; Next ? Next Sub c(n) s$="一二三四五六七八九" If n>19Then?Mid$(s$,Int(n/10)*3-2,3);Fi If n=10Then?"一";Fi If n>9Then?"十";Fi ?Mid$(s$,Mod(n,10)*3-2,3); End Sub ``` [Try it online!](https://tio.run/##q0xMSizOTP7/3y2/SKHI1jAkX8GSC8ROBrOLuJI1kjWBRJEml2eaYpFWsp1lSEZqnr3S033TlazdMkFSWkAV9koKStZcfqkVJVz2ECq4NEkhWSNPk6tYxVbpyY6GJ7t6nuzofDp79pNdU562rn2yo/lp6@onO@cqAQ1WyLMzhJjrm5miolGsouOZV6KRp29ooKllrGukY6wJsgqkztbQAGI/0EQlmCDcTb2NYDG4Kb75KRp5OkimcLnmpSgAXfb/PwA "Yabasic – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 196 bytes ``` lambda c=' 一二三四五六七八九':[[c[j]+c[i]+[('得'+c[(i*j%10)]),((c[(int(i*j/10))]*((i*j>19)or(i*j==10)))+'十'+(c[i*j%10])*(i*j%10!=0))][i*j>9]for j in range(1,i+1)]for i in range(1,10)] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHZVl3hyY6GJ7t6nuzofDp79pNdU562rn2yo/lp6@onO@eqW0VHJ0dnxWonR2fGakdrqD/dN10dyNHI1MpSNTTQjNXU0dAAcfNKQEL6QCHNWC0NENvO0FIzvwjEsrUFCWtqqz/tbVTXBiqHaI7V1IIao2gL0gYStrOMTcsvUshSyMxTKErMS0/VMNTJ1DbUBItmIouCLP8PF03T0LTiUgCCgiKwUzT/AwA "Python 3 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 100 characters, 122 bytes ``` 9* _ $`_$n _ $%`_$.%= (_+)(.) $.1,$2,$.($.1*$2*) \B. :$& :0 : 1:\b : ,(. ) ,0$1 T`,d:`_得一二三四五六七八九十 ``` [Try it online!](https://tio.run/##K0otycxLNPz/n8tSiyueSyUhXiUPRKsCGXqqtgpcGvHamhp6mlwqeoY6KkY6KnoaQJaWipGWJleMkx6XlYoal5UBlxWXoVVMEpDS0dBT0OTSMVAx5ApJ0EmxSoh/um/6kx0NT3b1PNnR@XT27Ce7pjxtXftkR/PT1tVPds592tv4/z8A "Retina – Try It Online") Explanation: ``` 9* ``` Insert nine `_`s. ``` _ $`_$n ``` Expand to 9 rows of 1 to 9 `_`s. ``` _ $%`_$.%= ``` (note trailing space) Expand to 9 rows of 1 to i `_`s plus i as a digit. ``` (_+)(.) $.1,$2,$.($.1*$2*) ``` Convert the `_`s to decimal and multiply by i. ``` \B. :$& ``` Insert a `:` if the answer has two digits. This will become the `ten` character. ``` :0 : ``` Delete zero units. ``` 1:\b : ``` Delete the `1` from `1:` unless it's `1:0` which had its zero removed. ``` ,(. ) ,0$1 ``` Inser a `0` for single-digit answers; this will become the `get` character. ``` T`,d:`_得一二三四五六七八九十 ``` Fix up all the characters. [Answer] # [Python 3](https://docs.python.org/3/), 142 bytes Structure is similar to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)'s 146 byte answer, but the middle terms work in a different way. ``` n=" 一二三四五六七八九" for x in range(1,10):print([n[y//x]+n[x]+n[y//10][20>y!=10:]+'得十'[y>9]+n[y%10]for y in range(x,x*x+1,x)]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P89WSeHJjoYnu3qe7Oh8Onv2k11TnraufbKj@Wnr6ic75ypxpeUXKVQoZOYpFCXmpadqGOoYGmhaFRRl5pVoROdFV@rrV8Rq50WDCSDH0CA22sjArlLR1tDAKlZb/em@6U97G9WjK@0swSpUgQpAJlYiTKzQqdCq0DbUqdCM1fz/HwA "Python 3 – Try It Online") # Explanation The most interesting term is the term for the number of tens: ``` n[y//10][20>y!=10:] ``` Note that `20>y!=10` means `20 > y and y != 10`, which is `False` when the number of tens should be included and `True` otherwise. `False` has an integer value of `0` and `True` has an integer value of `1`, so whereas `n[y//10]` is always one character long, the subscript `[20>y!=10:]` is equivalent to `[0:1]` (i.e. "the character") when the number of tens should be included and `[1:1]` (i.e. "no characters") otherwise. The following term, ``` '得十'[y>9] ``` is easier to understand; note that: * The output for every result <= 9 should contain `得` * The output for every result > 9 should contain `十` * `得` can be handled after the 'tens' term because the 'tens' term always evaluates to an empty string when there is a `得` ### Note on trailing spaces The trailing spaces for multiples of ten stretch the specification slightly - as mentioned by [rod](https://codegolf.stackexchange.com/users/47120/rod), this could be made visually perfect by using a zero-width space, but then you would also have to unpack the arrays using `print(*[...])` as the zero-width space is represented as a literal `"\u200b"` when printed in an array. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 141/130 bytes ``` (s=[...'得一二三四五六七八九'])=>s.map((A,i)=>s.map((B,j)=>i<j|!j?'':B+A+[s[(q=i*j)/10|-(q>11&q<19)]]+(q>9?'十':'')+[s[q%10||s]])) ``` [Try it online!](https://tio.run/##Rco9DgFBFADgsyjkvWcZpvSzKxQusabYIDITdowR1RZEFBI6iUKcQPRL4TQz51hUyi/5VLJO7GgpF6taqseTYhAWaMOYMQb@fXH5xr2OLj/469W9zn7/cPnO7@/ueQNBYWTZPFkg9qryj35VfSE7KiupLkCrH/SC2MZoQllRVOeNDE2H88xEvEk1LkSAJmp2wZ@20AKgXzblb8usEERFe6RTq2cTNtNTHCAxpWWKMEyBqF18AA "JavaScript (Node.js) – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~75~~ 100 characters, ~~97~~ 122 bytes ``` k t←' 一二三四五六七八九得十'10 ∘.{⍺<⍵:''⋄(s=10)∨19<s←⍺×⍵:k[1+⍵⍺(⌊s÷t)11,t|s]⋄9<s:k[1+⍵⍺,11,t|s]⋄k[⍵⍺t s+1]}⍨⍳9 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P1uh5FHbBHWFJzsanuzqebKj8@ns2U92TXnauvbJjuanrauf7Jz7dN/0p72N6oYGXI86ZuhVP@rdZfOod6uVuvqj7haNYltDA81HHSsMLW2KgQYBJQ9PB8lmRxtqA2kgX@NRT1fx4e0lmoaGOiU1xbFAXUC1SAp0EBLZ0RChEoVibcPY2ke9Kx71brYcGq4EAA "APL (Dyalog Unicode) – Try It Online") [Answer] # JavaScript, 190 bytes ``` (s="得一二三四五六七八九十",o="")=>eval(`for(i=1;i<10;i++){for(j=1;j<=i;j++){o+=s[j]+s[i]+(i*j<10?s[0]:i*j<11?s[1]+s[10]:i*j<20?s[10]:s[i*j/10|0]+s[10])+(i*j%10?s[i*j%10]:"")+" "}o+="\\n"}`) ``` I will try to golf this later. [Answer] # [Ruby](https://www.ruby-lang.org/), 136 bytes Byte count in UTF-8, should be 128 bytes with Han characters counted as 2 instead of 3. ``` 1.upto(9){|x|p (1..x).map{|y|[y,x,x*y/10,?X,x*y%10].join.sub(/(?<=0)X|1(?=X[1-9])|0$/,'').tr"0-9X","得一二三四五六七八九十"}} ``` [Try it online!](https://tio.run/##KypNqvz/31CvtKAkX8NSs7qmoqZAQcNQT69CUy83saC6prImulKnQqdCq1Lf0EDHPgLEUjU0iNXLys/M0ysuTdLQ17C3sTXQjKgx1LC3jYg21LWM1awxUNHXUVfX1CspUjLQtYxQ0lF6um/6kx0NT3b1PNnR@XT27Ce7pjxtXftkR/PT1tVPds592tuoVFv7/z8A "Ruby – Try It Online") 1. Construct the strings from multipliers' and products' digits with the latter separated by `X` as a placeholder for `十`. 2. Do some regex fun to drop `X` for products <10, leading ones for "-teen" products, and trailing zeroes. 3. Translate digits and `X` to Han characters. [Answer] # [///](https://esolangs.org/wiki////), 301 bytes (GBK\*) ``` /*/\/\///1/一*2/二*3/三*4/四*5/五*6/六*7/七*8/八*9/九*0/十*=/得*I/ 1*t/ 2*T/ 3/11=1I2=2t2=4I3=3t3=6T3=9I4=4t4=8T402 4406I5=5t510T505 4520 55205I6=6t602T608 46204 5630 66306I7=7t704T7201 47208 57305 67402 77409I8=8t806T8204 48302 5840 68408 78506 88604I9=9t908T9207 49306 59405 69504 79603 89702 99801 ``` [Try it online!](https://tio.run/##FY0xSoRBDEZ7T5E6TTIzSSZTzAGmn9LGQrCw2zmAIhaCdgsWiycQe7XwNPuf4zdL4BG@8L0c7m8Od7eHfSek6xiiROfvB8x0/n3FEvsLCm2nE2okRzTanr@wRv6EHvsnNjr/fCDT9vaInba/dxx0lXARZJwEhVLqaeSeV@4ySi@rdJultyFdlnSfwhlE2IZ2XZp4KiuIZgYN6LBuyzhPYwexzAJqhcECNmqvq7LMmjmBBB20lhBYvXhrsA3vvpxt@qUsXuKgLqEIOFRXNnA3ltF6W419tswVpMUH0CYXXdPo1mZcwFsNQ2vOad//AQ "/// – Try It Online") \*Spec explicitly allows GBK → Unicode conversion. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 49 characters, 71 [bytes](https://mothereff.in/byte-counter#J%22%20%E4%B8%80%E4%BA%8C%E4%B8%89%E5%9B%9B%E4%BA%94%E5%85%AD%E4%B8%83%E5%85%AB%E4%B9%9D%22jmj%3Bm%2Bs%40LJkr6%3E3%2B%5C%E5%BE%97j%5C%E5%8D%81%40LJj%2AFkT%2CRdSdS9) ``` J" 一二三四五六七八九"jmj;m+s@LJkr6>3+\得j\十@LJj*FkT,RdSdS9 ``` Uses UTF-8 encoding. Try it online [here](https://pyth.herokuapp.com/?code=J%22%20%E4%B8%80%E4%BA%8C%E4%B8%89%E5%9B%9B%E4%BA%94%E5%85%AD%E4%B8%83%E5%85%AB%E4%B9%9D%22jmj%3Bm%2Bs%40LJkr6%3E3%2B%5C%E5%BE%97j%5C%E5%8D%81%40LJj%2AFkT%2CRdSdS9&debug=0). In the following explanation, the `?` characters are substitutes for the correct Chinese characters - I'm too lazy to make everything line up properly... ``` J" ?????????"jmj;m+s@LJkr6>3+\?j\?@LJj*FkT,RdSdS9 J" ?????????" Assign space + glyphs for 1-9 to J S9 [1-9] m Map each element, as d, using: Sd [1-d] ,Rd Pair each element of the above with d e.g. for d=3, yields [[1,3],[2,3],[3,3]] m Map each element, as k, using: *Fk Get the product of the pair j T Get decimal digits of the above (convert to base 10) @LJ Map each digit to its index in J j\? Join the above on ? ("Ten") +\? Prepend ? ("Get") >3 Take the last 3 characters of the above r6 Strip whitespace + Prepend to the above... s@LJk Concatenated digits of k in lookup string j; Join result on spaces j Join result on newlines, implicit print ``` [Answer] # Deadfish~, 5210 bytes ``` {{i}dd}dc{iii}ic{d}ic{dd}ddc{iii}ic{d}ic{ddd}c{iii}c{i}iiiiic{dddd}iiic{iii}ic{d}ic{{d}i}dc{{i}ddd}dc{iii}ic{d}ic{dd}iiic{iii}iiiiic{d}iic{dddd}c{iii}c{i}iiiiic{ddd}ddc{iii}iiiiic{d}iic{{d}ii}ic{iiiii}iic{iii}iiiiic{d}iic{ddd}iiic{iii}iiiiic{d}iic{dddd}c{iii}c{i}iiiiic{dddd}ddddddc{iiii}iciiiiiic{{d}}{d}iiic{{i}ddd}dc{iii}ic{d}ic{dd}iiic{ii}c{i}c{dddd}dddc{iii}c{i}iiiiic{ddd}ddc{ii}c{i}c{{d}ii}ddc{iiiii}iic{iii}iiiiic{d}iic{ddd}iiic{ii}c{i}c{dddd}dddc{iii}c{i}iiiiic{ddd}dddc{ii}iic{i}iiiiic{{d}i}iic{iiiii}iic{ii}c{i}c{ddd}c{ii}c{i}c{dddd}dddc{iii}c{i}iiiiic{dddd}iic{iii}dddciiiiic{{d}}c{{i}ddd}dc{iii}ic{d}ic{ddd}dc{iiii}iciiiiiic{dddd}ddddddc{iii}c{i}iiiiic{dddd}ddddddc{iiii}iciiiiiic{{d}ii}dddddc{iiiii}iic{iii}iiiiic{d}iic{dddd}dc{iiii}iciiiiiic{dddd}ddddddc{iii}c{i}iiiiic{ddddd}iiic{iii}iiiiiicddc{{d}iii}dc{iiiii}iic{ii}c{i}c{dddd}ddddc{iiii}iciiiiiic{ddd}dddc{ii}dddc{i}dc{dd}ddddddc{iii}iiiiic{d}iic{{d}ii}ic{iiii}ddc{iiii}iciiiiiic{ddddd}iiic{iiii}iciiiiiic{ddd}dddc{ii}dddc{i}dc{ddd}iiic{ii}iic{i}iiiiic{{d}}{d}c{{i}ddd}dc{iii}ic{d}ic{ddd}dc{iii}iiiiic{i}iiic{ddddd}iiic{iii}c{i}iiiiic{dddd}ddddddc{iii}iiiiic{i}iiic{{d}ii}ddddddc{iiiii}iic{iii}iiiiic{d}iic{dddd}dc{iii}iiiiic{i}iiic{dddd}ic{iii}ic{d}ic{dd}iiic{ii}dddc{i}dc{{d}ii}iic{iiiii}iic{ii}c{i}c{dddd}ddddc{iii}iiiiic{i}iiic{ddd}ddddc{ii}dddc{i}dc{dddd}c{iii}iiiiic{i}iiic{{d}ii}ddddddc{iiii}ddc{iiii}iciiiiiic{ddddd}iiic{iii}iiiiic{i}iiic{ddd}ddddc{iii}iiiiic{d}iic{ddd}iiic{ii}dddc{i}dc{{d}ii}iic{iiii}ddc{iii}iiiiic{i}iiic{ddddd}iic{iii}iiiiic{i}iiic{ddd}ddddc{iii}iiiiic{d}iic{ddd}iiic{ii}dddc{i}dc{dddd}c{iii}iiiiic{i}iiic{{d}}{d}iic{{i}ddd}dc{iii}ic{d}ic{dd}iic{ii}iic{i}iiiiic{ddddd}ic{iii}c{i}iiiiic{ddd}dddc{ii}iic{i}iiiiic{{d}i}iic{iiiii}iic{iii}iiiiic{d}iic{ddd}iic{ii}iic{i}iiiiic{ddd}ddddddc{ii}dddc{i}dc{dd}ddddddc{iii}iiiiic{d}iic{{d}ii}ic{iiiii}iic{ii}c{i}c{ddd}dc{ii}iic{i}iiiiic{ddd}ddddddc{ii}dddc{i}dc{dddd}dc{iii}iiiiiicddc{{d}iii}dc{iiii}ddc{iiii}iciiiiiic{ddd}ddddc{ii}iic{i}iiiiic{ddd}ddddddc{iii}iiiiic{d}iic{ddd}iiic{ii}dddc{i}dc{dddd}c{iiii}iciiiiiic{{d}ii}dddddc{iiii}ddc{iii}iiiiic{i}iiic{ddd}dddddc{ii}iic{i}iiiiic{ddd}ddddddc{ii}c{i}c{ddd}c{ii}dddc{i}dc{{d}ii}iic{iiiii}ic{ii}iic{i}iiiiic{dddd}iiic{ii}iic{i}iiiiic{ddd}ddddddc{ii}c{i}c{ddd}c{ii}dddc{i}dc{ddd}iiic{ii}iic{i}iiiiic{{d}}{d}c{{i}ddd}dc{iii}ic{d}ic{dd}iic{ii}ddc{ii}dddc{ddddd}iiic{iii}c{i}iiiiic{ddd}dddc{ii}ddc{ii}dddc{{d}ii}ddddddc{iiiii}iic{iii}iiiiic{d}iic{ddd}iic{ii}ddc{ii}dddc{ddd}ddddc{ii}dddc{i}dc{dddd}c{iiii}iciiiiiic{{d}ii}dddddc{iiiii}iic{ii}c{i}c{ddd}dc{ii}ddc{ii}dddc{ddd}ddddc{iii}iiiiic{d}iic{ddd}iiic{ii}dddc{i}dc{ddd}dc{iii}ic{d}ic{{d}iii}ic{iiii}ddc{iiii}iciiiiiic{ddd}ddddc{ii}ddc{ii}dddc{ddd}ddddc{iii}iiiiic{d}iic{ddd}iiic{ii}dddc{i}dc{dddd}dc{iii}iiiiiicddc{{d}iii}dc{iiii}ddc{iii}iiiiic{i}iiic{ddd}dddddc{ii}ddc{ii}dddc{ddd}ddddc{ii}c{i}c{ddd}c{ii}dddc{i}dc{dddd}c{iii}iiiiic{i}iiic{{d}ii}ddddddc{iiiii}ic{ii}iic{i}iiiiic{dddd}iiic{ii}ddc{ii}dddc{ddddd}iic{iiii}iciiiiiic{ddd}dddc{ii}dddc{i}dc{dd}ddddddc{iii}iiiiic{d}iic{{d}ii}ic{iiiii}ic{ii}ddc{ii}dddc{ddd}dddddc{ii}ddc{ii}dddc{ddddd}iic{iiii}iciiiiiic{ddd}dddc{ii}dddc{i}dc{ddd}ddc{iii}dddciiiiic{{d}}c{{i}ddd}dc{iii}ic{d}ic{ddd}ddc{iii}iiiiiicddc{ddd}ddc{iii}c{i}iiiiic{ddddd}iiic{iii}iiiiiicddc{{d}iii}dc{iiiii}iic{iii}iiiiic{d}iic{dddd}ddc{iii}iiiiiicddc{dd}ic{ii}dddc{i}dc{ddd}iiic{ii}iic{i}iiiiic{{d}i}iic{iiiii}iic{ii}c{i}c{dddd}dddddc{iii}iiiiiicddc{dd}ic{iii}iiiiic{d}iic{ddd}iiic{ii}dddc{i}dc{dddd}c{iiii}iciiiiiic{{d}ii}dddddc{iiii}ddc{iiii}iciiiiiic{ddddd}iic{iii}iiiiiicddc{dd}ic{ii}c{i}c{ddd}c{ii}dddc{i}dc{dd}ddddddc{iii}iiiiic{d}iic{{d}ii}ic{iiii}ddc{iii}iiiiic{i}iiic{ddddd}ic{iii}iiiiiicddc{ddd}dddc{iiii}iciiiiiic{ddd}dddc{ii}dddc{i}dc{{d}ii}iic{iiiii}ic{ii}iic{i}iiiiic{ddddd}dc{iii}iiiiiicddc{ddd}dddc{iiii}iciiiiiic{ddd}dddc{ii}dddc{i}dc{dddd}dc{iii}iiiiiicddc{{d}iii}dc{iiiii}ic{ii}ddc{ii}dddc{ddddd}ic{iii}iiiiiicddc{ddd}dddc{iii}iiiiic{i}iiic{ddd}ddddc{ii}dddc{i}dc{ddd}iiic{ii}iic{i}iiiiic{{d}i}iic{iiii}dddc{iii}iiiiiicddc{ddd}ddddc{iii}iiiiiicddc{dd}c{ii}iic{i}iiiiic{ddd}ddddddc{ii}dddc{i}dc{dddd}c{iiii}iciiiiiic{{d}}{d}iiic{{i}ddd}dc{iii}ic{d}ic{dd}dddc{iii}dddciiiiic{dddd}ic{iii}c{i}iiiiic{dddd}iic{iii}dddciiiiic{{d}ii}iic{iiiii}iic{iii}iiiiic{d}iic{ddd}dddc{iii}dddciiiiic{dd}ddddddc{ii}dddc{i}dc{dddd}dc{iii}iiiiiicddc{{d}iii}dc{iiiii}iic{ii}c{i}c{ddd}ddddddc{iii}dddciiiiic{dd}ddddddc{iii}iiiiic{d}iic{ddd}iiic{ii}dddc{i}dc{ddd}iiic{ii}ddc{ii}dddc{{d}ii}ddddddc{iiii}ddc{iiii}iciiiiiic{dddd}ic{iii}dddciiiiic{dd}ddddddc{ii}c{i}c{ddd}c{ii}dddc{i}dc{ddd}iiic{ii}iic{i}iiiiic{{d}i}iic{iiii}ddc{iii}iiiiic{i}iiic{dddd}c{iii}dddciiiiic{dddd}c{iiii}iciiiiiic{ddd}dddc{ii}dddc{i}dc{dddd}c{iii}iiiiic{i}iiic{{d}ii}ddddddc{iiiii}ic{ii}iic{i}iiiiic{dddd}ddc{iii}dddciiiiic{dddd}c{iii}iiiiic{i}iiic{ddd}ddddc{ii}dddc{i}dc{dddd}c{iiii}iciiiiiic{{d}ii}dddddc{iiiii}ic{ii}ddc{ii}dddc{dddd}c{iii}dddciiiiic{ddd}iiic{ii}iic{i}iiiiic{ddd}ddddddc{ii}dddc{i}dc{dd}ddddddc{ii}c{i}c{{d}ii}ddc{iiii}dddc{iii}iiiiiicddc{dd}dddddc{iii}dddciiiiic{ddd}iiic{ii}ddc{ii}dddc{ddd}ddddc{ii}dddc{i}dc{dd}ddddddc{iii}iiiiic{d}iic{{d}ii}ic{iiii}iiiiiic{iii}dddciiiiic{ddd}ddc{iii}dddciiiiic{dddd}dc{iii}iiiiiicddc{dd}ic{ii}dddc{i}dc{ddd}dc{iii}ic{d}ic{{d}i}dc ``` ]
[Question] [ In the future when Time Travel (abbreviated as TT) will be common, coin tossing will become a serious mind-sport. To prepare for the future we create a competition for programs where time traveling will be really happening from the viewpoints of the entries. The competition is a round-robin style King of the Hill consisting of coin tossing matches between Java classes. ## Rules of the coin tossing match * There are two players and 100 rounds. * In every round a coin is tossed and based on the result one of the players scores 1 point. Each player has 50% chance to score a point. * After the tossing both players have a chance to control the time by pulling levers. * If you pull a **blue lever (revert stopper)** no TT is possible to the round the lever was used or any earlier round anymore. TT's attempting to go to these rounds will have no effect. * If you pull a **red lever (reverter)** you try to revert the time back to a former round. If succeeded the **opponent's memory will be reverted** to its memory before the chosen round and the **coin toss results starting from the chosen round will also be deleted**. The only possible sign for your opponent about the TT will be the number of its unused levers which will not be reverted back. * Each player has 5 blue and 20 red unused levers at the start of the match. These levers are not affected by TT's. * If no TT happens at the end of a 100th round the game ends and the player with the higher score wins. ## Details * Rounds have a 1-based indexing (form 1 to 100). * Before round `x` you are provided the number of available blue and red levers, the coin toss results until turn `x` (inclusive) and the memory of your (last) `x-1`th round. * Pulling a blue lever in round `x` stops any TT's that have a destination at round `x` or before (it blocks a TT if it happens on that same exact round too). * Reverting to round `x` means that the next round will be round `x`. * If both players choose to revert at the end of a round the time is reverted to the earlier destination which is not blocked. The player(s) who tried to revert to this time will keep their memory. ## Technical details * You should write a Java class implementing the provided Bot interface. * Add your bot to the project. * Add an instance of your Bot to the `Bot` in the file `Controller.java`. * Your class should **not keep information between calls**. (In most cases having only `final` variables outside of functions satisfies this requirement.) * You can give information to the controller in the `memory` field of your returned `Action` object. This will be given back to you in the next turn if no TT happened. If a TT happens, you will receive the corresponding earlier memory of yours. * You can use the `totalScore()` method of the `Game` class to get the score of a history string. ## Protocol * At every turn your `takeTurn(...)` method is called with 5 arguments: + the number of unused blue levers + the number of unused red levers + the coin tossing history, a string consisting of 1's and 0's marking your wins and losses in the previous rounds. The first character corresponds to the first coin tossing. (In the first round the length of the string will be `1`.) + a string, your stored memory from the previous round + the 1-based index of this round * At every turn your method returns an `Action` object containing + an integer in the `move` field describing your action: - `0` for no action - `-1` to pull a blue lever and block TT's going through this round - a positive integer `x`, not larger than the current round, to pull a red lever and try to revert back to round `x` - Invalid integers are treated as `0`. + a string containing your memory from this round which you want to preserve. Note that **storing memory is not a crucial part of the challenge**. You can make good entries without storing any useful data in the string. At the first round the string will be an empty string. * Your method should take no more time than 10 ms per round on average in a match. * Regularly failing the time-limit results in disqualification. ## Scoring * Winning a match earns 2 points and a draw earns 1 point for both players. Loss earns no points. * A bot's score will be the total number of points it collected. * The number of matches played between each pair of contestants will depend on the number of entries and their speed. Two simple example bots are posted as answers. The controller and the first couple Bots are [available here](https://github.com/randomra/Coin-Tossing). Test results with bots submitted until November 3.: Total Scores: ``` Oldschool: 3163 Random: 5871 RegretBot: 5269 Nostalgia: 8601 Little Ten: 8772 Analyzer: 17746 NoRegretsBot: 5833 Oracle: 15539 Deja Vu: 5491 Bad Loser: 13715 ``` (The controller is based on the [Cat catcher challenge](https://codegolf.stackexchange.com/questions/51030/asymmetrical-koth-catch-the-cat-catcher-thread)'s controller. Thanks for @flawr providing it as a base for this one.) Bonus: [a nice 6-minute film](https://www.youtube.com/watch?v=vBkBS4O3yvY) based on a similar concept. [Answer] # Analyzer This analyzes the past to make the best predictions for the future. **EDIT:** Avoids blue levered times. Uses blue levers effectively. Uses red levers more effectively. Added scariness for Halloween season. **EDIT:** Fixed off by 1 error. **EDIT:** Improved `computeWinningProbability` function. Now uses red levers and blue lever more aggressively. ``` //Boo! package bots; import main.Action; import main.Game; import java.util.*; import java.util.stream.Collectors; /** * Created 10/24/15 * * @author TheNumberOne */ public class Analyzer implements Bot{ @Override public String getName(){ return "Analyzer"; } @Override public Action takeTurn(int blue_levers, int red_levers, String history, String memory, int roundNumber) { /*System.out.println(Game.totalScore(history) + " : " + history); try { Thread.sleep(100); } catch (InterruptedException e) { }*/ int roundsLeft = 100 - roundNumber; int myScore = (Game.totalScore(history) + roundNumber) / 2; //My number of wins. int enemyScore = roundNumber - myScore; //Enemy's number of wins. Map<Integer, Double> bestRounds = new HashMap<>(); int timeLimit = 0; Scanner scanner = new Scanner(memory); if (scanner.hasNext()){ //No memory, first turn. boolean triedTimeTravel = scanner.nextBoolean(); if (triedTimeTravel){ int time = scanner.nextInt(); if (roundNumber > time) { //Failed. timeLimit = time; } } timeLimit = Math.max(timeLimit, scanner.nextInt()); int size = scanner.nextInt(); for (int i = 0; i < size; i++) { bestRounds.put(scanner.nextInt(), scanner.nextDouble()); } } else { bestRounds.put(1, 0.5); } clean(bestRounds, roundNumber, timeLimit); double winningProb = computeWinningProbability(myScore, enemyScore, roundsLeft); String newMemory = computeMemory(bestRounds, roundNumber, winningProb); if (winningProb >= new double[]{1.5, .75, .7, .65, .6, .55}[blue_levers]){ //Ensure success ... slowly. return getAction(-1, newMemory, timeLimit, roundNumber); } int bestRound = bestRound(bestRounds); double bestRoundProb = bestRounds.get(bestRound); if ((winningProb <= bestRoundProb - .05 || winningProb < .5 && bestRoundProb > winningProb) && red_levers > 0){ return getAction(bestRound, newMemory, timeLimit, roundNumber); //Let's find the best past. } else { return getAction(0, newMemory, timeLimit, roundNumber); //Let's wait it out :) } } //Should be combined with computeMemory. private static Action getAction(int actionNum, String newMemory, int timeLimit, int roundNumber){ if (actionNum == -1){ timeLimit = Math.max(timeLimit, roundNumber); newMemory = "false " + timeLimit + " " + newMemory; return new Action(actionNum, newMemory); } if (actionNum == 0){ return new Action(actionNum, "false " + timeLimit + " " + newMemory); } if (actionNum > 0){ return new Action(actionNum, "true " + actionNum + " " + timeLimit + " " + newMemory); } return null; } private static int bestRound(Map<Integer, Double> bestRounds) { int best = 0; //If no previous rounds ... just go forward a round. double bestScore = -1; for (Map.Entry<Integer, Double> entry : bestRounds.entrySet()){ if (entry.getValue() > bestScore){ best = entry.getKey(); bestScore = entry.getValue(); } } return best; } private static String computeMemory(Map<Integer, Double> map, int roundNumber, double winningProb) { StringBuilder builder = new StringBuilder(); builder.append(map.size() + 1).append(" "); for (Map.Entry<Integer, Double> entry : map.entrySet()){ builder.append(entry.getKey()).append(" ").append(entry.getValue()).append(" "); } builder.append(roundNumber + 1).append(" ").append(winningProb); return builder.toString(); } private static void clean(Map<Integer, Double> data, int round, int timeLimit) { data .entrySet() .stream() .filter(entry -> entry.getKey() > round || entry.getKey() <= timeLimit) .map(Map.Entry::getKey) .collect(Collectors.toList()).forEach(data::remove); } private static double computeWinningProbability(int myScore, int enemyScore, int roundsLeft){ //Too complex for IntelliJ int height = myScore - enemyScore; double total = 0.0; for (int i = Math.max(height - roundsLeft, 2); i <= height + roundsLeft; i += 2){ total += prob(roundsLeft, height, i); } total += prob(roundsLeft, height, 0) / 2; return total; } private static double prob(int roundsLeft, int height, int i){ double prob = 1; int up = i - height + (roundsLeft - Math.abs(i - height))/2; int down = roundsLeft - up; int r = roundsLeft; int p = roundsLeft; while (up > 1 || down > 1 || r > 1 || p > 0){ //Weird algorithm to avoid loss of precision. //Computes roundsLeft!/(2**roundsLeft*up!*down!) if ((prob >= 1.0 || r <= 1) && (up > 1 || down > 1 || p > 1)){ if (p > 0){ p--; prob /= 2; continue; } else if (up > 1){ prob /= up--; continue; } else if (down > 1){ prob /= down--; continue; } else { break; } } if (r > 1) { prob *= r--; continue; } break; } return prob; } } ``` ## Score (since Nov 2): ``` Total Scores: Oldschool: 3096 Random: 5756 RegretBot: 5362 Nostalgia: 8843 Little Ten: 8929 Analyzer: 17764 NoRegretsBot: 5621 Oracle: 15528 Deja Vu: 5281 Bad Loser: 13820 ``` [Answer] # Oracle I shamelessly copied some code from Analyzer (for parsing the memory). This submission tries to pull a blue lever early and then slowly builds up his lead. I think the performance of this bot makes up for the ugly code :) ``` package bots; import java.util.*; import java.util.Map.Entry; import main.*; public class Oracle implements Bot { @Override public String getName() { return "Oracle"; } @Override public Action takeTurn(int blue_levers, int red_levers, String history, String memory, int roundNumber) { int roundsLeft = 100 - roundNumber; Map<Integer, Integer> rounds = new HashMap<>(); int myScore = (Game.totalScore(history) + roundNumber) / 2; int difference = myScore*2 - roundNumber; int highestBlockedRound = -1; int bestScore = 0; boolean hasUsedBlueLever = false; Scanner scanner = new Scanner(memory); if (scanner.hasNext()) { //timeTravel toRound highestBlockedRound hasUsedBlueLever bestScore rounds round1 percent1 round2 percent2 round3 percent3... boolean triedTravel = scanner.nextBoolean(); int time = scanner.nextInt(); if (triedTravel){ if (roundNumber > time) { highestBlockedRound = time; } } highestBlockedRound = Math.max(highestBlockedRound, scanner.nextInt()); hasUsedBlueLever = scanner.nextBoolean(); bestScore = scanner.nextInt(); int size = scanner.nextInt(); for (int i = 0; i < size && i < roundNumber; i++) { int number = scanner.nextInt(); int diff = scanner.nextInt(); if (number < roundNumber) { rounds.put(number, diff); } } } rounds.put(roundNumber, difference); final int blockedRound = highestBlockedRound; int roundToRevert = 0; if (rounds.size() > 2) { Optional<Entry<Integer, Integer>> bestRound = rounds.entrySet() .stream() .filter(x -> x.getKey() >= blockedRound && x.getKey() <= roundNumber) .sorted(Comparator .comparingInt((Entry<Integer, Integer> x) -> x.getValue()*-1) .thenComparingInt(x -> x.getKey())) .findFirst(); if (bestRound.isPresent()) { roundToRevert = bestRound.get().getKey(); } } if (roundsLeft + Game.totalScore(history) <= 0 && red_levers > 0) { roundToRevert = highestBlockedRound+1; } else if (blue_levers > 0 && roundToRevert == roundNumber && ((hasUsedBlueLever && difference >= bestScore*1.5) || (!hasUsedBlueLever && difference > 1))) { roundToRevert = -1; hasUsedBlueLever = true; bestScore = difference; highestBlockedRound = roundNumber; } else if (red_levers > 0 && roundToRevert > 0 && rounds.get(roundToRevert) > difference+2) { roundToRevert += 1; } else { roundToRevert = 0; } StringBuilder sb = new StringBuilder(); sb.append(roundToRevert > 0).append(' '); sb.append(roundToRevert).append(' '); sb.append(highestBlockedRound).append(' '); sb.append(hasUsedBlueLever).append(' '); sb.append(bestScore).append(' '); sb.append(rounds.size()).append(' '); rounds.entrySet().stream().forEach((entry) -> { sb.append(entry.getKey()).append(' ').append(entry.getValue()).append(' '); }); String mem = sb.toString().trim(); scanner.close(); return new Action(roundToRevert, mem); } } ``` [Answer] ## RegretBot At the end of ~~our life~~ the match, we regret our past failures, and attempt to go back and fix them. ``` package bots; import main.Action; import main.Game; public final class RegretBot implements Bot { @Override public String getName() { return "RegretBot"; } @Override public Action takeTurn(int blue_levers, int red_levers, String history, String memory, int roundNumber) { int actionNum = 0; if(roundNumber == 100) { // if it's the end of the game and we're losing, go back // in time to the first loss, in hopes of doing better if(Game.totalScore(history)<=0 && red_levers > 0) { actionNum = history.indexOf("0")+1; } // if we're winning at the end, pull a blue lever if we can, // to prevent our opponent from undoing our victory else if(blue_levers > 0) { actionNum = -1; } } // we don't need no stinkin' memory! return new Action(actionNum, null); } } ``` [Answer] # Nostalgia ``` package bots; import main.Action; import main.Game; public class Nostalgia implements Bot { @Override public String getName() { return "Nostalgia"; } @Override public Action takeTurn(int blue_levers, int red_levers, String history, String memory, int roundNumber) { int current_score = Game.totalScore(history); // wait until the end to use blue levers if (current_score > 0 && blue_levers >= (100 - roundNumber)) { return new Action(-1, memory); } // become increasingly likely to go back as the gap between the good old days // and the horrible present increases if (current_score < 0 && red_levers > 0) { //identify the best time to travel back to int best_score = -100; int good_old_days = 1; int past_score = 0; int unreachable_past = 0; if(memory != "") { unreachable_past = Integer.parseInt(memory, 10); } for(int i = unreachable_past; i<roundNumber ; i++) { if(history.charAt(i) == '1') { past_score += 1; if(past_score > best_score) { best_score = past_score; good_old_days = i + 1; } } else { past_score -= 1; } } if(roundNumber >= 95 || Math.random() < (best_score - current_score) / 100.0) { return new Action(good_old_days, Integer.toString(good_old_days)); } } // if neither action was needed do nothing return new Action(0, memory); } } ``` Not tested, just a quick stab at trying to make a bot that's difficult to block (because it decides when to pull the red lever mostly randomly) but that makes decent decisions. Edit: I missed this rule: > > If you pull a blue lever (revert stopper) no TT is possible through that round anymore > > > That seems like a good reason to use memory -- if you remember trying to TT to a given round, you may have failed, so you shouldn't try to TT to that round again. Edited my bot to try to avoid this. [Answer] # Little Ten Little Ten does a lot of multiplying and dividing by 10, using numbers that are multiples of 10, and going back to rounds that are multiples of 10. ``` package bots; import main.Action; import main.Game; public class LittleTen implements Bot { @Override public String getName() { return "Little Ten"; } @Override public Action takeTurn(int blue_levers, int red_levers, String history, String memory, int roundNumber) { int score = Game.totalScore(history); char c = history.charAt(history.length() - 1); if (memory.isEmpty()) memory = "1"; if (roundNumber == 100) { if (score >= 0) // We're tied or ahead by the end of the match. Prevent time // travel if we can; otherwise whatever happens happens. return new Action(blue_levers > 0 ? -1 : 0, memory); else { // Travel to earlier rounds the farther behind we are if we can // (of course using 10 as a reference) if (red_levers > 0) { int i = Integer.parseInt(memory); int round = score <= -10 ? i : 100 - ((100 - i) / (11 + (score <= -10 ? -10 : score))); return new Action(round, memory); } } } else if (score >= 7 + roundNumber / 20 && blue_levers > 0) { // We're ahead; we don't want to lose our lead, especially if the // match is close to ending. But we don't want to use up our blue // levers too quickly. int choice = (int) (Math.random() * 100), bound = (roundNumber / 10 + 1) * 5 - ((6 - blue_levers) * 5 - 2); if (choice < bound) { memory = String.valueOf(roundNumber); return new Action(-1, memory); } } else if (score <= -3) { // Possibly use a red lever if we're falling too far behind if (red_levers > 0) { int choice = (int) (Math.random() * 100), bound = score <= -11 ? 90 : 10 * (-3 - score + 1); if (choice < bound) { // Check the first round that is the lower multiple of ten // and decide if we've been successful up to that point; if // so, travel back to that round, otherwise go back 10 more int round = roundNumber / 10 * 10; if (round < 10) return new Action(1, memory); String seq = history.substring(0, round-1); int minRound = Integer.parseInt(memory); while (Game.totalScore(seq) <= 0 && round > 10 && round > minRound) { round -= 10; seq = history.substring(0, round-1); } if (round == 0) round = 1; return new Action(round, memory); } } } return new Action(0, memory); } } ``` Edit: Changed the mechanics a little now that the explanation of what happens when a blue lever is pulled is clearer. Also did a bit of rebalancing. [Answer] # Random Random's strategy is the following: * **block** with a 10% chance if in the lead and has blue levers left * **travel back** one turn (replaying the last round) with 10% chance if behind in score and has red levers left ``` package bots; import main.Action; import main.Game; public class RandomBot implements Bot { @Override public String getName() { return "Random"; } @Override public Action takeTurn(int blue_levers, int red_levers, String history, String memory, int roundNumber) { // if in the lead and has blocks left, blocks with a 10% chance if (Game.totalScore(history) > 0 && blue_levers > 0 && Math.random() > 0.9) { return new Action(-1, null); } // if behind and has travels left, travel back the current step to // replay it with a 10% chance if (Game.totalScore(history) < 0 && red_levers > 0 && Math.random() > 0.9) { return new Action(roundNumber, null); } // if neither action were needed do nothing return new Action(0, null); } } ``` [Answer] # NoRegretsBot ``` package bots; import main.Action; import main.Game; public final class NoRegretsBot implements Bot { @Override public String getName() { return "NoRegretsBot"; } @Override public Action takeTurn(int blue_levers, int red_levers, String history, String memory, int roundNumber) { // every 20 turns, pull a blue lever to lock in the past // hopefully this will thwart some of those pesky time-travelers return new Action(roundNumber%20==0?-1:0, null); } } ``` [Answer] # Bad Loser This bot uses no memory and is surprisingly good (but it doesn't beat Analyzer or Oracle). ``` package main; import bots.Bot; /** * Created 11/2/15 * * @author TheNumberOne */ public class BadLoser implements Bot{ @Override public String getName() { return "Bad Loser"; } @Override public Action takeTurn(int blue_levers, int red_levers, String history, String memory, int roundNumber) { if (history.contains("00") && red_levers > 0){ //Subtract a zero for better performance against return new Action(history.indexOf("00") + 1, "");// Analyzer and Nostalgia, and worse performance // against everything else. } int wins = 0; for (char c : history.toCharArray()){ wins += c - '0'; } if (wins >= new int[]{101, 51, 40, 30, 20, 10}[blue_levers]){ return new Action(-1, ""); } return new Action(0, ""); } } ``` [Answer] # Oldschool This bot never does any action as Oldschool doesn't believe in time traveling. ``` package bots; import main.Action; public class OldschoolBot implements Bot { @Override public String getName() { return "Oldschool"; } @Override public Action takeTurn(int blue_levers, int red_levers, String history, String memory, int roundNumber) { // never tries to block or travel at all return new Action(0, null); } } ``` [Answer] ## Deja Vu Bot This bot tries to track when it pulls the blue to avoid red pulls into that region. Will only pull red levers when significantly behind in the score. ``` package bots; import main.*; public class Dejavu implements Bot { @Override public String getName() { return "Deja Vu"; } @Override public Action takeTurn(int blue_levers, int red_levers, String history, String memory, int roundNumber) { if(roundNumber == 1) { memory = "-1"; } int[] blevers = getBlueLevers(memory); char[] hist = history.toCharArray(); int ms = 0; int ts = 0; int rl = -1; boolean bl = false; boolean url = false; for(int i = 0; i < hist.length; i++) { switch(hist[i]) { case '1': ms++; break; case '0': ts++; break; } } if(ts - ms >= 10) { for(rl = hist.length - 1; ts - ms <= 5 && rl >= 0; rl--) { switch(hist[rl]) { case '1': ms--; break; case '0': ts--; break; } } url = true; } if(ms - ts >= 7) { bl = true; url = false; memory += "," + roundNumber; } for(int i = 0; i < blevers.length; i++) { if(rl <= blevers[i]) { rl = blevers[i] + 1; } } if(url) { return new Action(rl, memory); } else if(bl) { return new Action(-1, memory); } else { return new Action(0, memory); } } private int[] getBlueLevers(String s) { String[] b = s.split(","); int[] bl = new int[b.length]; for(int i = 0; i < b.length; i++) { bl[i] = Integer.parseInt(b[i]); } return bl; } } ``` ]